|
Server : LiteSpeed System : Linux premium92.web-hosting.com 4.18.0-553.44.1.lve.el8.x86_64 #1 SMP Thu Mar 13 14:29:12 UTC 2025 x86_64 User : rbnsfqys ( 805) PHP Version : 8.1.33 Disable Function : NONE Directory : /home/rbnsfqys/ali.rbn.services/wp-content/plugins/Repairplugin-pro/ |
<?php
use function RepairPluginPro\get_path;
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
$rp_unmodified_request_data = $_REQUEST ?? array();
$rp_start_time_before_rp_loading_hook = microtime( true );
$rp_start_time_after_rp_loading_hook = 0;
$rp_start_time_before_plugins_loaded_hook = 0;
$rp_start_time_after_plugins_loaded_hook = 0;
$rp_start_time_before_init_hook = 0;
$rp_start_time_after_init_hook = 0;
$rp_start_time_before_admin_init_hook = 0;
$rp_start_time_after_admin_init_hook = 0;
$rp_actions_ran_time = array();
$rp_track_used_options = array();
function rp_add_action( $hook = '', $callback = null, $priority = 10, $accepted_args = 1 ) {
$backtrace = debug_backtrace();
$calledByFunction = '';
if( isset( $backtrace[0] ) ) {
$calledByFunction = $backtrace[0] ?? array();
// remove args if exists
if( isset( $calledByFunction['args'] ) ) {
unset( $calledByFunction['args'] );
}
// remove object if exists
if( isset( $calledByFunction['object'] ) ) {
unset( $calledByFunction['object'] );
}
// remove type if exists
if( isset( $calledByFunction['type'] ) ) {
unset( $calledByFunction['type'] );
}
}
add_action( $hook, function(...$args) use ($hook, $callback, $calledByFunction) {
global $rp_actions_ran_time;
$nameOfCallback = '';
if( is_string( $callback ) ) {
$nameOfCallback = $callback;
} else if( is_array( $callback ) ) {
if( is_object( $callback[0] ) ) {
$nameOfCallback = get_class( $callback[0] ) . '::' . $callback[1];
} else {
$nameOfCallback = $callback[0] . '::' . $callback[1];
}
} else if( is_object( $callback ) ) {
$nameOfCallback = 'Closure Function '. uniqid() . '' . rand(0,10000);
} else {
}
if( !isset( $rp_actions_ran_time[ $hook ] ) ) {
$rp_actions_ran_time[ $hook ] = array();
}
$uniqueCallbackHash = md5( $hook . $nameOfCallback );
if( is_callable( $callback ) ) {
$startTime = microtime( true );
call_user_func_array( $callback, $args );
$executionTIme = microtime( true ) - $startTime;
$rp_actions_ran_time[ $hook ][] = array(
'callback' => $nameOfCallback,
'execution_time' => $executionTIme,
'backtrace' => $calledByFunction
);
} else {
throw new Exception( "Callback is not callable: " . $nameOfCallback . " For hook ". $hook );
}
}, $priority, $accepted_args );
}
//rp_get_execution_time_till_now
rp_add_action( 'plugins_loaded', function() {
global $rp_start_time_before_plugins_loaded_hook;
$rp_start_time_before_plugins_loaded_hook = microtime( true );
}, -9999);
rp_add_action( 'plugins_loaded', function() {
global $rp_start_time_after_plugins_loaded_hook;
$rp_start_time_after_plugins_loaded_hook = microtime( true );
}, 9999);
rp_add_action( 'init', function() {
global $rp_start_time_before_init_hook;
$rp_start_time_before_init_hook = microtime( true );
}, -9999);
rp_add_action( 'init', function() {
global $rp_start_time_after_init_hook;
$rp_start_time_after_init_hook = microtime( true );
}, 9999);
rp_add_action( 'admin_init', function() {
global $rp_start_time_before_admin_init_hook;
$rp_start_time_before_admin_init_hook = microtime( true );
}, -9999);
rp_add_action( 'admin_init', function() {
global $rp_start_time_after_admin_init_hook;
$rp_start_time_after_admin_init_hook = microtime( true );
}, 9999);
rp_add_action('admin_init', function(){
$wizard = new \RepairPluginPro\InstallationWizard();
$wizard->register_ajax_hooks();
});
function rp_get_execution_time_till_now( $start_time = 0 ) {
if( empty( $start_time ) ) {
return 0;
}
return round( microtime( true ) - $start_time, 10 );
}
if( !function_exists('rp_safe_wp_cache_flush') ) {
function rp_safe_wp_cache_flush() {
if( function_exists('wp_cache_flush') ) {
try {
wp_cache_flush();
} catch( Exception|Error $e ) {
// do nothing
}
}
}
}
$rp_cached_options = array();
function rp_delete_option( $option_name = '' ) {
do_action('rp_changing_option', $option_name);
global $rp_cached_options;
if( isset( $rp_cached_options[ $option_name ] ) ) {
unset( $rp_cached_options[ $option_name ] );
}
global $wpdb;
$options_table = $wpdb->prefix . 'options';
$sql = "DELETE FROM `$options_table` WHERE option_name = %s";
$sql = $wpdb->prepare( $sql, $option_name );
$result = $wpdb->query( $sql );
return $result;
}
function rp_update_option( $option_name = '', $option_value = '' ) {
do_action('rp_changing_option', $option_name);
global $rp_cached_options;
$original_option_value = $option_value;
if( !is_numeric($option_value) && !is_integer($option_value) && is_bool( $option_value ) ) {
$option_value = ( $option_value ) ? 'true' : 'false';
}
if( is_object( $option_value ) || is_array( $option_value ) ) {
$option_value = serialize( $option_value );
}
$rp_cached_options[ $option_name ] = $original_option_value;
global $wpdb;
$options_table = $wpdb->prefix . 'options';
// check if have option_name in options table
$sql = "SELECT option_name FROM `$options_table` WHERE option_name = %s";
$sql = $wpdb->prepare( $sql, $option_name );
$result = $wpdb->get_row( $sql );
if( empty( $result ) ) {
// insert option_name and option_value into options table
$sql = "INSERT INTO `$options_table` (option_name, option_value) VALUES (%s, %s)";
$sql = $wpdb->prepare( $sql, $option_name, $option_value );
$result = $wpdb->query( $sql );
return $result;
}
$sql = "UPDATE `$options_table` SET option_value = %s WHERE option_name = %s";
$sql = $wpdb->prepare( $sql, $option_value, $option_name );
$result = $wpdb->query( $sql );
return $result;
}
function rp_add_option( $option_name = '', $option_value = '' ) {
do_action('rp_changing_option', $option_name);
global $rp_cached_options;
$orginal_option_value = $option_value;
if( !is_numeric($option_value) && !is_integer($option_value) && is_bool( $option_value ) ) {
$option_value = ( $option_value ) ? 'true' : 'false';
}
if( is_object( $option_value ) || is_array( $option_value ) ) {
$option_value = serialize( $option_value );
}
$rp_cached_options[ $option_name ] = $orginal_option_value;
global $wpdb;
$options_table = $wpdb->prefix . 'options';
$sql = "INSERT INTO `$options_table` (option_name, option_value) VALUES (%s, %s)";
$sql = $wpdb->prepare( $sql, $option_name, $option_value );
$result = $wpdb->query( $sql );
return $result;
}
function rp_is_serialized( $string = '' ) {
if( empty( trim( $string ) ) || is_numeric( $string ) || !is_string( $string ) ) {
return false;
}
// if string doesn't have {,},:,; then it is not serialized
$mustHave = array('{', '}', ':', ';');
foreach ($mustHave as $must) {
if( strpos( $string, $must ) === false ) {
return false;
}
}
// check if it is serialized false (b:0;)
try {
$array = @unserialize($string);
} catch (Exception|Error $e) {
return false;
}
if ($array === false && $string !== 'b:0;') {
return false;
}
return true;
}
function rp_filter_get_option_before_return( $result = '' ) {
if( empty( $result ) || !is_string($result) ) {
return $result;
}
if( is_serialized( $result ) || rp_is_serialized( $result ) ) {
$result = unserialize( $result );
}
if( $result === 'true' ) {
$result = true;
}
if( $result === 'false' ) {
$result = false;
}
return $result;
}
function rp_get_option( $option_name = '', $default = '' ) {
do_action('rp_using_option_name', $option_name);
global $rp_cached_options;
global $wpdb;
$options_table = $wpdb->prefix . 'options';
if( empty($rp_cached_options) ) {
// select * from options table where option_name start with rp_ or wp_repair_
$sql = "SELECT option_name, option_value FROM `$options_table` WHERE option_name LIKE 'rp_%' OR option_name LIKE 'wp_repair_%'";
$results = $wpdb->get_results( $sql );
if( !empty( $results ) ) {
foreach( $results as $result ) {
$rp_cached_options[ $result->option_name ] = rp_filter_get_option_before_return($result->option_value);
}
}
}
if( !empty( $rp_cached_options ) && array_key_exists($option_name, $rp_cached_options) ) {
return $rp_cached_options[ $option_name ];
}
// prepare sql using $wpdb->prepare() method
$sql = "SELECT option_value FROM `$options_table` WHERE option_name = %s";
$sql = $wpdb->prepare( $sql, $option_name );
$result = $wpdb->get_row( $sql );
if( empty( $result ) ) {
$rp_cached_options[ $option_name ] = $default;
return $default;
}
$result = $result->option_value;
if( empty( $result ) ) {
$rp_cached_options[ $option_name ] = $result;
return $result;
}
$result = rp_filter_get_option_before_return( $result );
$rp_cached_options[ $option_name ] = $result;
return $result;
}
// Load an Autoloader which will load
// PHP Classes files present in the Repairplugin-pro/classes folder
function wp_repair_classes_autoloader() {
global $rpQuery, $wpdb;
$fileName = WP_REPAIR_PLUGIN_PATH.'classes/Autoloader.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
$rpQuery = new RepairPluginPro\RP_Queries_Cache_Handler( $wpdb );
require_once WP_REPAIR_PLUGIN_PATH.'database_structure.php';
if( rp_get_option('rp_smart_cache_version', '') !== WP_REPAIR_SMART_CACHE_VERSION ) {
// clear all smart cache
rp_clear_all_smart_cache();
}
}
wp_repair_classes_autoloader();
function rp_clear_all_smart_cache() {
global $rpQuery;
// Flush Cache
rp_safe_wp_cache_flush();
// Queries Cache
$rpQuery->_clear_all_cache();
// Functions Cache
rp_get_object_cache_class()->_clear_all_cache();
// Output Cache (Front-End Steps Cache)
( RepairPluginPro\RP_Front_End_Steps_Cache::get_static_instance() )->_clear_all_cache();
// Update the smart cache version
rp_update_option( 'rp_smart_cache_version', WP_REPAIR_SMART_CACHE_VERSION );
// Update the full smart cache clear time
rp_update_option( 'rp_full_smart_cache_clear_time', time() );
}
function rp_get_total_filesize_of_cache() {
global $rpQuery;
$total_size = 0;
$total_size += $rpQuery->get_total_filesize_of_cache();
$total_size += rp_get_object_cache_class()->get_total_filesize_of_cache();
$total_size += ( RepairPluginPro\RP_Front_End_Steps_Cache::get_static_instance() )->get_total_filesize_of_cache();
return $total_size;
}
function rp_get_total_filesize_of_cache_readable( $total_size = 0 ) {
// convert it to KB, MB, GB (whatever makes sense)
if( $total_size > 1024 * 1024 * 1024 ) {
$total_size = round( $total_size / ( 1024 * 1024 * 1024 ), 2 ) . ' GB';
} elseif( $total_size > 1024 * 1024 ) {
$total_size = round( $total_size / ( 1024 * 1024 ), 2 ) . ' MB';
} elseif( $total_size > 1024 ) {
$total_size = round( $total_size / 1024, 2 ) . ' KB';
} else {
$total_size = $total_size . ' Bytes';
}
return $total_size;
}
function _rp_handle_query_affected_tables_for_frontend_cache( $affected_tables = array() ) {
if( empty( $affected_tables ) ) {
return;
}
global $rpQuery;
if( empty( $rpQuery ) ) {
return;
}
$frontend_cache = RepairPluginPro\RP_Front_End_Steps_Cache::get_static_instance();
$all_steps = $frontend_cache->get_registered_steps();
$cleared_steps = array();
foreach( $all_steps as $the_step => $listening_tables ) {
foreach( $listening_tables as $listening_table ) {
$listening_table = $rpQuery->prefix . $listening_table;
foreach( $affected_tables as $affected_table ) {
if( !in_array( $the_step, $cleared_steps ) && $affected_table == $listening_table ) {
$frontend_cache->clear_step_cache( $the_step );
$cleared_steps[] = $the_step;
}
}
}
}
}
add_action( 'rp_query_affected_tables', '_rp_handle_query_affected_tables_for_frontend_cache', 10, 1 );
function _rp_handle_changing_option_for_frontend_cache( $changing_option_name = '' ) {
if( empty( $changing_option_name ) ) {
return;
}
$frontend_cache = RepairPluginPro\RP_Front_End_Steps_Cache::get_static_instance();
$all_steps = $frontend_cache->get_registered_step_options();
$cleared_steps = array();
foreach( $all_steps as $the_step => $listening_options ) {
foreach( $listening_options as $listening_option ) {
if( !in_array( $the_step, $cleared_steps ) && strpos( $changing_option_name, $listening_option ) !== false ) {
$frontend_cache->clear_step_cache( $the_step );
$cleared_steps[] = $the_step;
}
}
}
}
add_action( 'rp_changing_option', '_rp_handle_changing_option_for_frontend_cache', 10, 1 );
function rp_get_admin_ajax_url_for_front_end() {
return admin_url( 'admin-ajax.php' );
}
function rp_get_admin_ajax_url_for_back_end() {
return admin_url( 'admin-ajax.php' );
}
function rp_show_refresh_form_success_message() {
RepairPluginPro\RP_Session_Handler::start();
$success_msg = $_SESSION['rp_refresh_form_success'] ?? '';
if( !empty( $success_msg ) ) {
unset( $_SESSION['rp_refresh_form_success'] );
}
RepairPluginPro\RP_Session_Handler::close();
if( !empty( $success_msg ) ) {
?>
<style type="text/css">
.rp_refresh_form_success {
margin-top: 15px;
margin-bottom: 0px;
background: #d4edda;
color: #155724;
border-radius: 8px;
border: 2px solid #c3e6cb;
padding: 12px;
font-size: 13px;
width: calc(100% - 60px);
line-height: 1.4em;
}
</style>
<div class="rp_refresh_form_success"><i class="fas fa-check-circle"></i> <?php echo $success_msg; ?></div>
<?php
}
}
function rp_show_validation_error_message() {
rp_show_refresh_form_success_message();
$error = RepairPluginPro\RP_Form_Inputs::get_validation_error();
if( !empty( $error ) ) {
?>
<style type="text/css">
.rp_validation_error {
margin-top: 15px;
margin-bottom: 0px;
background: #f8d7da;
color: #721c24;
border-radius: 8px;
border: 2px solid #f5c6cb;
padding: 12px;
font-size: 13px;
width: calc(100% - 60px);
line-height: 1.4em;
}
</style>
<div class="rp_validation_error"><i class="fas fa-exclamation-circle"></i> <?php echo $error; ?></div>
<?php
}
}
function rp_escape_sql( $string = '' ) {
global $rpQuery;
return $rpQuery->rp_escape_sql( $string );
}
function rpDebugPrint() {
RepairPluginPro\RP_Log_Information::init( WP_REPAIR_PLUGIN_PATH . 'rpdebug.log' );
RepairPluginPro\RP_Log_Information::debug();
}
function rpDebug( $message = '', $additional = array() ) {
RepairPluginPro\RP_Log_Information::init( WP_REPAIR_PLUGIN_PATH . 'rpdebug.log' );
RepairPluginPro\RP_Log_Information::log( $message, $additional );
}
function rp_ajax_for_public( $ajax_action = '', $callback = null ) {
RepairPluginPro\RP_Ajax_Handler::ajax_for_public( $ajax_action, $callback );
}
function rp_ajax_for_admin( $ajax_action = '', $callback = null ) {
RepairPluginPro\RP_Ajax_Handler::ajax_for_admin( $ajax_action, $callback );
}
function rp_add_quick_ajax_for_public( $action = '', $callback = '' ) {
if( isset( $_REQUEST['action'] ) && ( $_REQUEST['action'] ?? '' ) == $action ) {
try {
if( is_callable( $callback ) ) {
call_user_func( $callback );
}
} catch ( Exception|Error $e ) {
$fullErrorLine = $e->getMessage() . " on line " . $e->getLine() . " in file " . $e->getFile();
echo json_encode(array(
'status' => false,
'message' => $fullErrorLine
));
exit;
}
}
}
function rp_add_quick_ajax_for_admin( $action = '', $callback = '' ) {
if( isset( $_REQUEST['action'] ) && ( $_REQUEST['action'] ?? '' ) == $action ) {
try {
if( is_callable( $callback ) ) {
call_user_func( $callback );
}
} catch ( Exception|Error $e ) {
$fullErrorLine = $e->getMessage() . " on line " . $e->getLine() . " in file " . $e->getFile();
echo json_encode(array(
'status' => false,
'message' => $fullErrorLine
));
exit;
}
}
}
function rp_get_smart_cache_status() {
static $status = NULL;
if( $status !== NULL ) {
return $status;
}
if( rp_get_option( 'rp_smart_cache_status', '0' ) == '1' ) {
$status = true;
} else {
$status = false;
}
return $status;
}
function rp_get_object_cache_class() {
static $object_cache_class = NULL;
if( $object_cache_class !== NULL ) {
return $object_cache_class;
}
$object_cache_class = ( new RepairPluginPro\RP_Object_Output_Cache() );
return $object_cache_class;
}
function rp_get_cached_object( $object = '', $callback = null ) {
return ( new RepairPluginPro\RP_Object_Output_Cache( $object ) )->callback( $callback );
}
// sanitize the input before printing it on the page
function rp_sanitize_output( $string = '' ) {
if( empty( $string ) ) {
return $string;
}
return rp_get_cached_object( $string, function( $string ) {
$org = $string;
if( is_array( $string ) && !empty( $string ) && isset($string[0]) && is_object($string[0]) ) {
foreach ($string as $key => $value) {
foreach ($value as $k => $v) {
$string[$key]->$k = RepairPluginPro\RP_Request_Handler::strip_tags_recursive( $v );
}
}
return $string;
} else if(is_object($string)) {
foreach ($string as $key => $value) {
$string->$key = RepairPluginPro\RP_Request_Handler::strip_tags_recursive( $value );
}
return $string;
} else {
}
$string = RepairPluginPro\RP_Request_Handler::strip_tags_recursive( $string );
$exclude_keys = array('ship_device_instructions', '_email_template');
if( is_array( $org ) ) {
foreach ($org as $key => $value) {
foreach ($exclude_keys as $exclude_key) {
if( strpos($key, $exclude_key) !== false ) {
$string[$key] = RepairPluginPro\RP_Request_Handler::strip_tags_recursive( $value, 'disallowed', array('script', 'link') );
}
}
}
}
return $string;
} );
}
// function to allow only snake case
function rp_snake_case($string = '') {
/* Added in V1.4.4 */
$string = preg_replace('/\s+/', '_', trim($string));
$string = preg_replace('/[^A-Za-z0-9\_]/', '', $string);
$string = preg_replace('/\_+/', '_', $string);
return trim(strtolower($string));
}
function wp_repair_polylang_compatibility( $repair_language_setting = 'English (United States)' ) {
if(function_exists('pll_current_language') && function_exists('pll_default_language') && defined('POLYLANG_BASENAME')) {
$locale = pll_current_language('locale');
if(empty($locale)) {
$locale = pll_default_language('locale');
}
if(isset($locale) && !empty($locale)) {
if(strpos(strtolower($locale), 'nl_') !== FALSE) {
return 'Dutch (Netherlands)';
} else if(strpos(strtolower($locale), 'en_') !== FALSE) {
return 'English (United States)';
} else {
return $repair_language_setting;
}
}
}
return $repair_language_setting;
}
function rp_remove_support_email_from_front_end_trans( $arr = array() ) {
foreach( $arr as $key => $value ) {
$arr[$key] = str_replace( 'support@repairplugin.com', '[support_email]', $value );
}
if( isset( $arr['all_country_names'] ) ) {
unset( $arr['all_country_names'] );
}
return $arr;
}
function rp_initialize_pre_selected_enhanced_location() {
global $pre_selected_enhanced_location;
$pre_selected_enhanced_location = rp_get_pre_selected_enhanced_location();
}
rp_add_action('init', 'rp_initialize_pre_selected_enhanced_location', 999);
function rp_get_pre_selected_enhanced_location() {
if( rp_is_enabled_pricing_based_on_location() != TRUE ) {
return 0;
}
global $rpQuery;//pre_selected_enhanced_location
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$valid_locations = $rpQuery->get_results("SELECT * FROM $rs_company_location;");
$valid_location_ids = array();
foreach( $valid_locations as $vl_key => $valid_location ) {
$valid_location_ids[] = $valid_location->location_id;
}
$selected = 0;
$need_to_read = false;
if( function_exists('is_admin') && !is_admin() && !defined('REST_REQUEST') ) {
$need_to_read = true;
} else if( !empty($_POST['action'] ?? '') && (strpos($_POST['action'], 'rp_') === 0 || strpos($_POST['action'], 'me_post_pdf') === 0 || strpos($_POST['action'], 'get_schedules') === 0 || strpos($_POST['action'], 'get_schedules_new_dm') === 0) ) {
$need_to_read = true;
} else {
$need_to_read = false;
}
if( $need_to_read === true ) {
RepairPluginPro\RP_Session_Handler::read();
if( isset( $_SESSION ) && isset( $_SESSION['rp_pre_selected_enhanced_location'] ) && !empty( $_SESSION['rp_pre_selected_enhanced_location'] ) ) {
$selected = $_SESSION['rp_pre_selected_enhanced_location'];
}
}
return $selected;
}
function rp_get_selected_language() {
global $rpQuery;
$localization = $rpQuery->prefix . "rs_localization";
$result = $rpQuery->get_row("SELECT * FROM $localization LIMIT 1;");
if( empty( $result ) ) {
return '';
}
$selected = wp_repair_polylang_compatibility($result->set_language);
$need_to_read = false;
if( function_exists('is_admin') && !is_admin() && !defined('REST_REQUEST') ) {
$need_to_read = true;
} else if( !empty($_POST['action'] ?? '') && (strpos($_POST['action'], 'rp_') === 0 || strpos($_POST['action'], 'me_post_pdf') === 0 || strpos($_POST['action'], 'get_schedules') === 0 || strpos($_POST['action'], 'get_schedules_new_dm') === 0) ) {
$need_to_read = true;
} else {
$need_to_read = false;
}
if( $need_to_read === true ) {
RepairPluginPro\RP_Session_Handler::read();
$enabled_language_selector = rp_get_option('rp_enable_language_selector', '1') == '1' ? true : false;
$overwritten_language = false;
if( isset( $_SESSION ) && isset( $_SESSION['rp_overwritten_language'] ) && !empty( $_SESSION['rp_overwritten_language'] ) ) {
$overwritten_language = true;
}
$need_to_read = ( $enabled_language_selector == true || $overwritten_language == true ) ? true : false;
if( $need_to_read == true && isset( $_SESSION ) && isset( $_SESSION['rp_selected_language'] ) && !empty( $_SESSION['rp_selected_language'] ) ) {
$selected = $_SESSION['rp_selected_language'];
}
}
return trim($selected);
}
function rp_get_static_translations_based_on_category() {
$categories = get_all_static_translations_category();
$key_value_pair = rp_get_where_translation_is_used();
$translations = array();
foreach($categories as $category) {
$translations[$category] = array();
foreach($key_value_pair as $key => $value) {
if( $value === $category ) {
$translations[$category][] = $key;
}
}
}
return $translations;
}
function get_all_static_translations_category() {
$key_value_pair = rp_get_where_translation_is_used();
$unique_categories = array(
'Step wizard',
'Searchbar [Repair_All]',
'What Model Popup',
'iDEAL in3 Popup',
'Pre-select location',
'Step 1',
'Step 2',
'Step 3',
'Step 4',
'Offer Popup',
'Step 5',
'Step 6',
'Come By Our Store',
'Ship Device',
'Pickup Service',
'Repair on your location',
// NEWLY ADDED TRANSLATIONS - START
'Paypal',
'Stripe',
'Mollie',
'iDEAL in3',
'Pay after repair',
// NEWLY ADDED TRANSLATIONS - END
'Offer PDF',
'Offer PDF Filename',
'Emails',
'Approved Page',
'Canceled Page',
'Searchbar',
'Pricing Table',
'License issue',
'Opening Hours Indicator',
'Countries List'
);
foreach ($key_value_pair as $key => $value) {
// if value is not in array then add it
if( $value === 'Remove' || $value === 'Not used' ) {
continue;
}
if( !in_array($value, $unique_categories) ) {
$unique_categories[] = $value;
}
}
return $unique_categories;
}
function rp_get_where_translation_is_used() {
$pair = array(
'please_wait' => 'Offer Popup',
'pdf_email_sent' => 'Offer Popup',
'please_fill_all_pdf_fields' => 'Offer Popup',
'service' => 'Offer PDF',
'excluding_short_form' => 'Offer PDF',
'amount' => 'Not used',
'pdf_repair_amount' => 'Offer PDF',
'total' => 'Offer PDF',
'tax' => 'Offer PDF',
'discount' => 'Offer PDF',
'subtotal' => 'Offer PDF',
'do_not_hesitate_to_contact_us' => 'Offer PDF',
'kind_regards' => 'Offer PDF',
'dear' => 'Offer PDF',
'device_details' => 'Offer PDF',
'imei' => 'Offer PDF',
'appointment_offer_thank_you_message' => 'Offer PDF',
'appointment_offer_footer' => 'Offer PDF',
'finalize_appointment' => 'Emails',
'number' => 'Offer PDF',
'quotation' => 'Offer PDF',
'date' => 'Not used',
'select' => 'Step wizard',
'type_in_your_brand_model_or_modelcode' => 'Searchbar [Repair_All]',
'model_searchbar_placeholder_text' => 'Searchbar [Repair_All]',
'which_model_do_you_have' => 'Step wizard',
'what_model_do_i_have' => 'Step wizard',
'filter_by_series' => 'Step 3',
'reset_filter' => 'Step 3',
'all_models' => 'Step 3',
'total_models' => 'Step 3',
'review_all_page' => 'Not used',
'how_to_find_your_model_code' => 'What Model Popup',
'what_model_step_1' => 'What Model Popup',
'what_model_step_2' => 'What Model Popup',
'what_model_step_3' => 'What Model Popup',
'button_ios' => 'What Model Popup',
'what_model_ios_step_1_desc' => 'What Model Popup',
'what_model_ios_step_2_desc' => 'What Model Popup',
'what_model_ios_step_3_desc' => 'What Model Popup',
'button_android' => 'What Model Popup',
'what_model_android_step_1_desc' => 'What Model Popup',
'what_model_android_step_2_desc' => 'What Model Popup',
'what_model_android_step_3_desc' => 'What Model Popup',
'indicator_now_open_message' => 'Opening Hours Indicator',
'indicator_now_closed_message' => 'Opening Hours Indicator',
'indicator_open_before_breaktime_message' => 'Opening Hours Indicator',
'indicator_open_but_breaktime_message' => 'Opening Hours Indicator',
'indicator_opening_soon_message' => 'Opening Hours Indicator',
'indicator_closing_soon_message' => 'Opening Hours Indicator',
'indicator_special_date_open_message' => 'Opening Hours Indicator',
'indicator_special_date_close_message' => 'Opening Hours Indicator',
'indicator_closed' => 'Opening Hours Indicator',
'short_month_name_jan' => 'Opening Hours Indicator',
'short_month_name_feb' => 'Opening Hours Indicator',
'short_month_name_mar' => 'Opening Hours Indicator',
'short_month_name_apr' => 'Opening Hours Indicator',
'short_month_name_may' => 'Opening Hours Indicator',
'short_month_name_jun' => 'Opening Hours Indicator',
'short_month_name_jul' => 'Opening Hours Indicator',
'short_month_name_aug' => 'Opening Hours Indicator',
'short_month_name_sep' => 'Opening Hours Indicator',
'short_month_name_oct' => 'Opening Hours Indicator',
'short_month_name_nov' => 'Opening Hours Indicator',
'short_month_name_dec' => 'Opening Hours Indicator',
'full_month_name_january' => 'Opening Hours Indicator',
'full_month_name_february' => 'Opening Hours Indicator',
'full_month_name_march' => 'Opening Hours Indicator',
'full_month_name_april' => 'Opening Hours Indicator',
'full_month_name_may' => 'Opening Hours Indicator',
'full_month_name_june' => 'Opening Hours Indicator',
'full_month_name_july' => 'Opening Hours Indicator',
'full_month_name_august' => 'Opening Hours Indicator',
'full_month_name_september' => 'Opening Hours Indicator',
'full_month_name_october' => 'Opening Hours Indicator',
'full_month_name_november' => 'Opening Hours Indicator',
'full_month_name_december' => 'Opening Hours Indicator',
'type' => 'Not used',
'types' => 'Not used',
'brands' => 'Not used',
'brand' => 'Not used',
'or_select_your_type' => 'Step 1',
'or_select_your_brand' => 'Step 2',
'no_brands_available' => 'Step 2',
'no_models_available' => 'Step 3',
'models' => 'Not used',
'model' => 'Not used',
'repairs' => 'Step wizard',
'repair' => 'Step wizard',
'order' => 'Step wizard',
'device' => 'Step wizard',
'device_mobile' => 'Step wizard',
'thanks' => 'Not used',
'come_by_our_store' =>'Come By Our Store',
// NEWLY ADDED TRANSLATIONS -- START
'rp_paypal_label' => 'Paypal',
'rp_pay_repair_label' => 'Pay after repair',
'rp_mollie_label' => 'Mollie',
'rp_ideal_in3_label' => 'iDEAL in3',
'rp_ideal_in3_description' => 'iDEAL in3',
'rp_stripe_label' => 'Stripe',
'please_select_any_payment_method' => 'Step 5',
'payment_method_error' => 'Step 5',
'select_payment_method' => 'Step 5',
'payment_status_pending' => 'Step 6',
'payment_status_paid' => 'Step 6',
'payment_method' => 'Step 6',
'payment_status' => 'Step 6',
'processing_your_request' => 'Step wizard',
'please_wait_it_may_take_a_while' => 'Step wizard',
'prepare_for_your_upcoming_appointment' => 'Step 6',
// NEWLY ADDED TRANSLATIONS -- END
'i_accept_terms' => 'Step 5',
'please_accept_terms' => 'Step 5',
'ship_device' =>'Ship Device',
'Repair_within_24_hours' => 'Ship Device',
'ship_device_instructions' =>'Ship Device',
// NEWLY ADDED TRANSLATIONS -- START
'user_location_zipcode' => 'Step 5',
'user_location_house_number' => 'Step 5',
'user_location_street_address' => 'Step 5',
'user_location_city' => 'Step 5',
'user_location_country' => 'Step 5',
'pickup_service' => 'Pickup Service',
'let_us_pickup_your_device' => 'Pickup Service',
'pickup_service_description' => 'Pickup Service',
'repair_on_your_location' => 'Repair on your location',
'repair_on_your_location_description' => 'Repair on your location',
// NEWLY ADDED TRANSLATIONS -- END
'finalize_order' =>'Not used',
'thank_you_page' => 'Not used',
'select_device' => 'Not used',
'select_repair' => 'Not used',
'select_model' => 'Not used',
'type_model_name' => 'Step 3',
'type_brand_name' => 'Not used',
'select_type' => 'Not used',
'select_color' => 'Not used',
'select_color_new' => 'Step 4',
'select_repair_new' => 'Step 4',
'minutes' => 'Step 4',
'minutes_singular' => 'Step 4',
'minutes_plural' => 'Step 4',
'days_singular' => 'Step 4',
'days_plural' => 'Step 4',
'hours_singular' => 'Step 4',
'hours_plural' => 'Step 4',
'show_all_x_repairs' => 'Step 4',
'no_repairs_available' => 'Step 4',
'special_deals_for_you' =>'Step 4',
'this_is_what_we_will_repair_for_you' => 'Step 4',
'sub_total' => 'Step 4',
'combo_dicount' => 'Step 4',
'coupon_code' => 'Step 4',
'invalid_coupon' => 'Step 4',
'add_to' => 'Step 6',
'calendar' => 'Step 6',
'open_in_google_maps' => 'Step 6',
'coupon' => 'Step 5',
'coupon_discount' => 'Offer PDF',
'total' => 'Offer PDF',
'incl' => 'Step 4',
'excl' => 'Step 4',
'excluding' => 'Step 5',
'send_offer_pdf' => 'Step 4',
'directly_in_your_mailbox' => 'Step 4',
'finalize' => 'Step wizard',
'booking' => 'Step 5',
'you_only_pay_after_your_repair' => 'Step 4',
'receive_your_offer' => 'Offer Popup',
'by_email' => 'Offer Popup',
'please_fill_in_all_necessary_information' => 'Offer Popup',
'name' => 'Not used',
'zipcode_city' => 'Offer Popup',
'your_email_address' => 'Offer Popup',
'imei_number' => 'Offer Popup',
'send_offer' => 'Offer Popup',
'select_delivery_method' => "Step 5",
'done_while_you_are_waiting' => 'Come By Our Store',
'choose_location' => 'Not used',
'select_location' => 'Step 5',
'your_location' => 'Step 5',
'select_date' => 'Step 5',
'select_time' => 'Step 5',
'select_priority' => 'Step 5',
'select_date_and_time' => "Not used",
'private' => 'Step 5',
'business' => 'Step 5',
'your_name' => 'Step 5',
'first_name' => 'Step 5',
'last_name' => 'Step 5',
'business_name' => 'Step 5',
'your_phone_number' => 'Step 5',
'notes' => 'Step 5',
'dropdown_select' => 'Step 5',
'confirm_booking' => 'Step 5',
'you_can_cancel_anytime' => 'Step 5',
'thanks_for_purchasing_from_us!' => 'Step 6',
'you_will_receive_a_confirmation_by_email' => 'Step 6',
'please_choose_color_and_any_repair/upsale_first_before_proceeding' => 'Step 4',
'appointment' => 'Not used',
'appointment_on' => 'Step 5',
'appointment_only' => 'Step 5',
'on/op_only' => 'Step 5',
'invalid_license_code' => 'Remove',
'enter_your_license_key_here' => 'Remove',
'do_you_need_help' => 'Remove',
'if_you_dont_have_license' => 'Remove',
'license_code' => 'Remove',
'license_email' => 'Remove',
'we_will_send_updated_news_of_this_product' => 'Remove',
'shop_is_closed_for_today' => 'Step 5',
'shop_has_closed_for_today' => 'Step 5',
'appointment_booking_has_closed_for_today' => 'Step 5',
'we_are_on_a_break' => 'Step 5',
'please_check_other_times' => 'Step 5',
'this_timeslot_is_fully_booked' => 'Step 5',
'translation_of_day_mon' => 'Step 5',
'translation_of_day_tue' => 'Step 5',
'translation_of_day_wed' => 'Step 5',
'translation_of_day_thu' => 'Step 5',
'translation_of_day_fri' => 'Step 5',
'translation_of_day_sat' => 'Step 5',
'translation_of_day_sun' => 'Step 5',
'breaktime' => 'Step 5',
'weekday_monday' => 'Step 5',
'weekday_tuesday' => 'Step 5',
'weekday_wednesday' => 'Step 5',
'weekday_thursday' => 'Step 5',
'weekday_friday' => 'Step 5',
'weekday_saturday' => 'Step 5',
'weekday_sunday' => 'Step 5',
'registeration_id' => 'Offer PDF',
'customer_details' => 'Offer PDF',
'expiration_date' => 'Offer PDF',
'quotation_date' => 'Offer PDF',
'pdf_offer_filename' => 'Offer PDF Filename',
'order_summary' => 'Emails',
'cancel_booking' => 'Emails',
'fe_no_license_with_contact' => 'License issue',
'fe_no_license_no_contact' => 'License issue',
'distance_verification_please_wait_msg' => 'Step 5',
'distance_verification_not_available_msg' => 'Step 5',
'distance_verification_is_available_msg' => 'Step 5',
'please_select_appointment_time' => 'Step 5',
'please_select_priority' => 'Step 5',
'repair_sidebar_next_step' => 'Step 4',
'thank_you_at' => 'Step 5',
'thank_you_address_details' => 'Step 6',
'finalize_view_order' => 'Step 5',
'finalize_hide_order' => 'Step 5',
'please_select_any_delivery_method' => 'Step 5', // Please select any service method
'search_for_nearest_location' => 'Step 5', // Enter your address to find nearest location
'approx_radius_distance' => 'Step 5', // Approx. {distance} Radius Distance
'browser_does_not_support_geolocation' => 'Step 5', // Your browser doesn't support geolocation! Please try search instead.
'error_getting_geolocation' => 'Step 5', // Error getting location: {error}
'address_is_too_short' => 'Step 5', // Address is too short!
'live_location_btn_text' => 'Step 5', // Live Location
'nearest_location_distance_unit_km' => 'Step 5', // KM
'nearest_location_distance_unit_miles' => 'Step 5', // Miles
'today' => 'Step 5', // Today
'send_device_to' => 'Step 6',
'free_repair_text' => 'Step 4', //vrije
'price_on_request_text' => 'Step 4', // Prijs op aanvraag
'repair_starting_at' => 'Step 4', // vanaf
'no_results_found' => 'Searchbar',
'loading_data' => 'Searchbar',
'search_bar_placeholder_text' => 'Searchbar',
'cancel_appointment' => 'Canceled Page',
'are_you_sure_you_want_to_cancel' => 'Canceled Page',
'yes_cancel' => 'Canceled Page',
'approve_appointment' => 'Approved Page',
'are_you_sure_you_want_to_approve' => 'Approved Page',
'yes_approve' => 'Approved Page',
'booking_cancelled' => 'Canceled Page',
'your_appointment_has_been_cancelled' => 'Canceled Page',
'appointment_approved' => 'Approved Page',
'your_appointment_has_been_approved' => 'Approved Page',
'the_price_was_updated_on' => 'Step 4',
'combo_discount_percent_off' => 'Step 4',
'pre_select_location_heading' => 'Pre-select location',
'all_locations' => 'Pre-select location',
'total_locations' => 'Pre-select location',
'no_locations_found' => 'Pre-select location',
'combo_discount_info' => 'Step 4',
'item_name' => 'Pricing Table',
'price' => 'Pricing Table',
'uncategorised' => 'Pricing Table',
'upsales' => 'Pricing Table',
'ideal_in3_popup_heading' => 'iDEAL in3 Popup',
'ideal_in3_popup_description' => 'iDEAL in3 Popup',
'ideal_in3_popup_subtext' => 'iDEAL in3 Popup',
'ideal_in3_popup_footer_text' => 'iDEAL in3 Popup',
'ideal_in3_or' => 'Step 4'
);
$countries_key_pair = rp_get_countries_list_key_pair_for_translation_category();
foreach( $countries_key_pair as $key => $value ) {
$pair[ $key ] = $value;
}
return apply_filters('rp_get_where_translation_is_used', $pair);
}
function rp_get_static_translations_of_language($language = 'English (United States)') {
if($language == 'Dutch (Netherlands)'){
$pair = array(
'please_wait' => 'Even wachten a.u.b.',
'pdf_email_sent' => 'Email is succesvol verzonden naar je emailbox.',
'please_fill_all_pdf_fields' => 'Vul a.u.b. alle velden in.',
'service' => 'Diensten',
'excluding_short_form' => 'excl.',
'amount' => 'Aantal',
'pdf_repair_amount' => 'Bedrag',
'total' => 'Totaal',
'tax' => 'BTW',
'discount' => 'Combinatiekorting',
'subtotal' => 'Subtotaal',
'do_not_hesitate_to_contact_us' => 'We hopen u hiermee voldoende geïnformeerd te hebben. Indien u vragen heeft, neem dan alstublieft contact met ons op.',
'kind_regards' => 'Met vriendelijke groet,',
'dear' => 'Beste',
'device_details' => 'Toestelgegevens',
'imei' => 'IMEI',
'appointment_offer_thank_you_message' => 'Hierbij ontvangt u van ons de prijsopgave voor de onderstaande diensten.',
'appointment_offer_footer' => 'Deze offerte is afkomstig van onze website en is bedoeld als richtlijn. Aan de informatie in deze offerte kunnen geen rechten worden ontleend. Wij zijn niet aansprakelijk voor eventuele fouten of verkeerde informatie.',
'finalize_appointment' => 'Voltooi de afspraak',
'number' => 'Nummer',
'quotation' => 'Offerte',
'date' => 'Datum',
'select' => 'Selecteer',
'type_in_your_brand_model_or_modelcode' => 'Type in your <b>brand</b>, <b>model</b> or <b>modelcode</b> directly',
'model_searchbar_placeholder_text' => 'iPhone 12 pro max',
'which_model_do_you_have' => 'Welk <b>model</b> heb je?',
'what_model_do_i_have' => 'Welk model heb ik?',
'filter_by_series' => 'Filter op serie',
'reset_filter' => 'Filter Resetten',
'total_models' => 'Totaal',
'all_models' => 'Alle modellen',
'review_all_page' => 'bekijk alle pagina`s',
'how_to_find_your_model_code' => 'How to find your <b>model code?</b>',
'what_model_step_1' => 'Step 1',
'what_model_step_2' => 'Step 2',
'what_model_step_3' => 'Step 3',
'button_ios' => 'Apple iOS',
'what_model_ios_step_1_desc' => 'Step 1 Description for <b>Apple iOS</b>',
'what_model_ios_step_2_desc' => 'Step 2 Description for <b>Apple iOS</b>',
'what_model_ios_step_3_desc' => 'Step 3 Description for <b>Apple iOS</b>',
'button_android' => 'Android',
'what_model_android_step_1_desc' => 'Step 1 Description for <b>Android</b>',
'what_model_android_step_2_desc' => 'Step 2 Description for <b>Android</b>',
'what_model_android_step_3_desc' => 'Step 3 Description for <b>Android</b>',
'indicator_now_open_message' => 'Today is {day}, {month} {day_of_month}. We\'re open from {from} - {to}.',
'indicator_now_closed_message' => 'It\'s {day}, we\'re closed now (open again on {next_open_day} at {next_open_time}.',
'indicator_open_before_breaktime_message' => 'Today is {day}, {month} {day_of_month}. We are open until {to} with a breaktime between {to_first_half} - {from_second_half}',
'indicator_open_but_breaktime_message' => 'We are on a short break. Will be back at {from_second_half}',
'indicator_opening_soon_message' => 'It\'s {time}, we\'re opening soon in {countdown}.',
'indicator_closing_soon_message' => 'It\'s {time}. Hurry, we\'re closing in {minutes}!',
'indicator_special_date_open_message' => 'Modified hours for {specialdate_name}: from {from} to {to}.',
'indicator_special_date_close_message' => 'It\'s {specialdate_name} today, we\'re closed.',
'indicator_closed' => 'Closed',
'short_month_name_jan' => 'Jan',
'short_month_name_feb' => 'Feb',
'short_month_name_mar' => 'Mar',
'short_month_name_apr' => 'Apr',
'short_month_name_may' => 'May',
'short_month_name_jun' => 'Jun',
'short_month_name_jul' => 'Jul',
'short_month_name_aug' => 'Aug',
'short_month_name_sep' => 'Sep',
'short_month_name_oct' => 'Oct',
'short_month_name_nov' => 'Nov',
'short_month_name_dec' => 'Dec',
'full_month_name_january' => 'January',
'full_month_name_february' => 'February',
'full_month_name_march' => 'March',
'full_month_name_april' => 'April',
'full_month_name_may' => 'May',
'full_month_name_june' => 'June',
'full_month_name_july' => 'July',
'full_month_name_august' => 'August',
'full_month_name_september' => 'September',
'full_month_name_october' => 'October',
'full_month_name_november' => 'November',
'full_month_name_december' => 'December',
'type' => 'type',
'types' => 'types',
'brands' => 'merken',
'brand' => 'merk',
'or_select_your_type' => 'Or select your <b>type</b>',
'or_select_your_brand' => 'Or select your <b>brand</b>',
'no_brands_available' => 'Geen merken beschikbaar',
'no_models_available' => 'Geen modellen beschikbaar',
'models' => 'modellen',
'model' => 'model',
'repairs' => 'reparaties',
'repair' => 'reparatie',
'order' => 'afspraak',
'device' => 'apparaat',
'device_mobile' => 'apparaten',
'thanks' => 'Met dank',
'come_by_our_store' =>'Kom langs in onze winkel',
'i_accept_terms' => 'Ik accepteer de [algemene voorwaarden]',
'please_accept_terms' => 'Accepteer de algemene voorwaarden',
'ship_device' =>'Verstuur apparaat',
'ship_device_instructions' =>'$ShipDeviceAddress$',
// NEWLY ADDED TRANSLATIONS -- START
'user_location_zipcode' => 'Postcode',
'user_location_house_number' => 'Huisnummer',
'user_location_street_address' => 'Straat adres',
'user_location_city' => 'STAD',
'user_location_country' => 'Country',
'pickup_service' => 'Pickup service',
'let_us_pickup_your_device' => 'Laat ons uw toestel ophalen',
'pickup_service_description' => 'Reparatie binnen 24 uur',
'repair_on_your_location' => 'Reparatie bij u op locatie',
'repair_on_your_location_description' => 'Klaar terwijl u wacht',
// NEWLY ADDED TRANSLATIONS -- END
'finalize_order' =>'Bestelling afronden',
'thank_you_page' => 'bedankt pagina',
'select_device' => 'selecteer apparaat',
'select_repair' => 'SELECTEER REPARATIE',
'select_model' => 'Selecteer model',
'type_model_name' => 'Typ modelnaam',
'type_brand_name' => 'Typ merknaam',
'select_type' => 'Selecteer type',
'select_color' => 'SELECTEER KLEUR',
'select_color_new' => 'Select <b>Color</b>',
'select_repair_new' => 'Select <b>Repair</b>',
'minutes' => 'minuten',
'minutes_singular' => 'minuut',
'minutes_plural' => 'minuten',
'days_singular' => 'dag',
'days_plural' => 'dagen',
'hours_singular' => 'uur',
'hours_plural' => 'uren',
'show_all_x_repairs' => 'Toon alle % reparaties',
'no_repairs_available' => 'Geen reparaties beschikbaar',
'special_deals_for_you' =>'Aanbevolen accessoires',
'this_is_what_we_will_repair_for_you' => 'Reparatie lijst',
'sub_total' => 'Subtotaal',
'combo_dicount' => 'Combinatiekorting',
'coupon_code' => 'Coupon Code',
'invalid_coupon' => 'Invalid Coupon',
'add_to' => 'Add to',
'calendar' => 'Calendar',
'open_in_google_maps' => 'Open in',
'coupon' => 'Coupon',
'coupon_discount' => 'Coupon Korting',
'total' => 'Totaal',
'incl' => 'incl',
'excl' => 'excl',
'excluding' => 'Exclusief',
'send_offer_pdf' => 'Stuur Offerte in PDF',
'directly_in_your_mailbox' => 'Direct in je mailbox',
'finalize' => 'Maak',
'booking' => 'een afspraak',
'you_only_pay_after_your_repair' => 'Je betaalt pas na de reparatie',
'receive_your_offer' => 'Ontvang een offerte',
'by_email' => 'per e-mail',
'please_fill_in_all_necessary_information' => 'Vul a.u.b. alle benodigde informatie in',
'name' => 'NAAM',
'zipcode_city' => 'POSTCODE + STAD',
'your_email_address' => 'JOUW E-MAILADRES',
'imei_number' => 'IMEI NUMMER',
'notes' => 'NOTITIES',
'dropdown_select' => '-- Select --',
'send_offer' => 'STUUR OFFERTE',
'select_delivery_method' => 'SELECTEER BEZORGMETHODE',
'done_while_you_are_waiting' => 'Klaar terwijl je wacht',
// NEWLY ADDED TRANSLATIONS -- START
'rp_paypal_label' => 'Paypal',
'rp_pay_repair_label' => 'Pay after repair',
'rp_mollie_label' => 'Mollie',
'rp_ideal_in3_label' => 'In3, pay in 3 installments',
'rp_ideal_in3_description' => 'This allows you to enjoy your purchase now while paying over time without any additional costs. No hidden fees, no interest — just simple, transparent payments.',
'rp_stripe_label' => 'Stripe',
'please_select_any_payment_method' => 'Please select any payment method',
'payment_method_error' => 'Something went wrong with the payment. Please try again or choose another payment option.',
'select_payment_method' => 'Select Payment Method',
'payment_status_pending' => 'Pending',
'payment_status_paid' => 'Paid',
'payment_method' => 'Payment Method',
'payment_status' => 'Payment Status',
'processing_your_request' => 'Processing your request...',
'please_wait_it_may_take_a_while' => 'Please wait it may take a while',
'prepare_for_your_upcoming_appointment' => 'Prepare for your upcoming appointment',
// NEWLY ADDED TRANSLATIONS -- END
'choose_location' => 'KIES LOCATIE',
'select_location' => 'Select Location',
'your_location' => 'Your Location',
'select_date' => 'Select Date',
'select_time' => 'Select Time',
'select_priority' => 'Select <b>priority</b>',
'select_date_and_time' => 'SELECTEER DATUM EN TIJD',
'Repair_within_24_hours' => 'Reparatie binnen 24 uur',
'private' => 'Particulier',
'business' => 'Zakelijk',
'your_name' => 'NAAM',
'first_name' => 'FIRST NAME',
'last_name' => 'LAST NAME',
'business_name' => 'Bedrijfsnaam',
'your_phone_number' => 'TELEFOON NUMMER',
'confirm_booking' => 'Bevestig afspraak',
'you_can_cancel_anytime' => 'Je kunt op elk moment annuleren',
'thanks_for_purchasing_from_us!' => 'Bedankt voor het maken van een afspraak!',
'you_will_receive_a_confirmation_by_email' => 'Je ontvangt een bevestiging per e-mail',
'please_choose_color_and_any_repair/upsale_first_before_proceeding' => 'Kies a.u.b. een kleur voordat je verder kunt',
'appointment' => 'Afspraak op',
'appointment_on' => 'Afspraak op',
'appointment_only' => 'Afspraak',
'on/op_only' => 'op',
'invalid_license_code' => 'Licentie code is niet juist',
'enter_your_license_key_here' => 'Voer de licentie code in om het product te activeren en krijg updates en premium support',
'do_you_need_help' => 'Heb je hulp nodig? <a target="_blank" href="https://help.repairplugin.com/">Ons helpcentrum</a> bevat antwoorden op de meeste van uw vragen.',
'if_you_dont_have_license' => 'Als je geen licentie hebt of de licentie is verlopen, dan kun je er één bestellen op <a target="_blank" href="https://www.repairplugin.com/nl/prijzen/">www.repairplugin.com/nl/prijzen</a>. Als er iets mis is gegaan en de licentie code werkt niet, neem dan contact met ons op via <a href="mailto:support@repairplugin.com">support@repairplugin.com</a>',
'license_code' => 'Licentie code',
'license_email' => 'Emailadres',
'we_will_send_updated_news_of_this_product' => 'Wij sturen nieuws over dit product via dit e-mailadres, maak je geen zorgen, wij haten spam.',
'shop_is_closed_for_today' => 'Vandaag gesloten!',
'shop_has_closed_for_today' => 'De winkel is voor vandaag gesloten!',
'appointment_booking_has_closed_for_today' => 'Het boeken van een afspraak voor vandaag is gesloten!',
'we_are_on_a_break' => 'Unfortunately, we\'re on a break at this time slot.',
'please_check_other_times' => 'Sorry, u kunt op zeer korte termijn geen afspraak maken. Controleer de andere beschikbare tijden.',
'this_timeslot_is_fully_booked' => 'Dit tijdslot is volgeboekt.',
'translation_of_day_mon' => 'Ma',
'translation_of_day_tue' => 'Di',
'translation_of_day_wed' => 'Wo',
'translation_of_day_thu' => 'Do',
'translation_of_day_fri' => 'Vr',
'translation_of_day_sat' => 'Za',
'translation_of_day_sun' => 'Zo',
'breaktime' => 'Lunchpauze',
'weekday_monday' => 'Maandag',
'weekday_tuesday' => 'Dinsdag',
'weekday_wednesday' => 'Woensdag',
'weekday_thursday' => 'Donderdag',
'weekday_friday' => 'Vrijdag',
'weekday_saturday' => 'Zaterdag',
'weekday_sunday' => 'Zondag',
'registeration_id' => 'kvk',
'customer_details' => 'KLANTGEGEVENS',
'expiration_date' => 'Vervaldatum',
'quotation_date' => 'Offertedatum',
'pdf_offer_filename' => 'Offerte',
'order_summary' => 'Order overzicht',
'cancel_booking' => 'Annuleer afspraak',
'fe_no_license_with_contact' => 'Ons afsprakensysteem is tijdelijk niet beschikbaar. Neem contact met ons op: $contact$',
'fe_no_license_no_contact' => 'Ons afsprakensysteem is tijdelijk niet beschikbaar.',
'distance_verification_please_wait_msg' => 'Please wait while we verify if we can provide this service to your address..',
'distance_verification_not_available_msg' => 'Unfortunately, we cannot provide this service to your address. [service_method] is only available within [max_distance] radius.',
'distance_verification_is_available_msg' => 'Great! We can provide this service to your address.',
'please_select_appointment_time' => 'Selecteer Afspraaktijd',
'please_select_priority' => 'Please select priority',
'repair_sidebar_next_step' => 'Volgende stap',
'thank_you_at' => 'om',
'thank_you_address_details' => 'Adresgegevens',
'finalize_view_order' => 'bestelling bekijken',
'finalize_hide_order' => 'bestelling verbergen',
'please_select_any_delivery_method' => 'Please select any service method', // Please select any service method
'search_for_nearest_location' => 'Enter your address to find nearest location', // Enter your address to find nearest location
'approx_radius_distance' => 'Approx. {distance} Radius Distance', // Approx. {distance} Radius Distance
'browser_does_not_support_geolocation' => 'Your browser doesn\'t support geolocation! Please try search instead.', // Your browser doesn't support geolocation! Please try search instead.
'error_getting_geolocation' => 'Error getting location: {error}', // Error getting location: {error}
'address_is_too_short' => 'Address is too short!', // Address is too short!
'live_location_btn_text' => 'Live Location', // Live Location
'nearest_location_distance_unit_km' => 'km', // KM
'nearest_location_distance_unit_miles' => 'miles', // Miles
'today' => 'Vandaag', // Today
'send_device_to' => 'Verstuur apparaat naar:',
'free_repair_text' => 'GRATIS', //vrije
'price_on_request_text' => 'Prijs op aanvraag', // Prijs op aanvraag
'repair_starting_at' => 'vanaf', // vanaf
'no_results_found' => 'Geen resultaten gevonden.',
'loading_data' => 'Loading Data..',
'search_bar_placeholder_text' => 'Zoek je merk, model of modelcode',
'cancel_appointment' => 'Cancel Appointment',
'are_you_sure_you_want_to_cancel' => 'Are you sure you want to cancel this appointment?',
'yes_cancel' => 'Yes, Cancel',
'approve_appointment' => 'Approve Appointment',
'are_you_sure_you_want_to_approve' => 'Are you sure you want to approve this appointment?',
'yes_approve' => 'Yes, Approve',
'booking_cancelled' => 'Boeking geannuleerd', // Boeking geannuleerd
'appointment_approved' => 'Appointment Approved',
'your_appointment_has_been_approved' => 'Your appointment [appointment_number] has been approved.',
'your_appointment_has_been_cancelled' => 'Uw afspraak is geannuleerd.', // Uw afspraak is geannuleerd
'the_price_was_updated_on' => 'De prijs is bijgewerkt op [date]',
'combo_discount_percent_off' => 'OFF',
'pre_select_location_heading' => 'Welke <b>locatie</b> heeft uw voorkeur?',
'all_locations' => 'Alle locaties',
'total_locations' => 'Totaal',
'no_locations_found' => 'Geen locaties gevonden',
'combo_discount_info' => 'Add an extra repair and receive <b>[combo_discount] discount</b>.',
'item_name' => 'Item Name',
'price' => 'Price',
'uncategorised' => 'Uncategorised',
'upsales' => 'Upsales',
'ideal_in3_popup_heading' => 'Pay in 3 installments via in3',
'ideal_in3_popup_description' => 'This allows you to enjoy your purchase now while paying over time without any additional costs. No hidden fees, no interest — just simple, transparent payments.',
'ideal_in3_popup_subtext' => 'Pay in 3 installments',
'ideal_in3_popup_footer_text' => 'Handled instantly via iDEAL. Done in 1 minute.',
'ideal_in3_or' => 'of'
);
} else {
$pair = array(
'please_wait' => 'Please wait',
'pdf_email_sent' => 'Email sent successfully, please check your mailbox.',
'please_fill_all_pdf_fields' => 'Please fill all fields',
'service' => 'Service',
'excluding_short_form' => 'excl.',
'amount' => 'Amount',
'pdf_repair_amount' => 'Amount',
'total' => 'Total',
'tax' => 'Tax',
'discount' => 'Discount',
'subtotal' => 'Subtotal',
'do_not_hesitate_to_contact_us' => 'If you have any questions, please do not hesitate to contact us.',
'kind_regards' => 'Kind regards,',
'dear' => 'Dear',
'device_details' => 'Device details',
'imei' => 'IMEI',
'appointment_offer_thank_you_message' => 'Thank you for your interest in our services. We hereby make you the following offer:',
'appointment_offer_footer' => 'This quotation was generated from our website and is intended as a guideline. No rights can be derived from the information in this quotation. We are not liable for any errors or misinformation.',
'finalize_appointment' => 'Finalize Appointment',
'number' => 'Number',
'quotation' => 'Quotation',
'date' => 'Date',
'select' => 'Select',
'type_in_your_brand_model_or_modelcode' => 'Type in your <b>brand</b>, <b>model</b> or <b>modelcode</b> directly',
'model_searchbar_placeholder_text' => 'iPhone 12 pro max',
'which_model_do_you_have' => 'Which <b>model</b> do you have?',
'what_model_do_i_have' => 'What model do I have?',
'filter_by_series' => 'Filter by series',
'reset_filter' => 'Reset Filter',
'total_models' => 'Total',
'all_models' => 'All models',
'review_all_page' => 'review all pages',
'how_to_find_your_model_code' => 'How to find your <b>model code?</b>',
'what_model_step_1' => 'Step 1',
'what_model_step_2' => 'Step 2',
'what_model_step_3' => 'Step 3',
'button_ios' => 'Apple iOS',
'what_model_ios_step_1_desc' => 'Step 1 Description for <b>Apple iOS</b>',
'what_model_ios_step_2_desc' => 'Step 2 Description for <b>Apple iOS</b>',
'what_model_ios_step_3_desc' => 'Step 3 Description for <b>Apple iOS</b>',
'button_android' => 'Android',
'what_model_android_step_1_desc' => 'Step 1 Description for <b>Android</b>',
'what_model_android_step_2_desc' => 'Step 2 Description for <b>Android</b>',
'what_model_android_step_3_desc' => 'Step 3 Description for <b>Android</b>',
'indicator_now_open_message' => 'Today is {day}, {month} {day_of_month}. We\'re open from {from} - {to}.',
'indicator_now_closed_message' => 'It\'s {day}, we\'re closed now (open again on {next_open_day} at {next_open_time}.',
'indicator_open_before_breaktime_message' => 'Today is {day}, {month} {day_of_month}. We are open until {to} with a breaktime between {to_first_half} - {from_second_half}',
'indicator_open_but_breaktime_message' => 'We are on a short break. Will be back at {from_second_half}',
'indicator_opening_soon_message' => 'It\'s {time}, we\'re opening soon in {countdown}.',
'indicator_closing_soon_message' => 'It\'s {time}. Hurry, we\'re closing in {minutes}!',
'indicator_special_date_open_message' => 'Modified hours for {specialdate_name}: from {from} to {to}.',
'indicator_special_date_close_message' => 'It\'s {specialdate_name} today, we\'re closed.',
'indicator_closed' => 'Closed',
'short_month_name_jan' => 'Jan',
'short_month_name_feb' => 'Feb',
'short_month_name_mar' => 'Mar',
'short_month_name_apr' => 'Apr',
'short_month_name_may' => 'May',
'short_month_name_jun' => 'Jun',
'short_month_name_jul' => 'Jul',
'short_month_name_aug' => 'Aug',
'short_month_name_sep' => 'Sep',
'short_month_name_oct' => 'Oct',
'short_month_name_nov' => 'Nov',
'short_month_name_dec' => 'Dec',
'full_month_name_january' => 'January',
'full_month_name_february' => 'February',
'full_month_name_march' => 'March',
'full_month_name_april' => 'April',
'full_month_name_may' => 'May',
'full_month_name_june' => 'June',
'full_month_name_july' => 'July',
'full_month_name_august' => 'August',
'full_month_name_september' => 'September',
'full_month_name_october' => 'October',
'full_month_name_november' => 'November',
'full_month_name_december' => 'December',
'type' => 'type',
'types' => 'types',
'brands' => 'brands',
'brand' => 'Brand',
'or_select_your_type' => 'Or select your <b>type</b>',
'or_select_your_brand' => 'Or select your <b>brand</b>',
'no_brands_available' => 'No Brands Available',
'no_models_available' => 'No Models Available',
'models' => 'models',
'model' => 'model',
'repairs' => 'repairs',
'repair' => 'repair',
'order' => 'order',
'device' => 'device',
'device_mobile' => 'devices',
'thanks' => 'thanks',
'come_by_our_store' =>'Come by our store',
'i_accept_terms' => 'I accept the [terms & conditions]',
'please_accept_terms' => 'Please accept terms & conditions',
'ship_device' =>'Ship device',
'ship_device_instructions' =>'$ShipDeviceAddress$',
// NEWLY ADDED TRANSLATIONS -- START
'user_location_zipcode' => 'Zipcode',
'user_location_house_number' => 'House number',
'user_location_street_address' => 'Street address',
'user_location_city' => 'City',
'user_location_country' => 'Country',
'pickup_service' => 'Pickup service',
'let_us_pickup_your_device' => 'Let us pickup your device',
'pickup_service_description' => 'Repair within 24 hours',
'repair_on_your_location' => 'Repair on your location',
'repair_on_your_location_description' => 'Done while you are waiting',
// NEWLY ADDED TRANSLATIONS -- END
'finalize_order' =>'Finalize order',
'thank_you_page' => 'Thank you page',
'select_device' => 'select device',
'select_repair' => 'SELECT REPAIR',
'select_model' => 'Select model',
'type_model_name' => 'Type model name',
'type_brand_name' => 'Type brand name',
'select_type' => 'select type',
'select_color' => 'SELECT COLOR',
'select_color_new' => 'Select <b>Color</b>',
'select_repair_new' => 'Select <b>Repair</b>',
'minutes' => 'minutes',
'minutes_singular' => 'minute',
'minutes_plural' => 'minutes',
'days_singular' => 'day',
'days_plural' => 'days',
'hours_singular' => 'hour',
'hours_plural' => 'hours',
'show_all_x_repairs' => 'Show all % repairs',
'no_repairs_available' => 'No repairs available',
'special_deals_for_you' =>'Recommended accessories',
'this_is_what_we_will_repair_for_you' => 'Repair List',
'sub_total' => 'sub-total',
'combo_dicount' => 'Combo-discount',
'coupon_code' => 'Coupon Code',
'invalid_coupon' => 'Invalid Coupon',
'add_to' => 'Add to',
'calendar' => 'Calendar',
'open_in_google_maps' => 'Open in',
'coupon' => 'Coupon',
'coupon_discount' => 'Coupon Discount',
'total' => 'Total',
'incl' => 'incl',
'excl' => 'excl',
'excluding' => 'Excluding',
'send_offer_pdf' => 'Send Quote PDF',
'directly_in_your_mailbox' => 'Directly in your mailbox',
'finalize' => 'Finalize',
'booking' => 'booking',
'you_only_pay_after_your_repair' => 'You only pay after your repair',
'receive_your_offer' => 'Receive your quote',
'by_email' => 'by email',
'please_fill_in_all_necessary_information' => 'Please fill in all necessary information',
'name' => 'NAME',
'zipcode_city' => 'ZIPCODE + CITY',
'your_email_address' => 'EMAIL',
'imei_number' => 'IMEI NUMBER',
'notes' => 'NOTES',
'dropdown_select' => '-- Select --',
'send_offer' => 'SEND QUOTE',
'select_delivery_method' => "SELECT SERVICE METHOD",
'done_while_you_are_waiting' => 'Done while you are waiting',
// NEWLY ADDED TRANSLATIONS -- START
'rp_paypal_label' => 'Paypal',
'rp_pay_repair_label' => 'Pay after repair',
'rp_mollie_label' => 'Mollie',
'rp_ideal_in3_label' => 'In3, pay in 3 installments',
'rp_ideal_in3_description' => 'This allows you to enjoy your purchase now while paying over time without any additional costs. No hidden fees, no interest — just simple, transparent payments.',
'rp_stripe_label' => 'Stripe',
'please_select_any_payment_method' => 'Please select any payment method',
'payment_method_error' => 'Something went wrong with the payment. Please try again or choose another payment option.',
'select_payment_method' => 'Select Payment Method',
'payment_status_pending' => 'Pending',
'payment_status_paid' => 'Paid',
'payment_method' => 'Payment Method',
'payment_status' => 'Payment Status',
'processing_your_request' => 'Processing your request...',
'please_wait_it_may_take_a_while' => 'Please wait it may take a while',
'prepare_for_your_upcoming_appointment' => 'Prepare for your upcoming appointment',
// NEWLY ADDED TRANSLATIONS -- END
'choose_location' => 'CHOOSE LOCATION',
'select_location' => 'Select Location',
'your_location' => 'Your Location',
'select_date' => 'Select Date',
'select_time' => 'Select Time',
'select_priority' => 'Select <b>priority</b>',
'select_date_and_time' => "SELECT DATE AND TIME",
'Repair_within_24_hours' => 'Repair within 24 hours',
'private' => 'Private',
'business' => 'Business',
'your_name' => 'NAME',
'first_name' => 'FIRST NAME',
'last_name' => 'LAST NAME',
'business_name' => 'Bussiness Name',
'your_phone_number' => 'PHONE',
'confirm_booking' => 'Confirm booking',
'you_can_cancel_anytime' => 'You can cancel anytime',
'thanks_for_purchasing_from_us!' => 'Thank you for purchasing from us!',
'you_will_receive_a_confirmation_by_email' => 'You will receive a confirmation by e-mail',
'please_choose_color_and_any_repair/upsale_first_before_proceeding' => 'Please choose color and any repair/upsale first before proceeding.',
'appointment' => 'Appointment',
'appointment_on' => 'Appointment on',
'appointment_only' => 'Appointment',
'on/op_only' => 'on',
'invalid_license_code' => 'Invalid license code',
'enter_your_license_key_here' => 'Enter your license key here to activate the product, and get complete feature updates and premium support.',
'do_you_need_help' => 'Do you need any help? <a target="_blank" href="https://help.repairplugin.com/">Our help center</a> contains answers to most of your questions.',
'if_you_dont_have_license' => 'If you don\'t have a license or your license is expired, you can get one on <a target="_blank" href="https://www.repairplugin.com/">repairplugin.com</a>. If there is something wrong, feel free to contact us at <a href="mailto:support@repairplugin.com">support@repairplugin.com</a>',
'license_code' => 'License code',
'license_email' => 'Email Address',
'we_will_send_updated_news_of_this_product' => 'We will send updated news of this product by this email address, don\'t worry, we hate spam.',
'shop_is_closed_for_today' => 'Shop is closed for today!',
'shop_has_closed_for_today' => 'Shop has closed for today!',
'appointment_booking_has_closed_for_today' => 'Appointment booking has closed for today!',
'we_are_on_a_break' => 'Unfortunately, we\'re on a break at this time slot.',
'please_check_other_times' => 'Sorry, you can\'t book an appointment on very short notice. Please check other available times.',
'this_timeslot_is_fully_booked' => 'This timeslot is fully booked.',
'translation_of_day_mon' => 'Mon',
'translation_of_day_tue' => 'Tue',
'translation_of_day_wed' => 'Wed',
'translation_of_day_thu' => 'Thu',
'translation_of_day_fri' => 'Fri',
'translation_of_day_sat' => 'Sat',
'translation_of_day_sun' => 'Sun',
'breaktime' => 'Breaktime',
'weekday_monday' => 'Monday',
'weekday_tuesday' => 'Tuesday',
'weekday_wednesday' => 'Wednesday',
'weekday_thursday' => 'Thursday',
'weekday_friday' => 'Friday',
'weekday_saturday' => 'Saturday',
'weekday_sunday' => 'Sunday',
'registeration_id' => 'ID',
'customer_details' => 'CUSTOMER DETAILS',
'expiration_date' => 'Expiration Date',
'quotation_date' => 'Quotation Date',
'pdf_offer_filename' => 'Quotation',
'order_summary' => 'Order Summary',
'cancel_booking' => 'Cancel Booking',
'fe_no_license_with_contact' => 'Our appointment system is temporarily unavailable. Please contact us on: $contact$',
'fe_no_license_no_contact' => 'Our appointment system is temporarily unavailable.',
'distance_verification_please_wait_msg' => 'Please wait while we verify if we can provide this service to your address..',
'distance_verification_not_available_msg' => 'Unfortunately, we cannot provide this service to your address. [service_method] is only available within [max_distance] radius.',
'distance_verification_is_available_msg' => 'Great! We can provide this service to your address.',
'please_select_appointment_time' => 'Please select appointment time',
'please_select_priority' => 'Please select priority',
'repair_sidebar_next_step' => 'Next step',
'thank_you_at' => 'at',
'thank_you_address_details' => 'Address Details',
'finalize_view_order' => 'view order',
'finalize_hide_order' => 'hide order',
'please_select_any_delivery_method' => 'Please select any service method', // Please select any service method
'search_for_nearest_location' => 'Enter your address to find nearest location', // Enter your address to find nearest location
'approx_radius_distance' => 'Approx. {distance} Radius Distance', // Approx. {distance} Radius Distance
'browser_does_not_support_geolocation' => 'Your browser doesn\'t support geolocation! Please try search instead.',
'error_getting_geolocation' => 'Error getting location: {error}', // Error getting location: {error}
'address_is_too_short' => 'Address is too short!', // Address is too short!
'live_location_btn_text' => 'Live Location', // Live Location
'nearest_location_distance_unit_km' => 'km', // KM
'nearest_location_distance_unit_miles' => 'miles', // Miles
'today' => 'Today', // Today
'send_device_to' => 'Send device to:',
'free_repair_text' => 'FREE', //vrije
'price_on_request_text' => 'Price on request', // Prijs op aanvraag
'repair_starting_at' => 'starting at', // vanaf
'no_results_found' => 'No results found.',
'loading_data' => 'Loading Data..',
'search_bar_placeholder_text' => 'Please enter your brand, model or modelcode',
'cancel_appointment' => 'Cancel Appointment',
'are_you_sure_you_want_to_cancel' => 'Are you sure you want to cancel this appointment?',
'yes_cancel' => 'Yes, Cancel',
'approve_appointment' => 'Approve Appointment',
'are_you_sure_you_want_to_approve' => 'Are you sure you want to approve this appointment?',
'yes_approve' => 'Yes, Approve',
'booking_cancelled' => 'Booking cancelled', // Boeking geannuleerd
'appointment_approved' => 'Appointment Approved',
'your_appointment_has_been_approved' => 'Your appointment [appointment_number] has been approved.',
'your_appointment_has_been_cancelled' => 'Your appointment has been canceled.', // Uw afspraak is geannuleerd
'the_price_was_updated_on' => 'The price was updated on [date]',
'combo_discount_percent_off' => 'OFF',
'pre_select_location_heading' => 'Which <b>location</b> do you prefer?',
'all_locations' => 'All locations',
'total_locations' => 'Total',
'no_locations_found' => 'No locations found',
'combo_discount_info' => 'Add an extra repair and receive <b>[combo_discount] discount</b>.',
'item_name' => 'Item Name',
'price' => 'Price',
'uncategorised' => 'Uncategorised',
'upsales' => 'Upsales',
'ideal_in3_popup_heading' => 'Pay in 3 installments via in3',
'ideal_in3_popup_description' => 'This allows you to enjoy your purchase now while paying over time without any additional costs. No hidden fees, no interest — just simple, transparent payments.',
'ideal_in3_popup_subtext' => 'Pay in 3 installments',
'ideal_in3_popup_footer_text' => 'Handled instantly via iDEAL. Done in 1 minute.',
'ideal_in3_or' => 'or'
);
}
$countries_key_pair = rp_get_countries_list_key_pair_for_translation();
foreach( $countries_key_pair as $key => $value ) {
$pair[ $key ] = $value;
}
return apply_filters('rp_returning_static_translations_pair', $pair, $language);
}
function rp_get_dynamic_translations_of_language( $language = '' ) {
global $rpQuery;
$table_rs_languages = $rpQuery->prefix . 'rs_languages';
$table_rs_translations = $rpQuery->prefix . 'rs_translations';
$static_translations = rp_get_static_translations_of_language( $language );
// check if language exists in database
$language_exists = $rpQuery->get_row( "SELECT * FROM `$table_rs_languages` WHERE `name` = '".rp_escape_sql($language)."';" );
if ( !empty($language_exists) ) {
$dynamic_translations = $rpQuery->get_results( "SELECT * FROM `$table_rs_translations` WHERE `language` = '".rp_escape_sql($language)."';" );
if( !empty( $dynamic_translations ) ) {
foreach($dynamic_translations as $row) {
if( isset( $static_translations[$row->key] ) ) {
$static_translations[$row->key] = $row->value;
}
}
}
}
return $static_translations;
}
function rp_is_valid_language_name( $set_language = '' ) {
$all_languages = rp_get_all_languages();
if( !empty( $all_languages ) ) {
$all_languages_names = array();
foreach($all_languages as $language) {
$all_languages_names[] = trim($language->name);
}
if( !in_array($set_language, $all_languages_names) ) {
return FALSE;
}
return TRUE;
}
return FALSE;
}
function rp_reset_plugin_language() {
global $wp_repair_selected_language;
global $wp_repair_lang;
global $wp_repair_selected_language_org;
global $wp_repair_lang_org;
if( isset( $wp_repair_selected_language_org ) && !empty( $wp_repair_selected_language_org ) ) {
$wp_repair_selected_language = $wp_repair_selected_language_org;
$wp_repair_selected_language_org = null;
}
if( isset( $wp_repair_lang_org ) && !empty( $wp_repair_lang_org ) ) {
$wp_repair_lang = $wp_repair_lang_org;
$wp_repair_lang_org = null;
}
}
function rp_set_new_plugin_language( $language_name = '' ) {
global $wp_repair_selected_language;
global $wp_repair_lang;
global $wp_repair_selected_language_org;
global $wp_repair_lang_org;
$wp_repair_selected_language_org = $wp_repair_selected_language;
$wp_repair_lang_org = $wp_repair_lang;
if( rp_is_valid_language_name( $language_name ) === TRUE ) {
$wp_repair_selected_language = $language_name;
$wp_repair_lang = rp_get_dynamic_translations_of_language($language_name);
}
}
function set_plugin_language(){
global $wp_repair_lang;
global $wp_repair_selected_language;
$all_languages = rp_get_all_languages();
$set_language = rp_get_selected_language();
if( !empty( $all_languages ) ) {
$all_languages_names = array();
foreach($all_languages as $language) {
$all_languages_names[] = trim($language->name);
}
if( !in_array($set_language, $all_languages_names) ) {
$set_language = rp_get_default_language();
}
} else {
$set_language = 'English (United States)';
}
$wp_repair_selected_language = $set_language;
$wp_repair_lang = rp_get_dynamic_translations_of_language($set_language);
}
rp_add_action('init', 'set_plugin_language', 999);
function rp_wp_enqueue_style( $id = '', $src = '', $deps = array(), $ver = false, $media = 'all' ) {
// Some code here!
if( function_exists('is_admin') && is_admin() ) {
rp_add_action('admin_head', function() use ($id, $src) {
echo '<link rel="stylesheet" id="'.$id.'" href="'.$src.'">';
}, 9999);
} else {
wp_enqueue_style( $id, $src, $deps, $ver, $media );
}
}
function loadTheRequiredWPRepairScript() {
rp_wp_enqueue_style('jquery-ui-css', 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css');
wp_enqueue_script('jquery-ui-js', 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js', array('jquery'));
if(isset($_GET['page'])) {
rp_wp_enqueue_style('font-awesome-css', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');
switch ($_GET['page']) {
case 'wp_repair_appointments':
rp_wp_enqueue_style('wp-repair-plugin-appointments-css', WP_REPAIR_PLUGIN_URL.'assets/css/appointments.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'wp_repair_customers':
rp_wp_enqueue_style('wp-repair-plugin-customers-css', WP_REPAIR_PLUGIN_URL.'assets/css/customers.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'wp_repair_analytics':
rp_wp_enqueue_style('wp-repair-plugin-analytics-css', WP_REPAIR_PLUGIN_URL.'assets/css/analytics.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'wp_repair_manage_categories':
rp_wp_enqueue_style('wp-repair-plugin-categories-css', WP_REPAIR_PLUGIN_URL.'assets/css/categories.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'wp_repair_manage_models':
rp_wp_enqueue_style('wp-repair-plugin-repairs-css', WP_REPAIR_PLUGIN_URL.'assets/css/repairs.css?what='.WP_REPAIR_ASSETS_CACHE_V);
rp_wp_enqueue_style('wp-repair-plugin-models-css', WP_REPAIR_PLUGIN_URL.'assets/css/models.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'wp_repair_default_repairs':
rp_wp_enqueue_style('wp-repair-plugin-drepairs-css', WP_REPAIR_PLUGIN_URL.'assets/css/drepairs.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'rp-setup-wizard':
rp_wp_enqueue_style('rp-wizard-style', WP_REPAIR_PLUGIN_URL.'assets/css/wizard.css?what='.WP_REPAIR_ASSETS_CACHE_V);
wp_enqueue_script('rp-wizard-script', WP_REPAIR_PLUGIN_URL.'assets/js/wizard.js?what='.WP_REPAIR_ASSETS_CACHE_V, ['jquery'], null, true);
wp_enqueue_script('confetti-script', 'https://cdn.jsdelivr.net/npm/canvas-confetti@1.4.0/dist/confetti.browser.min.js', [], null, true);
break;
case 'wp_repair_download_libraries':
rp_wp_enqueue_style('wp-repair-plugin-libraries-css', WP_REPAIR_PLUGIN_URL.'assets/css/download_libraries.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'wp_repair_manage_upsales':
rp_wp_enqueue_style('wp-repair-plugin-upsales-css', WP_REPAIR_PLUGIN_URL.'assets/css/upsales.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'wp_repair_settings':
rp_wp_enqueue_style('wp-repair-plugin-settings-css', WP_REPAIR_PLUGIN_URL.'assets/css/settings.css?what='.WP_REPAIR_ASSETS_CACHE_V);
if(isset($_GET['section'])) {
switch ($_GET['section']) {
case 'localization':
rp_wp_enqueue_style('wp-repair-plugin-settings-localization-css', WP_REPAIR_PLUGIN_URL.'assets/css/localization.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'styling':
rp_wp_enqueue_style('wp-repair-plugin-settings-localization-css', WP_REPAIR_PLUGIN_URL.'assets/css/fe_styling.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'planning_discount':
rp_wp_enqueue_style('wp-repair-plugin-settings-planning_discount-css', WP_REPAIR_PLUGIN_URL.'assets/css/planning_discount.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'coupons':
rp_wp_enqueue_style('wp-repair-plugin-settings-coupons-css', WP_REPAIR_PLUGIN_URL.'assets/css/coupons.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'special_opening_times':
rp_wp_enqueue_style('wp-repair-plugin-settings-coupons-css', WP_REPAIR_PLUGIN_URL.'assets/css/coupons.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'notification_offer':
rp_wp_enqueue_style('wp-repair-plugin-settings-notification_offer-css', WP_REPAIR_PLUGIN_URL.'assets/css/notification_offer.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
case 'manage_permission':
rp_wp_enqueue_style('wp-repair-plugin-settings-manage_permission-css', WP_REPAIR_PLUGIN_URL.'assets/css/manage_permission.css?what='.WP_REPAIR_ASSETS_CACHE_V);
break;
default:
break;
}
}
break;
default:
break;
}
}
}
rp_add_action('wp_enqueue_scripts', 'loadTheRequiredWPRepairScript');
rp_add_action('admin_enqueue_scripts', 'loadTheRequiredWPRepairScript');
function wp_repair_admin_setup_tour_nav_html() {
$requirements = array(
'rp_setup_guide_meet_download_libraries_requirement',
'rp_setup_guide_meet_default_repairs_requirement',
'rp_setup_guide_meet_manage_upsales_requirement',
'rp_setup_guide_meet_configure_settings_requirement'
);
if(rp_get_option('rp_skip_quick_start_wizard', FALSE) === FALSE) {
$needToShow = FALSE;
foreach ($requirements as $callback) {
if(call_user_func($callback) === FALSE) {
$needToShow = TRUE;
}
}
if($needToShow === TRUE) {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/setup_tour_nav.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
}
}
function wp_repair_admin_appointments_page_html() {
rp_print_execution_time_json_code();
rp_show_validation_error_message();
wp_repair_admin_setup_tour_nav_html();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/appointments.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
rp_end_page_render_time();
}
function wp_repair_admin_customers_page_html() {
rp_print_execution_time_json_code();
rp_show_validation_error_message();
wp_repair_admin_setup_tour_nav_html();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/customers.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
rp_end_page_render_time();
}
function wp_repair_admin_analytics_page_html() {
rp_print_execution_time_json_code();
rp_show_validation_error_message();
wp_repair_admin_setup_tour_nav_html();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/analytics_html.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
rp_end_page_render_time();
}
function rp_handle_customers_csv_export() {
if( ($_REQUEST['page'] ?? '') == 'wp_repair_customers' && ($_REQUEST['export_csv'] ?? '') == '1' ) {
$_POST['rp_csrf_token'] = $_REQUEST['rp_csrf_token'] ?? '';
if( !rp_verify_csrf_token('customers') ) {
rp_redirect_refresh_form_with_error('customers', 'Invalid CSRF Token', 'admin.php?page=wp_repair_customers');
exit;
}
$has_permission = rp_current_user_has_full_access_cached() || rp_is_current_user_location_head();
if( $has_permission === false ) {
rp_redirect_refresh_form_with_error('customers', 'You do not have permission to export customers', 'admin.php?page=wp_repair_customers');
exit;
}
require_once WP_REPAIR_PLUGIN_PATH . 'html/customers_reusable.php';
$csv_content = rp_create_customer_export_csv_content( $all_orders );
$filename = 'customers-' . date('Y-m-d_H-i-s') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=' . $filename);
echo $csv_content;
exit;
}
}
add_action('init', 'rp_handle_customers_csv_export', 9999);
function rp_handle_appointments_csv_export() {
if( ($_REQUEST['page'] ?? '') == 'wp_repair_appointments' && ($_REQUEST['export_csv'] ?? '') == '1' ) {
$_POST['rp_csrf_token'] = $_REQUEST['rp_csrf_token'] ?? '';
if( !rp_verify_csrf_token('appointments') ) {
rp_redirect_refresh_form_with_error('appointments', 'Invalid CSRF Token', 'admin.php?page=wp_repair_appointments');
exit;
}
$has_permission = rp_current_user_has_full_access_cached() || rp_is_current_user_location_head();
if( $has_permission === false ) {
rp_redirect_refresh_form_with_error('appointments', 'You do not have permission to export appointments', 'admin.php?page=wp_repair_appointments');
exit;
}
require_once WP_REPAIR_PLUGIN_PATH . 'html/appointments_reusable.php';
$csv_content = rp_create_appointments_export_csv_content( $all_orders );
$filename = 'appointments-' . date('Y-m-d_H-i-s') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=' . $filename);
echo $csv_content;
exit;
}
}
add_action('init', 'rp_handle_appointments_csv_export', 9999);
function wp_repair_admin_manage_categories_page_html() {
rp_print_execution_time_json_code();
rp_show_validation_error_message();
wp_repair_admin_setup_tour_nav_html();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/manage_categories.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
rp_end_page_render_time();
}
function wp_repair_admin_manage_models_page_html() {
rp_print_execution_time_json_code();
rp_show_validation_error_message();
wp_repair_admin_setup_tour_nav_html();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/manage_models.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
rp_end_page_render_time();
}
function wp_repair_get_rs_category_by_name( $name = '' ) {
global $rpQuery;
$rs_category = $rpQuery->prefix . 'rs_category';
$category_name = $name;
return $rpQuery->get_results("SELECT * FROM $rs_category WHERE `c_name` LIKE '".rp_escape_sql($category_name)."'");
}
function wp_repair_verify_selected_default_repairs_category() {
if( !empty( $_GET['repairs_category'] ?? '' ) ) {
$repairs_category = trim(str_replace('-', ' ', $_GET['repairs_category']));
return !empty( wp_repair_get_rs_category_by_name( $repairs_category ) );
}
return FALSE;
}
function wp_repair_admin_default_repairs_page_html() {
rp_print_execution_time_json_code();
rp_show_validation_error_message();
if( empty( $_GET['repairs_category'] ?? '' ) || !wp_repair_verify_selected_default_repairs_category() ) {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/default_repairs_select_category.php';
} else {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/default_repairs.php';
}
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
rp_end_page_render_time();
}
function wp_repair_admin_download_libraries_page_html() {
rp_print_execution_time_json_code();
rp_show_validation_error_message();
$page = 'download_languages';
if( isset($_REQUEST['section']) && $_REQUEST['section'] === 'download_libraries' ) {
$page = 'download_libraries';
}
if( isset($_REQUEST['section']) && $_REQUEST['section'] === 'repairs' ) {
$page = 'download_repairs';
}
$fileName = WP_REPAIR_PLUGIN_PATH.'html/'.$page.'.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
rp_end_page_render_time();
}
function wp_repair_admin_general_info_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/general_info.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_styling_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/styling.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_special_opening_times_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/special_opening_times.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_localization_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/localization.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_planning_discount_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/planning_discount.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_notification_offer_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/notification_offer.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_manage_permission_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/manage_permission.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_coupons_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/coupons.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_configure_mail_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/configure_mail.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_plugin_shortcode_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/plugin_shortcode.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_reset_all_data_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/reset_all_data.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_caching_performance_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/caching_performance.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_email_smtp_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/email_smtp.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_webhooks_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/webhooks.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_opening_hours_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/opening_hours.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_display_opening_hours_page_html() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/display_opening_hours.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function wp_repair_admin_backups_page_html( $whichPage = '' ) {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/'.$whichPage.'.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function _rp_print_execution_time_json_code() {
if( rp_get_option('rp_repairplugin_inspect', '0') != '1' || !current_user_can('activate_plugins') ) {
return;
}
$request_details = _rp_get_request_details_for_debug();
$data = json_encode(
array(
$request_details
)
);
?>
<style type="text/css" style="display:none">
#rp-tracking-console,
#rp-tracking-console div,
#rp-tracking-console span,
#rp-tracking-console p,
#rp-tracking-console table {
font-family: "Segoe UI", "Arial", sans-serif;
}
#rp-tracking-console table {
border: 0px;
border-collapse: collapse;
}
#rp-tracking-console table th,
#rp-tracking-console table td {
line-height: 1.5em;
}
#rp-tracking-console b,
#rp-tracking-console strong {
font-weight: 600;
}
#rp-tracking-console {
font-size: 13px;
}
#rp-tracking-console pre {
display: block;
font-family: monospace;
unicode-bidi: isolate;
white-space: pre;
margin: 0px;
background: none !important;
padding: 0px 8px;
line-height: 1.4em;
}
#rp-tracking-console.rp-closed-console {
width: 160px;
left: calc(50% - 100px);
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
#rp-tracking-console.rp-closed-console .full-screen-icon {
display: none;
}
#rp-tracking-console .rp-console-heading {
background: #efefef;
font-weight: 500;
display: flex;
align-items: center;
}
#rp-tracking-console .full-screen-icon {
width: 16px;
display: inline-block;
height: 16px;
padding: 6px;
background: #ddd;
border-radius: 2px;
margin-right: 8px;
box-sizing: content-box;
}
#rp-tracking-console .full-screen-icon svg {
width: 16px;
height: 16px;
fill: #3c434a;
}
#rp-tracking-console .full-screen-icon svg.expand {
display: block;
}
#rp-tracking-console .full-screen-icon svg.minimize {
display: none;
}
#rp-tracking-console.full-screen .full-screen-icon svg.expand {
display: none;
}
#rp-tracking-console.full-screen .full-screen-icon svg.minimize {
display: block;
}
#rp-tracking-console.rp-closed-console .rp-console-heading {
background: #fff;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
text-align: center;
}
#rp-tracking-console:hover .rp-console-heading,
#rp-tracking-console.rp-closed-console:hover .rp-console-heading {
background: #efefef;
}
#rp-tracking-console {
width: 100%;
position: fixed;
bottom: 0px;
left: 0;
z-index: 100000;
background: #fff;
display: block;
box-shadow: 0px 0px 9px -3px rgba(0, 0, 0, 0.3);
overflow: hidden;
}
#rp-tracking-console .rp-row {
width: 100%;
margin: 0px;
}
#rp-tracking-console .rp-console-heading {
padding: 8px 16px;
cursor: pointer;
}
.console-content-row {
display: flex;
}
#rp-tracking-console.rp-closed-console .console-content-row {
display: none;
}
#rp-tracking-console .rp-col-md-3 {
width: 25%;
border-right: 1px solid #efefef;
height: 50vh;
max-height: 50vh;
min-height: 50vh;
overflow-y: auto;
}
#rp-tracking-console .rp-col-md-9 {
width: 75%;
position: relative;
}
#rp-tracking-console .rp-col-md-9 .rp-debug-console-request-overview,
#rp-tracking-console .rp-col-md-9 .rp-debug-console-request-payload,
#rp-tracking-console .rp-col-md-9 .rp-debug-console-request-queries {
width: 100%;
height: calc(50vh - 30px);
max-height: calc(50vh - 30px);
min-height: calc(50vh - 30px);
overflow-y: auto;
box-sizing: border-box;
}
#rp-tracking-console span.highlight-backtrace,
#rp-tracking-console span.sql-query-backtrace {
display: block;
background: #efefef;
border-radius: 5px;
padding: 5px 10px;
font-weight: 400;
}
#rp-tracking-console span.sql-query-single {
padding: 5px 10px;
display: block;
}
#rp-tracking-console.full-screen .rp-col-md-3 {
height: 85vh;
max-height: 85vh;
min-height: 85vh;
}
#rp-tracking-console.full-screen .rp-col-md-9 .rp-debug-console-request-overview,
#rp-tracking-console.full-screen .rp-col-md-9 .rp-debug-console-request-payload,
#rp-tracking-console.full-screen .rp-col-md-9 .rp-debug-console-request-queries {
height: calc(85vh - 30px);
max-height: calc(85vh - 30px);
min-height: calc(85vh - 30px);
}
#rp-tracking-console .rp-col-md-9 .rp-debug-console-request-payload {
padding: 16px;
}
.rp-debug-console-request-uri {
padding: 6px 8px;
border-bottom: 1px solid #ddd;
white-space: normal;
word-break: break-all;
cursor: pointer;
line-height: 1.4em;
}
.rp-debug-console-request-uri.is_last_request {
opacity: 0.5;
}
.rp-debug-console-request-uri.selected {
background: #d3e3f2;
}
.rp-debug-console-request-header-button {
background: #efefef !important;
color: #404040 !important;
border: 1px solid #ddd !important;
padding: 5px !important;
padding-bottom: 7px !important;
cursor: pointer !important;
box-sizing: border-box !important;
font-size: 13px !important;
line-height: 1.4em !important;
}
.rp-debug-console-request-header-button.selected {
background: #fff !important;
border-top: 0px !important;
border-bottom: 0px !important;
box-shadow: 0px -2px 0px 0px inset #1275c2 !important;
}
.rp-debug-console-request-overview,
.rp-debug-console-request-payload,
.rp-debug-console-request-queries {
padding: 10px;
}
.rp-debug-console-request-overview table,
.rp-debug-console-request-payload table,
.rp-debug-console-request-queries table {
width: 100%;
}
.rp-debug-console-request-overview table th,
.rp-debug-console-request-payload table th,
.rp-debug-console-request-queries table th,
.rp-debug-console-request-overview table td,
.rp-debug-console-request-payload table td,
.rp-debug-console-request-queries table td {
text-align: left;
padding: 7px;
border:0px;
border-bottom: 1px solid #ddd;
word-break: break-word;
}
.rp-debug-console-request-overview table tr > td:nth-child(1) {
width: 35%;
}
.rp-debug-console-request-overview table tr > td:nth-child(2) {
width: 65%;
}
.rp-debug-console-request-queries table tr > th:nth-child(1) {
width: 80%;
}
.rp-debug-console-request-queries table tr > th:nth-child(2) {
width: 20%;
}
</style>
<div id="rp-tracking-console" class="rp-closed-console">
<div class="rp-row">
<div class="rp-col-md-12 rp-console-heading">
<span class="full-screen-icon"><svg class="expand" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--!Font Awesome Free 6.6.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M448 344v112a23.9 23.9 0 0 1 -24 24H312c-21.4 0-32.1-25.9-17-41l36.2-36.2L224 295.6 116.8 402.9 153 439c15.1 15.1 4.4 41-17 41H24a23.9 23.9 0 0 1 -24-24V344c0-21.4 25.9-32.1 41-17l36.2 36.2L184.5 256 77.2 148.7 41 185c-15.1 15.1-41 4.4-41-17V56a23.9 23.9 0 0 1 24-24h112c21.4 0 32.1 25.9 17 41l-36.2 36.2L224 216.4l107.2-107.3L295 73c-15.1-15.1-4.4-41 17-41h112a23.9 23.9 0 0 1 24 24v112c0 21.4-25.9 32.1-41 17l-36.2-36.2L263.5 256l107.3 107.3L407 327.1c15.1-15.2 41-4.5 41 16.9z"/></svg><svg class="minimize" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.6.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M200 288H88c-21.4 0-32.1 25.8-17 41l32.9 31-99.2 99.3c-6.2 6.2-6.2 16.4 0 22.6l25.4 25.4c6.2 6.2 16.4 6.2 22.6 0L152 408l31.1 33c15.1 15.1 40.9 4.4 40.9-17V312c0-13.3-10.7-24-24-24zm112-64h112c21.4 0 32.1-25.9 17-41l-33-31 99.3-99.3c6.2-6.2 6.2-16.4 0-22.6L481.9 4.7c-6.2-6.2-16.4-6.2-22.6 0L360 104l-31.1-33C313.8 55.9 288 66.6 288 88v112c0 13.3 10.7 24 24 24zm96 136l33-31.1c15.1-15.1 4.4-40.9-17-40.9H312c-13.3 0-24 10.7-24 24v112c0 21.4 25.9 32.1 41 17l31-32.9 99.3 99.3c6.2 6.2 16.4 6.2 22.6 0l25.4-25.4c6.2-6.2 6.2-16.4 0-22.6L408 360zM183 71.1L152 104 52.7 4.7c-6.2-6.2-16.4-6.2-22.6 0L4.7 30.1c-6.2 6.2-6.2 16.4 0 22.6L104 152l-33 31.1C55.9 198.2 66.6 224 88 224h112c13.3 0 24-10.7 24-24V88c0-21.3-25.9-32-41-16.9z"/></svg></span>RepairPlugin Inspect
</div>
</div>
<div class="rp-row console-content-row">
</div>
</div>
<script type="text/javascript">
function rp_debug_console_generate_unique_id() {
return 'id_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
window.rp_execution_time_object = <?php echo $data; ?>;
if( 'repairPluginUI' in window ) {
let lastResponse = repairPluginUI.getFromLocalStorage('rp_last_execution_time_object');
if( lastResponse !== null ) {
lastResponse.is_last_request = true;
// add as first element
window.rp_execution_time_object.unshift(lastResponse);
}
}
jQuery("#rp-tracking-console .rp-console-heading").on('click', function(e) {
// if clicked on full-screen icon, then toggle full-screen
if( jQuery(e.target).is('.full-screen-icon') || jQuery(e.target).is('.full-screen-icon *') ) {
jQuery(this).closest('#rp-tracking-console').toggleClass('full-screen');
} else {
jQuery(this).closest('#rp-tracking-console').toggleClass('rp-closed-console');
}
});
window.all_rp_execution_time_requests = {};
window.all_rp_execution_time_request_details = {};
window._rp_debug_console_renderCol1 = function() {
rp_debug_console_renderCol1();
}
function remove_first_item_from_all_rp_execution_time_request_details() {
// first of all check if all queries combined are more than 100
let totalQueries = 0;
let maxQueries = 10000;
for (const [key, value] of Object.entries(window.all_rp_execution_time_request_details)) {
totalQueries += ( value.queries.length + value.cached_queries_file.length + value.cached_queries_memory.length );
}
if( totalQueries > maxQueries ) {
// simply remove first item from all_rp_execution_time_request_details and all_rp_execution_time_requests
let firstKey = Object.keys(window.all_rp_execution_time_request_details)[0];
// also remove targeted item
jQuery('#rp-tracking-console .rp-debug-console-request-uri[data-udid="'+firstKey+'"]').remove();
// if no active item, click on first item
if( jQuery('#rp-tracking-console .rp-debug-console-request-uri.selected').length === 0 ) {
jQuery('#rp-tracking-console .rp-debug-console-request-uri').first().click();
}
delete window.all_rp_execution_time_request_details[firstKey];
delete window.all_rp_execution_time_requests[firstKey];
}
}
function rp_debug_console_renderCol1() {
let onlyNewlyAdded = [];
window.rp_execution_time_object.forEach(function(row){
let udid = rp_debug_console_generate_unique_id();
window.all_rp_execution_time_requests[udid] = row;
window.all_rp_execution_time_request_details[udid] = row;
onlyNewlyAdded.push(udid);
});
window.rp_execution_time_object = [];
let rp_debug_console = jQuery("#rp-tracking-console .console-content-row");
if( jQuery("#rp-tracking-console .console-content-row > .rp-col-md-3").length > 0 ) {
// append only newly added requests
onlyNewlyAdded.forEach(function(udid) {
let pageOrAction = all_rp_execution_time_request_details[udid].action;
if( pageOrAction == '' ) {
pageOrAction = all_rp_execution_time_request_details[udid].page;
}
if( pageOrAction != '' ) {
pageOrAction = '<strong>'+pageOrAction+'</strong>';
}
let $item = jQuery('<div class="rp-debug-console-request-uri" data-udid="'+udid+'">'+pageOrAction+'</div>');
let requestUriActual = jQuery('<div class="request-uri-actual"></div>').text(window.all_rp_execution_time_requests[udid].request_uri);
$item.append(requestUriActual);
jQuery("#rp-tracking-console .console-content-row > .rp-col-md-3").append($item);
});
} else {
// print all request uris in col-md-3
let $col1 = jQuery('<div class="rp-col-md-3"></div>');
let isFirst = true;
for (const [key, value] of Object.entries(window.all_rp_execution_time_requests)) {
let pageOrAction = all_rp_execution_time_request_details[key].action;
if( pageOrAction == '' ) {
pageOrAction = all_rp_execution_time_request_details[key].page;
}
if( pageOrAction != '' ) {
pageOrAction = '<strong>'+pageOrAction+'</strong>';
}
let is_last_request = ( 'is_last_request' in value ) ? 'is_last_request ' : '';
let selected = '';
if( isFirst === true && is_last_request === '' ) {
selected = 'selected';
isFirst = false;
}
let $item = jQuery('<div class="rp-debug-console-request-uri '+is_last_request+selected+'" data-udid="'+key+'">'+pageOrAction+'</div>');
let requestUriActual = jQuery('<div class="request-uri-actual"></div>').text(value.request_uri);
$item.append(requestUriActual);
$col1.append($item);
}
rp_debug_console.append($col1);
}
remove_first_item_from_all_rp_execution_time_request_details();
}
rp_debug_console_renderCol1();
function rp_debug_console_renderCol2( whichTab = 'overview' ) {
jQuery("#rp-tracking-console .console-content-row > .rp-col-md-9").remove();
if( jQuery('#rp-tracking-console .rp-debug-console-request-uri.selected').length === 0 ) {
return;
}
let rp_debug_console = jQuery("#rp-tracking-console .console-content-row");
let udid = jQuery('#rp-tracking-console .rp-debug-console-request-uri.selected').data('udid');
let selectedRequestDetails = window.all_rp_execution_time_request_details[udid];
// print request details of first request in col-md-9
// We need following sub-columns: Overview, Payload, Queries
let $col2 = jQuery('<div class="rp-col-md-9"></div>');
// add header
let $header = jQuery('<div class="rp-debug-console-request-header"></div>');
let overviewSelected = '';
if( whichTab === 'overview' ) {
overviewSelected = 'selected';
}
let payloadSelected = '';
if( whichTab === 'payload' ) {
payloadSelected = 'selected';
}
let responseSelected = '';
if( whichTab === 'org_response' ) {
responseSelected = 'selected';
}
let queriesSelected = '';
if( whichTab === 'queries' ) {
queriesSelected = 'selected';
}
let duplicatedQueriesSelected = '';
if( whichTab === 'duplicate_queries' ) {
duplicatedQueriesSelected = 'selected';
}
let cachedQueriesFileSelected = '';
if( whichTab === 'cached_queries_file' ) {
cachedQueriesFileSelected = 'selected';
}
let cachedQueriesMemorySelected = '';
if( whichTab === 'cached_queries_memory' ) {
cachedQueriesMemorySelected = 'selected';
}
let ranActions = '';
if( whichTab === 'ran_actions' ) {
ranActions = 'selected';
}
// add buttons (Overview, Payload, Queries)
let $overview_button = jQuery('<button class="rp-debug-console-request-header-button '+overviewSelected+'" data-tab="overview" data-udid="'+udid+'">Overview</button>');
let $payload_button = jQuery('<button class="rp-debug-console-request-header-button '+payloadSelected+'" data-tab="payload" data-udid="'+udid+'">Payload</button>');
let $response_button = jQuery('<button class="rp-debug-console-request-header-button '+responseSelected+'" data-tab="org_response" data-udid="'+udid+'">Response</button>');
let $queries_button = jQuery('<button class="rp-debug-console-request-header-button '+queriesSelected+'" data-tab="queries" data-udid="'+udid+'">Database Queries</button>');
let $duplicate_queries_button = jQuery('<button class="rp-debug-console-request-header-button '+duplicatedQueriesSelected+'" data-tab="duplicate_queries" data-udid="'+udid+'">Duplicate Queries</button>');
let $file_queries_button = jQuery('<button class="rp-debug-console-request-header-button '+cachedQueriesFileSelected+'" data-tab="cached_queries_file" data-udid="'+udid+'">Cached Queries (File)</button>');
let $memory_queries_button = jQuery('<button class="rp-debug-console-request-header-button '+cachedQueriesMemorySelected+'" data-tab="cached_queries_memory" data-udid="'+udid+'">Cached Queries (Memory)</button>');
let $ran_actions_button = jQuery('<button class="rp-debug-console-request-header-button '+ranActions+'" data-tab="ran_actions" data-udid="'+udid+'">Action Hooks</button>');
$header.append($overview_button);
$header.append($payload_button);
if( 'org_response' in selectedRequestDetails && selectedRequestDetails.org_response != null ) {
$header.append($response_button);
}
$header.append($queries_button);
$header.append($duplicate_queries_button);
if( 'cached_queries_file' in selectedRequestDetails && selectedRequestDetails.cached_queries_file != null ) {
$header.append($file_queries_button);
}
if( 'cached_queries_memory' in selectedRequestDetails && selectedRequestDetails.cached_queries_memory != null ) {
$header.append($memory_queries_button);
}
$header.append($ran_actions_button);
$col2.append($header);
if( whichTab === 'overview' ) {
// add sub-columns first and keep Overview as selected
let $overview = jQuery('<div class="rp-debug-console-request-overview selected"></div>');
let $overview_table = jQuery('<table></table>');
let $overview_table_body = jQuery('<tbody></tbody>');
let itemsToPrint = {
'request_details': 'Request Details',
'request_uri': 'Request URI',
'page': 'Page',
'action': 'Action',
'rp_optimised_request_status': 'Optimized Request Status',
'request_method': 'Request Method',
'queries_heading': 'Database Queries',
'total_queries': 'Total',
'duplicate_queries_count': 'Duplicate',
'rp_execution_time': 'RepairPlugin Execution Time (s)',
'rp_loading': 'Initial Load',
'page_render_time': 'Actual Time of Rendering Requested Page / Processing Requested Action -- Excluding All Unrelated Code Ran by RepairPlugin While Loading',
'total_queries_execution_time': 'Database Queries',
'total_file_queries_execution_time': 'Cached Queries(File)',
'total_memory_queries_execution_time': 'Cached Queries(Memory)',
'total_actions_execution_time': 'Hooks Execution Time',
'hooks_execution_time': 'WP Hooks Execution Time (s) (All Themes/Plugins)',
'plugins_loaded_hook': 'plugins_loaded',
'init_hook': 'init',
'admin_init_hook': 'admin_init',
'wp_total_execution_time': 'WP Request Execution Time (s) (All Themes/Plugins)',
'all_time_after_rp_reached': 'Tracking Starts After Request Reach RepairPlugin',
'wp_environment': 'WordPress Environment',
'wp_version': 'WP Version',
'active_plugins': 'WP Active Plugins',
'wp_debug_mode': 'WP Debug Mode',
'timezone': 'WP Timezone',
'current_date': 'WP Current Date',
'current_time': 'WP Current Time',
'server_environment': 'Server Environment',
'server_software': 'Server Info',
'php_version': 'PHP Version',
'memory_usage': 'PHP Memory Usage',
'max_upload_size': 'PHP Max Upload Size',
'post_max_size': 'PHP Post Max Size',
'max_execution_time': 'PHP Max Execution Time',
'max_input_vars': 'PHP Max Input Vars'
};
for( var itemToPrint in itemsToPrint ) {
let valueOfItem = itemsToPrint[ itemToPrint ];
$overview_table_row = jQuery('<tr></tr>');
if( itemToPrint == 'server_environment' || itemToPrint == 'queries_heading' || itemToPrint == 'wp_environment' || itemToPrint == 'request_details' || itemToPrint == 'hooks_execution_time' || itemToPrint == 'rp_execution_time' || itemToPrint == 'wp_total_execution_time' ) {
$overview_table_row_key = jQuery('<td colspan="2"></td>').html('<b>----- '+valueOfItem+' -----</b>');
$overview_table_row_value = null;
} else {
$overview_table_row_key = jQuery('<td></td>').text(valueOfItem);
$overview_table_row_value = jQuery('<td></td>').text(selectedRequestDetails[itemToPrint]);
}
$overview_table_row.append($overview_table_row_key);
if( $overview_table_row_value ) {
$overview_table_row.append($overview_table_row_value);
}
$overview_table_body.append($overview_table_row);
}
$overview_table.append($overview_table_body);
$overview.append($overview_table);
$col2.append($overview);
}
if( whichTab === 'queries' ) {
// add sub-columns first and keep Overview as selected
let $queries = jQuery('<div class="rp-debug-console-request-queries selected"></div>');
let $queries_table = jQuery('<table></table>');
let $queries_table_body = jQuery('<tbody></tbody>');
// add request uri
let $queries_table_row = jQuery('<tr></tr>');
let $queries_table_row_key = jQuery('<th></th>').text('Query');
let $queries_table_row_key2 = jQuery('<th></th>').text('Execution Time (s)');
$queries_table_row.append($queries_table_row_key);
$queries_table_row.append($queries_table_row_key2);
$queries_table_body.append($queries_table_row);
// end
selectedRequestDetails.queries.forEach(function(query) {
$queries_table_row = jQuery('<tr></tr>');
$query_sql_html = jQuery('<span class="sql-query-single"></span>').text(query.sql);
$query_backtrace_html = jQuery('<span class="sql-query-backtrace"></span>').text(query.backtrace.replace('#1', 'in file'));
$queries_table_row_key = jQuery('<td></td>').append($query_sql_html).append($query_backtrace_html);
$queries_table_row_key2 = jQuery('<td></td>').text(query.execution_time);
$queries_table_row.append($queries_table_row_key);
$queries_table_row.append($queries_table_row_key2);
$queries_table_body.append($queries_table_row);
});
$queries_table.append($queries_table_body);
$queries.append($queries_table);
$col2.append($queries);
}
if( whichTab === 'duplicate_queries' ) {
// add sub-columns first and keep Overview as selected
let $queries = jQuery('<div class="rp-debug-console-request-queries selected"></div>');
let $queries_table = jQuery('<table></table>');
let $queries_table_body = jQuery('<tbody></tbody>');
// add request uri
let $queries_table_row = jQuery('<tr></tr>');
let $queries_table_row_key = jQuery('<th></th>').text('Query');
let $queries_table_row_key2 = jQuery('<th></th>').text('Execution Time (s)');
$queries_table_row.append($queries_table_row_key);
$queries_table_row.append($queries_table_row_key2);
$queries_table_body.append($queries_table_row);
// end
selectedRequestDetails.duplicate_queries.forEach(function(query) {
$queries_table_row = jQuery('<tr></tr>');
$queries_table_row_key = jQuery('<td></td>').text('('+query.count+') '+ query.sql);
$queries_table_row_key2 = jQuery('<td></td>').text(query.execution_time);
$queries_table_row.append($queries_table_row_key);
$queries_table_row.append($queries_table_row_key2);
$queries_table_body.append($queries_table_row);
});
$queries_table.append($queries_table_body);
$queries.append($queries_table);
$col2.append($queries);
}
if( whichTab === 'cached_queries_file' ) {
// add sub-columns first and keep Overview as selected
let $queries = jQuery('<div class="rp-debug-console-request-queries selected"></div>');
let $queries_table = jQuery('<table></table>');
let $queries_table_body = jQuery('<tbody></tbody>');
// add request uri
let $queries_table_row = jQuery('<tr></tr>');
let $queries_table_row_key = jQuery('<th></th>').text('Query');
let $queries_table_row_key2 = jQuery('<th></th>').text('Execution Time (s)');
$queries_table_row.append($queries_table_row_key);
$queries_table_row.append($queries_table_row_key2);
$queries_table_body.append($queries_table_row);
// end
selectedRequestDetails.cached_queries_file.forEach(function(query) {
$queries_table_row = jQuery('<tr></tr>');
$query_sql_html = jQuery('<span class="sql-query-single"></span>').text(query.sql);
$query_backtrace_html = jQuery('<span class="sql-query-backtrace"></span>').text(query.backtrace.replace('#1', 'in file'));
$queries_table_row_key = jQuery('<td></td>').append($query_sql_html).append($query_backtrace_html);
$queries_table_row_key2 = jQuery('<td></td>').text(query.execution_time);
$queries_table_row.append($queries_table_row_key);
$queries_table_row.append($queries_table_row_key2);
$queries_table_body.append($queries_table_row);
});
$queries_table.append($queries_table_body);
$queries.append($queries_table);
$col2.append($queries);
}
if( whichTab === 'cached_queries_memory' ) {
// add sub-columns first and keep Overview as selected
let $queries = jQuery('<div class="rp-debug-console-request-queries selected"></div>');
let $queries_table = jQuery('<table></table>');
let $queries_table_body = jQuery('<tbody></tbody>');
// add request uri
let $queries_table_row = jQuery('<tr></tr>');
let $queries_table_row_key = jQuery('<th></th>').text('Query');
let $queries_table_row_key2 = jQuery('<th></th>').text('Execution Time (s)');
$queries_table_row.append($queries_table_row_key);
$queries_table_row.append($queries_table_row_key2);
$queries_table_body.append($queries_table_row);
// end
selectedRequestDetails.cached_queries_memory.forEach(function(query) {
$queries_table_row = jQuery('<tr></tr>');
$query_sql_html = jQuery('<span class="sql-query-single"></span>').text(query.sql);
$query_backtrace_html = jQuery('<span class="sql-query-backtrace"></span>').text(query.backtrace.replace('#1', 'in file'));
$queries_table_row_key = jQuery('<td></td>').append($query_sql_html).append($query_backtrace_html);
$queries_table_row_key2 = jQuery('<td></td>').text(query.execution_time);
$queries_table_row.append($queries_table_row_key);
$queries_table_row.append($queries_table_row_key2);
$queries_table_body.append($queries_table_row);
});
$queries_table.append($queries_table_body);
$queries.append($queries_table);
$col2.append($queries);
}
if( whichTab === 'ran_actions' ) {
// add sub-columns first and keep Overview as selected
let $queries = jQuery('<div class="rp-debug-console-request-queries selected"></div>');
let $queries_table = jQuery('<table></table>');
let $queries_table_body = jQuery('<tbody></tbody>');
// add request uri
let $queries_table_row = jQuery('<tr></tr>');
let $queries_table_row_key = jQuery('<th></th>').text('Action');
let $queries_table_row_key2 = jQuery('<th></th>').text('Execution Time (s)');
$queries_table_row.append($queries_table_row_key);
$queries_table_row.append($queries_table_row_key2);
$queries_table_body.append($queries_table_row);
// end
selectedRequestDetails.rp_actions_ran_time_prepared.forEach(function(query) {
$queries_table_row = jQuery('<tr></tr>');
if( !query.backtrace ) {
query.backtrace = {};
}
if( !query.backtrace.file || query.backtrace.file == '' ) {
query.backtrace.file = 'N/A';
}
if( !query.backtrace.line || query.backtrace.line == '' ) {
query.backtrace.line = 'N/A';
}
$query_sql_html = jQuery('<span class="sql-query-single"></span>').text(query.callback);
$query_backtrace_html = jQuery('<span class="sql-query-backtrace"></span>').text('in file '+query.backtrace.file + ' on line '+query.backtrace.line);
$queries_table_row_key = jQuery('<td></td>').append($query_sql_html).append($query_backtrace_html);
$queries_table_row_key2 = jQuery('<td></td>').text(query.execution_time);
$queries_table_row.append($queries_table_row_key);
$queries_table_row.append($queries_table_row_key2);
$queries_table_body.append($queries_table_row);
});
$queries_table.append($queries_table_body);
$queries.append($queries_table);
$col2.append($queries);
}
if( whichTab === 'payload' ) {
// add sub-columns first and keep Overview as selected
let $payload = jQuery('<div class="rp-debug-console-request-payload selected"></div>');
let $payload_div = jQuery('<pre></pre>');
// simply print json encoded payload
$payload_div.text(JSON.stringify(selectedRequestDetails.payload, null, 2));
$payload.append($payload_div);
$col2.append($payload);
}
if( whichTab === 'org_response' && 'org_response' in selectedRequestDetails && selectedRequestDetails.org_response != null ) {
// add sub-columns first and keep Overview as selected
let $responseTab = jQuery('<div class="rp-debug-console-request-payload selected"></div>');
let $responseTab_div = jQuery('<pre></pre>');
// simply print json encoded org_response
$responseTab_div.text(JSON.stringify(selectedRequestDetails.org_response, null, 2));
$responseTab.append($responseTab_div);
$col2.append($responseTab);
}
rp_debug_console.append($col2);
}
rp_debug_console_renderCol2( 'overview' );
jQuery(document).on('click', '.rp-debug-console-request-header-button', function() {
let whichTab = jQuery(this).data('tab');
rp_debug_console_renderCol2( whichTab );
});
jQuery(document).on('click', '.rp-debug-console-request-uri', function() {
jQuery('#rp-tracking-console .rp-debug-console-request-uri').removeClass('selected');
let selectedTab = jQuery('.rp-debug-console-request-header-button.selected').data('tab');
if( selectedTab == '' ) {
selectedTab = 'overview';
}
jQuery(this).addClass('selected');
rp_debug_console_renderCol2( selectedTab );
});
</script>
<?php
}
function rp_start_tracking_ajax_request() {
rp_start_tracking_page_render_time();
}
function _rp_get_request_details_for_debug() {
// comebackfaster
_rp_set_default_tiemzone();
global $rpQuery;
global $wp_version;
global $rp_start_time_before_rp_loading_hook;
global $rp_start_time_after_rp_loading_hook;
global $rp_start_time_before_plugins_loaded_hook;
global $rp_start_time_after_plugins_loaded_hook;
global $rp_start_time_before_init_hook;
global $rp_start_time_after_init_hook;
global $rp_start_time_before_admin_init_hook;
global $rp_start_time_after_admin_init_hook;
global $rp_actions_ran_time;
global $rp_unmodified_request_data;
$payload = $rp_unmodified_request_data ?? array();
$request_uri = $_SERVER['REQUEST_URI'] ?? '';
$page = isset($_GET['page']) ? $_GET['page'] : '';
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
$request_method = $_SERVER['REQUEST_METHOD'] ?? '';
$all_queries = $rpQuery->getSortedQueriesByExcetionTime();
$cached_queries_file = $rpQuery->getSortedFileQueriesByExcetionTime();
$cached_queries_memory = $rpQuery->getSortedMemoryQueriesByExcetionTime();
$duplicate_queries = $rpQuery->getDuplicatedQueries();
try {
$timezone_string = wp_timezone_string();
} catch( Exception|Error $e ) {
$timezone_string = 'N/A';
}
$current_date = date('Y-m-d');
$currentTime = strtoupper(str_replace(':', ' : ', date('h:i a')));
if( !isset( $wp_version ) || empty( $wp_version ) ) {
$wp_version = 'N/A';
} else {
$wp_version = 'v' . $wp_version;
}
$php_version = 'N/A';
try {
if( function_exists('phpversion') ) {
$php_version = phpversion();
}
} catch( Exception|Error $e ) {
}
$total_memory = 'N/A';
try {
$memory_limit = @ini_get('memory_limit');
if( !isset( $memory_limit ) || empty( $memory_limit ) ) {
} else {
$memory_limit = trim( $memory_limit );
$last = strtolower( $memory_limit[ strlen( $memory_limit ) - 1 ] );
switch( $last ) {
case 'g':
$memory_limit = (int) $memory_limit * 1024;
break;
case 'm':
$memory_limit = (int) $memory_limit;
break;
case 'k':
$memory_limit = (int) $memory_limit / 1024;
break;
}
$total_memory = $memory_limit;
}
} catch( Exception|Error $e ) {
$total_memory = 'N/A';
}
if( $total_memory == 'N/A' || $total_memory < 1 ) {
$total_memory = 'N/A';
}
$used_memory = 'N/A';
try {
if( function_exists('memory_get_usage') ) {
$memory_usage = memory_get_usage( true );
$used_memory = round( $memory_usage / 1024 / 1024, 2 );
}
} catch( Exception|Error $e ) {
$used_memory = 'N/A';
}
if( $used_memory == 'N/A' || $used_memory < 1 ) {
$used_memory = 'N/A';
}
if( $total_memory == 'N/A' || $used_memory == 'N/A' ) {
$memory_usage_msg = 'N/A';
} else {
$memory_usage_msg = $used_memory . ' MB / ' . $total_memory . ' MB';
}
$max_upload_size = 'N/A';
try {
$max_upload = (int)( @ini_get( 'upload_max_filesize' ) );
$max_post = (int)( @ini_get( 'post_max_size' ) );
$memory_limit = (int)( @ini_get( 'memory_limit' ) );
$max_upload_size = min( $max_upload, $max_post, $memory_limit );
if( $max_upload_size < 1 ) {
$max_upload_size = 'N/A';
} else {
$max_upload_size = $max_upload_size . ' MB';
}
} catch( Exception|Error $e ) {
$max_upload_size = 'N/A';
}
$max_input_vars = 'N/A';
try {
$max_input_vars = @ini_get( 'max_input_vars' );
if( !isset( $max_input_vars ) || empty( $max_input_vars ) || $max_input_vars < 1 ) {
$max_input_vars = 'N/A';
}
} catch( Exception|Error $e ) {
$max_input_vars = 'N/A';
}
$post_max_size = 'N/A';
try {
$post_max_size = @ini_get( 'post_max_size' );
if( !isset( $post_max_size ) || empty( $post_max_size ) ) {
$post_max_size = 'N/A';
} else {
$post_max_size = trim( $post_max_size );
$last = strtolower( $post_max_size[ strlen( $post_max_size ) - 1 ] );
switch( $last ) {
case 'g':
$post_max_size = (int) $post_max_size * 1024;
break;
case 'm':
$post_max_size = (int) $post_max_size;
break;
case 'k':
$post_max_size = (int) $post_max_size / 1024;
break;
}
if( $post_max_size == 'N/A' || $post_max_size < 1 ) {
$post_max_size = 'N/A';
} else {
$post_max_size = $post_max_size . ' MB';
}
}
} catch( Exception|Error $e ) {
$post_max_size = 'N/A';
}
$max_execution_time = 'N/A';
try {
$max_execution_time = @ini_get( 'max_execution_time' );
if( !isset( $max_execution_time ) || empty( $max_execution_time ) || $max_execution_time < 1 ) {
$max_execution_time = 'N/A';
}
} catch( Exception|Error $e ) {
$max_execution_time = 'N/A';
}
$server_software = 'N/A';
try {
if( isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
$server_software = $_SERVER['SERVER_SOFTWARE'] ?? '';
} else {
$server_software = 'N/A';
}
} catch( Exception|Error $e ) {
$server_software = 'N/A';
}
$ss_debug_mode = ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ? 'Yes' : 'No';
$active_plugins = 0;
try {
$active_plugins = get_option( 'active_plugins' );
if( function_exists('is_multisite') && function_exists('get_site_option') && is_multisite() ) {
$active_plugins = array_merge( $active_plugins, get_site_option( 'active_sitewide_plugins' ) );
}
$active_plugins = count( $active_plugins );
} catch( Exception|Error $e ) {
$active_plugins = 0;
}
$total_actions_execution_time = 0;
foreach( $rp_actions_ran_time as $hook_callbacks ) {
foreach( $hook_callbacks as $callback_info ) {
$total_actions_execution_time += $callback_info['execution_time'];
}
}
$rp_actions_ran_time_prepared = array();
foreach( $rp_actions_ran_time as $hook => $hook_callbacks ) {
foreach( $hook_callbacks as $callback_info ) {
$hash = md5( $hook . $callback_info['callback'] );
if( !isset( $rp_actions_ran_time_prepared[ $hash ] ) ) {
$rp_actions_ran_time_prepared[ $hash ] = array(
'callback' => $hook . ' > ' . $callback_info['callback'],
'execution_time' => round( $callback_info['execution_time'], 10 ),
'count' => 1,
'backtrace' => $callback_info['backtrace']
);
} else {
$rp_actions_ran_time_prepared[ $hash ]['execution_time'] += round( $callback_info['execution_time'], 10 );
$rp_actions_ran_time_prepared[ $hash ]['execution_time'] = round( $rp_actions_ran_time_prepared[ $hash ]['execution_time'], 10 );
$rp_actions_ran_time_prepared[ $hash ]['count'] += 1;
}
}
}
$rp_actions_ran_time_prepared = array_values( $rp_actions_ran_time_prepared );
$executionTimes = array();
foreach ($rp_actions_ran_time_prepared as $key => $query) {
$executionTimes[ $key ] = $query['execution_time'];
}
array_multisort( $executionTimes, SORT_DESC, $rp_actions_ran_time_prepared );
$request_details = array(
'request_uri' => $request_uri,
'page' => $page,
'action' => $action,
'rp_optimised_request_status' => ( $GLOBALS['rp_optimised_request_status'] ?? '0' ),
'payload' => $payload,
'request_method' => $request_method,
'total_queries' => $rpQuery->total_executed_queries(),
'rp_actions_ran_time_prepared' => $rp_actions_ran_time_prepared,
'total_queries_execution_time' => round( $rpQuery->calculateTotalQueriesExecutionTime(), 10 ),
'total_file_queries_execution_time' => round( $rpQuery->calculateTotalFileQueriesExecutionTime(), 10 ),
'total_memory_queries_execution_time' => round( $rpQuery->calculateTotalMemoryQueriesExecutionTime(), 10 ),
'queries' => $all_queries,
'cached_queries_file' => $cached_queries_file,
'cached_queries_memory' => $cached_queries_memory,
'duplicate_queries' => $duplicate_queries,
'duplicate_queries_count' => count( $duplicate_queries ),
'page_render_time' => round ( rp_get_page_render_time(), 10 ),
'all_time_after_rp_reached' => rp_get_execution_time_till_now( $rp_start_time_before_rp_loading_hook ),
'rp_loading' => round( rp_get_execution_time_till_now( $rp_start_time_before_rp_loading_hook ) - rp_get_execution_time_till_now( $rp_start_time_after_rp_loading_hook ), 10 ),
'total_actions_execution_time' => $total_actions_execution_time,
'plugins_loaded_hook' => round( rp_get_execution_time_till_now( $rp_start_time_before_plugins_loaded_hook ) - rp_get_execution_time_till_now( $rp_start_time_after_plugins_loaded_hook ), 10 ),
'init_hook' => round( rp_get_execution_time_till_now( $rp_start_time_before_init_hook ) - rp_get_execution_time_till_now( $rp_start_time_after_init_hook ), 10 ),
'admin_init_hook' => round( rp_get_execution_time_till_now( $rp_start_time_before_admin_init_hook ) - rp_get_execution_time_till_now( $rp_start_time_after_admin_init_hook ), 10 ),
// DEBUG INFO!!
'wp_version' => $wp_version,
'active_plugins' => $active_plugins,
'wp_debug_mode' => $ss_debug_mode,
'timezone' => $timezone_string,
'current_date' => $current_date,
'current_time' => $currentTime,
'server_software' => $server_software,
'php_version' => $php_version,
'memory_usage' => $memory_usage_msg,
'max_upload_size' => $max_upload_size,
'post_max_size' => $post_max_size,
'max_execution_time' => $max_execution_time,
'max_input_vars' => $max_input_vars
);
return $request_details;
}
function rp_refresh_form_debug_info_save() {
if( rp_get_option('rp_repairplugin_inspect', '0') != '1' || !current_user_can('activate_plugins') ) {
return;
}
rp_end_page_render_time();
$info = _rp_get_request_details_for_debug();
?>
<script type="text/javascript">
try {
let rpRequestDebugInfo = <?php echo json_encode($info); ?>;
if(typeof rpRequestDebugInfo === 'object') {
rpRequestDebugInfo = JSON.stringify(rpRequestDebugInfo);
}
// make sure localStorage is available
if( 'localStorage' in window && window.localStorage !== null ) {
localStorage.setItem('rp_last_execution_time_object', rpRequestDebugInfo);
}
} catch(e) {
console.error('Error while saving debug info to localStorage : ', e);
}
</script>
<?php
}
function rp_ajax_response( $data = array() ) {
rp_end_page_render_time();
$data['rp_inspect'] = _rp_get_request_details_for_debug();
return json_encode($data);
}
function rp_start_tracking_page_render_time() {
global $rp_page_render_start_time;
$rp_page_render_start_time = microtime(TRUE);
}
$rp_calculated_page_render_time = null;
$rp_page_render_start_time = null;
function rp_get_page_render_time() {
global $rp_calculated_page_render_time;
if( !isset($rp_calculated_page_render_time) ) {
return 'N/A';
}
return $rp_calculated_page_render_time;
}
function rp_end_page_render_time() {
global $rp_calculated_page_render_time;
global $rp_page_render_start_time;
$rp_calculated_page_render_time = microtime(TRUE) - $rp_page_render_start_time;
}
function rp_print_execution_time_json_code() {
static $already_printed = false;
if( $already_printed ) {
return;
}
$already_printed = true;
rp_add_action('admin_print_footer_scripts', '_rp_print_execution_time_json_code', 99999);
rp_add_action('wp_footer', '_rp_print_execution_time_json_code', 99999);
rp_start_tracking_page_render_time();
}
function wp_repair_admin_settings_page_html() {
$section = 'general_info';
$section_is_set = false;
if(isset($_GET['section']) && !empty($_GET['section'])) {
$section = $_GET['section'];
$section_is_set = true;
}
rp_show_validation_error_message();
wp_repair_admin_setup_tour_nav_html();
if( !rp_current_user_has_full_access_cached() ) {
if( $section_is_set == false ) {
$section = 'enhanced_locations';
}
$allowed_location_head_sections = array('enhanced_locations', 'special_opening_times');
if( !in_array( $section, $allowed_location_head_sections ) ) {
$url_to_redirect_to = admin_url('admin.php?page=wp_repair_settings§ion=enhanced_locations');
rp_redirect_refresh_form_with_error('enhanced_locations', 'Sorry, looks like section you are trying to access is not available for you.', $url_to_redirect_to);
}
$tab = $_GET['tab'] ?? 'schedules';
if( !rp_current_user_has_full_access_cached() ) {
$allowed_location_head_sections = array('schedules', 'locations_crud');
if( !in_array( $tab, $allowed_location_head_sections ) ) {
$url_to_redirect_to = admin_url('admin.php?page=wp_repair_settings§ion=enhanced_locations');
rp_redirect_refresh_form_with_error('enhanced_locations', 'Sorry, looks like tab you are trying to access is not available for you.', $url_to_redirect_to);
}
}
}
rp_print_execution_time_json_code();
$loaded_through_addon = apply_filters('rp_returning_admin_setting_page_html', FALSE, $section);
if($loaded_through_addon) {
rp_end_page_render_time();
return;
}
if($section === 'general_info') {
wp_repair_admin_general_info_page_html();
} else if($section === 'localization') {
wp_repair_admin_localization_page_html();
} else if($section === 'styling') {
wp_repair_admin_styling_page_html();
} else if($section === 'special_opening_times') {
wp_repair_admin_special_opening_times_page_html();
} else if($section === 'opening_hours') {
wp_repair_admin_opening_hours_page_html();
} else if($section === 'display_opening_hours') {
wp_repair_admin_display_opening_hours_page_html();
} else if($section === 'planning_discount') {
wp_repair_admin_planning_discount_page_html();
} else if($section === 'notification_offer') {
wp_repair_admin_notification_offer_page_html();
} else if($section === 'coupons') {
wp_repair_admin_coupons_page_html();
}else if($section === 'configure_mail') {
wp_repair_admin_configure_mail_page_html();
}else if($section === 'plugin_shortcode') {
wp_repair_admin_plugin_shortcode_page_html();
}else if($section === 'webhooks') {
wp_repair_admin_webhooks_page_html();
}else if($section === 'caching_performance') {
wp_repair_admin_caching_performance_page_html();
}else if($section === 'reset_all_data') {
wp_repair_admin_reset_all_data_page_html();
}else if($section === 'backups') {
if(!current_user_can('activate_plugins')) {
echo 'Sorry, you are not allowed to see this page.';
} else {
$which_page = 'import_export';
$debugTypes = array('import', 'export');
if( !empty($_REQUEST['rpdebug'] ?? '') && in_array( ($_REQUEST['rpdebug'] ?? ''), $debugTypes ) ) {
$which_page = 'import_export_debug';
}
wp_repair_admin_backups_page_html($which_page);
}
} else if($section === 'manage_permission') {
if(!current_user_can('activate_plugins')) {
echo 'Sorry, you are not allowed to see this page.';
} else {
wp_repair_admin_manage_permission_page_html();
}
}else if($section === 'email_smtp') {
wp_repair_admin_email_smtp_page_html();
}else {
wp_repair_admin_general_info_page_html();
}
rp_end_page_render_time();
}
function wp_repair_admin_manage_upsales_page_html() {
rp_print_execution_time_json_code();
rp_show_validation_error_message();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/manage_upsales.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
rp_end_page_render_time();
}
function wp_repair_admin_main_page_html() {
echo 'Hi from WP Repair Plugin!';
}
function wp_repair_show_alert_if_no_license() {
ob_start();
if(defined('WP_REPAIR_REQUIRE_LICENSE')) {
global $rpQuery;
global $wp_repair_lang;
$rs_company_information = $rpQuery->prefix . 'rs_company_information';
$info = $rpQuery->get_results("SELECT * FROM $rs_company_information LIMIT 1;");
$contact = '';
if(!empty($info)) {
if(!empty($info[0]->company_phone)) {
$contact = $info[0]->company_phone;
} else if(!empty($info[0]->company_email)) {
$contact = $info[0]->company_email;
} else {
$contact = '';
}
}
?>
<style type="text/css">
.wp-repair-FE-alert-license {
all: initial;
animation : none;
animation-delay : 0;
animation-direction : normal;
animation-duration : 0;
animation-fill-mode : none;
animation-iteration-count : 1;
animation-name : none;
animation-play-state : running;
animation-timing-function : ease;
backface-visibility : visible;
background : 0;
background-attachment : scroll;
background-clip : border-box;
background-color : transparent;
background-image : none;
background-origin : padding-box;
background-position : 0 0;
background-position-x : 0;
background-position-y : 0;
background-repeat : repeat;
background-size : auto auto;
border : 0;
border-style : none;
border-width : medium;
border-color : inherit;
border-bottom : 0;
border-bottom-color : inherit;
border-bottom-left-radius : 0;
border-bottom-right-radius : 0;
border-bottom-style : none;
border-bottom-width : medium;
border-collapse : separate;
border-image : none;
border-left : 0;
border-left-color : inherit;
border-left-style : none;
border-left-width : medium;
border-radius : 0;
border-right : 0;
border-right-color : inherit;
border-right-style : none;
border-right-width : medium;
border-spacing : 0;
border-top : 0;
border-top-color : inherit;
border-top-left-radius : 0;
border-top-right-radius : 0;
border-top-style : none;
border-top-width : medium;
bottom : auto;
box-shadow : none;
box-sizing : content-box;
caption-side : top;
clear : none;
clip : auto;
color : inherit;
columns : auto;
column-count : auto;
column-fill : balance;
column-gap : normal;
column-rule : medium none currentColor;
column-rule-color : currentColor;
column-rule-style : none;
column-rule-width : none;
column-span : 1;
column-width : auto;
content : normal;
counter-increment : none;
counter-reset : none;
cursor : auto;
direction : ltr;
display : inline;
empty-cells : show;
float : none;
font : normal;
font-family : inherit;
font-size : medium;
font-style : normal;
font-variant : normal;
font-weight : normal;
height : auto;
hyphens : none;
left : auto;
letter-spacing : normal;
line-height : normal;
list-style : none;
list-style-image : none;
list-style-position : outside;
list-style-type : disc;
margin : 0;
margin-bottom : 0;
margin-left : 0;
margin-right : 0;
margin-top : 0;
max-height : none;
max-width : none;
min-height : 0;
min-width : 0;
opacity : 1;
orphans : 0;
outline : 0;
outline-color : invert;
outline-style : none;
outline-width : medium;
overflow : visible;
overflow-x : visible;
overflow-y : visible;
padding : 0;
padding-bottom : 0;
padding-left : 0;
padding-right : 0;
padding-top : 0;
page-break-after : auto;
page-break-before : auto;
page-break-inside : auto;
perspective : none;
perspective-origin : 50% 50%;
position : static;
/* May need to alter quotes for different locales (e.g fr) */
quotes : '\201C' '\201D' '\2018' '\2019';
right : auto;
tab-size : 8;
table-layout : auto;
text-align : inherit;
text-align-last : auto;
text-decoration : none;
text-decoration-color : inherit;
text-decoration-line : none;
text-decoration-style : solid;
text-indent : 0;
text-shadow : none;
text-transform : none;
top : auto;
transform : none;
transform-style : flat;
transition : none;
transition-delay : 0s;
transition-duration : 0s;
transition-property : none;
transition-timing-function : ease;
unicode-bidi : normal;
vertical-align : baseline;
visibility : visible;
white-space : normal;
widows : 0;
width : auto;
word-spacing : normal;
z-index : auto;
/* basic modern patch */
all: initial;
all: unset;
max-height: unset;
max-width: unset;
}
.wp-repair-FE-alert-license {
padding: 8px 12px !important;
font-size: 15px !important;
color: #004085;
background-color: #cce5ff !important;
border: 1px solid #b8daff !important;
border-radius: 6px !important;
margin: auto !important;
text-align: left !important;
display: table !important;
margin: 15px 0px !important;
margin: auto !important;
margin-top: 15px !important;
margin-bottom: 15px !important;
width: 100% !important;
max-width: 800px !important;
text-align: center !important;
}
</style>
<br>
<div class="wp-repair-FE-alert-license">
<?php
if(!empty($contact)) {
echo str_replace('$contact$', $contact, $wp_repair_lang['fe_no_license_with_contact']);
} else {
echo $wp_repair_lang['fe_no_license_no_contact'];
}
?>
</div>
<br>
<?php
}
$content = ob_get_contents();
ob_get_clean();
return trim($content);
}
function rp_create_column_sort_link_manage_models($column_name = '', $sort_key = '') {
$brand = $_REQUEST['brand'] ?? '';
$category = $_REQUEST['category'] ?? '';
$search_model = $_REQUEST['search_model'] ?? '';
$sort_by = $_REQUEST['sort_by'] ?? '';
$sort_order = $_REQUEST['sort_order'] ?? 'ASC';
$brand = trim($brand);
$category = trim($category);
$search_model = trim($search_model, '%');
$sort_by = trim($sort_by);
$sort_order = trim($sort_order);
$get_paramters = array();
if(!empty($brand) && trim(strtolower($brand)) !== 'all') {
$get_paramters[] = "brand=$brand";
}
if(!empty($category)) {
$get_paramters[] = "category=$category";
}
if(!empty($search_model)) {
$get_paramters[] = "search_model=".urlencode($search_model);
}
if(!empty($get_paramters)) {
$get_paramters_str = '&'.join('&', $get_paramters);
} else {
$get_paramters_str = '';
}
if($sort_key === $sort_by) {
// Currently Sorted...
if($sort_order === 'ASC') {
return "<a class=\"rp_sortable_link\" href=\"?page=wp_repair_manage_models$get_paramters_str&sort_by=$sort_key&sort_order=DESC\">$column_name <i style=\"font-size: 14px; position: relative; top: 1px; line-height: 1.5em;\" class=\"fas fa-caret-up\"></i></a>";
} else {
return "<a class=\"rp_sortable_link\" href=\"?page=wp_repair_manage_models$get_paramters_str&sort_by=$sort_key&sort_order=ASC\">$column_name <i style=\"font-size: 14px; position: relative; top: 1px; line-height: 1.5em;\" class=\"fas fa-caret-down\"></i></a>";
}
} else {
return "<a class=\"rp_sortable_link\" href=\"?page=wp_repair_manage_models$get_paramters_str&sort_by=$sort_key&sort_order=ASC\">$column_name</a>";
}
}
function wp_repair_add_colors_to_models_if_needed() {
global $rpQuery;
$model_table = $rpQuery->prefix . "rs_model";
$default_color_table = $rpQuery->prefix . "rs_default_color";
$modelcolor_table = $rpQuery->prefix . "rs_model_color";
$m_result = $rpQuery->get_results("SELECT * FROM $model_table");
$rpQuery->query('START TRANSACTION');
foreach($m_result as $m){
$color_ids = $m->color_ids;
$m_id = $m->m_id;
if($color_ids != null){
$all_model_colors = rp_get_all_model_color_ids($m_id);
$color_idz = explode(',', $color_ids);
foreach($color_idz as $c){
$m_color = $rpQuery->get_results("SELECT * FROM $default_color_table WHERE dc_id = '".rp_escape_sql($c)."'");
$mc_id = $m_color[0]->dc_id;
$color_name = $m_color[0]->dc_name;
$color_code = $m_color[0]->dc_code;
$mc_uq_id = $m_color[0]->dc_uq_id;
if(array_search(trim($mc_uq_id), $all_model_colors) === FALSE) {
$all_model_colors[] = trim($mc_uq_id);
$rpQuery->query("INSERT INTO $modelcolor_table(color_name,color_code,mc_uq_id,m_id_fk) VALUES('".rp_escape_sql($color_name)."','".rp_escape_sql($color_code)."','".rp_escape_sql($mc_uq_id)."','".rp_escape_sql($m_id)."')");
}
}
$rpQuery->query("UPDATE $model_table SET color_ids='' WHERE m_id='".rp_escape_sql($m_id)."'");
}
}
$rpQuery->query('COMMIT');
}
function wp_repair_get_brands_of_category() {
global $rpQuery;
$rs_category = $rpQuery->prefix . 'rs_category';
$rs_brand = $rpQuery->prefix . 'rs_brand';
$categories = $rpQuery->get_results("SELECT * FROM `$rs_category`");
if(!empty($categories)) {
$key_value_pair = array();
foreach ($categories as $key => $category) {
if(!isset($key_value_pair[$category->c_id])) {
$key_value_pair[$category->c_id] = array();
}
$brands = $rpQuery->get_results("SELECT * FROM `$rs_brand` WHERE `c_id_fk` = '".rp_escape_sql($category->c_id)."'");
if(!empty($brands)) {
foreach ($brands as $_key => $brand) {
$key_value_pair[$category->c_id][] = array($brand->b_id, $brand->b_name);
}
}
}
return $key_value_pair;
}
return array();
}
function rp_before_getting_fe_pre_selected_location() {
if( isset( $_POST ) && !empty( $_POST ) && isset( $_POST['rp_pre_selected_location'] ) && !empty( $_POST['rp_pre_selected_location'] ) ) {
if( rp_verify_selected_location_frontend( intval( $_POST['rp_pre_selected_location'] ?? 0 ) ) == FALSE ) {
$_POST['rp_pre_selected_location'] = 0;
} else {
$_POST['rp_pre_selected_location'] = intval( $_POST['rp_pre_selected_location'] ?? 0 );
}
}
if( isset( $_POST ) && !empty( $_POST ) && isset( $_POST['get_o_id_fk'] ) && !empty( $_POST['get_o_id_fk'] ) ) {
global $rpQuery;
$o_id_fk = (int) ($_POST['get_o_id_fk'] ?? 0);
$table_rs_orders = $rpQuery->prefix . 'rs_orders';
$order = $rpQuery->get_row( "SELECT * FROM `$table_rs_orders` WHERE `o_id` = '".rp_escape_sql($o_id_fk)."';" );
if( !empty( $order ) && !empty( $order->location_id_fk ?? 0 ) ) {
$_POST['rp_pre_selected_location'] = $order->location_id_fk;
}
}
}
rp_add_action('rp_before_getting_fe_pre_selected_location', 'rp_before_getting_fe_pre_selected_location', 10);
function rp_handle_default_language_overwrite( $lang_alt_name = '' ) {
if( empty( $lang_alt_name ) ) {
// Do nothing!
return;
}
if( isset( $_SESSION ) && !empty( $_SESSION ?? array() ) && isset( $_SESSION['rp_selected_language'] ) && !empty( $_SESSION['rp_selected_language'] ) ) {
// User has already selected a language, so do nothing!
return;
}
global $rpQuery;
$rs_languages = $rpQuery->prefix . 'rs_languages';
// where name = $lang_alt_name OR alt_name = $lang_alt_name OR name starts with $lang_alt_name
$lang = $rpQuery->get_row( "SELECT * FROM `$rs_languages` WHERE `name` = '".rp_escape_sql($lang_alt_name)."' OR `alt_name` = '".rp_escape_sql($lang_alt_name)."' OR `name` LIKE '%".rp_escape_sql($lang_alt_name)."%' LIMIT 1;" );
if( empty( $lang ) ) {
// Do nothing!
return;
}
$selected_language = $lang->name;
// No user language selected? Great! Overwrite the one with the default one!
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['rp_overwritten_language'] = $selected_language;
$_SESSION['rp_selected_language'] = $selected_language;
RepairPluginPro\RP_Session_Handler::close();
rp_set_new_plugin_language($selected_language);
}
function rp_fe_get_trying_to_visit_repairs_page() {
if( in_array( strtolower( trim( explode( '/', $_GET['selected'] ?? '' )[0] ) ), array('repairs') ) != TRUE ) {
// Not a request to repairs page!
return array();
}
$uri_path = $_SERVER['REQUEST_URI'];
if( !empty( trim( $uri_path ?? '' ) ) ) {
$uri_path = explode('&token', $uri_path)[0];
}
$fixedURISegment = str_replace(array('http://', 'https://'), '', str_replace($_SERVER['HTTP_HOST'] ?? '', '', get_site_url()));
$fixedURISegment = $fixedURISegment;
if(!empty($fixedURISegment)) {
$uri_path = str_replace($fixedURISegment, '', $uri_path);
}
if(preg_match('~%[0-9A-F]{2}~i', $uri_path)) {
$uri_path = urldecode($uri_path);
}
$uri_path = str_replace('reschedule=1&', '', $uri_path);
$uri_path = str_replace('payment_cancel=1&', '', $uri_path);
$uri_segments = explode('/', $uri_path);
$secondKey = count($uri_segments) -2;
$segment = end($uri_segments);
$second_segment = $uri_segments[$secondKey] ?? '';
$m_name = str_replace('-slash-','/',$segment);
$m_name = str_replace('-',' ',$m_name);
$m_name = str_replace('%20',' ',$m_name);
$m_name = str_replace('_','-',$m_name);
$m_name = str_replace('plus','+',$m_name);
$b_name = str_replace('Oneplus', 'OnePlus', $second_segment); // captialize the P
$b_name = str_replace('-',' ',$b_name);
$b_name = str_replace('%20',' ',$b_name);
$b_name = str_replace('_','-',$b_name);
$b_name = str_replace('plus','+',$b_name);
$b_name = str_replace('OnePlus', 'Oneplus', $b_name); // uncaptialize the P
return array( $b_name, $m_name );
}
function wp_repair_show_FE_templates( $atts ) {
$atts = array_change_key_case( ( array )$atts, CASE_LOWER );
$shortcode_attributes = shortcode_atts(
array(
'location' => '', // default location
'brand' => '',
'language' => ''
), $atts );
// Accept both Location ID / Name ---- START
$shortcode_attributes = rp_get_final_location_id_for_shortcode( $shortcode_attributes );
// Accept both Location ID / Name ---- END
$GLOBALS['rp_shortcode_brand_name'] = esc_attr( $shortcode_attributes['brand'] );
$_REQUEST['rp_shortcode_brand_name'] = ($GLOBALS['rp_shortcode_brand_name'] ?? '');
$location = esc_attr( $shortcode_attributes['location'] );
$GLOBALS['rp_fe_pre_selected_location'] = '';
$main_location_id = rp_get_main_location_id_of_company();
$GLOBALS['rp_correct_shortcode_for_loc_based_name'] = 'Repair_All';
$GLOBALS['rp_correct_shortcode_for_loc_based_attrs'] = 'location='.$main_location_id;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
if ( !empty( trim($location ?? '') ) ) {
if( rp_verify_selected_location_frontend( (int) (trim( $location )) ) == TRUE ) {
$GLOBALS['rp_fe_pre_selected_location'] = (int) (trim( $location ));
}
}
}
rp_handle_default_language_overwrite( $shortcode_attributes['language'] );
$content = wp_repair_show_alert_if_no_license();
if(!empty($content)) {
return $content;
}
return wp_repair_show_FE_bundle_page();
}
add_shortcode('Repair_All', 'wp_repair_show_FE_templates');
function wp_repair_show_FE_bundle_page() {
rp_print_execution_time_json_code();
ob_start();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/front_end/bundle.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
include $fileName;
$content = ob_get_clean();
rp_end_page_render_time();
return $content;
}
function rp_start_session_for_RP_front_end() {
if( isset( $_GET['selected'] ) ) {
if( strpos( $_GET['selected'], 'finalize' ) !== FALSE || strpos( $_GET['selected'], 'shortcode_finalize_order' ) !== FALSE ) {
RepairPluginPro\RP_Session_Handler::read();
}
}
}
rp_add_action('init', 'rp_start_session_for_RP_front_end', 999);
function wp_repair_show_FE_model_shortcode_bundle_page() {
rp_print_execution_time_json_code();
ob_start();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/front_end/bundle_model_shortcode.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
include $fileName;
$content = ob_get_clean();
rp_end_page_render_time();
return $content;
}
function wp_repair_show_FE_type_page() {
ob_start();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/front_end/types.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
$content = ob_get_clean();
return $content;
}
function wp_repair_show_FE_brand_page() {
ob_start();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/front_end/brands.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
$content = ob_get_clean();
return $content;
}
function wp_repair_show_FE_model_page() {
ob_start();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/front_end/models.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
$content = ob_get_clean();
return $content;
}
function wp_repair_show_FE_repair_page() {
ob_start();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/front_end/repairs.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
$content = ob_get_clean();
return $content;
}
function wp_repair_show_FE_finalize_page() {
ob_start();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/front_end/repair_finalize.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
$content = ob_get_clean();
return $content;
}
function wp_repair_show_FE_thanks_page() {
ob_start();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/front_end/thanks.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
$content = ob_get_clean();
return $content;
}
function wp_repair_show_FE_cancel_page() {
ob_start();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/front_end/cancel.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
$content = ob_get_clean();
return $content;
}
function cssLineStartsWith($string, $startString) {
$len = strlen($startString);
return (substr($string, 0, $len) === $startString);
}
function rp_fetch_image_from_base_using_curl($link = '') {
$result = rp_curl_get( $link, 8 ); // 8 seconds timeout
if( empty($result) ) {
return false;
}
list( $info, $response, $error ) = $result;
if( $info['http_code'] != '200' || empty( $response ) ) {
return false;
}
return $response;
}
function rp_fetch_image_from_base_using_fgc($link = '') {
return file_get_contents( $link, false, stream_context_create( array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false ) ) ) );
}
function rp_get_wp_abs_path() {
$plugin_dir = dirname( __FILE__ );
$plugins_folder = dirname( $plugin_dir );
$wp_content = dirname( $plugins_folder );
if( basename( $wp_content ) == 'wp-content' ) {
$wp_abs_path = dirname( $wp_content ) . DIRECTORY_SEPARATOR;
} else {
$wp_abs_path = ABSPATH;
}
return $wp_abs_path;
}
function rp_fetch_image_from_base($link = '') {
// check if link contains ABSPATH to check if it is a local file
if( strpos( $link, rp_get_wp_abs_path() ) !== FALSE ) {
return file_get_contents( $link );
}
if( filter_var( ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN ) === TRUE ) {
return rp_fetch_image_from_base_using_fgc($link);
} else {
return rp_fetch_image_from_base_using_curl($link);
}
}
function editCSSLineByLine($css_file = '', $func = NULL, $save = FALSE) {
$file = WP_REPAIR_PLUGIN_PATH.'assets/css/front_end/'.$css_file.'.css';
if(@file_exists($file)) {
$content = rp_fetch_image_from_base($file);
$content = explode("\n", $content);
foreach ($content as $lineNum => $value) {
$value = trim($value);
$content[$lineNum] = $func($value, $lineNum);
}
if($save === TRUE) {
return file_put_contents($file, $content) !== FALSE;
}
return implode("\n", $content);
}
return '';
}
function rp_get_final_location_id_for_shortcode( $shortcode_attributes = array() ) {
$location_attr = esc_attr( $shortcode_attributes['location'] );
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
if( is_numeric( $location_attr ) ) {
if( !empty( $found_location = rp_get_location_by_id( (int) $location_attr ) ) ) {
$shortcode_attributes['location'] = $found_location->location_id ?? false;
}
} else {
if( !empty( $location_attr ) && !empty( $found_location = rp_get_location_by_name( $location_attr ) ) ) {
$shortcode_attributes['location'] = $found_location->location_id ?? false;
}
}
}
return $shortcode_attributes;
}
function model_shortcode( $atts ) {
$atts = array_change_key_case( ( array )$atts, CASE_LOWER );
$shortcode_attributes = shortcode_atts(
array(
'code' => '', // default url
'location' => '',
'language' => ''
), $atts );
$code = esc_attr( $shortcode_attributes['code'] );
// Accept both Location ID / Name ---- START
$shortcode_attributes = rp_get_final_location_id_for_shortcode( $shortcode_attributes );
// Accept both Location ID / Name ---- END
if ( $code ) {
$location = esc_attr( $shortcode_attributes['location'] );
$GLOBALS['rp_fe_pre_selected_location'] = '';
$main_location_id = rp_get_main_location_id_of_company();
$GLOBALS['rp_correct_shortcode_for_loc_based_name'] = 'models';
$GLOBALS['rp_correct_shortcode_for_loc_based_attrs'] = 'code=' . $code . ' location='.$main_location_id;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
if ( !empty( trim($location ?? '') ) ) {
if( rp_verify_selected_location_frontend( (int) (trim( $location )) ) == TRUE ) {
$GLOBALS['rp_fe_pre_selected_location'] = (int) (trim( $location ));
}
}
}
$GLOBALS['model_code'] = $code;
rp_handle_default_language_overwrite( $shortcode_attributes['language'] );
$content = wp_repair_show_alert_if_no_license();
if(!empty($content)) {
return $content;
}
return wp_repair_show_FE_model_shortcode_bundle_page();
}
}
function rp_category_shortcode( $atts ) {
$atts = array_change_key_case( ( array )$atts, CASE_LOWER );
$shortcode_attributes = shortcode_atts(
array(
'code' => '', // default url
'location' => '', // pre-selected location
'language' => ''
), $atts );
$code = esc_attr( $shortcode_attributes['code'] );
// Accept both Location ID / Name ---- START
$shortcode_attributes = rp_get_final_location_id_for_shortcode( $shortcode_attributes );
// Accept both Location ID / Name ---- END
if ( $code ) {
$location = esc_attr( $shortcode_attributes['location'] );
$GLOBALS['rp_fe_pre_selected_location'] = '';
$main_location_id = rp_get_main_location_id_of_company();
$GLOBALS['rp_correct_shortcode_for_loc_based_name'] = 'categories';
$GLOBALS['rp_correct_shortcode_for_loc_based_attrs'] = 'code=' . $code . ' location='.$main_location_id;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
if ( !empty( trim($location ?? '') ) ) {
if( rp_verify_selected_location_frontend( (int) (trim( $location )) ) == TRUE ) {
$GLOBALS['rp_fe_pre_selected_location'] = (int) (trim( $location ));
}
}
}
$GLOBALS['category_shortcode'] = $code;
rp_handle_default_language_overwrite( $shortcode_attributes['language'] );
$content = wp_repair_show_alert_if_no_license();
if(!empty($content)) {
return $content;
}
return wp_repair_show_FE_bundle_page();
}
}
add_shortcode('categories', 'rp_category_shortcode');
function rp_brand_shortcode( $atts ) {
$atts = array_change_key_case( ( array )$atts, CASE_LOWER );
$shortcode_attributes = shortcode_atts(
array(
'code' => '', // default url
'location' => '',
'language' => '' // pre-selected location
), $atts );
$code = esc_attr( $shortcode_attributes['code'] );
// Accept both Location ID / Name ---- START
$shortcode_attributes = rp_get_final_location_id_for_shortcode( $shortcode_attributes );
// Accept both Location ID / Name ---- END
if ( $code ) {
$location = esc_attr( $shortcode_attributes['location'] );
$GLOBALS['rp_fe_pre_selected_location'] = '';
$main_location_id = rp_get_main_location_id_of_company();
$GLOBALS['rp_correct_shortcode_for_loc_based_name'] = 'brands';
$GLOBALS['rp_correct_shortcode_for_loc_based_attrs'] = 'code=' . $code . ' location='.$main_location_id;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
if ( !empty( trim($location ?? '') ) ) {
if( rp_verify_selected_location_frontend( (int) (trim( $location )) ) == TRUE ) {
$GLOBALS['rp_fe_pre_selected_location'] = (int) (trim( $location ));
}
}
}
$GLOBALS['brand_shortcode'] = $code;
rp_handle_default_language_overwrite( $shortcode_attributes['language'] );
$content = wp_repair_show_alert_if_no_license();
if(!empty($content)) {
return $content;
}
return wp_repair_show_FE_bundle_page();
}
}
add_shortcode('brands', 'rp_brand_shortcode');
function rp_get_settings_placeholder_email() {
$placeholder_email = '';
if(defined('WP_REPAIR_SETTINGS_PLACEHOLDER_EMAIL') && !empty(WP_REPAIR_SETTINGS_PLACEHOLDER_EMAIL)) {
$placeholder_email = WP_REPAIR_SETTINGS_PLACEHOLDER_EMAIL;
}
return trim($placeholder_email);
}
add_shortcode( 'models', 'model_shortcode' );
register_activation_hook(WP_REPAIR_PLUGIN_FILE,'repair_plugin_table_create');
register_deactivation_hook(WP_REPAIR_PLUGIN_FILE,'repair_plugin_dactivate');
function rp_default_rows_add_if_needed() {
global $rpQuery;
// *****************
// Company Information (rs_company_information)
// *****************
$company_information = $rpQuery->prefix . "rs_company_information";
$count_company_information = $rpQuery->get_var("SELECT COUNT(*) FROM $company_information");
if($count_company_information == 0){
$placeholder_email = rp_get_settings_placeholder_email();
$rpQuery->query("INSERT INTO $company_information(company_name,company_email,company_phone,company_logo,company_reg_no,tax_reg_no,company_theme_color) VALUES('abc','".rp_escape_sql($placeholder_email)."','12345','http://site.com/picture','','','2781c7')");
}
// *****************
// Company Location (rs_company_location)
// *****************
$company_location = $rpQuery->prefix . "rs_company_location";
$count_company_location = $rpQuery->get_var("SELECT COUNT(*) FROM $company_location");
if($count_company_location == 0){
$rpQuery->query("INSERT INTO $company_location(location_name,location_address,location_city_district) VALUES('Repairshop','','')");
}
// *****************
// Company Schedules (rs_company_schedules)
// *****************
$company_schedules = $rpQuery->prefix . "rs_company_schedules";
$count_company_schedules = $rpQuery->get_var("SELECT COUNT(*) FROM $company_schedules");
if($count_company_schedules == 0){
for($i = 0; $i < 7; $i++ ){
$days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
$rpQuery->query("INSERT INTO $company_schedules(cs_day,cs_open_timing,cs_close_timing,cs_breaktime_from,cs_breaktime_to,is_closed,location_id_fk) VALUES('".rp_escape_sql($days[$i])."','09:00','18:00','12:00','13:00','0','1')");
}
}
// *****************
// Coupons
// *****************
$table_coupons = $rpQuery->prefix . "rs_coupons";
$count_table_coupons = $rpQuery->get_var("SELECT COUNT(*) FROM $table_coupons");
if($count_table_coupons == 0 && rp_get_option('rp_created_default_coupon', '0') != '1' ){
rp_update_option('rp_created_default_coupon', '1');
$rpQuery->query("INSERT INTO $table_coupons(coupons_own_reference,coupons_code,coupons_amount,coupons_set_limit,is_active,coupons_used_limit,expired_date,coupons_min_order_amount) VALUES('Customer 1','20OFFNOW','20','unlimited','0', 0, '', 0)");
}
// *****************
// Localization
// *****************
$table_rs_localization = $rpQuery->prefix . "rs_localization";
$count_table_rs_localization = $rpQuery->get_var("SELECT COUNT(*) FROM $table_rs_localization");
if($count_table_rs_localization == 0){
$rpQuery->query("INSERT INTO $table_rs_localization(set_language,set_currency,set_price_symbols,set_decimals,show_even_price,show_decimals,set_time_format,tax,tax_indicator) VALUES('English (United States)','€','Left (\$10)','comma','0','1','24 hours (e.g. 15:00)','21','BTW')");
}
// *****************
// Notification Types
// *****************
$table_rs_notification_types = $rpQuery->prefix . "rs_notification_types";
$count_table_rs_notification_types = $rpQuery->get_var("SELECT COUNT(*) FROM $table_rs_notification_types");
if($count_table_rs_notification_types == 0){
$types = ['Booking Pending','PDF Offer','Booking Approved','Booking Canceled'];
for($i = 0;$i < 4 ;$i++){
$rpQuery->query("INSERT INTO $table_rs_notification_types(noti_type) VALUES('".rp_escape_sql($types[$i])."')");
}
}
// *****************
// Notifications and Offers
// *****************
$table_rs_notifications_and_offers = $rpQuery->prefix . "rs_notifications_and_offers";
$count_table_rs_notifications_and_offers = $rpQuery->get_var("SELECT COUNT(*) FROM $table_rs_notifications_and_offers");
if($count_table_rs_notifications_and_offers == 0){
$subject = [
get_email_template_of_wp_repair('pending')[0],
get_email_template_of_wp_repair('offer')[0],
get_email_template_of_wp_repair('approved')[0],
get_email_template_of_wp_repair('cancelled')[0]
];
$message = [
get_email_template_of_wp_repair('pending')[1],
get_email_template_of_wp_repair('offer')[1],
get_email_template_of_wp_repair('approved')[1],
get_email_template_of_wp_repair('cancelled')[1]
];
$x = 0;
for($i=1;$i<5;$i++){
$rpQuery->query("INSERT INTO $table_rs_notifications_and_offers(noti_subject,noti_message,noti_type_id_fk,shortcode_name,shortcode_symbol,is_active) VALUES('".rp_escape_sql($subject[$x])."','".rp_escape_sql($message[$x])."','".rp_escape_sql($i)."','','','1')");
$x++;
}
}
// *****************
// Planning and Discount
// *****************
$table_rs_planning_and_discount = $rpQuery->prefix . "rs_planning_and_discount";
$count_table_rs_planning_and_discount = $rpQuery->get_var("SELECT COUNT(*) FROM $table_rs_planning_and_discount");
if($count_table_rs_planning_and_discount == 0){
$rpQuery->query("INSERT INTO $table_rs_planning_and_discount(booking_slots_length,booking_amount_per_slot,is_combo_discount,amount,max_amount,come_our_store,ship_device) VALUES('30 Minutes (Default)','Unlimited (Default)','1','10','None (Default)','1','1')");
}
// *****************
// Order Status
// *****************
$table_rs_order_status = $rpQuery->prefix . "rs_order_status";
$count_table_rs_order_status = $rpQuery->get_var("SELECT COUNT(*) FROM $table_rs_order_status");
if($count_table_rs_order_status == 0){
for($i=0;$i<4;$i++){
$status = ['Pending','Offered','Approved','Canceled'];
$rpQuery->query("INSERT INTO $table_rs_order_status(s_name) VALUES('".rp_escape_sql($status[$i])."')");
}
}
if(rp_get_option('rp_use_customer_info_for_duplicate_email', FALSE) === FALSE) {
rp_add_option('rp_use_customer_info_for_duplicate_email', '1');
}
$status_change_emails = array(
1, // Pending
2, // PDF Offer
3, // Approved
4 // Cancelled
);
foreach ($status_change_emails as $email_noti_id) {
if(rp_get_option('wp_repair_admin_duplicate_email_status_'.$email_noti_id, FALSE) === FALSE) {
rp_add_option('wp_repair_admin_duplicate_email_status_'.$email_noti_id, '1');
}
}
}
rp_add_action('init', 'rp_default_rows_add_if_needed', 1);
function repair_plugin_table_create(){
rp_clear_all_smart_cache();
// Clear the database structure version
rp_delete_option('rp_last_db_structure_version');
}
// Register activation hook
register_activation_hook(WP_REPAIR_PLUGIN_FILE, 'repair_plugin_table_create');
function rp_decide_if_setup_needs_installation() {
global $rpQuery;
if( rp_get_option('rp_decided_if_setup_needs_installation', '0') == '1' ) {
// Already decided, skip further checks
return;
}
rp_update_option('rp_decided_if_setup_needs_installation', '1');
$rs_model = $rpQuery->prefix . 'rs_model';
$model_count = $rpQuery->get_var("SELECT COUNT(*) FROM $rs_model");
if( $model_count > 0 ) {
// No installation is needed so rp_installation_completed = true
rp_update_option('rp_installation_completed', true);
} else {
// Leave it as is meaning installation is needed!
}
}
rp_add_action('admin_init', 'rp_decide_if_setup_needs_installation', 10);
function rp_maybe_redirect_to_wizard() {
// Check if installation is completed or has valid license
if (\RepairPluginPro\InstallationWizard::isInstallationCompleted()) {
return; // Skip redirect since installation is completed
}
// Regular check for incomplete installation
if (is_admin()) {
$current_url = $_SERVER['REQUEST_URI'];
// Only redirect if on plugin pages
if (strpos($current_url, 'wp_repair') !== false || strpos($current_url, 'repair-plugin') !== false) {
// Don't redirect if already on wizard page
if (strpos($current_url, 'rp-setup-wizard') === false) {
wp_safe_redirect(admin_url('admin.php?page=rp-setup-wizard'));
exit;
}
}
}
}
// redirect to setup wizard if needed
rp_add_action('admin_init', 'rp_maybe_redirect_to_wizard', 11);
function repair_plugin_dactivate(){
rp_clear_all_smart_cache();
}
// ----------------------------------------------- get company email
function rp_get_settings_company_email() {
global $rpQuery;
$company_information = $rpQuery->prefix ."rs_company_information";
$company_results = $rpQuery->get_results("SELECT * FROM $company_information");
$company_email = '';
if(!empty($company_results)) {
$company_email = $company_results[0]->company_email;
}
return trim($company_email);
}
//--------------------------------------------------- get coupon
function coupon_code(){
rp_verify_csrf_token_for_ajax('frontend');
global $rpQuery;
global $wp_repair_lang;
$rs_coupons = $rpQuery->prefix . "rs_coupons";
$coupon = trim( $_POST['coupon'] ?? '' );
$m_id = intval( $_POST['m_id'] ?? 0 );
$selected_repairs = ($_POST['selected_repairs'] ?? array());
$selected_attrs = ($_POST['selected_attrs'] ?? array());
$subtotal_after_combo_discount = ($_POST['subtotal_after_combo_discount'] ?? 0 );
$result = $rpQuery->get_results("SELECT * FROM $rs_coupons WHERE coupons_code = '".rp_escape_sql($coupon)."'");
$more_info = array();
if( !empty( $result ) ) {
$coupons_amount = $result[0]->coupons_amount;
$coupons_id = $result[0]->coupons_id;
$min_order_amount = ($result[0]->coupons_min_order_amount ?? 0);
if( ( (float) $min_order_amount ) < 0 ) {
$min_order_amount = 0;
}
$usage = rp_verify_coupon_usage( $coupons_id, $m_id, $selected_repairs, $selected_attrs, $subtotal_after_combo_discount );
if( !empty( $usage ) && $usage['status'] == true ) {
echo json_encode(Array('status'=> true, 'message' => $coupons_amount, 'coupons_id' => $coupons_id, 'type' => $result[0]->coupons_type, 'more_info' => $usage, 'min_order_amount' => $min_order_amount));
exit;
} else {
$more_info = $usage;
}
}
echo json_encode(Array('status'=> false, 'message' => $wp_repair_lang['invalid_coupon'], 'more_info' => $more_info));
exit();
}
rp_ajax_for_public('coupon_code','coupon_code');
//-------------------------------------------------------------------delete repairs
function delete_repair(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$rs_rattr_translations = $rpQuery->prefix . "rs_rattr_translations";
$rs_location_prices = $rpQuery->prefix . "rs_location_prices";
$rid = $_POST['rid'];
$result = $rpQuery->get_row("SELECT * FROM $rs_repair WHERE r_id = '".rp_escape_sql($rid)."'");
if( !empty( $result ) ) {
$dr_category = rp_get_model_cached_category_by_mid( $result->m_id_fk );
$rpQuery->query("DELETE FROM `$rs_r_translations` WHERE uq_id = '".rp_escape_sql($result->r_uq_id)."' AND m_id_fk = '".rp_escape_sql($result->m_id_fk)."'");
$rpQuery->query("DELETE FROM `$rs_rattr_translations` WHERE r_id_fk = '".rp_escape_sql($rid)."';");
$rpQuery->query("DELETE FROM $rs_repair WHERE r_id='".rp_escape_sql($rid)."'");
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'r' AND `connection_id` = '".rp_escape_sql($rid)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
$repair_attrs = $rpQuery->get_results("SELECT * FROM $rs_repair_attr WHERE r_id_fk = '".rp_escape_sql($rid)."'");
if( !empty( $repair_attrs ) ) {
foreach( $repair_attrs as $repair_attr ) {
$rpQuery->query("DELETE FROM `$rs_repair_attr` WHERE a_id='".rp_escape_sql($repair_attr->a_id)."'");
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'a' AND `connection_id` = '".rp_escape_sql($repair_attr->a_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
}
}
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted'));
exit();
}
rp_ajax_for_admin('delete_repair','delete_repair');
//-------------------------------------------------------------------delete repair category
function delete_repair_category(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
list( $selected_location_id, $rp_location_based_price_id ) = rp_must_verify_selected_location_if_needed_ajax();
global $rpQuery;
$rs_repairs_category = $rpQuery->prefix . "rs_repairs_category";
$rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$rcid = $_POST['rcid'];
$category_based = array();
$categoriesCount = 0;
$m_id_fk = 0;
$result = $rpQuery->get_row("SELECT * FROM $rs_repairs_category WHERE c_id = '".rp_escape_sql($rcid)."'");
if( !empty( $result ) ) {
$rpQuery->query("DELETE FROM `$rs_r_translations` WHERE uq_id = '".rp_escape_sql($result->c_uq_id)."' AND m_id_fk = '".rp_escape_sql($result->m_id_fk)."'");
$rpQuery->query("DELETE FROM $rs_repairs_category WHERE c_id='".rp_escape_sql($rcid)."'");
list( $category_based, $categoriesCount ) = rp_get_model_related_repairs_for_admin_page( $result->m_id_fk );
$m_id_fk = $result->m_id_fk;
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted', 'category_based' => $category_based, 'categories_count' => $categoriesCount, 'm_id_fk' => $m_id_fk));
exit();
}
rp_ajax_for_admin('delete_repair_category','delete_repair_category');
//-------------------------------------------------------------------delete default repairs
function rp_get_all_m_ids_by_category( $category_id ) {
$cache_key = 'rp_get_all_m_ids_by_category|'.$category_id;
$cached = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if(!empty($cached)) {
return $cached;
}
global $rpQuery;
$m_ids = array();
$rs_model = $rpQuery->prefix . 'rs_model';
$models = $rpQuery->get_results("SELECT * FROM `$rs_model` WHERE `device_type` = '".rp_escape_sql($category_id)."'");
if(!empty($models)) {
foreach ($models as $model) {
$m_ids[] = $model->m_id;
}
}
RepairPluginPro\RP_Memory_Cache::save($cache_key, $m_ids);
return $m_ids;
}
function delete_default_repair(){
rp_verify_csrf_token_for_ajax('default_repairs');
rp_verify_user_full_access_ajax();
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$default_repair_table = $rpQuery->prefix . "rs_default_repair";
$rs_default_repair_attr = $rpQuery->prefix . "rs_default_repair_attr";
$rs_dr_translations = $rpQuery->prefix . "rs_dr_translations";
$rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$rs_rattr_translations = $rpQuery->prefix . "rs_rattr_translations";
$rs_location_prices = $rpQuery->prefix . "rs_location_prices";
$rid = $_POST['rid'];
$dr_category = $_POST['dr_category'] ?? 0;
$result = $rpQuery->get_results("SELECT dr_uq_id FROM $default_repair_table WHERE dr_id='".rp_escape_sql($rid)."' AND dr_category = '".rp_escape_sql($dr_category)."' LIMIT 1;");
if(!empty($result)) {
$dr_uq_id = $result[0]->dr_uq_id;
// delete from rs_dr_translations where uq_id = $dr_uq_id
// select * from rs_default_repair_attr where dr_id_fk = $rid
$attrs = $rpQuery->get_results("SELECT * FROM `$rs_default_repair_attr` WHERE dr_id_fk='".rp_escape_sql($rid)."'");
if( !empty($attrs) ) {
foreach($attrs as $attr_row) {
$rpQuery->query("DELETE FROM `$rs_dr_translations` WHERE uq_id = '".rp_escape_sql($attr_row->da_uq_id)."'");
$rpQuery->query("DELETE FROM `$rs_rattr_translations` WHERE uq_id = '".rp_escape_sql($attr_row->da_uq_id)."'");
}
}
$rpQuery->query("DELETE FROM `$rs_dr_translations` WHERE uq_id = '".rp_escape_sql($dr_uq_id)."'");
$rpQuery->query("DELETE FROM `$rs_r_translations` WHERE uq_id = '".rp_escape_sql($dr_uq_id)."'");
$m_ids = rp_get_all_m_ids_by_category( $dr_category );
if(!empty($m_ids)) {
$m_ids = join(',', $m_ids);
$result1 = $rpQuery->query("DELETE FROM $rs_repair WHERE r_uq_id='".rp_escape_sql($dr_uq_id)."' AND m_id_fk IN (".rp_escape_sql($m_ids).")");
}
$result2 = $rpQuery->query("DELETE FROM $default_repair_table WHERE dr_id='".rp_escape_sql($rid)."' AND dr_category = '".rp_escape_sql($dr_category)."'");
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'dr' AND `uqid` = '".rp_escape_sql($dr_uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'r' AND `uqid` = '".rp_escape_sql($dr_uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
$related_dr_attrs = $rpQuery->get_results("SELECT * FROM `$rs_default_repair_attr` WHERE dr_id_fk='".rp_escape_sql($rid)."'");
if( !empty( $related_dr_attrs ) ) {
foreach( $related_dr_attrs as $dr_attr_row ) {
$current_da_uq_id = $dr_attr_row->da_uq_id;
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'da' AND `uqid` = '".rp_escape_sql($current_da_uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'a' AND `uqid` = '".rp_escape_sql($current_da_uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
}
}
// delete from rs_default_repair_attr where dr_id_fk = $rid
$result3 = $rpQuery->query("DELETE FROM `$rs_default_repair_attr` WHERE dr_id_fk='".rp_escape_sql($rid)."'");
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted'));
exit();
}
rp_ajax_for_admin('delete_default_repair','delete_default_repair');
function rp_must_verify_selected_location_if_needed_ajax() {
$selected_location_id = 0;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
$selected_location_id = intval( $_POST['selected_location_id'] ?? 0 );
if( empty( $selected_location_id ) ) {
echo json_encode(Array('status' => false, 'message' => 'Invalid location id'));
exit();
}
global $rp_location_based_price_id;
$rp_location_based_price_id = $selected_location_id;
}
$secondVal = 0;
if( isset( $rp_location_based_price_id ) && !empty( $rp_location_based_price_id ) ) {
$secondVal = $rp_location_based_price_id;
}
return array( $selected_location_id, $secondVal );
}
function delete_default_repair_category(){
rp_verify_csrf_token_for_ajax('default_repairs');
rp_verify_user_full_access_ajax();
list( $selected_location_id, $rp_location_based_price_id ) = rp_must_verify_selected_location_if_needed_ajax();
global $rpQuery;
$rs_repairs_category = $rpQuery->prefix . "rs_repairs_category";
$rs_repair_cat_linking = $rpQuery->prefix . "rs_repair_cat_linking";
$rs_default_repairs_category = $rpQuery->prefix . "rs_default_repairs_category";
$rs_dr_translations = $rpQuery->prefix . "rs_dr_translations";
$rcid = $_POST['rcid'];
$dr_category = $_POST['dr_category'] ?? 0;
$result = $rpQuery->get_results("SELECT dc_uq_id FROM $rs_default_repairs_category WHERE dc_id='".rp_escape_sql($rcid)."' AND dc_category = '".rp_escape_sql($dr_category)."' LIMIT 1;");
if(!empty($result)) {
$dc_uq_id = $result[0]->dc_uq_id;
// delete from rs_dr_translations where uq_id = $dr_uq_id
$rpQuery->query("DELETE FROM `$rs_dr_translations` WHERE uq_id = '".rp_escape_sql($dc_uq_id)."'");
$m_ids = rp_get_all_m_ids_by_category( $dr_category );
if(!empty($m_ids)) {
$m_ids = join(',', $m_ids);
$result1 = $rpQuery->query("DELETE FROM $rs_repairs_category WHERE c_uq_id='".rp_escape_sql($dc_uq_id)."' AND m_id_fk IN (".rp_escape_sql($m_ids).")");
}
$result2 = $rpQuery->query("DELETE FROM $rs_default_repairs_category WHERE dc_id='".rp_escape_sql($rcid)."' AND dc_category = '".rp_escape_sql($dr_category)."'");
}
// delete from rs_repair_cat_linking where c_id_fk = dr_category and rc_uq_id = dc_uq_id
$result3 = $rpQuery->query("DELETE FROM `$rs_repair_cat_linking` WHERE c_id_fk = '".rp_escape_sql($dr_category)."' AND rc_uq_id = '".rp_escape_sql($dc_uq_id)."'");
$default_listing_range = rp_get_option( 'rp_default_listing_index_' . ((int)$dr_category), 6 );
$default_listing_range = (int) $default_listing_range;
$default_listing_range = rp_round_to_even_number( $default_listing_range );
list( $category_based, $categoriesCount ) = rp_get_default_repairs_again_after_update($dr_category, $default_listing_range);
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted', 'categories_count' => $categoriesCount, 'category_based' => $category_based));
exit();
}
rp_ajax_for_admin('delete_default_repair_category','delete_default_repair_category');
//-------------------------------------------------------------------delete repairs
function _rp_delete_model_related_repairs( $mrid = 0 ) {
if( empty( $mrid ) ) {
return;
}
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$rs_rattr_translations = $rpQuery->prefix . "rs_rattr_translations";
$rs_location_prices = $rpQuery->prefix . "rs_location_prices";
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$results = $rpQuery->get_results("SELECT * FROM $rs_repair WHERE m_id_fk='".rp_escape_sql($mrid)."'");
if( !empty( $results ) ) {
foreach( $results as $result ) {
$rid = $result->r_id;
$dr_category = rp_get_model_cached_category_by_mid( $result->m_id_fk );
$rpQuery->query("DELETE FROM `$rs_r_translations` WHERE uq_id = '".rp_escape_sql($result->r_uq_id)."' AND m_id_fk = '".rp_escape_sql($result->m_id_fk)."'");
$rpQuery->query("DELETE FROM `$rs_rattr_translations` WHERE r_id_fk = '".rp_escape_sql($rid)."';");
$rpQuery->query("DELETE FROM $rs_repair WHERE r_id='".rp_escape_sql($rid)."'");
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'r' AND `connection_id` = '".rp_escape_sql($rid)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
$repair_attrs = $rpQuery->get_results("SELECT * FROM $rs_repair_attr WHERE r_id_fk = '".rp_escape_sql($rid)."'");
if( !empty( $repair_attrs ) ) {
foreach( $repair_attrs as $repair_attr ) {
$rpQuery->query("DELETE FROM `$rs_repair_attr` WHERE a_id='".rp_escape_sql($repair_attr->a_id)."'");
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'a' AND `connection_id` = '".rp_escape_sql($repair_attr->a_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
}
}
}
}
}
function delete_model_related_repairs(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
$mrid = $_POST['mrid'] ?? 0;
_rp_delete_model_related_repairs( $mrid );
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted'));
exit;
}
rp_ajax_for_admin('delete_model_related_repairs','delete_model_related_repairs');
//-------------------------------------------------------------------delete repairs attr
function delete_r_attr(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$rs_rattr_translations = $rpQuery->prefix . "rs_rattr_translations";
$rs_location_prices = $rpQuery->prefix . "rs_location_prices";
$aid = $_POST['aid'];
if( !empty($aid) ) {
$result = $rpQuery->get_row("SELECT * FROM $rs_repair_attr WHERE a_id = '".rp_escape_sql($aid)."'");
if( !empty( $result ) ) {
$rpQuery->query("DELETE FROM `$rs_rattr_translations` WHERE uq_id = '".rp_escape_sql($result->a_uq_id)."' AND r_id_fk = '".rp_escape_sql($result->r_id_fk)."'");
$rpQuery->query("DELETE FROM $rs_repair_attr WHERE a_id='".rp_escape_sql($aid)."'");
$parent_repair_row = $rpQuery->get_row("SELECT * FROM $rs_repair WHERE r_id = '".rp_escape_sql($result->r_id_fk)."'");
if( !empty( $parent_repair_row ) ) {
$dr_category = rp_get_model_cached_category_by_mid( $parent_repair_row->m_id_fk );
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'a' AND `connection_id` = '".rp_escape_sql($aid)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
}
}
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted'));
}
rp_ajax_for_admin('delete_r_attr','delete_r_attr');
//-------------------------------------------------------------------delete default repairs attr
function delete_dr_attr(){
rp_verify_csrf_token_for_ajax('default_repairs');
rp_verify_user_full_access_ajax();
global $rpQuery;
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$rs_default_repair_attr = $rpQuery->prefix . "rs_default_repair_attr";
$rs_dr_translations = $rpQuery->prefix . "rs_dr_translations";
$rs_rattr_translations = $rpQuery->prefix . "rs_rattr_translations";
$rs_location_prices = $rpQuery->prefix . "rs_location_prices";
$aid = $_POST['aid'];
$dr_category = $_POST['dr_category'] ?? 0;
$result = $rpQuery->get_results("SELECT da_uq_id FROM $rs_default_repair_attr WHERE da_id='".rp_escape_sql($aid)."' AND dr_category = '".rp_escape_sql($dr_category)."' LIMIT 1;");
if(!empty($result)) {
$da_uq_id = $result[0]->da_uq_id;
// delete from rs_dr_translations where uq_id = $da_uq_id
$rpQuery->query("DELETE FROM `$rs_dr_translations` WHERE uq_id = '".rp_escape_sql($da_uq_id)."'");
$rpQuery->query("DELETE FROM `$rs_rattr_translations` WHERE uq_id = '".rp_escape_sql($da_uq_id)."'");
$r_ids = rp_get_all_repair_ids_related_to_category($dr_category);
if(!empty($r_ids)) {
$r_ids = join(',', $r_ids);
$rpQuery->query("DELETE FROM $rs_repair_attr WHERE a_uq_id='".rp_escape_sql($da_uq_id)."' AND r_id_fk IN (".rp_escape_sql($r_ids).")");
}
$rpQuery->query("DELETE FROM $rs_default_repair_attr WHERE da_id='".rp_escape_sql($aid)."' AND dr_category = '".rp_escape_sql($dr_category)."'");
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'da' AND `uqid` = '".rp_escape_sql($da_uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'a' AND `uqid` = '".rp_escape_sql($da_uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."'");
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted'));
}
rp_ajax_for_admin('delete_dr_attr','delete_dr_attr');
//-------------------------------------------------------------------update repairs attr
function update_r_attr(){
global $rpQuery;
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$aid = $_POST['aid'];
$name = $_POST['name'];
$price = $_POST['price'];
$rpQuery->query("UPDATE $rs_repair_attr SET a_name='".rp_escape_sql($name)."',a_price='".rp_escape_sql($price)."' WHERE a_id='".rp_escape_sql($aid)."'");
echo json_encode(Array('status'=> true, 'message' => 'Successfully updated'));
}
rp_ajax_for_admin('update_r_attr','update_r_attr');
//-------------------------------------------------------------------delete models
function delete_model(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$rs_model = $rpQuery->prefix . "rs_model";
$modelcolor_table = $rpQuery->prefix . "rs_model_color";
$mid = $_POST['mid'];
_rp_delete_model_related_repairs( $mid );
$result = $rpQuery->query("DELETE FROM $rs_model WHERE m_id='".rp_escape_sql($mid)."'");
$rpQuery->query("DELETE FROM $modelcolor_table WHERE m_id_fk='".rp_escape_sql($mid)."'");
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted'));
}
rp_ajax_for_admin('delete_model','delete_model');
//-------------------------------------------------------------------delete models color
function delete_model_color(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
global $rpQuery;
$modelcolor_table = $rpQuery->prefix . "rs_model_color";
$mc_id = $_POST['mc_id'] ?? null;
if(!empty($mc_id)) {
$rpQuery->query("DELETE FROM $modelcolor_table WHERE mc_id='".rp_escape_sql($mc_id)."'");
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted'));
exit();
}
rp_ajax_for_admin('delete_model_color','delete_model_color');
//------------------------------------------------------------------- get related brands
function rp_get_only_normal_schedule($loc_id = '', $day = '', $date_ymd = '') {
$schedules = apply_filters('rp_getting_only_normal_schedule_filter', array(), $loc_id, $day, $date_ymd);
if( !empty( $schedules ) ) {
return $schedules;
}
global $rpQuery;
$rs_company_schedules = $rpQuery->prefix . "rs_company_schedules";
$org_schedules = $rpQuery->get_row("SELECT * FROM $rs_company_schedules WHERE cs_day = '".rp_escape_sql($day)."' AND location_id_fk = '".rp_escape_sql($loc_id)."' LIMIT 1");
$schedules = array( $org_schedules );
return $schedules;
}
function rp_get_special_schedule($loc_id = '', $day = '', $date_ymd = '') {
$schedules = apply_filters('rp_getting_special_schedule_filter', array(), $loc_id, $day, $date_ymd);
if( !empty( $schedules ) ) {
return $schedules;
}
global $rpQuery;
$rs_company_schedules = $rpQuery->prefix . "rs_company_schedules";
// get only m-d of Y-m-d format from $date_ymd
$date_md = explode('-', $date_ymd);
$date_md = $date_md[1] . '-' . $date_md[2];
$result = rp_get_special_timing( $date_md, $loc_id );
$org_schedules = $rpQuery->get_row("SELECT * FROM $rs_company_schedules WHERE cs_day = '".rp_escape_sql($day)."' AND location_id_fk = '".rp_escape_sql($loc_id)."' LIMIT 1");
// If special timing is there and close, consider it
// Otherwise for special timing to be considered, it must be there and original schedule must not be closed!
if( ( !empty( $result ) && ( ( $result->is_closed ?? 0 ) == 1 || ( $org_schedules->is_closed ?? 0 ) == 0 ) ) ) {
$result->cs_day = $day;
$result->reminder_name = rp_get_static_translations_of_special_date_name_selected('reminder_name', $result->cs_id, 'selected');
$schedules = array($result);
} else {
$schedules = array( $org_schedules );
}
return $schedules;
}
function rp_is_day_off_new_dm( $loc_id = 0, $day = '', $date_ymd = '' ) {
$schedules = rp_get_special_schedule_new_methods($loc_id, $day, $date_ymd);
$schedules = rp_sanitize_output($schedules);
if( !empty( $schedules ) ) {
if( ($schedules[0]->is_closed ?? '0') == '1' ) {
return true;
}
}
$delivery_timeslots = rp_get_delivery_timeslots($loc_id, $day);
if( !empty( $delivery_timeslots ) ) {
return false;
}
return true;
}
function rp_is_day_off( $loc_id = 0, $day = '', $date_ymd = '' ) {
$schedules = rp_get_special_schedule($loc_id, $day, $date_ymd);
$schedules = rp_sanitize_output($schedules);
if( !empty( $schedules ) ) {
if( $schedules[0]->is_closed == '1' ) {
return true;
}
}
return false;
}
function _get_schedules( $loc_id = 0, $weekday_name = '', $date_dmy = '' ) {
global $rpQuery;
global $wp_repair_lang;
_rp_set_default_tiemzone();
$rs_company_schedules = $rpQuery->prefix . "rs_company_schedules";
$rs_planning_and_discount = $rpQuery->prefix . "rs_planning_and_discount";
$rs_localization = $rpQuery->prefix . "rs_localization";
$day = $weekday_name;
$date = $date_dmy;
$date_ymd = explode('-', $date);
$date_ymd = $date_ymd[2] . '-' . $date_ymd[1] . '-' . $date_ymd[0];
$available_days = rp_get_come_our_store_available_days($loc_id, $date_ymd);
$schedules = rp_get_special_schedule($loc_id, $day, $date_ymd);
$schedules = rp_sanitize_output($schedules);
if( !empty( $schedules ) ) {
if( $schedules[0]->is_closed == '1' ) {
if( !empty($schedules[0]->reminder_name ?? '') ) {
return (array('status'=> false, 'available_days' => $available_days, 'message' => trim($schedules[0]->reminder_name)));
}
$schedules = array();
}
}
if(!empty($schedules)){
$has_valid_breaktime = TRUE;
$valid_break_time_start = preg_match('/(?:\d){1,2}(?:\:){1}(?:\d){1,2}(?:(\sam|\spm)|($))+/i', $schedules[0]->cs_breaktime_from);
$valid_break_time_end = preg_match('/(?:\d){1,2}(?:\:){1}(?:\d){1,2}(?:(\sam|\spm)|($))+/i', $schedules[0]->cs_breaktime_to);
if(empty($schedules[0]->cs_breaktime_from) || empty($schedules[0]->cs_breaktime_to)) {
$has_valid_breaktime = FALSE;
}
if($valid_break_time_start === 0 || $valid_break_time_end === 0) {
$has_valid_breaktime = FALSE;
}
$planning_discount = $rpQuery->get_results("SELECT * FROM $rs_planning_and_discount");
$time_slots = $planning_discount[0]->booking_slots_length;
$time_slots = str_replace(' Minutes (Default)', '', $time_slots);
$time_slots = (int) $time_slots;
$localization = $rpQuery->get_results("SELECT * FROM $rs_localization");
if($localization[0]->set_time_format == '24 hours (e.g. 15:00)'){
$from_time = date("H:i",strtotime($schedules[0]->cs_open_timing));
$to_time = date("H:i",strtotime($schedules[0]->cs_close_timing));
$minutes = round(abs(strtotime($to_time) - strtotime($from_time)) / 60,2);
if($has_valid_breaktime === TRUE) {
$break_from_time = date("H:i",strtotime($schedules[0]->cs_breaktime_from));
$break_to_time = date("H:i",strtotime($schedules[0]->cs_breaktime_to));
$break_minutes = round(abs(strtotime($break_to_time) - strtotime($break_from_time)) / 60,2);
$break_start_after_x_minutes = (strtotime($schedules[0]->cs_breaktime_from) - strtotime($schedules[0]->cs_open_timing)) / 60;
$break_ends_after_x_minutes = (strtotime($schedules[0]->cs_breaktime_to) - strtotime($schedules[0]->cs_open_timing)) / 60;
}
}else{
$from_time = date("g:i a",strtotime($schedules[0]->cs_open_timing));
$to_time = date("g:i a",strtotime($schedules[0]->cs_close_timing));
$minutes = round(abs(strtotime($to_time) - strtotime($from_time)) / 60,2);
if($has_valid_breaktime === TRUE) {
$break_from_time = date("g:i a",strtotime($schedules[0]->cs_breaktime_from));
$break_to_time = date("g:i a",strtotime($schedules[0]->cs_breaktime_to));
$break_minutes = round(abs(strtotime($break_to_time) - strtotime($break_from_time)) / 60,2);
$break_start_after_x_minutes = (strtotime($schedules[0]->cs_breaktime_from) - strtotime($schedules[0]->cs_open_timing)) / 60;
$break_ends_after_x_minutes = (strtotime($schedules[0]->cs_breaktime_to) - strtotime($schedules[0]->cs_open_timing)) / 60;
}
}
$break_times = array();
if($has_valid_breaktime === TRUE) {
if($break_start_after_x_minutes >= 0 && $break_start_after_x_minutes <= $minutes && $break_ends_after_x_minutes >= 0 && $break_ends_after_x_minutes <= $minutes) {
} else {
$has_valid_breaktime = FALSE;
}
}
for ($x = 0; $x <= $minutes; $x+=$time_slots) {
$add_time = strtotime($from_time)+($x*60);
if($localization[0]->set_time_format == '24 hours (e.g. 15:00)'){
$adding = date('H:i',$add_time);
$slot_time[] = $adding;
}else{
$adding = date('g:i a',$add_time);
$slot_time[] = $adding;
}
if($has_valid_breaktime === TRUE) {
if($x >= $break_start_after_x_minutes && $x < $break_ends_after_x_minutes) {
$break_times[] = $adding;
}
}
}
$last_time = strtotime(date('Y-m-d H:i:s', strtotime($date_ymd.' '.$schedules[0]->cs_close_timing . ' -'.$time_slots.' minutes')));
$shop_close_time = strtotime(date('Y-m-d H:i:s', strtotime($date_ymd.' '.$schedules[0]->cs_close_timing)));
$current_time = date('Y-m-d H:i:s');
$current_time_str = strtotime($current_time);
$booking_must_wait_time = (int) rp_get_option('wp_repair_booking_must_wait_time', 60);
$booking_must_wait_time_until = strtotime(date('Y-m-d H:i:s', strtotime($current_time .' +'.$booking_must_wait_time.' minutes')));
$time_slots_printed = FALSE;
$not_allowed = array();
$fully_booked = array();
foreach($slot_time as $time_key => $time_val) {
$loop_time = strtotime(date('Y-m-d H:i:s', strtotime($date_ymd.' '.$time_val)));
if($loop_time < $current_time_str) {
unset($slot_time[$time_key]);
continue;
}
if($loop_time > $last_time) {
unset($slot_time[$time_key]);
continue;
}
if(rp_is_available_slot($loc_id, date('Y-m-d', strtotime($date_ymd.' '.$time_val)), date('H:i:s', strtotime($date_ymd.' '.$time_val))) === FALSE) {
$fully_booked[] = $time_val;
} else if($loop_time < $booking_must_wait_time_until) {
$not_allowed[] = $time_val;
} else {
$time_slots_printed = TRUE;
}
}
if($time_slots_printed === FALSE) {
if($current_time_str >= $shop_close_time) {
return (array('status'=> false, 'available_days' => $available_days, 'message' => $wp_repair_lang['shop_has_closed_for_today']));
} else {
return (array('status'=> false, 'available_days' => $available_days, 'message' => $wp_repair_lang['appointment_booking_has_closed_for_today']));
}
} else {
$slot_time = array_values($slot_time);
}
return (array('status'=> true, 'available_days' => $available_days, 'message' => $slot_time, 'break_times' => $break_times, 'not_allowed' => $not_allowed, 'fully_booked' => $fully_booked));
}else{
return (array('status'=> false, 'available_days' => $available_days, 'message' => $wp_repair_lang['shop_is_closed_for_today']));
}
}
function get_schedules(){
echo json_encode( _get_schedules( ($_POST['loc_id'] ?? 0), ( $_POST['day'] ?? '' ), ( $_POST['date'] ?? '' ) ) );
exit;
}
rp_ajax_for_public('get_schedules','get_schedules');
function get_schedules_new_dm(){
global $rpQuery;
global $wp_repair_lang;
_rp_set_default_tiemzone();
$rs_company_schedules = $rpQuery->prefix . "rs_company_schedules";
$rs_planning_and_discount = $rpQuery->prefix . "rs_planning_and_discount";
$rs_localization = $rpQuery->prefix . "rs_localization";
$day = $_POST['day'] ?? '';
$date = $_POST['date'] ?? '';
$date_ymd = explode('-', $date);
$date_ymd = $date_ymd[2] . '-' . $date_ymd[1] . '-' . $date_ymd[0];
$loc_id = $_POST['method'] ?? '';
if( $loc_id === 'pickup_service' ) {
$_method = 'ps';
}
if( $loc_id === 'repair_on_location' ) {
$_method = 'rol';
}
$debug_info = array();
$debug_info[] = array(
'rs_company_schedules' => $rs_company_schedules,
'cs_day' => $day,
'location_id_fk' => $loc_id
);
$schedules = rp_get_special_schedule_new_methods($loc_id, $day, $date_ymd);
$schedules = rp_sanitize_output($schedules);
if( !empty( $schedules ) ) {
if( ($schedules[0]->is_closed ?? '0') == '1' ) {
if( !empty($schedules[0]->reminder_name ?? '') ) {
echo json_encode(Array('status'=> false, 'debug_info' => $debug_info, 'message' => trim($schedules[0]->reminder_name)));
exit();
}
$schedules = array();
}
}
$delivery_timeslots = rp_get_delivery_timeslots($loc_id, $day);
if( !empty( $schedules ) && !empty( $delivery_timeslots ) ) {
// Has special timing!
if( $schedules[0]->is_closed == 0 ) {
$from_time = strtotime($schedules[0]->cs_open_timing);
$to_time = strtotime($schedules[0]->cs_close_timing);
$filtered_delivery_timeslots = array();
foreach( $delivery_timeslots as $dt_row ) {
$slot_start = strtotime($dt_row->slot_start);
$slot_end = strtotime($dt_row->slot_end);
if( $slot_start >= $from_time && $slot_end <= $to_time ) {
$filtered_delivery_timeslots[] = $dt_row;
}
}
$delivery_timeslots = $filtered_delivery_timeslots;
} else {
$delivery_timeslots = array();
}
}
if(!empty($delivery_timeslots)){
$debug_info[] = 'Found related schedules';
$debug_info[] = $delivery_timeslots;
$localization = $rpQuery->get_results("SELECT * FROM $rs_localization");
if(!empty($localization)) {
$debug_info[] = 'Got localization row';
$debug_info[] = array($localization[0]);
} else {
$debug_info[] = 'localization Row Could\'t found!';
}
$slot_time = array();
$last_time = '';
$shop_close_time = '';
foreach($delivery_timeslots as $dt_row) {
$slot_start = strtotime($date_ymd . ' ' . $dt_row->slot_start);
$slot_end = strtotime($date_ymd . ' ' . $dt_row->slot_end);
if( $localization[0]->set_time_format == '24 hours (e.g. 15:00)' ) {
$slot_time[] = date('H:i', $slot_start).' — '.date('H:i', $slot_end);
} else {
$slot_time[] = date('g:i a', $slot_start).' — '.date('g:i a', $slot_end);
}
if( empty( $last_time ) ) {
$last_time = $slot_start;
} else {
if( $last_time < $slot_start ) {
$last_time = $slot_start;
}
}
if( empty( $shop_close_time ) ) {
$shop_close_time = $slot_end;
} else {
if( $shop_close_time < $slot_end ) {
$shop_close_time = $slot_end;
}
}
}
$current_time = date('Y-m-d H:i:s');
$current_time_str = strtotime($current_time);
$booking_must_wait_time = (int) rp_get_option('wp_repair_booking_must_wait_time_'.$_method, 60);
$booking_must_wait_time_until = strtotime(date('Y-m-d H:i:s', strtotime($current_time .' +'.$booking_must_wait_time.' minutes')));
$debug_info[] = array(
'last_time' => $last_time,
'shop_close_time' => $shop_close_time,
'current_time' => $current_time,
'current_time_str' => $current_time_str,
'booking_must_wait_time' => $booking_must_wait_time,
'booking_must_wait_time_until' => $booking_must_wait_time_until
);
$time_slots_printed = FALSE;
$not_allowed = array();
$fully_booked = array();
foreach($slot_time as $time_key => $time_val) {
$the_time = explode(' — ', $time_val)[0];
$loop_time = strtotime(date('Y-m-d H:i:s', strtotime($date_ymd.' '.$the_time)));
if($loop_time < $current_time_str) {
unset($slot_time[$time_key]);
continue;
}
if($loop_time > $last_time) {
unset($slot_time[$time_key]);
continue;
}
if(rp_is_available_slot_new_delivery_methods($loc_id, date('Y-m-d', strtotime($date_ymd)), $time_val) === FALSE) {
$fully_booked[] = $time_val;
} else if($loop_time < $booking_must_wait_time_until) {
$not_allowed[] = $time_val;
} else {
$debug_info[] = 'Timeslot Printed!';
$time_slots_printed = TRUE;
}
}
$debug_info[] = array(
'not_allowed' => $not_allowed,
'fully_booked' => $fully_booked
);
if($time_slots_printed === FALSE) {
if($current_time_str >= $shop_close_time) {
echo json_encode(Array('status'=> false, 'debug_info' => $debug_info, 'message' => $wp_repair_lang['shop_has_closed_for_today']));
exit();
} else {
echo json_encode(Array('status'=> false, 'debug_info' => $debug_info, 'message' => $wp_repair_lang['appointment_booking_has_closed_for_today']));
exit();
}
} else {
$slot_time = array_values($slot_time);
}
echo json_encode(Array('status'=> true, 'debug_info' => $debug_info, 'message' => $slot_time, 'not_allowed' => $not_allowed, 'fully_booked' => $fully_booked));
exit();
}else{
echo json_encode(Array('status'=> false, 'debug_info' => $debug_info, 'message' => $wp_repair_lang['shop_is_closed_for_today']));
exit();
}
}
rp_ajax_for_public('get_schedules_new_dm','get_schedules_new_dm');
function rp_get_special_schedule_new_methods($method = '', $day = '', $date_ymd = '') {
if( $method === 'pickup_service' ) {
$method = 'ps';
}
if( $method === 'repair_on_location' ) {
$method = 'rol';
}
// get only m-d of Y-m-d format from $date_ymd
$date_md = explode('-', $date_ymd);
$date_md = $date_md[1] . '-' . $date_md[2];
$result = rp_get_special_timing( $date_md, $method );
$schedules = array();
if( !empty( $result ) ) {
$result->cs_day = $day;
$result->reminder_name = rp_get_static_translations_of_special_date_name_selected('reminder_name', $result->cs_id, 'selected');
$schedules = array($result);
}
return $schedules;
}
//-------------------------------------------------------------------Check Valid Breaktime
function get_invalid_breaktimes_errors() {
global $rpQuery;
$company_location = $rpQuery->prefix . "rs_company_location";
$company_schedules = $rpQuery->prefix . "rs_company_schedules";
$get_location = $rpQuery->get_results("SELECT * FROM $company_location");
$errors = array();
foreach($get_location as $loc){
$locid = $loc->location_id;
$schedules = $rpQuery->get_results("SELECT * FROM $company_schedules WHERE location_id_fk = '".rp_escape_sql($locid)."'");
if(!empty($schedules)) {
foreach ($schedules as $sch) {
$result = is_valid_breaktime($sch->cs_day, $locid);
if($result !== TRUE) {
if(array_search($result, $errors) === FALSE) {
$errors[] = $result;
}
}
}
}
}
return $errors;
}
function is_valid_breaktime($day, $loc_id){
global $rpQuery;
global $wp_repair_lang;
$rs_company_schedules = $rpQuery->prefix . "rs_company_schedules";
$rs_planning_and_discount = $rpQuery->prefix . "rs_planning_and_discount";
$rs_localization = $rpQuery->prefix . "rs_localization";
if(!isset($GLOBALS['schedules_for_breaktime'])) {
$_schedulesList = $rpQuery->get_results("SELECT * FROM $rs_company_schedules WHERE is_closed = '0'");
$schedulesList = array();
foreach ($_schedulesList as $key => $value) {
$schedulesList[$value->location_id_fk.$value->cs_day] = $value;
}
$GLOBALS['schedules_for_breaktime'] = $schedulesList;
}
if(isset($GLOBALS['schedules_for_breaktime'][$loc_id.$day])) {
$schedules = array($GLOBALS['schedules_for_breaktime'][$loc_id.$day]);
} else {
$schedules = null;
}
if($schedules){
$valid_break_time_start = preg_match('/(?:\d){1,2}(?:\:){1}(?:\d){1,2}(?:(\sam|\spm)|($))+/i', $schedules[0]->cs_breaktime_from);
$valid_break_time_end = preg_match('/(?:\d){1,2}(?:\:){1}(?:\d){1,2}(?:(\sam|\spm)|($))+/i', $schedules[0]->cs_breaktime_to);
if(empty($schedules[0]->cs_breaktime_from) || empty($schedules[0]->cs_breaktime_to)) {
return TRUE;
}
if($valid_break_time_start === 0 || $valid_break_time_end === 0) {
return 'invalid_break_time';
}
$planning_discount = $rpQuery->get_results("SELECT * FROM $rs_planning_and_discount");
$time_slots = $planning_discount[0]->booking_slots_length;
$time_slots = (int) trim(explode('Minutes', $time_slots)[0]);
$localization = $rpQuery->get_results("SELECT * FROM $rs_localization");
if($localization[0]->set_time_format == '24 hours (e.g. 15:00)'){
$from_time = date("H:i",strtotime($schedules[0]->cs_open_timing));
$to_time = date("H:i",strtotime($schedules[0]->cs_close_timing));
$minutes = round(abs(strtotime($to_time) - strtotime($from_time)) / 60,2);
$break_from_time = date("H:i",strtotime($schedules[0]->cs_breaktime_from));
$break_to_time = date("H:i",strtotime($schedules[0]->cs_breaktime_to));
$break_minutes = round(abs(strtotime($break_to_time) - strtotime($break_from_time)) / 60,2);
$break_start_after_x_minutes = (strtotime($schedules[0]->cs_breaktime_from) - strtotime($schedules[0]->cs_open_timing)) / 60;
$break_ends_after_x_minutes = (strtotime($schedules[0]->cs_breaktime_to) - strtotime($schedules[0]->cs_open_timing)) / 60;
}else{
$from_time = date("g:i a",strtotime($schedules[0]->cs_open_timing));
$to_time = date("g:i a",strtotime($schedules[0]->cs_close_timing));
$minutes = round(abs(strtotime($to_time) - strtotime($from_time)) / 60,2);
$break_from_time = date("g:i a",strtotime($schedules[0]->cs_breaktime_from));
$break_to_time = date("g:i a",strtotime($schedules[0]->cs_breaktime_to));
$break_minutes = round(abs(strtotime($break_to_time) - strtotime($break_from_time)) / 60,2);
$break_start_after_x_minutes = (strtotime($schedules[0]->cs_breaktime_from) - strtotime($schedules[0]->cs_open_timing)) / 60;
$break_ends_after_x_minutes = (strtotime($schedules[0]->cs_breaktime_to) - strtotime($schedules[0]->cs_open_timing)) / 60;
}
$break_times = array();
if($break_start_after_x_minutes >= 0 && $break_start_after_x_minutes <= $minutes && $break_ends_after_x_minutes >= 0 && $break_ends_after_x_minutes <= $minutes) {
} else {
return 'mistake_in_am_pm';
}
if($break_start_after_x_minutes > $break_ends_after_x_minutes) {
return 'break_start_is_greater';
}
for ($x = 0; $x <= $minutes; $x+=$time_slots) {
$add_time = strtotime($from_time)+($x*60);
if($localization[0]->set_time_format == '24 hours (e.g. 15:00)'){
$adding = date('H:i',$add_time);
$slot_time[] = $adding;
}else{
$adding = date('g:i a',$add_time);
$slot_time[] = $adding;
}
if($x >= $break_start_after_x_minutes && $x < $break_ends_after_x_minutes) {
$break_times[] = $adding;
}
}
if(empty($break_times)) {
return 'mistake_in_am_pm';
} else {
return TRUE;
}
}else{
return TRUE;
}
}
// ---------------------------------------- Get Duplicate Email by Status
function wp_repair_admin_duplicate_email($status = '', $location_id = '') {
return wp_repair_get_location_email( $status, $location_id );
}
// ---------------------------------------- Get Location Email by Location Id
function wp_repair_get_location_email($status = '', $location_id = '') {
$admin_enabled = rp_get_option('wp_repair_admin_duplicate_email_status_'.$status, '0');
if($admin_enabled === '1') {
// Need to Send Email!
// Get related special email
$admin_email = wp_repair_get_location_email_org( $location_id );
$recipient = FALSE;
if(!empty($admin_email)) {
// Special Email is Set
// Special Email Must NOT Equal to Placeholder email & must be valid
if(trim($admin_email) !== rp_get_settings_placeholder_email() && filter_var(trim($admin_email), FILTER_VALIDATE_EMAIL) !== FALSE) {
// Good to Set As Recipient
$recipient = trim($admin_email);
}
} else {
// Send Email to Company Email
$company_email = rp_get_settings_company_email();
// Company Email Must NOT Equal to Placeholder email & must be valid
if(trim($company_email) !== rp_get_settings_placeholder_email() && filter_var(trim($company_email), FILTER_VALIDATE_EMAIL) !== FALSE) {
// Good to Set As Recipient
$recipient = trim($company_email);
}
}
return $recipient;
}
// No Need to send email..
return FALSE;
}
// ---------------------------------------- Check Whether Duplicate Email by Status is Synced with Company Email
function wp_repair_admin_duplicate_email_is_synced($status = '') {
// Get related special email
$admin_email = rp_get_option('wp_repair_admin_duplicate_email_status_'.$status.'_email', NULL);
// Means it is synced with Company Email
return empty($admin_email);
}
// ---------------------------------------- Check Whether Location Email by Status is Synced with Company Email
function wp_repair_get_location_email_org($id = '') {
global $rpQuery;
$company_location = $rpQuery->prefix . "rs_company_location";
$location = $rpQuery->get_row("SELECT * FROM $company_location WHERE location_id = $id LIMIT 1;");
if( !empty( $location ) ) {
return (!empty( $location->location_email ) ? $location->location_email : NULL);
}
return NULL;
}
function wp_repair_location_email_is_synced($id = '') {
return empty( wp_repair_get_location_email_org( $id ) );
}
//-------------------------------------------------------------------update appointment status
function rp_get_location_id_of_order( $o_id = '' ) {
if( empty( $o_id ) ) {
return 0;
}
global $rpQuery;
$rs_orders = $rpQuery->prefix . "rs_orders";
$order = $rpQuery->get_row("SELECT * FROM $rs_orders WHERE o_id = '".rp_escape_sql($o_id)."' LIMIT 1;");
if( !empty( $order ) ) {
return ($order->location_id_fk ?? 0);
}
return 0;
}
function rp_find_link_pattern($what = '', $message = '') {
if( !empty( $what ) && !empty( $message ) ) {
preg_match_all('/(?:\['.$what.'=(?:"|"))[\p{L}\s!@#\$%\^&\*\(\)_\+-=\{\}\\\|;:\'\/\?.,<>]+(?:(?:"|")\])/u', $message, $matches);
if( !empty( $matches ) && isset( $matches[0] ) && !empty( $matches[0] ) ) {
if( isset( $matches[0][0] ) && !empty( $matches[0][0] ) ) {
return $matches[0][0];
}
}
}
return FALSE;
}
function rp_get_total_amount_text( $total_amount = 0 ) {
global $rpQuery;
global $wp_repair_lang;
$rs_localization = $rpQuery->prefix . "rs_localization";
$localization = $rpQuery->get_results("SELECT * FROM $rs_localization");
$decimal = $localization[0]->set_decimals;
$total_cost = $total_amount;
if($decimal == 'comma'){
$total_cost = number_format((float)$total_cost, 2, '.', '');
$total_cost = str_replace('.',',',$total_cost);
} else {
$total_cost = number_format((float)$total_cost, 2, '.', '');
}
$tax = $localization[0]->tax;
$int = ctype_digit($tax);
if($int == 1){
$tax = $tax;
} else{
if($decimal == 'comma'){
$tax = number_format((float)$tax, 2, '.', '');
$tax = str_replace('.',',',$tax);
} else{
$tax = number_format((float)$tax, 2, '.', '');
}
}
$total_cost = rp_handle_currency_position($total_cost, $localization[0]->set_currency, TRUE);
$text = $wp_repair_lang['total'] . ' <b>'.$total_cost.'</b> '.$wp_repair_lang['incl'].'. '.$tax.'% '.$wp_repair_lang['tax'];
return $text;
}
function rp_handle_currency_position($amount = 0, $currency = '', $add_space = FALSE) {
$currency_position = rp_get_option('rp_set_price_symbol', 'left');
$space = ($add_space === TRUE ? ' ' : '');
if($currency_position == 'left') {
return $currency.$space.$amount;
} else {
return $amount.$space.$currency;
}
}
function rp_repair_name_fix_filter( $name = '', $r_id = '' ) {
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$repair = $rpQuery->get_row("SELECT * FROM `$rs_repair` WHERE r_id = '".rp_escape_sql($r_id)."' LIMIT 1;");
if( !empty( $repair ) ) {
list($rows, $ig) = rp_translate_locked_repairs_and_attributes( array($repair), array() );
$repair = $rows[0];
if( !empty( $repair ) ) {
$name = $repair->r_name . ' - '. $name;
}
}
return $name;
}
function rp_add_repair_name_fix_filter() {
add_filter('rp_preparing_attributes_name', 'rp_repair_name_fix_filter', 10, 2);
}
function rp_remove_repair_name_fix_filter() {
remove_filter('rp_preparing_attributes_name', 'rp_repair_name_fix_filter', 10, 2);
}
function rp_get_wordpress_upload_path() {
$upload_dir = wp_upload_dir();
return $upload_dir['basedir'];
}
function rp_get_wordpress_upload_dir_url() {
$upload_dir = wp_upload_dir();
return $upload_dir['baseurl'];
}
function rp_get_site_domain() {
$site_url = get_site_url();
$site_url = str_replace('http://', '', $site_url);
$site_url = str_replace('https://', '', $site_url);
$site_url = str_replace('/', '', $site_url);
return $site_url;
}
function rp_download_temp_image_for_pdf( $link = '' ) {
$imageData = rp_fetch_image_from_base( str_replace( ' ', '%20', trim( $link ) ) );
if(empty($imageData)) {
return '';
}
$only_file_name = explode('/', $link);
$only_file_name = $only_file_name[(count($only_file_name) - 1)];
$wp_upload_dir = wp_upload_dir();
$upload_path = $wp_upload_dir['path'];
$uniqueFileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $upload_path.'/'.str_replace(array(':', '_', ' ', '!', '@', '#', '$','%','^','&','*','(',')', ',', '=', '+'), '-', $only_file_name));
$fileExtension = '';
$mayBeFileExtension = substr($uniqueFileName, (strlen($uniqueFileName) - 8));
$mayBeFileExtension = explode('.', $mayBeFileExtension);
$mayBeFileExtension = $mayBeFileExtension[(count($mayBeFileExtension) - 1)];
if(file_exists($uniqueFileName)) {
$uniqueFileName = str_replace('.'.$mayBeFileExtension, '', $uniqueFileName);
$uniqueFileName .= '-'.uniqid() . '.' . $mayBeFileExtension;
}
file_put_contents($uniqueFileName, $imageData);
$url = $wp_upload_dir['url'] . '/' . basename( $uniqueFileName );
return $url;
}
function rp_get_correct_image_path_for_pdf( $url = '' ) {
$old = $url;
if( strpos( $url, rp_get_site_domain() ) === FALSE ) {
$url = rp_download_temp_image_for_pdf( $url );
}
$url = rp_fix_www_image_pdf_issue( $url );
$path = str_replace(rp_get_wordpress_upload_dir_url(), rp_get_wordpress_upload_path(), $url);
$last_five_letters = substr($path, -5);
// convert webp to png
if( $last_five_letters === '.webp' ) {
$path = rp_convert_image_to_png_if_it_is_webp( $path );
$last_five_letters = substr($path, -5);
if( $last_five_letters !== '.webp' ) {
// meaning .webp is converted to png
$url = str_replace('.webp', '.png', $url);
}
}
return array( $url, $path );
}
function rp_fix_www_image_pdf_issue( $the_image = '' ) {
$site_url = rp_get_wordpress_upload_dir_url();
// replace www. from site url
$site_url = str_replace('//www.', '//', $site_url);
// replace www. from company logo url
$the_image = str_replace('//www.', '//', $the_image);
$site_url_with_https = str_replace('http://', 'https://', $site_url);
$site_url_with_http = str_replace('https://', 'http://', $site_url_with_https);
// replace site url from company logo url
$the_image = str_replace($site_url_with_https, '', $the_image);
$the_image = str_replace($site_url_with_http, '', $the_image);
// readd original site url
$the_image = rp_get_wordpress_upload_dir_url().$the_image;
return $the_image;
}
function rp_get_company_theme_color() {
global $rpQuery;
$company_information = $rpQuery->prefix . "rs_company_information";
$company_results = $rpQuery->get_results("SELECT * FROM `$company_information`");
$theme_color = $company_results[0]->company_theme_color;
if( !empty( $theme_color ) ) {
return $theme_color;
}
return '2781c7';
}
function rp_get_customer_address_lines( $user_pdf_row = NULL ) {
if( empty( $user_pdf_row ) ) {
return array('', '');
}
$sorted_fields = rp_get_sorted_customer_address_fields();
$key_pairs = array(
'house_no' => 'house_no',
'street_address' => 'streetname_phone',
'user_city' => 'zipcode_city',
'user_zipcode' => 'zipcode_only'
);
$address_lines = array();
$address_lines_final = array();
foreach( $sorted_fields as $theSortedField ) {
$row_key = $key_pairs[ $theSortedField ] ?? '';
if( !empty( $row_key ) ) {
$address_lines[] = ($user_pdf_row->{$row_key} ?? '');
}
}
// if line 1 and line 2 are not empty, then add a comma between them
if( !empty( $address_lines[0] ) && !empty( $address_lines[1] ) ) {
$address_lines_final[] = $address_lines[0] . ', ' . $address_lines[1];
} else {
$address_lines_final[] = trim( $address_lines[0] . ' ' . $address_lines[1] );
}
// if line 3 and line 4 are not empty, then add a comma between them
if( !empty( $address_lines[2] ) && !empty( $address_lines[3] ) ) {
$address_lines_final[] = $address_lines[2] . ', ' . $address_lines[3];
} else {
$address_lines_final[] = trim( $address_lines[2] . ' ' . $address_lines[3] );
}
return $address_lines_final;
}
function rp_handle_currency_position_in_pdf($amount = 0, $currency = '', $add_space = FALSE) {
$currency_position = rp_get_option('rp_set_price_symbol', 'left');
$space = ($add_space === TRUE ? ' ' : '');
if( $currency == 'د.إ' || $currency == 'ریال' ) {
$currency_position = 'right';
$currency = ' <span style="direction:rtl; font-family:DejaVuSans;">'. $currency . '</span>';
}
if($currency_position == 'left') {
return $currency.$space.$amount;
} else {
return $amount.$space.$currency;
}
}
function rp_convert_image_to_png_if_it_is_webp( $imagePath = '' ) {
try {
if( !file_exists( $imagePath ) ) {
return $imagePath;
}
// check if already png
$ext = pathinfo($imagePath, PATHINFO_EXTENSION);
if( strtolower($ext) !== 'webp' ) {
// Looks already good!
return $imagePath;
}
// convert to png
$pngPath = str_replace('.'.$ext, '.png', $imagePath);
// if png already exists, return
if( file_exists($pngPath) ) {
return $pngPath;
}
$image = imagecreatefromstring(file_get_contents($imagePath));
if( $image !== false ) {
imagepng($image, $pngPath, 0);
imagedestroy($image);
return $pngPath;
} else {
return $imagePath;
}
} catch( Exception|Error $e ) {
return $imagePath;
}
}
function rp_handle_sending_pdf_offer( $received_o_id = '' ) {
global $rpQuery;
global $wp_repair_lang;
global $wp_repair_selected_language;
$rs_localization = $rpQuery->prefix . "rs_localization";
$rs_model = $rpQuery->prefix. "rs_model";
$rs_brand = $rpQuery->prefix. "rs_brand";
$rs_user_pdfs = $rpQuery->prefix. "rs_user_pdfs";
$rs_customer = $rpQuery->prefix. "rs_customer";
$rs_orders = $rpQuery->prefix. "rs_orders";
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$rs_order_repairs = $rpQuery->prefix. "rs_order_repairs";
$rs_order_repair_attr = $rpQuery->prefix. "rs_order_repair_attr";
$rs_order_upsales = $rpQuery->prefix. "rs_order_upsales";
$tax_row = $rpQuery->get_row("SELECT * FROM $rs_localization LIMIT 1;");
if( !empty( $tax_row ) ) {
$tax = $tax_row->tax;
} else {
$tax = 0;
}
$order_row = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE o_id = '$received_o_id' LIMIT 1;");
if( empty( $order_row ) ) {
return FALSE;
}
$mid = $order_row->m_id_fk;
$rp_location_id_fk = $order_row->location_id_fk;
$selected_location_row = $rpQuery->get_row("SELECT * FROM `$rs_company_location` WHERE location_id = '$rp_location_id_fk' LIMIT 1;");
$model_name = '';
if( !empty( $mid ) ) {
$model_row = $rpQuery->get_row("SELECT m_id, m_name FROM $rs_model WHERE m_id = ':m_id' LIMIT 1;", array(
'm_id' => $mid
));
if( empty( $model_row ) ) {
$mid = 0;
} else {
$model_name = $model_row->m_name;
}
}
list( $rpCart, $calculations ) = rp_get_latest_order_calculations( $received_o_id );
$combo = $calculations['combo_discount'];
$coupon = $calculations['coupon_amount'];
$final_price = $calculations['total'];
$coupon_info = $rpCart->get_coupon_info();
$rid = array();
$aid = array();
$upid = array();
foreach( $rpCart->repairs as $cartRow ) {
$rid[] = $cartRow->r_id;
}
foreach( $rpCart->repair_attrs as $cartRow ) {
$rid[] = $cartRow->r_id_fk;
$aid[] = $cartRow->a_id;
}
foreach( $rpCart->upsales as $cartRow ) {
$upid[] = $cartRow->upsales_id;
}
rp_add_repair_name_fix_filter();
$prepared_post_data = $rpCart->prepare_post_data( $rid, $upid );
rp_remove_repair_name_fix_filter();
list( $rid, $array_name, $array_price, $aid, $upid ) = $prepared_post_data;
$order_id_fk = $received_o_id;
$color_name = $order_row->color;
$customer_id_fk = $order_row->customer_id_fk;
$user_pdf_row = $rpQuery->get_row("SELECT * FROM `$rs_user_pdfs` WHERE `o_id_fk` = '$received_o_id' LIMIT 1;");
$pdf_date_time = date('Y-m-d H:i:s');
$customer_row = $rpQuery->get_row("SELECT * FROM `$rs_customer` WHERE `customer_id` = '$customer_id_fk' LIMIT 1;");
if( !empty( $customer_row ) ) {
$user_name = $customer_row->customer_name;
$user_phone = $customer_row->customer_phone;
$email = $customer_row->customer_email;
} else {
$user_name = '--';
$user_phone = '--';
$email = '';
}
if( !empty( $user_pdf_row ) ) {
$user_country = rp_get_single_translated_country_name($user_pdf_row->user_country ?? '');
$street_phone = $user_pdf_row->streetname_phone;
$house_no = $user_pdf_row->house_no ?? '';
if( !empty( $house_no ) ) {
$street_phone = $house_no . ', ' . $user_pdf_row->streetname_phone;
}
$zipcode_city = $user_pdf_row->zipcode_city . ', '. $user_pdf_row->zipcode_only;
list( $street_phone, $zipcode_city ) = rp_get_customer_address_lines( $user_pdf_row );
$notes = $user_pdf_row->notes ?? '';
$user_pdf_row->finalize_link = rp_override_reschedule_or_finalize_link( $user_pdf_row->finalize_link );
$finalize_btn_link = $user_pdf_row->finalize_link;
$offer_id = $user_pdf_row->user_pdfs_id;
$rpQuery->query("UPDATE `$rs_user_pdfs` SET `pdf_date_time` = '{$pdf_date_time}' WHERE `o_id_fk` = '$received_o_id' LIMIT 1;");
} else {
$user_country = '';
$street_phone = '';
$zipcode_city = '';
$notes = '';
$finalize_btn_link = '';
$offer_id = '0';
}
if( rp_get_option('rp_is_enabled_pdf_field_customer_address', '1') == '0' ) {
$user_country = '';
$street_phone = '';
$zipcode_city = '';
} else {
// It is either 1 (Required) or 2 (Optional)
$street_phone = trim( ltrim( rtrim( trim( $street_phone ), ',' ), ',' ) );
$street_phone = preg_replace('/\s+/', ' ', $street_phone);
$zipcode_city = trim( ltrim( rtrim( trim( $zipcode_city ), ',' ), ',' ) );
$zipcode_city = preg_replace('/\s+/', ' ', $zipcode_city);
}
if( rp_get_option('rp_is_enabled_pdf_field_imei_number', '2') == '0' ) {
$notes = '';
} else {
// It is either 1 (Required) or 2 (Optional)
}
if(!empty($mid)) {
$cmodel = $rpQuery->get_results("SELECT * FROM `$rs_model` WHERE m_id = '".rp_escape_sql($mid)."' LIMIT 1;");
} else {
$cmodel = $rpQuery->get_results("SELECT * FROM `$rs_model` WHERE m_name = '".rp_escape_sql($model_name)."' LIMIT 1;");
}
$brand_name = '';
if(!empty($cmodel)) {
$bid = $cmodel[0]->brand_id_fk;
$cbrand = $rpQuery->get_results("SELECT * FROM `$rs_brand` WHERE b_id = '".rp_escape_sql($bid)."'");
if(!empty($cbrand)) {
$brand_name = $cbrand[0]->b_name . ' ';
}
}
$etp = 1 + (($tax * 1) / 100);
$ex_tax_price = $final_price/$etp;
$total_tax = (float)$final_price - (float)$ex_tax_price;
$total_tax = number_format((float)$total_tax, 2, '.', '');
$ex_tax_price = number_format((float)$ex_tax_price, 2, '.', '');
$company_information = $rpQuery->prefix . "rs_company_information";
$c_results = $rpQuery->get_results("SELECT * FROM $company_information");
$company_location = $rpQuery->prefix . "rs_company_location";
$company_address = $rpQuery->get_results("SELECT * FROM $company_location");
if( rp_is_active_enhanced_locations_addon() === true ) {
if( !empty( $selected_location_row ) && !empty( $selected_location_row->location_email ?? '' ) ) {
$c_results[0]->company_email = $selected_location_row->location_email;
}
if( !empty( $selected_location_row ) && !empty( $selected_location_row->location_telephone ?? '' ) ) {
$c_results[0]->company_phone = $selected_location_row->location_telephone;
}
if( !empty( $selected_location_row ) ) {
$company_address = array( $selected_location_row );
}
}
$rs_localization = $rpQuery->prefix . "rs_localization";
$localization = $rpQuery->get_results("SELECT * FROM $rs_localization");
$tax_indicator = $localization[0]->tax_indicator;
$tax_indicator = $wp_repair_lang['tax'];
$p_symbol = $localization[0]->set_currency;
$decimal = $localization[0]->set_decimals;
if(strpos($total_tax, '.') === FALSE) {
$total_tax = number_format((float)$total_tax, 2, '.', '');
}
if(!empty($combo)) {
$combo = number_format((float)$combo, 2, '.', '');
}
if(!empty($coupon)) {
$coupon = number_format((float)$coupon, 2, '.', '');
}
$final_price = number_format((float)$final_price, 2, '.', '');
if($decimal == 'comma'){
$ex_tax_price = str_replace('.',',',$ex_tax_price);
$total_tax = str_replace('.',',',$total_tax);
$final_price = str_replace('.',',',$final_price);
if(!empty($combo)) {
$combo = str_replace('.', ',', $combo);
}
if(!empty($coupon)) {
$coupon = str_replace('.', ',', $coupon);
}
}
require_once plugin_dir_path( WP_REPAIR_PLUGIN_FILE).'html/front_end/dompdf/autoload.inc.php';
require_once plugin_dir_path( WP_REPAIR_PLUGIN_FILE ).'html/front_end/App/autoload_arabic.php';
$file_name = $wp_repair_lang['pdf_offer_filename'].pretty_offer_id($offer_id).'.pdf';
$pdf = new RPDompdf\Dompdf();
$font_family = 'font-family: Arial, sans-serif;';
$montSerratBoldFontFamily = 'font-family: \'Montserrat-Bold\'; font-weight: 700;';
$montSerratRegularFontFamily = 'font-family: \'Montserrat-Regular\';';
$montSerratMediumFontFamily = 'font-family: \'Montserrat-Medium\';';
$rightDirectionLanguages = array('Arabic');
$isRightDirection = FALSE;
foreach( $rightDirectionLanguages as $rightDirectionLanguage ) {
if( strpos( $wp_repair_selected_language, $rightDirectionLanguage ) !== FALSE ) {
$isRightDirection = TRUE;
break;
}
}
$datesCol1Width = 70;
$datesCol2Width = 30;
$headCol1Width = 51;
$headCol2Width = 49;
$headRightColWidthTable = '100%';
$headRightColWidth1 = '100px';
$headRightColWidth2 = '205px';
$quotation_text_dates_TableWidth = '100%';
$quotation_text_dates_TableWidthCol1 = '60%';
$quotation_text_dates_TableWidthCol2 = '40%';
$expirationDateTd = '<td width="'.$quotation_text_dates_TableWidthCol1.'" style="text-align:right" class="font-envelope">'.$wp_repair_lang['expiration_date'].':</td>';
$actualQuotationDirection = '';
$quotationTd = '<td width="'.$datesCol1Width.'%"><h2><span>'.$wp_repair_lang['quotation'].' '.pretty_offer_id($offer_id).'</span></h2></td>';
if( $isRightDirection == TRUE ) {
$headRightColWidthTable = '325px';
$headRightColWidth1 = '120px';
$headRightColWidth2 = '205px';
$expirationDateTd = '<td width="'.$quotation_text_dates_TableWidthCol1.'" style="text-align:right; position:relative;" class="font-envelope"><span style="position:absolute; right: -25px; top: 0px;">'.$wp_repair_lang['expiration_date'].':</span></td>';
$datesCol1Width = 60;
$datesCol2Width = 40;
$headCol1Width = 48;
$headCol2Width = 52;
$font_family = 'font-family: \'DejaVuSans\'; direction: rtl;';
$montSerratBoldFontFamily = 'font-family: \'DejaVuSans\'; direction: rtl;';
$montSerratMediumFontFamily = 'font-family: \'DejaVuSans\'; direction: rtl;';
$montSerratRegularFontFamily = 'font-family: \'DejaVuSans\'; direction: rtl;';
$actualQuotationDirection = '
.actual-quotation-number {
direction: ltr;
}
';
$quotationTd = '<td width="'.$datesCol1Width.'%"><h2><span>'.$wp_repair_lang['quotation'].'</span> <span class="actual-quotation-number">'.pretty_offer_id($offer_id).'</span></h2></td>';
}
$html = '';
$rp_theme_color = rp_get_company_theme_color();
$html .= '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; content="charset=utf-8" />
<style type="text/css">
* {
'.$font_family.'
}
body, html {
width: 100%;
padding: 0px;
margin: 0px;
}
table td {
'.$montSerratMediumFontFamily.'
font-size: 13px;
}
body {
padding: 50px 55px;
position: relative;
}
.company-details {
border-spacing: 0px;
margin-top: 8px;
}
.company-details td {
font-size: 14px;
}
.quotation_text_dates {
border-spacing: 0px;
}
.medium {
'.$montSerratMediumFontFamily.'
line-height: 1.4em;
}
.medium.addr {
line-height: 1em;
}
td, th, p {
font-size: 14px;
line-height: 1em;
}
h1, h2, h3, h4, h5, h6, p {
display: table;
}
h2 {
display: inline-table;
float: left;
margin:0px;
padding:0px;
line-height: 1em;
}
.quotation_text td {
border-spacing: 0px;
margin:0px;
padding:25px 0px;
vertical-align: middle;
}
.p-table {
border-spacing: 0px;
}
.quotation_text {
padding: 0px;
padding-top: 50px;
}
.company-logo {
display: block;
margin: 0px;
padding: 0px;
position: absolute;
top: 15px;
}
.font-envelope {
font-size: 12px;
'.$montSerratMediumFontFamily.'
}
.font-dates {
font-size: 12px;
'.$montSerratMediumFontFamily.'
direction: ltr;
}
.customer-details {
display: table;
margin: 0px;
padding: 0px;
position: absolute;
top: 185px;
left: 100px;
}
.font-envelope-customer-details {
'.$montSerratRegularFontFamily.'
font-size: 9px;
letter-spacing: 1px;
padding-bottom: 7px;
color: #5a5a5a;
}
.quotation_text_dates td {
padding: 0px;
}
.p-text {
line-height: 1.3em;
'.$montSerratMediumFontFamily.'
font-size: 13px;
}
h2 span,b {
'.$montSerratBoldFontFamily.'
}
'.$actualQuotationDirection.'
.no-border-spacing,
.no-border-spacing tr,
.no-border-spacing tr td,
.no-border-spacing img,
.no-border-spacing span,
.no-border-spacing span.medium,
.no-border-spacing h4,
.no-border-spacing h2,
.no-border-spacing b {
border-spacing: 0px;
padding: 0px;
margin: 0px;
line-height: 1em;
}
.no-border-spacing tr td {
padding: 5px;
vertical-align:top;
}
.no-border-spacing.location-table tr td {
padding: 0px 5px;
}
.t-align-center {
text-align:center;
}
.t-align-right {
text-align:right;
}
.icon,
.location-icon,
.phone-icon {
padding-top: 3px;
}
.icon-text {
font-size: 10px;
padding-top: 4px;
}
.location-table.city-district {
padding-bottom: 22px;
}
.long_email {
font-size: 12px;
}
.percent-off-badge {
'.$montSerratBoldFontFamily.'
font-size: 10px;
background: #fff;
color: #'.$rp_theme_color.';
border: 1px solid #'.$rp_theme_color.';
line-height: 9px;
text-transform: uppercase;
padding: 0px 5px 0px 5px !important;
box-sizing: border-box;
border-radius: 6px;
vertical-align: middle;
white-space: nowrap;
display: inline-block;
height: 14px;
width: auto;
margin-left: 5px;
margin-top:2px;
}
</style>
<title>Offer PDF</title>
</head>
<body>';
if(strtolower($tax_indicator) === 'vat') {
$tax_indicator_cd = 'VAT';
} else if(strtolower($tax_indicator) === 'btw') {
$tax_indicator_cd = 'btw';
} else {
$tax_indicator_cd = $tax_indicator;
}
$tax_indicator_id = $wp_repair_lang['registeration_id'];
if(!empty($c_results[0]->company_logo) && $c_results[0]->company_logo !== 'http://site.com/picture') {
list( $correct_url, $correct_path ) = rp_get_correct_image_path_for_pdf( $c_results[0]->company_logo );
$c_results[0]->company_logo = $correct_url;
$company_logo_img_path = $correct_path;
list($company_logo_img_size_w, $company_logo_img_size_h) = getimagesize($company_logo_img_path);
$company_logo_img = '<img class="company-logo" src="'.rp_encode_img_base64($c_results[0]->company_logo).'" '.rp_get_company_logo_width_height_attrs($company_logo_img_size_w, $company_logo_img_size_h).'>';
} else {
$company_logo_img = '';
}
if(strlen($c_results[0]->company_email) > 24) {
$long_email = 'long_email';
} else {
$long_email = '';
}
if(strtolower($tax_indicator_cd) === 'btw') {
$tax_indicator_cd = 'Btw';
$tax_indicator_cd_small = 'btw';
$tax_indicator = 'Btw';
} else {
$tax_indicator_cd = $tax_indicator_cd;
$tax_indicator_cd_small = $tax_indicator_cd;
}
if(!empty($cmodel[0]->m_img) && $cmodel[0]->m_img !== 'http://site.com/picture') {
list( $correct_url, $correct_path ) = rp_get_correct_image_path_for_pdf( $cmodel[0]->m_img );
$cmodel[0]->m_img = $correct_url;
$m_img_path = $correct_path;
list($m_img_size_w, $m_img_size_h) = getimagesize($m_img_path);
$m_img = '<img class="company-logo" src="'.rp_encode_img_base64($cmodel[0]->m_img).'" '.rp_get_m_img_width_height_attrs($m_img_size_w, $m_img_size_h).'>';
} else {
$m_img = '';
}
$device_imei_number = $wp_repair_lang['imei'].' '.$notes;
if( empty( $notes ) ) {
$device_imei_number = '';
}
// get only normal alphanumberic
$tax_indicator_id_cls = preg_replace('/[^a-zA-Z0-9]/', '', $tax_indicator_id);
$taxRegNoIcon = '<td width="'.$headRightColWidth1.'" class="t-align-right"><div class="icon-text"><b>'.$tax_indicator_cd_small.'</b></div></td>';
$companyRegNoIcon = '<td width="'.$headRightColWidth1.'" class="t-align-right"><div class="icon-text '.strtolower(str_replace(' ', '-', $tax_indicator_id_cls)).'"><b>'.$tax_indicator_id.'</b></div></td>';
if( $isRightDirection == TRUE ) {
$taxRegNoIcon = '<td width="'.$headRightColWidth1.'" class="t-align-right" style="position:relative;"><div style="position:absolute; right:-15px;" class="icon-text"><b>'.$tax_indicator_cd_small.'</b></div></td>';
$companyRegNoIcon = '<td width="'.$headRightColWidth1.'" class="t-align-right" style="position:relative;"><div style="position:absolute; right:-20px;" class="icon-text '.strtolower(str_replace(' ', '-', $tax_indicator_id_cls)).'"><b>'.$tax_indicator_id.'</b></div></td>';
}
$taxRegNoTr = '';
if( !empty( trim( $c_results[0]->tax_reg_no ) ) ) {
$taxRegNoTr = '
<tr>
<td>
<table width="'.$headRightColWidthTable.'" class="no-border-spacing icon-text-table">
<tr>
'.$taxRegNoIcon.'
<td width="'.$headRightColWidth2.'"><span class="medium">'.$c_results[0]->tax_reg_no.'</span></td>
</tr>
</table>
</td>
</tr>
';
}
$companyRegNoTr = '';
if( !empty( trim( $c_results[0]->company_reg_no ) ) ) {
$companyRegNoTr = '
<tr>
<td>
<table width="'.$headRightColWidthTable.'" class="no-border-spacing icon-text-table">
<tr>
'.$companyRegNoIcon.'
<td width="'.$headRightColWidth2.'"><span class="medium">'. $c_results[0]->company_reg_no.'</span></td>
</tr>
</table>
</td>
</tr>
';
}
$taxIndicatorTh = '<td width="15%" style="text-transform: capitalize;text-align: right"><b>'.$wp_repair_lang['pdf_repair_amount'].'</b></td>
<td width="10%" style="text-transform: capitalize;text-align: right"><b>'.$tax_indicator.'</b></td>';
if( $isRightDirection == TRUE ) {
$taxIndicatorTh = '
<td width="18%" style="text-transform: capitalize;text-align: right"><b>'.$wp_repair_lang['pdf_repair_amount'].'</b></td>
<td width="7%" style="text-transform: capitalize;text-align: right"><b>'.$tax_indicator.'</b></td>';
}
$html .= '<table width="100%">
<tr>
<td width="'.$headCol1Width.'%">'.$company_logo_img.'</td>
<td width="'.$headCol2Width.'%">
<table class="company-details">
<tr>
<td>
<table width="'.$headRightColWidthTable.'" class="no-border-spacing location-table">
<tr>
<td width="'.$headRightColWidth1.'" class="t-align-right">'.show_dompdf_svg('location').'</td>
<td width="'.$headRightColWidth2.'"><h4><b>'.$c_results[0]->company_name.'</b></h4></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="'.$headRightColWidthTable.'" class="no-border-spacing location-table">
<tr>
<td width="'.$headRightColWidth1.'" class="t-align-right"> </td>
<td width="'.$headRightColWidth2.'"><span class="medium addr">'.$company_address[0]->location_address.'</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="'.$headRightColWidthTable.'" class="no-border-spacing location-table city-district">
<tr>
<td width="'.$headRightColWidth1.'" class="t-align-right"> </td>
<td width="'.$headRightColWidth2.'"><span class="medium addr">'.$company_address[0]->location_city_district.'</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="'.$headRightColWidthTable.'" class="no-border-spacing">
<tr>
<td width="'.$headRightColWidth1.'" class="t-align-right">'.show_dompdf_svg('email').'</td>
<td width="'.$headRightColWidth2.'"><span class="medium '.$long_email.'">'. $c_results[0]->company_email.'</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="'.$headRightColWidthTable.'" class="no-border-spacing">
<tr>
<td width="'.$headRightColWidth1.'" class="t-align-right">'.show_dompdf_svg('phone').'</td>
<td width="'.$headRightColWidth2.'"><span class="medium">'. $c_results[0]->company_phone.'</span></td>
</tr>
</table>
</td>
</tr>
'.$companyRegNoTr.'
'.$taxRegNoTr.'
</table>
</td>
</tr>
</table>
<table width="100%" class="customer-details">
<tr>
<td class="font-envelope-customer-details">'.$wp_repair_lang['customer_details'].'</td>
</tr>
<tr>
<td class="font-envelope">'.$user_name.'</td>
</tr>
<tr>
<td class="font-envelope">'.$street_phone.'</td>
</tr>
<tr>
<td class="font-envelope">'.$zipcode_city.'</td>
</tr>
<tr>
<td class="font-envelope">'.($user_country ?? '').'</td>
</tr>
</table>
<table width="100%" style="margin: 10px 0px;" class="quotation_text">
<tr>
'.$quotationTd.'
<td width="'.$datesCol2Width.'%">
<table width="'.$quotation_text_dates_TableWidth.'" style="margin: 10px 0px; position:relative;" class="quotation_text_dates">
<tr>
<td width="'.$quotation_text_dates_TableWidthCol1.'" style="text-align:right" class="font-envelope">'.$wp_repair_lang['quotation_date'].':</td>
<td width="'.$quotation_text_dates_TableWidthCol2.'" style="text-align: right" class="font-dates">'.date('d-m-Y',strtotime($pdf_date_time)).'</td>
</tr>
<tr>
'.$expirationDateTd.'
<td width="'.$quotation_text_dates_TableWidthCol2.'" style="text-align: right" class="font-dates">'.date('d-m-Y',strtotime($pdf_date_time .' +'.rp_get_option('rp_expire_offer_after_x_days', 14).' days')).'</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="margin-top:0px;">
<div style="display:inline-block; margin-top:-60px; ">'.$m_img.'</div>
<table width="100%" style="margin-top:-50px; margin-left:55px;" class="quotation_text_dates">
<tr>
<td width="65%" style="line-hright:1.3em; text-transform:capitalize !important ; '.$montSerratRegularFontFamily.' font-size:9px; letter-spacing:1px ; padding-bottom:3px; color:#5a5a5a; ">
'.strtoupper($wp_repair_lang['device_details']).'
</td>
</tr>
<tr>
<td width="65%" style="line-height:1.1em; font-size:12px; text-transform:caplitalize;">
'.$brand_name.$model_name.'
</td>
</tr>
<tr>
<td width="65%" style="line-height:1.1em; font-size:12px; text-transform:caplitalize;">
'.$color_name.'
</td>
</tr>
<tr>
<td width="65%" style="line-height:1.1em; font-size:12px; text-transform:caplitalize;">
'.$device_imei_number.'
</td>
</tr>
</table>
</td>
</tr>
</table>
<table class="p-table" width="100%" style="margin: -10px 0px 10px 0px;">
<tr>
<td style="margin:0px 0px 5px 0px" class="p-text">'.$wp_repair_lang['dear'].' <span>'.$user_name.'</span>,</td>
</tr>
</table>
<table class="p-table" width="100%" style="margin: 10px 0px;">
<tr>
<td style="margin:5px 0px" class="p-text">'.$wp_repair_lang['appointment_offer_thank_you_message'].'</td>
</tr>
</table>
<table width="100%" style="margin: 25px 0px 0px 0px;border-bottom: 1px solid; padding: 5px 0px;">
<tr>
<td width="10%" style="text-transform: capitalize"></td>
<td width="65%" style="text-transform: capitalize;"><b>'.$wp_repair_lang['repairs'].'</b></td>
'.$taxIndicatorTh.'
</tr>
</table>';
if($array_name){
$array_name_count = count($array_name);
$array_name_worked = 0;
foreach($array_name as $i => $a_name){if($a_name != ''){
$array_name_worked++;
if($array_name_worked === $array_name_count) {
$border_bottom = '1px solid #000';
} else {
$border_bottom = '0.8px solid #929292';
}
//correct_repair_ids_order
$repair_details = $rpCart->correct_repair_ids_order[ $i ] ?? array();
$is_discounted_price = '';
if(!empty( $repair_details ) && $repair_details['type'] != 'upsale') {
list($is_discounted_price, $discounted_price) = $rpCart->showable_repair_price( $repair_details['id'], $repair_details['type'] );
$array_price[$i] = $discounted_price;
}
$repair_ex_tax_price = $array_price[$i];
$repair_ex_tax_price = number_format((float)$repair_ex_tax_price, 2, '.', '');
if($decimal == 'comma'){
$repair_ex_tax_price = str_replace('.',',',$repair_ex_tax_price);
}
$percent_off_badge_text = '';
if( $is_discounted_price == '1' ) {
if( $rpCart->get_combo_discount_percentage() > 0 ) {
$percent_off_badge_text = '<span class="percent-off-badge">'.$rpCart->get_combo_discount_percentage().'% '.$wp_repair_lang['combo_discount_percent_off'].'</span>';
} else {
if( $isRightDirection == TRUE ) {
$percent_off_badge_text = '<span class="percent-off-badge"><span>'.$wp_repair_lang['combo_discount_percent_off'].'</span>'.rp_handle_currency_position_in_pdf($rpCart->get_combo_discount(), $localization[0]->set_currency, FALSE).'</span>';
} else {
$percent_off_badge_text = '<span class="percent-off-badge">'.rp_handle_currency_position_in_pdf($rpCart->get_combo_discount(), $localization[0]->set_currency, FALSE).' '.$wp_repair_lang['combo_discount_percent_off'].'</span>';
}
}
}
$html .=
'<table width="100%" style="margin: 0px;padding: 8px 0px 7px 0px;border-bottom: '.$border_bottom.';">
<tr>
<td width="10%" style="direction:ltr;">1 x</td>
<td width="65%" style="line-height: 1em; text-transform: capitalize;">'. $brand_name.$model_name.' - '.$a_name.$percent_off_badge_text.'</td>
<td width="15%" style="line-height: 1em; text-transform: capitalize;text-align: right; direction:ltr;">'.rp_handle_currency_position_in_pdf($repair_ex_tax_price, $p_symbol, TRUE).'</td>
<td width="10%" style="line-height: 1em; text-transform: capitalize;text-align: right">'.$tax.'%</td>
</tr>
</table>';
} } }
if(!empty($combo)) {
$html .= '<table width="90%" style="text-align:right; margin: 0px;padding: 8px 0px 0px 0px;">
<tr>
<td width="85%" style="line-height: 1em; text-transform: capitalize;text-align: right;">'.$wp_repair_lang['discount'].'</td>
<td style="line-height: 1em; text-transform: capitalize;text-align: right; direction:ltr;">'.rp_handle_currency_position_in_pdf($combo, $p_symbol, TRUE).'</td>
</tr>
</table>
';
}
if(!empty($coupon_info) && ($coupon_info->coupons_type ?? '') == 'percent') {
$coupon_td_first = $wp_repair_lang['coupon_discount'] . ' (' . $coupon_info->coupons_amount . '%)';
} else {
$coupon_td_first = $wp_repair_lang['coupon_discount'];
}
if(!empty($coupon)) {
$html .= '<table width="90%" style="text-align:right; margin: 0px;padding: 8px 0px 0px 0px;">
<tr>
<td width="85%" style="line-height: 1em; text-transform: capitalize;text-align: right;">'.$coupon_td_first.'</td>
<td style="line-height: 1em; text-transform: capitalize;text-align: right; direction:ltr;">'.rp_handle_currency_position_in_pdf($coupon, $p_symbol, TRUE).'</td>
</tr>
</table>
';
}
$excludingTextTd = '<td width="85%" style="line-height: 1em;text-transform: capitalize;text-align: right;"><b>'.trim( $wp_repair_lang['subtotal'].' '.trim( $wp_repair_lang['excluding_short_form'] ).' '.trim($tax_indicator) ).'</b></td>';
$taxIndicatorTd = '<td width="85%" style="line-height: 1em; text-transform: capitalize;text-align:right;margin-left:auto;float:right">'.$tax.'% '.$tax_indicator.'</td>';
$theTotalTd = '<td width="85%" style="text-transform: capitalize;text-align: right;margin: 0px;padding: 2px 0px 0px 0px; line-height: 1em;"><b>'.$wp_repair_lang['total'].'</b></td>';
if( $isRightDirection == TRUE ) {
$excludingTextTd = '<td width="540px" style="line-height: 1em;text-transform: capitalize;text-align: right;"><b>'.trim( $wp_repair_lang['subtotal'].' '.trim( $wp_repair_lang['excluding_short_form'] ).' '.trim($tax_indicator) ).'</b></td>';
$theTotalTd = '<td width="500px" style="text-transform: capitalize;text-align: right;margin: 0px;padding: 2px 0px 0px 0px; line-height: 1em;"><b>'.$wp_repair_lang['total'].'</b></td>';
}
$html .=
'<table width="90%" style="text-align:right; margin: 0px;padding: 6px 0px 0px 0px;">
<tr>
'.$excludingTextTd.'
<td style="line-height: 1em; text-transform: capitalize;text-align: right; direction:ltr;">'.rp_handle_currency_position_in_pdf($ex_tax_price, $p_symbol, TRUE).'</td>
</tr>
</table>
<table width="90%" style="text-align:right; margin: 0px;padding: 6px 0px 0px 0px;">
<tr>
'.$taxIndicatorTd.'
<td style="text-transform: capitalize;text-align: right; direction:ltr;">'.rp_handle_currency_position_in_pdf($total_tax, $p_symbol, TRUE).'</td>
</tr>
</table>
<table width="90%" style="text-align:right;">
<tr>
<td width="50%"></td><td width="50%" style="line-height: 1em; border-bottom: 1px solid;text-align:right;margin: 0px;padding: 4px 0px 0px 0px;"></td>
</tr>
</table>
<table width="90%" style="text-align:right; margin-bottom: 25px;">
<tr>
'.$theTotalTd.'
<td style="text-transform: capitalize;text-align: right;margin: 0px;padding: 2px 0px 0px 0px; line-height: 1em;;"><b style="direction:ltr">'.rp_handle_currency_position_in_pdf($final_price, $p_symbol, TRUE).'</b></td>
</tr>
</table>
<table class="p-table" width="100%" style="margin: 10px 0px 10px 0px">
<tr>
<td class="p-text">'.$wp_repair_lang['do_not_hesitate_to_contact_us'].'</td>
</tr>
</table>
<table class="p-table" width="100%" style="margin: 10px 0px">
<tr>
<td class="p-text">'.$wp_repair_lang['kind_regards'].'</td>
</tr>
</table>
<table class="p-table" width="100%" style="margin: 10px 0px">
<tr>
<td class="p-text">'.$c_results[0]->company_name.'</td>
</tr>
</table>';
$html .= '</body>
</html> ';
$options = $pdf->getOptions();
$options->set(array('isRemoteEnabled' => true));
$pdf->setOptions($options);
$pdf->loadHtml($html);
$pdf->setPaper('A4', 'portrait');
$pdf->render();
// PDF Footer
$canvas = $pdf->get_canvas();
$the_text = $wp_repair_lang['appointment_offer_footer'];
$font = "Arial";
$font_size = 7;
$page_width = $canvas->get_width();
$page_height = $canvas->get_height();
$max_width = 0.86 * $page_width;
$lines = array();
$line = "";
if ( $isRightDirection == TRUE ) {
$orgText = $the_text;
$Arabic = new \App\Libraries\I18N\I18N_Arabic('Glyphs');
$the_text = $Arabic->utf8Glyphs($the_text);
// explode arabic correctly
$words = explode(".", $the_text);
// reverse
$words = array_reverse($words);
foreach ($words as $word) {
$test_line = "." . $word . $line;
$test_width = $canvas->get_text_width($test_line, $font, $font_size);
if ($test_width > $max_width) {
$lines[] = $line;
$line = "." . $word;
} else {
$line = $test_line;
}
}
} else {
$words = explode(" ", $the_text);
foreach ($words as $word) {
$test_line = $line . $word . " ";
$test_width = $canvas->get_text_width($test_line, $font, $font_size);
if ($test_width > $max_width) {
$lines[] = $line;
$line = $word . " ";
} else {
$line = $test_line;
}
}
}
array_push($lines, $line);
$line_count = count($lines);
$line_height = $font_size * 1.5;
$total_height = $line_count * $line_height;
$start_y = $page_height - 30 - ( $total_height / 2 ) ;
for($i = 0; $i < $line_count; $i++) {
$theLineOfText = $lines[$i];
$y = $start_y + ($i * $line_height);
$text_width = $canvas->get_text_width($theLineOfText, $font, $font_size);
$center_position = ($page_width / 2) - ($text_width / 2);
$canvas->text($center_position, $y, $theLineOfText, $font, $font_size, array(0.5,0.5,0.5));
}
$file = $pdf->output();
if( defined( 'WP_REPAIR_DEVELOPMENT_MODE' ) ) {
file_put_contents(WP_REPAIR_PLUGIN_PATH.$file_name, $file);
echo json_encode(Array('status'=> true, 'message' => 'Successfully Sent'));
exit();
}
$wp_content = defined( 'WP_CONTENT_DIR' ) ? WP_CONTENT_DIR : (rp_get_wp_abs_path() . 'wp-content');
$file_name = $wp_content . DIRECTORY_SEPARATOR . $file_name;
file_put_contents($file_name, $file);
//$file_name = 'report_'.time();
// $pdf->load_html($html,'UTF-8');
// $pdf->render();
// $pdf->stream($file_name.".pdf");
$rs_notifications_and_offers = $rpQuery->prefix . "rs_notifications_and_offers";
$offers = $rpQuery->get_results("SELECT * FROM $rs_notifications_and_offers WHERE noti_type_id_fk ='2'");
$pdf_offer = $offers[0]->is_active;
if($pdf_offer == '1'){
$to = $email;
$email_translation_key = get_translation_key_by_noti_type_id($offers[0]->noti_type_id_fk);
$subject = $wp_repair_lang[$email_translation_key.'_email_subject'];
$message = $wp_repair_lang[$email_translation_key.'_email_template'];
$message = '<div class="display: block; width: 100%; margin-bottom: 20px;">'.$message.'</div>';
$link = $finalize_btn_link;
$headers = array('Content-Type: text/html; charset=UTF-8');
$mail_attachment = array($file_name);
include_once WP_REPAIR_PLUGIN_PATH.'html/order_emails.php';
$rp_theme_color = rp_get_company_theme_color();
$message = str_replace('$FinalizeButton$', '<br><p><a href="'.$link.'" style="background-color:#'.$rp_theme_color.'; color:white; padding:12px 20px; text-decoration:none; font-size: 1em;border-radius: 5px;margin: 20px 0px;">'.ucfirst(strtolower($wp_repair_lang['finalize_appointment'])).'</a></p><br>', $message);
$match = rp_find_link_pattern('finalize', $message);
if( !empty($match) && strpos($message, '[finalize=') !== FALSE ) {
$matchText = str_replace('[finalize="', '', $match);
$matchText = str_replace('[finalize="', '', $matchText);
$matchText = str_replace('"]', '', $matchText);
$matchText = str_replace('"]', '', $matchText);
$finalizeMarkup = '<br><p><a href="'.$link.'" style="background-color:#'.$rp_theme_color.'; color:white; padding:12px 20px; text-decoration:none; font-size: 1em;border-radius: 5px;margin: 20px 0px;">'.$matchText.'</a></p><br>';
$message = str_replace($match, $finalizeMarkup, $message);
}
$message_template = $message;
$message = wp_repair_prepare_order_email($order_id_fk, $subject, $message_template);
$subject = wp_repair_prepare_order_email_subject($order_id_fk, $subject);
if(!defined('WP_REPAIR_REQUIRE_LICENSE')) {
rp_mail_wrapper($to, $subject, $message, $headers, $mail_attachment);
$duplicate_email = wp_repair_admin_duplicate_email('2', rp_get_location_id_of_order($order_id_fk));
if(!empty($duplicate_email)) {
rp_wp_mail_change_sender_info($email, $user_name);
$message = wp_repair_prepare_order_email_for_admin($order_id_fk, $subject, $message_template);
rp_mail_wrapper($duplicate_email, $subject, $message, $headers, $mail_attachment);
}
}
unlink($file_name);
return TRUE;
}
return FALSE;
}
// where noti_type_id_fk = 5, check if is_active = 1 in rs_notifications_and_offers table
function rp_check_if_notifaction_is_active($noti_type_id_fk = 0){
if( $noti_type_id_fk === 0 ) {
return FALSE;
}
global $rpQuery;
$rs_notifications_and_offers = $rpQuery->prefix . "rs_notifications_and_offers";
$offer = $rpQuery->get_row("SELECT is_active FROM $rs_notifications_and_offers WHERE noti_type_id_fk = '$noti_type_id_fk' LIMIT 1;");
if($offer->is_active == '1'){
return TRUE;
}
return FALSE;
}
function rp_quick_debug_email( $oid = '', $is_newly_created = FALSE ) {
rp_add_action('init', function() use ($oid, $is_newly_created) {
rp_send_appointment_status_update_email( $oid, $is_newly_created, TRUE );
exit;
});
}
function rp_get_single_order_row_by_o_id( $order_id = '' ) {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$order_row = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '".rp_escape_sql( $order_id )."' LIMIT 1;");
return $order_row;
}
function rp_send_appointment_status_update_email( $oid = '', $is_newly_created = FALSE, $debugging = FALSE ){
global $rpQuery;
global $wp_repair_lang;
include_once WP_REPAIR_PLUGIN_PATH.'html/order_emails.php';
if( $debugging === TRUE ) {
if( !defined('WP_REPAIR_DEVELOPMENT_MODE') ) {
define('WP_REPAIR_DEVELOPMENT_MODE', TRUE);
}
}
rp_set_order_related_language($oid);
$rs_orders = $rpQuery->prefix . "rs_orders";
$rs_customer = $rpQuery->prefix . "rs_customer";
$rs_user_pdfs = $rpQuery->prefix . "rs_user_pdfs";
$rs_notifications_and_offers = $rpQuery->prefix . "rs_notifications_and_offers";
$order_row = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '$oid' LIMIT 1;");
$rp_which_action_when_por = rp_which_action_when_por();
if( $order_row->status_id_fk == 11 ) {
// Completed status doesn't have email at the moment...
return TRUE;
}
if( $order_row->status_id_fk == 2 && strtolower(trim($order_row->delivery_method)) == 'pdf offer' ) {
// When it is PDF Offer.. No matter what, it should be set to 'set_price'
$rp_which_action_when_por = 'set_price';
}
if($is_newly_created === TRUE && (!empty(rp_get_por_repairs_by_order_id( $oid )) || !empty(rp_get_por_repair_attr_by_order_id( $oid ))) && $rp_which_action_when_por == 'set_price' ) {
$order_row->status_id_fk = 5;
}
$_delivery_method = str_replace(' ', '_', strtolower(trim($order_row->delivery_method)));
if( $order_row->status_id_fk == 3 && $_delivery_method == 'ship_device' ) {
$order_row->status_id_fk = 6;
}
if( $order_row->status_id_fk == 3 && $_delivery_method == 'pickup_service' ) {
$order_row->status_id_fk = 9;
}
if( $order_row->status_id_fk == 3 && $_delivery_method == 'repair_on_location' ) {
$order_row->status_id_fk = 10;
}
$order_row->status_id_fk = apply_filters('rp_override_status_while_sending_email', $order_row->status_id_fk, $order_row);
$status = $order_row->status_id_fk;
$user_pdf_row = $rpQuery->get_row("SELECT * FROM `$rs_user_pdfs` WHERE `o_id_fk` = '$oid' LIMIT 1;");
if( $status == '2' && !empty( $user_pdf_row ) ) {
// Need to send an offer!
$pdf_result = rp_handle_sending_pdf_offer( $oid );
rp_unset_order_related_language();
return $pdf_result;
}
$customer_row = $rpQuery->get_row("SELECT * FROM `$rs_customer` WHERE `customer_id` = '{$order_row->customer_id_fk}' LIMIT 1;");
$user_name = $customer_row->customer_name;
$email = $customer_row->customer_email;
$rp_location_id = rp_get_location_id_of_order( $oid );
$offer = $rpQuery->get_row("SELECT * FROM $rs_notifications_and_offers WHERE `noti_type_id_fk` = '{$status}' LIMIT 1;");
$is_active = $offer->is_active;
$to = $email;
if( $is_active == '1' ) {
$email_translation_key = get_translation_key_by_noti_type_id($offer->noti_type_id_fk);
$subject = $wp_repair_lang[$email_translation_key.'_email_subject'];
$message_template = $wp_repair_lang[$email_translation_key.'_email_template'];
$message = wp_repair_prepare_order_email($oid, $subject, $message_template);
if( $debugging === TRUE ) {
print_r( $message );
exit;
}
$subject = wp_repair_prepare_order_email_subject($oid, $subject);
wp_repair_send_mail($to, $subject, $message);
$duplicate_email = wp_repair_admin_duplicate_email($status, $rp_location_id);
if(!empty($duplicate_email)) {
rp_wp_mail_change_sender_info($email, $user_name);
$bcc_email = rp_get_bcc_email_of_location( $rp_location_id );
// Re-create the message for admin
$message = wp_repair_prepare_order_email_for_admin($oid, $subject, $message_template);
wp_repair_send_mail($duplicate_email, $subject, $message, $bcc_email);
}
rp_unset_order_related_language();
return TRUE;
}
rp_unset_order_related_language();
return FALSE;
}
function rp_override_reschedule_or_finalize_link( $reschedule_link = '' ) {
if( empty( $reschedule_link ) ) {
// unexpected
return $reschedule_link;
}
$customBaseURL = rp_get_search_box_redirect_link();
if( empty( $customBaseURL ) ) {
// Find automatically is enabled
return $reschedule_link;
}
// get occurence of first ? in the URL
$firstQuestionMark = strpos( $reschedule_link, '?' );
// get everything after the first question mark
$everythingAfterFirstQuestionMark = substr( $reschedule_link, $firstQuestionMark );
// Now create the new URL
$newURL = $customBaseURL . $everythingAfterFirstQuestionMark;
$newURL = str_replace('selected=shortcode_finalize_order', 'selected=finalize', $newURL);
return $newURL;
}
function rp_get_info_for_checking_location_permission() {
static $cached = NULL;
if( $cached !== NULL ) {
return $cached;
}
$full_access = rp_current_user_has_full_access_cached();
$pricing_based_on_location = rp_is_enabled_pricing_based_on_location();
$selectable_locations = rp_get_allowed_locations_of_current_user();
$cached = array( $full_access, $pricing_based_on_location, $selectable_locations );
return $cached;
}
function rp_check_if_user_can_update_location( $selected_location_id = 0 ) {
list( $full_access, $pricing_based_on_location, $selectable_locations ) = rp_get_info_for_checking_location_permission();
if( $full_access === TRUE ) {
return TRUE;
}
if( $pricing_based_on_location == FALSE ) {
// Looks like you do not have permission to do this action.
return FALSE;
}
if( empty( $selected_location_id ) || !in_array( $selected_location_id, $selectable_locations ) ) {
// The selected location is either invalid or you are not assigned as the manager of this location.
return FALSE;
}
return TRUE;
}
function rp_mark_all_appointments_as_completed() {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$_POST['rp_incomplete_appointment_ids'] = wp_unslash( $_POST['rp_incomplete_appointment_ids'] ?? '' );
try {
$incomplete_appointment_ids = json_decode( $_POST['rp_incomplete_appointment_ids'], TRUE );
if( JSON_ERROR_NONE !== json_last_error() ) {
$incomplete_appointment_ids = array();
}
} catch( Exception|Error $e ) {
$incomplete_appointment_ids = array();
}
foreach( $incomplete_appointment_ids as $oid ) {
$oid = (int) $oid;
if( empty( $oid ) ) {
continue;
}
$order_row = rp_get_single_order_row_by_o_id( $oid );
if( empty( $order_row ) ) {
continue;
}
if( !rp_check_if_user_can_update_location( $order_row->location_id_fk ?? 0 ) ) {
continue;
}
$pending_order_statuses = array( 1, 3, 5 ); // pending | approved | price_requested
$isPDFOffer = strtolower( trim( $order_row->delivery_method ) ) === 'pdf offer';
if( in_array( $order_row->status_id_fk ?? 0, $pending_order_statuses ) && !$isPDFOffer ) {
$rpQuery->query("UPDATE `$rs_orders` SET status_id_fk = 11 WHERE o_id = $oid");
rp_trigger_order_webhooks_in_background( $oid );
}
}
echo json_encode( array( 'success' => true ) );
exit;
}
rp_ajax_for_admin('rp_mark_all_appointments_as_completed', 'rp_mark_all_appointments_as_completed');
function rp_trigger_order_webhooks_in_background( $oid = 0 ) {
if( !isset( $_REQUEST['rp_process_background_job'] ) || empty( $_REQUEST['rp_process_background_job'] ) ) {
rp_insert_rs_background_jobs_table(__FUNCTION__, func_get_args());
return;
}
$oid = (int) $oid;
if( !empty( $oid ?? 0 ) ) {
$order_row = rp_get_single_order_row_by_o_id( $oid );
if( empty( $order_row ) ) {
return;
}
$order_delivery_method = rp_find_delivery_method_of_order( $oid );
if( !empty( $order_delivery_method ) && $order_delivery_method != 'ship device' && $order_delivery_method != 'pdf offer' ) {
if( ((int) $order_row->status_id_fk) !== 4 ) {
rp_trigger_outgoing_webhook( 'scheduled_appointment_updated', $oid );
} else {
rp_trigger_outgoing_webhook( 'scheduled_appointment_cancelled', $oid );
}
} else if( !empty( $order_delivery_method ) && $order_delivery_method == 'ship device' ) {
if( ((int) $order_row->status_id_fk) !== 4 ) {
rp_trigger_outgoing_webhook( 'ship_device_appointment_updated', $oid );
} else {
rp_trigger_outgoing_webhook( 'ship_device_appointment_cancelled', $oid );
}
} else if( !empty( $order_delivery_method ) && $order_delivery_method == 'pdf offer' ) {
if( ((int) $order_row->status_id_fk) !== 4 ) {
rp_trigger_outgoing_webhook( 'pdf_offer_updated', $oid );
} else {
rp_trigger_outgoing_webhook( 'pdf_offer_cancelled', $oid );
}
} else {
// Do nothing!
}
}
}
function update_appointment_status(){
rp_verify_csrf_token_for_ajax('appointments');
$_POST['selected_location_id'] = rp_get_location_id_of_order( (int) ($_POST['oid'] ?? 0) );
rp_verify_selected_location_id_by_location_head();
global $rpQuery;
$rs_orders = $rpQuery->prefix . "rs_orders";
$localization = $rpQuery->prefix . "rs_localization";
$localization_data = $rpQuery->get_results("SELECT * FROM `$localization`");
$oid = $_POST['oid'];
$status = $_POST['booking_status'];
$delivery_time = trim( $_POST['delivery_time'] ?? '' );
$delivery_date = trim( $_POST['delivery_date'] ?? '' );
$user_name = $_POST['user_name'];
$email = $_POST['email'];
if( !empty( $delivery_date ) ) {
$delivery_date = date('d-m-Y', strtotime( $delivery_date ) );
}
if( !empty( $delivery_time ) ) {
if( strpos( $delivery_time, ' — ' ) === FALSE ) {
if( $localization_data[0]->set_time_format == '24 hours (e.g. 15:00)' ) {
$delivery_time = date('H:i', strtotime( $delivery_time ) );
} else {
$delivery_time = date('g:i a', strtotime( $delivery_time ) );
}
} else {
$DateTime = explode(' — ', $delivery_time);
if( $localization_data[0]->set_time_format == '24 hours (e.g. 15:00)' ) {
$newDateTime1 = date('H:i', strtotime($DateTime[0]));
$newDateTime2 = date('H:i', strtotime($DateTime[1]));
$newDateTime = $newDateTime1 . ' — ' . $newDateTime2;
} else {
$newDateTime1 = date('g:i a', strtotime($DateTime[0]));
$newDateTime2 = date('g:i a', strtotime($DateTime[1]));
$newDateTime = $newDateTime1 . ' — ' . $newDateTime2;
}
$delivery_time = $newDateTime;
}
}
$sql = "UPDATE `$rs_orders` SET status_id_fk = '".rp_escape_sql($status)."'";
if( !empty( $delivery_date ) ) {
$sql .= ", delivery_date = '".rp_escape_sql($delivery_date)."'";
}
if( !empty( $delivery_time ) ) {
$sql .= ", delivery_time = '".rp_escape_sql($delivery_time)."'";
}
$sql .= " WHERE o_id = '".rp_escape_sql($oid)."'";
$rpQuery->query( $sql );
// $rpQuery->query("UPDATE $rs_orders SET status_id_fk = '".rp_escape_sql($status)."', delivery_time = '".rp_escape_sql($delivery_time)."' , delivery_date = '".rp_escape_sql($delivery_date)."' WHERE o_id = '".rp_escape_sql($oid)."'");
if( !empty( $oid ?? 0 ) ) {
$order_delivery_method = rp_find_delivery_method_of_order( $oid );
if( !empty( $order_delivery_method ) && $order_delivery_method != 'ship device' && $order_delivery_method != 'pdf offer' ) {
if( (int) $status !== 4 ) {
rp_trigger_outgoing_webhook( 'scheduled_appointment_updated', $oid );
} else {
rp_trigger_outgoing_webhook( 'scheduled_appointment_cancelled', $oid );
}
} else if( !empty( $order_delivery_method ) && $order_delivery_method == 'ship device' ) {
if( (int) $status !== 4 ) {
rp_trigger_outgoing_webhook( 'ship_device_appointment_updated', $oid );
} else {
rp_trigger_outgoing_webhook( 'ship_device_appointment_cancelled', $oid );
}
} else if( !empty( $order_delivery_method ) && $order_delivery_method == 'pdf offer' ) {
if( (int) $status !== 4 ) {
rp_trigger_outgoing_webhook( 'pdf_offer_updated', $oid );
} else {
rp_trigger_outgoing_webhook( 'pdf_offer_cancelled', $oid );
}
} else {
// Do nothing!
}
}
if( rp_send_appointment_status_update_email( $oid ) === TRUE ) {
echo json_encode(Array('status'=> true, 'message' => 'Successfully Sent'));
} else {
echo json_encode(Array('status'=> true, 'message' => 'Successfully updated'));
}
exit();
}
rp_ajax_for_admin('update_appointment_status','update_appointment_status');
//-------------------------------------------------------------------add location
function get_last_location_order() {
$locations = rp_get_all_company_locations();
$last_location_order = 0;
foreach( $locations as $theLocation ) {
if( $theLocation->location_order > $last_location_order ) {
$last_location_order = (int) $theLocation->location_order;
}
}
return $last_location_order;
}
function add_location(){
rp_verify_csrf_token_for_ajax('general_info');
global $rpQuery;
$company_location = $rpQuery->prefix . "rs_company_location";
$company_schedules = $rpQuery->prefix . "rs_company_schedules";
$loc_name = $_POST['loc_name'];
$loc_address = $_POST['loc_address'];
$loc_email = $_POST['loc_email'] ?? '';
if(!empty($loc_email) && filter_var($loc_email, FILTER_VALIDATE_EMAIL) !== FALSE) {
if( trim($loc_email) !== rp_get_settings_placeholder_email() && trim($loc_email) !== rp_get_settings_company_email() ) {
// Skip... So It will save the email.
} else {
$loc_email = '';
}
} else {
$loc_email = '';
}
$loc_city = $_POST['loc_city'];
$loc_google_map = $_POST['loc_google_map'] ?? '';
$schedule_group_id = 0;
$location_order = get_last_location_order() + 1;
$rpQuery->query("INSERT INTO $company_location(location_name,location_address,location_city_district,google_map_link,location_email,schedule_group_id, location_order) VALUES('".rp_escape_sql($loc_name)."','".rp_escape_sql($loc_address)."','".rp_escape_sql($loc_city)."','".rp_escape_sql($loc_google_map)."','".rp_escape_sql($loc_email)."', '".rp_escape_sql($schedule_group_id)."', '".rp_escape_sql($location_order)."')");
$location_id = $rpQuery->insert_id;
$cs_day = $_POST['cs_day'];
$cs_open_timing = $_POST['cs_open_timing'];
$cs_close_timing = $_POST['cs_close_timing'];
$cs_breaktime_from = $_POST["cs_breaktime_from"];
$cs_breaktime_to = $_POST["cs_breaktime_to"];
$is_closed = $_POST["is_closed"];
foreach($cs_day as $i => $day){
if($is_closed[$i] == 'true'){
$closed = '1';
}else{
$closed = '0';
}
$rpQuery->query("INSERT INTO $company_schedules(cs_day,cs_open_timing,cs_close_timing,cs_breaktime_from,cs_breaktime_to,is_closed,location_id_fk) VALUES('".rp_escape_sql($day)."','".rp_escape_sql($cs_open_timing[$i])."','".rp_escape_sql($cs_close_timing[$i])."','".rp_escape_sql($cs_breaktime_from[$i])."','".rp_escape_sql($cs_breaktime_to[$i])."','".rp_escape_sql($closed)."','".rp_escape_sql($location_id)."')");
}
}
rp_ajax_for_admin('add_location','add_location');
//-------------------------------------------------------------------update location
function update_locations(){
rp_verify_csrf_token_for_ajax('general_info');
global $rpQuery;
$company_location = $rpQuery->prefix . "rs_company_location";
$company_schedules = $rpQuery->prefix . "rs_company_schedules";
$loc_id = $_POST['loc_id'];
$location_name = $_POST['location_name'];
$location_address = $_POST['location_address'];
$location_city = $_POST['location_city'];
$google_maps_link = $_POST['google_maps_link'];
$loc_email = $_POST['location_email'] ?? '';
if(!empty($loc_email) && filter_var($loc_email, FILTER_VALIDATE_EMAIL) !== FALSE) {
if( trim($loc_email) !== rp_get_settings_placeholder_email() && trim($loc_email) !== rp_get_settings_company_email() ) {
// Skip... So It will save the email.
} else {
$loc_email = '';
}
} else {
$loc_email = '';
}
$schedule_group_id = 0;
$rpQuery->query("UPDATE $company_location SET location_name='".rp_escape_sql($location_name)."',location_address='".rp_escape_sql($location_address)."',location_city_district='".rp_escape_sql($location_city)."',google_map_link='".rp_escape_sql($google_maps_link)."',location_email='".rp_escape_sql($loc_email)."',schedule_group_id='".rp_escape_sql($schedule_group_id)."' WHERE location_id='".rp_escape_sql($loc_id)."'");
$cs_id = $_POST['cs_id'];
$cs_day = $_POST['cs_day'];
$cs_open_timing = $_POST['cs_open_timing'];
$cs_close_timing = $_POST['cs_close_timing'];
$cs_breaktime_from = $_POST["cs_breaktime_from"];
$cs_breaktime_to = $_POST["cs_breaktime_to"];
$is_closed = $_POST["is_closed"];
foreach($cs_id as $i => $id){
if($is_closed[$i] == 'true'){
$closed = '1';
}else{
$closed = '0';
}
$rpQuery->query("UPDATE $company_schedules SET cs_day='".rp_escape_sql($cs_day[$i])."',cs_open_timing='".rp_escape_sql($cs_open_timing[$i])."',cs_close_timing='".rp_escape_sql($cs_close_timing[$i])."',cs_breaktime_from='".rp_escape_sql($cs_breaktime_from[$i])."',cs_breaktime_to='".rp_escape_sql($cs_breaktime_to[$i])."',is_closed='".rp_escape_sql($closed)."',location_id_fk='".rp_escape_sql($loc_id)."' WHERE cs_id='".rp_escape_sql($id)."'");
//$i++;
//$abc[] = $closed;
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully Updated'));
exit();
}
rp_ajax_for_admin('update_locations','update_locations');
//-------------------------------------------------------------------delete location
function delete_location(){
rp_verify_csrf_token_for_ajax('general_info');
global $rpQuery;
$company_location = $rpQuery->prefix . "rs_company_location";
$loc_id = $_POST['loc_id'];
$rpQuery->query("DELETE FROM $company_location WHERE location_id='".rp_escape_sql($loc_id)."'");
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted'));
}
rp_ajax_for_admin('delete_location','delete_location');
// ---------------------------------------- Update Category & Brand Position
function rp_update_category_and_brand_position() {
rp_verify_csrf_token_for_ajax('manage_categories');
global $rpQuery;
$rs_category = $rpQuery->prefix . "rs_category";
$c_position = $_POST['c_position'] ?? array();
$c_statuses = $_POST['c_statuses'] ?? array();
$i = 1;
foreach($c_position as $c_index => $cp){
$status_to_set = $c_statuses[$c_index] ?? '0';
$rpQuery->query("UPDATE $rs_category SET is_active='".rp_escape_sql($status_to_set)."' WHERE c_id='".rp_escape_sql($cp)."'");
$rpQuery->query("UPDATE $rs_category SET c_position='".rp_escape_sql($i)."' WHERE c_id='".rp_escape_sql($cp)."'");
$i++;
}
$rs_brand = $rpQuery->prefix . "rs_brand";
$b_position = $_POST['b_position'] ?? array();
$b_statuses = $_POST['b_statuses'] ?? array();
$i = 1;
foreach($b_position as $b_index => $bp){
$status_to_set = $b_statuses[$b_index] ?? '0';
$rpQuery->query("UPDATE $rs_brand SET is_active='".rp_escape_sql($status_to_set)."' WHERE b_id='".rp_escape_sql($bp)."'");
$rpQuery->query("UPDATE $rs_brand SET b_position='".rp_escape_sql($i)."' WHERE b_id='".rp_escape_sql($bp)."'");
$i++;
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully updated'));
exit();
}
rp_ajax_for_admin('update_category_and_brand_position','rp_update_category_and_brand_position');
//-------------------------------------------------------------------update category position
function update_category_position(){
rp_verify_csrf_token_for_ajax('manage_categories');
global $rpQuery;
$rs_category = $rpQuery->prefix . "rs_category";
$c_position = $_POST['c_position'];
$i = 1;
foreach($c_position as $cp){
$rpQuery->query("UPDATE $rs_category SET c_position='".rp_escape_sql($i)."' WHERE c_id='".rp_escape_sql($cp)."'");
$i++;
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully updated'));
exit();
}
rp_ajax_for_admin('update_category_position','update_category_position');
//-------------------------------------------------------------------update brand position
function update_brand_position(){
rp_verify_csrf_token_for_ajax('manage_categories');
global $rpQuery;
$rs_brand = $rpQuery->prefix . "rs_brand";
$b_position = $_POST['b_position'];
$i = 1;
foreach($b_position as $bp){
$rpQuery->query("UPDATE $rs_brand SET b_position='".rp_escape_sql($i)."' WHERE b_id='".rp_escape_sql($bp)."'");
$i++;
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully updated'));
exit();
}
rp_ajax_for_admin('update_brand_position','update_brand_position');
//-------------------------------------------------------------------update model position
function update_model_position(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
global $rpQuery;
$rs_model = $rpQuery->prefix . "rs_model";
$rs_model_color = $rpQuery->prefix . "rs_model_color";
$m_position = $_POST['m_position'];
$mc_position = $_POST['mc_position'];
$i = 1;
foreach($m_position as $mp){
$rpQuery->query("UPDATE $rs_model SET m_position='".rp_escape_sql($i)."' WHERE m_id='".rp_escape_sql($mp)."'");
$i++;
}
$i = 1;
foreach($mc_position as $mcp){
$rpQuery->query("UPDATE $rs_model_color SET mc_position='".rp_escape_sql($i)."' WHERE mc_id='".rp_escape_sql($mcp)."'");
$i++;
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully updated'));
exit();
}
rp_ajax_for_admin('update_model_position','update_model_position');
//-------------------------------------------------------------------update new model position
function get_model_position_first_found_index($brand_id = '', $positionByBrand = array()) {
foreach ($positionByBrand[$brand_id] as $index => $value) {
if(in_array($value->m_id, $_POST['m_position'])) {
return $index;
}
}
return 0;
}
function update_new_model_position(){
rp_verify_csrf_token_for_ajax('manage_models');
global $rpQuery;
$front_end_position = array();
$rs_model = $rpQuery->prefix . "rs_model";
if(isset($_POST['m_position']) && !empty($_POST['m_position'])) {
$m_position = implode(',', $_POST['m_position']);
$all_model_info = $rpQuery->get_results("SELECT m_id, m_position, brand_id_fk FROM $rs_model WHERE m_id IN(".rp_escape_sql($m_position).");");
if(!empty($all_model_info)) {
$brandIDs = array();
$getBrandByModel = array();
foreach ($all_model_info as $key => $value) {
if(array_search($value->brand_id_fk, $brandIDs) === FALSE) {
$brandIDs[] = $value->brand_id_fk;
}
$getBrandByModel[$value->m_id] = $value->brand_id_fk;
}
$brandIDs = implode(',', $brandIDs);
$all_model_info = $rpQuery->get_results("SELECT m_id, m_position, brand_id_fk FROM $rs_model WHERE brand_id_fk IN(".rp_escape_sql($brandIDs).") ORDER BY brand_id_fk ASC, m_position ASC, release_date DESC;");
$usableMPosition = array();
foreach ($_POST['m_position'] as $mposid) {
if(!isset($usableMPosition[$getBrandByModel[$mposid]])) {
$usableMPosition[$getBrandByModel[$mposid]] = array();
}
$usableMPosition[$getBrandByModel[$mposid]][] = $mposid;
}
if(!empty($all_model_info)) {
$positionByBrand = array();
foreach ($all_model_info as $key => $value) {
if(!isset($positionByBrand[$value->brand_id_fk])) {
$positionByBrand[$value->brand_id_fk] = array();
}
$positionByBrand[$value->brand_id_fk][] = $value;
}
foreach($positionByBrand as $brand => $models) {
$all_zero = TRUE;
foreach( $models as $modelRow ) {
if( $modelRow->m_position != 0 && $modelRow->m_position >= 1 ) {
$all_zero = FALSE;
break;
}
}
if( $all_zero === TRUE ) {
$xyz = 1;
foreach( $models as $modelKey => $modelRow ) {
$modelRow->m_position = $xyz;
// update model position
$rpQuery->query("UPDATE $rs_model SET m_position='".rp_escape_sql($xyz)."' WHERE m_id='".rp_escape_sql($modelRow->m_id)."'");
$xyz++;
$models[$modelKey] = $modelRow;
}
}
$positionByBrand[$brand] = $models;
}
foreach ($positionByBrand as $brand => $models) {
$prepare_for_db = array();
$isStart = FALSE;
if(in_array($positionByBrand[$brand][0]->m_id, $_POST['m_position'])) {
$isStart = TRUE;
}
if($isStart === FALSE) {
$firstIndex = get_model_position_first_found_index($brand, $positionByBrand);
$firstIndex = $firstIndex + 1;
foreach ($usableMPosition[$brand] as $_m_id) {
$prepare_for_db[$_m_id] = $firstIndex;
$firstIndex++;
}
} else {
$i = 1;
foreach ($usableMPosition[$brand] as $_m_id) {
$prepare_for_db[$_m_id] = $i;
$i++;
}
}
foreach ($prepare_for_db as $update_m_id => $position_to_set) {
$rpQuery->query("UPDATE $rs_model SET m_position='".rp_escape_sql($position_to_set)."' WHERE m_id='".rp_escape_sql($update_m_id)."'");
$front_end_position[$update_m_id] = $position_to_set;
}
}
}
}
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully updated', 'positions' => $front_end_position));
exit();
}
rp_ajax_for_admin('update_new_model_position','update_new_model_position');
//-------------------------------------------------------------------update repair
function rp_fix_posted_data_update_repair() {
if( isset( $_POST ) && !empty( $_POST ) && isset( $_POST['action'] ) && ( $_POST['action'] == 'update_repair' || $_POST['action'] == 'update_default_repair' ) ) {
$posted_data = $_POST['data'] ?? '';
if( !empty( $posted_data ) ) {
try {
$posted_data = json_decode( $posted_data, TRUE );
} catch ( Exception $e ) {
$posted_data = NULL;
}
if( !empty( $posted_data ) ) {
foreach( $posted_data as $key => $value ) {
$_POST[$key] = $value;
}
$_REQUEST = $_POST;
unset( $_POST['data'] );
}
}
}
}
function update_repair(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_selected_location_id_by_location_head();
$rp_current_user_has_full_access = rp_current_user_has_full_access();
global $rpQuery; $repairs = array(); $r_attrs = array();$s= array();
list( $selected_location_id, $rp_location_based_price_id ) = rp_must_verify_selected_location_if_needed_ajax();
$rs_repair = $rpQuery->prefix . "rs_repair";
$rs_repairs_category = $rpQuery->prefix . "rs_repairs_category";
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$rs_model = $rpQuery->prefix . "rs_model";
$planning = $rpQuery->prefix . "rs_planning_and_discount";
$planning_result = $rpQuery->get_results("SELECT * FROM $planning");
$default_repair_length = 30;
if(!empty($planning_result)) {
$lengthD = $planning_result[0]->booking_slots_length;
if(!empty(trim($lengthD))) {
$lengthD = trim(explode(' ', trim($lengthD))[0]);
if(!empty($lengthD)) {
$default_repair_length = (float) $lengthD;
}
}
}
$mid = $_POST['mid'];
$rid = $_POST['rid'] ?? array();
$title = $_POST['title'] ?? array();
$mins = $_POST['mins'] ?? array();
$duration_measure = $_POST['duration_measure'] ?? array();
$info = $_POST['info'] ?? array();
$badge = $_POST['badge'] ?? array();
$readmore = $_POST['readmore'] ?? array();
$readmoretext = $_POST['readmoretext'] ?? array();
$rprice = $_POST['rprice'] ?? array();
$rmargin = $_POST['rmargin'] ?? array();
$rfree = $_POST['rfree'] ?? array();
$status = $_POST['status'] ?? array();
$img_link = $_POST['img_link'] ?? array();
$skipped_index = array();
$rc_skipped_index = array();
$rcid = $_POST['rcid'] ?? array();
$rcname = $_POST['rcname'] ?? array();
$rcexpand = $_POST['rcexpand'] ?? array();
$rc_img_link = $_POST['rc_img_link'] ?? array();
$rcstatus = $_POST['rcstatus'] ?? array();
$category_repairs_count = $_POST['category_repairs_count'] ?? array();
$saveRepairReadMoreLinks = FALSE;
$saveAttrReadMoreLinks = FALSE;
if( rp_get_option('rp_enable_read_more_link_for_repairs', '0') == '1' ) {
$saveRepairReadMoreLinks = TRUE;
}
if( rp_get_option('rp_enable_read_more_link_for_attributes', '0') == '1' ) {
$saveAttrReadMoreLinks = TRUE;
}
// Update/Create Repairs of Model
foreach($rid as $i => $r){
if(preg_match('/,/',$rprice[$i])) {
$price = str_replace(',','.',$rprice[$i]);
}else{
$price = $rprice[$i];
}
if(empty(trim($price))) {
$price = 0;
}
$marginPrice = FALSE;
if( !empty( $rmargin ) ) {
if(preg_match('/,/',$rmargin[$i])) {
$marginPrice = str_replace(',','.',$rmargin[$i]);
}else{
$marginPrice = $rmargin[$i];
}
if(empty(trim($marginPrice))) {
$marginPrice = 0;
}
}
if( array_search( ($duration_measure[$i] ?? '' ) , array('minutes', 'hours', 'days') ) === FALSE ) {
$duration_measure[$i] = 'minutes';
}
$is_free = $rfree[$i] ?? 0;
if(empty(trim($mins[$i]))) {
$mins[$i] = $default_repair_length;
}
if(trim(strtoupper($r)) === 'NEW') {
if( $rp_current_user_has_full_access == false ) {
$skipped_index[] = $i;
continue;
}
// Create
if(!empty(trim($title[$i]))) {
$r_uq_id = uniqid('repair_');
$r_readmore_col = '';
$r_readmore_value = '';
if( $saveRepairReadMoreLinks == TRUE ) {
$r_readmore_col = ', `r_readmore`';
$r_readmore_value = ", '".rp_escape_sql($readmore[$i])."'";
$r_readmore_col .= ', `r_readmoretext`';
$r_readmore_value .= ", '".rp_escape_sql($readmoretext[$i])."'";
}
if( !empty( $selected_location_id ) ) {
// Price based on location
$r_price_db_col = ', `r_price`';
$r_price_db_value = ", '0'";
$r_margin = ', `r_margin`';
$r_margin_value = ", '0'";
$is_free_db_col = ', `is_free`';
$is_free_db_value = ", '0'";
} else {
$r_price_db_col = ', `r_price`';
$r_price_db_value = ", '".rp_escape_sql($price)."'";
if( $marginPrice !== FALSE ) {
$r_margin = ', `r_margin`';
$r_margin_value = ", '".rp_escape_sql($marginPrice)."'";
} else {
$r_margin = '';
$r_margin_value = '';
}
$is_free_db_col = ', `is_free`';
$is_free_db_value = ", '".rp_escape_sql($is_free)."'";
}
$rpQuery->query("INSERT INTO $rs_repair (r_name, r_duration, r_discription, r_badge, m_id_fk, r_uq_id, r_img, r_duration_measure $r_readmore_col $r_margin $is_free_db_col $r_price_db_col) VALUES ('".rp_escape_sql($title[$i])."', '".rp_escape_sql($mins[$i])."', '".rp_escape_sql($info[$i])."', '".rp_escape_sql($badge[$i])."', '".rp_escape_sql($mid)."', '".rp_escape_sql($r_uq_id)."', '".rp_escape_sql($img_link[$i])."', '".rp_escape_sql($duration_measure[$i])."' $r_readmore_value $r_margin_value $is_free_db_value $r_price_db_value);");
$rid[$i] = $rpQuery->insert_id;
} else {
$skipped_index[] = $i;
}
} else {
// Update
if( !empty( $selected_location_id ) ) {
// Price based on location
$r_price_db = '';
$r_margin = '';
$is_free_db = '';
} else {
$r_price_db = ', `r_price` = "'.rp_escape_sql($price).'"';
if( $marginPrice !== FALSE ) {
$r_margin = ', `r_margin` = "'.rp_escape_sql($marginPrice).'"';
} else {
$r_margin = '';
}
$is_free_db = ', `is_free` = "'.rp_escape_sql($is_free).'"';
}
if( $rp_current_user_has_full_access == true ) {
$rpQuery->query("UPDATE $rs_repair SET r_duration='".rp_escape_sql($mins[$i])."',r_img='".rp_escape_sql($img_link[$i])."',r_duration_measure='".rp_escape_sql($duration_measure[$i])."' $r_margin $r_price_db $is_free_db WHERE r_id='".rp_escape_sql($r)."' AND m_id_fk ='".rp_escape_sql($mid)."'");
}
}
}
if( !empty( $selected_location_id ) ) {
foreach($rid as $i => $r){
if(!in_array($i, $skipped_index)) {
if(preg_match('/,/',$rprice[$i])) {
$price = str_replace(',','.',$rprice[$i]);
}else{
$price = $rprice[$i];
}
if(empty(trim($price))) {
$price = 0;
}
$marginPrice = FALSE;
if( !empty( $rmargin ) ) {
if(preg_match('/,/',$rmargin[$i])) {
$marginPrice = str_replace(',','.',$rmargin[$i]);
}else{
$marginPrice = $rmargin[$i];
}
if(empty(trim($marginPrice))) {
$marginPrice = 0;
}
}
$is_free = $rfree[$i] ?? 0;
rp_update_individual_repair_price_based_on_location( $r, $selected_location_id, $price, $marginPrice, $is_free );
}
}
}
if( $rp_current_user_has_full_access == true ) {
// Update/Create Repairs of Model
foreach($rcid as $i => $rc){
$is_expand = $rcexpand[$i] ?? 0;
if(trim(strtoupper($rc)) === 'NEW') {
// Create
if(!empty(trim($rcname[$i]))) {
$c_uq_id = uniqid('rcat_');
$rpQuery->query("INSERT INTO $rs_repairs_category (c_name, m_id_fk, c_uq_id, c_img, `expand`) VALUES ('".rp_escape_sql($rcname[$i])."', '".rp_escape_sql($mid)."', '".rp_escape_sql($c_uq_id)."', '".rp_escape_sql($rc_img_link[$i])."', '".rp_escape_sql($is_expand)."');");
$rcid[$i] = $rpQuery->insert_id;
} else {
$rc_skipped_index[] = $i;
}
} else {
// Update
$rpQuery->query("UPDATE $rs_repairs_category SET c_img='".rp_escape_sql($rc_img_link[$i])."', `expand`='".rp_escape_sql($is_expand)."' WHERE c_id='".rp_escape_sql($rc)."' AND m_id_fk ='".rp_escape_sql($mid)."'");
}
}
}
// Update/Create Repair Attrs of Model
$raid = $_POST['raid'] ?? array();
foreach ($raid as $i => $arr) {
if(!in_array($i, $skipped_index)) {
$a_id = $_POST['raid'][$i];
$a_name = $_POST['raname'][$i];
$a_desc = $_POST['radesc'][$i];
$a_badge = $_POST['rabadge'][$i];
$a_readmore = $_POST['rareadmore'][$i];
$a_readmoretext = $_POST['rareadmoretext'][$i];
$a_duration = $_POST['raduration'][$i];
$a_duration_measure = $_POST['radurationmeasure'][$i];
$a_price = $_POST['raprice'][$i];
$a_margin = $_POST['ramargin'] ?? array();
if( !empty( $a_margin ) ) {
$a_margin = $_POST['ramargin'][$i] ?? array();
}
$a_is_active = $_POST['raactive'][$i] ?? array();
$skipped_a_index = array();
foreach($a_id as $x => $a){
if( empty( trim( $a_duration[$x] ?? '' ) ) ) {
$a_duration[$x] = $default_repair_length;
}
if(preg_match('/,/',$a_price[$x])) {
$a_price[$x] = str_replace(',','.',$a_price[$x]);
}
if(empty(trim($a_price[$x]))) {
$a_price[$x] = 0;
}
$attrMarginPrice = FALSE;
if( !empty( $a_margin ) ) {
if(preg_match('/,/',$a_margin[$x])) {
$attrMarginPrice = str_replace(',','.',$a_margin[$x]);
} else {
$attrMarginPrice = $a_margin[$x];
}
if(empty(trim($a_margin[$x]))) {
$attrMarginPrice = 0;
}
}
if(strtoupper($a_id[$x]) === 'NEW') {
if( $rp_current_user_has_full_access == false ) {
$skipped_a_index[] = $x;
continue;
}
if(!empty(trim($a_name[$x]))) {
$a_readmore_col = '';
$a_readmore_value = '';
if( $saveAttrReadMoreLinks == TRUE ) {
$a_readmore_col = ', `a_readmore`';
$a_readmore_value = ", '".rp_escape_sql($a_readmore[$x])."'";
$a_readmore_col .= ', `a_readmoretext`';
$a_readmore_value .= ", '".rp_escape_sql($a_readmoretext[$x])."'";
}
if( !empty( $selected_location_id ) ) {
// Price based on location
$a_price_db_col = ', `a_price`';
$a_price_db_value = ", '0'";
$_a_margin = ', `a_margin`';
$_a_margin_value = ", '0'";
} else {
$a_price_db_col = ', `a_price`';
$a_price_db_value = ", '".rp_escape_sql($a_price[$x])."'";
if( $attrMarginPrice !== FALSE ) {
$_a_margin = ', `a_margin`';
$_a_margin_value = ", '".rp_escape_sql($attrMarginPrice)."'";
} else {
$_a_margin = '';
$_a_margin_value = '';
}
}
$a_uq_id = uniqid('rattr_');
$rpQuery->query("INSERT INTO $rs_repair_attr (`a_name`, `a_desc`, `a_badge`, `a_duration`, `a_duration_measure`, `a_uq_id`, `r_id_fk` $a_readmore_col $_a_margin $a_price_db_col) VALUES('".rp_escape_sql($a_name[$x])."', '".rp_escape_sql($a_desc[$x])."', '".rp_escape_sql($a_badge[$x])."', '".rp_escape_sql($a_duration[$x])."', '".rp_escape_sql($a_duration_measure[$x])."', '".rp_escape_sql($a_uq_id)."', '".rp_escape_sql($rid[$i])."' $a_readmore_value $_a_margin_value $a_price_db_value)");
$a_id[$x] = $rpQuery->insert_id;
} else {
$skipped_a_index[] = $x;
}
} else {
if( !empty( $selected_location_id ) ) {
// Price based on location
$a_price_db = '';
$_a_margin = '';
} else {
$a_price_db = ', `a_price` = "'.rp_escape_sql($a_price[$x]).'"';
if( $attrMarginPrice !== FALSE ) {
$_a_margin = ', a_margin = "'.rp_escape_sql($attrMarginPrice).'"';
} else {
$_a_margin = '';
}
}
if( $rp_current_user_has_full_access == true ) {
$rpQuery->query("UPDATE $rs_repair_attr SET a_duration='".rp_escape_sql($a_duration[$x])."', a_duration_measure='".rp_escape_sql($a_duration_measure[$x])."' $_a_margin $a_price_db WHERE a_id='".rp_escape_sql($a_id[$x])."'");
}
}
}
if( !empty( $selected_location_id ) ) {
foreach($a_id as $x => $a){
if(!in_array($x, $skipped_a_index)) {
if(preg_match('/,/',$a_price[$x])) {
$a_price[$x] = str_replace(',','.',$a_price[$x]);
}
if(empty(trim($a_price[$x]))) {
$a_price[$x] = 0;
}
$attrMarginPrice = FALSE;
if( !empty( $a_margin ) ) {
if(preg_match('/,/',$a_margin[$x])) {
$attrMarginPrice = str_replace(',','.',$a_margin[$x]);
} else {
$attrMarginPrice = $a_margin[$x];
}
if(empty(trim($a_margin[$x]))) {
$attrMarginPrice = 0;
}
}
rp_update_individual_repair_attr_price_based_on_location( $a_id[$x], $selected_location_id, $a_price[$x], $attrMarginPrice, 0 );
}
}
}
if( $rp_current_user_has_full_access == true ) {
foreach($a_id as $x => $a){
if(!in_array($x, $skipped_a_index)) {
if( !empty( $a_is_active[ $x ] ) ) {
$_is_active = '1';
} else {
$_is_active = '0';
}
$rpQuery->query("UPDATE $rs_repair_attr SET is_active='".rp_escape_sql($_is_active)."' WHERE a_id='".rp_escape_sql($a_id[$x])."'");
}
}
if(isset($_POST['sub_sorting_reset']) && !empty($_POST['sub_sorting_reset']) && isset($_POST['sub_sorting_reset'][$i])) {
$sub_sorting_has_changed = $_POST['sub_sorting_reset'][$i];
if(!empty($sub_sorting_has_changed) && $sub_sorting_has_changed !== 'false' && $sub_sorting_has_changed !== false && $sub_sorting_has_changed !== '0') {
$a_i = 1;
foreach($a_id as $x => $a){
if(!in_array($x, $skipped_a_index)) {
$rpQuery->query("UPDATE $rs_repair_attr SET ra_position='".rp_escape_sql($a_i)."' WHERE a_id='".rp_escape_sql($a_id[$x])."'");
$a_i++;
}
}
}
}
}
}
}
if( $rp_current_user_has_full_access == true ) {
// Update Repair Position
if(isset($_POST['main_sorting_has_changed']) && !empty($_POST['main_sorting_has_changed']) && $_POST['main_sorting_has_changed'] !== 'false' && $_POST['main_sorting_has_changed'] !== '0' && $_POST['main_sorting_has_changed'] !== false) {
$r_i = 1;
foreach($rid as $i => $repairId){
if(!in_array($i, $skipped_index)) {
$rpQuery->query("UPDATE $rs_repair SET r_position='".rp_escape_sql($r_i)."' WHERE r_id='".rp_escape_sql($repairId)."'");
$r_i++;
}
}
}
// Update Repair Attr Position
// Update Repair Statuses
$rpQuery->query("UPDATE $rs_repair SET is_active= '0' WHERE m_id_fk ='".rp_escape_sql($mid)."'");
foreach($status as $i => $s){
if(!in_array($i, $skipped_index)) {
if(!empty($s)) {
$rpQuery->query("UPDATE $rs_repair SET is_active='1' WHERE r_id='".rp_escape_sql($rid[$i])."' AND m_id_fk ='".rp_escape_sql($mid)."'");
}
}
}
}
///////////////////
// Update Repair Position
if( $rp_current_user_has_full_access == true ) {
$catSortHasChanged = false;
$individual_repairs_category = rp_get_individual_repairs_categories( $mid );
$individual_repairs_category = rp_fix_default_repair_category_sorting( $individual_repairs_category, $mid );
$keyPairSaved = array();
foreach( $individual_repairs_category as $repairCategory ) {
$keyPairSaved[ $repairCategory->c_id ] = $repairCategory->c_position;
}
$keyPairNew = array();
$c_i = 1;
foreach($rcid as $i => $catId){
if(!in_array($i, $rc_skipped_index)) {
$keyPairNew[ $catId ] = $c_i;
$c_i++;
}
}
// check if something is changed between old and new
foreach( $keyPairSaved as $catId => $oldPosition ) {
if( isset( $keyPairNew[ $catId ] ) ) {
if( $keyPairNew[ $catId ] != $oldPosition ) {
$catSortHasChanged = true;
break;
}
} else {
$catSortHasChanged = true;
break;
}
}
if( $catSortHasChanged == true ) {
$c_i = 1;
foreach($rcid as $i => $catId){
if(!in_array($i, $rc_skipped_index)) {
$rpQuery->query("UPDATE $rs_repairs_category SET c_position='".rp_escape_sql($c_i)."' WHERE c_id='".rp_escape_sql($catId)."'");
$c_i++;
}
}
}
// Update Repair Attr Position
// Update Repair Statuses
$rpQuery->query("UPDATE $rs_repairs_category SET is_active= '0' WHERE m_id_fk ='".rp_escape_sql($mid)."'");
foreach($rcstatus as $i => $s){
if(!in_array($i, $rc_skipped_index)) {
if(!empty($s)) {
$rpQuery->query("UPDATE $rs_repairs_category SET is_active='1' WHERE c_id='".rp_escape_sql($rcid[$i])."' AND m_id_fk ='".rp_escape_sql($mid)."'");
}
}
}
$last_correct_category = null;
$addLaterToFirst = array();
$category_repairs_count_before = $category_repairs_count;
foreach( $category_repairs_count as $i => $cr_count ) {
if(!in_array($i, $rc_skipped_index)) {
$last_correct_category = $i;
if( !empty( $addLaterToFirst ) ) {
$category_repairs_count[ $last_correct_category ] += array_sum( $addLaterToFirst );
$addLaterToFirst = array();
}
} else {
if( $last_correct_category === null ) {
$addLaterToFirst[] = $cr_count;
} else {
$category_repairs_count[ $last_correct_category ] += $cr_count;
}
$category_repairs_count[ $i ] = 0;
}
}
if( !empty( $addLaterToFirst ) ) {
$category_repairs_count[ $last_correct_category ] += array_sum( $addLaterToFirst );
$addLaterToFirst = array();
}
$rid_copy = $rid;
$repairsByCategory = array();
foreach($rcid as $i => $catId){
if(!in_array($i, $rc_skipped_index)) {
$repairsByCategory[ $catId ] = array();
// total repairs in this category
$totalRepairs = $category_repairs_count[$i] ?? 0;
if( $totalRepairs > 0 ) {
$currentItem = 1;
foreach($rid_copy as $x => $repairId){
if( $currentItem > $totalRepairs ) {
break;
}
if(!in_array($x, $skipped_index)) {
$repairsByCategory[ $catId ][] = $repairId;
}
unset($rid_copy[$x]);
$currentItem++;
}
}
}
}
rp_update_repairs_by_model( $mid, $repairsByCategory );
}
/////////////////// comebackfast
$categoriesCount = count( rp_get_individual_repairs_categories( $mid ) );
if( $rp_current_user_has_full_access == true ) {
if( $categoriesCount < 2 && count( $_POST['rcid'] ?? array() ) < 2 && array_key_exists( 'default_listing_range', $_POST ) ) {
$default_listing_range = (int) ($_POST['default_listing_range'] ?? 6);
$default_listing_range = rp_round_to_even_number( $default_listing_range );
rp_update_option( 'rp_default_listing_index_model_' . $mid, $default_listing_range );
}
}
// Return Result Array
list( $category_based, $categoriesCount ) = rp_get_model_related_repairs_for_admin_page( $mid );
$all_dr_uq_ids = rp_get_all_dr_uq_id_from_rs_default_repair_table();
$all_da_uq_ids = rp_get_all_da_uq_id_from_rs_default_repair_attr_table();
$all_dc_uq_ids = rp_get_all_dc_uq_id_from_rs_default_repairs_category();
echo json_encode(Array('status' => true, 'message' => 'Successfully Updated', 'category_based' => $category_based, 'categories_count' => $categoriesCount, 'update_all_dr_uq_ids' => $all_dr_uq_ids, 'update_all_da_uq_ids' => $all_da_uq_ids, 'update_all_dc_uq_ids' => $all_dc_uq_ids));
exit();
}
rp_ajax_for_admin('update_repair','update_repair');
function rp_get_model_related_repairs_for_admin_page( $mid = '' ) {
if( empty( $mid ) ) {
return array();
}
global $rpQuery;
global $rp_location_based_price_id;
$rs_repair = $rpQuery->prefix . "rs_repair";
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$device_type = rp_get_model_cached_category_by_mid( $mid );
$default_listing_range = rp_get_option( 'rp_default_listing_index_model_' . $mid, FALSE);
if( $default_listing_range === FALSE ){
$default_listing_range = rp_get_option( 'rp_default_listing_index_'. $device_type, 6 );
}
$default_listing_range = (int) $default_listing_range;
$default_listing_range = rp_round_to_even_number( $default_listing_range );
$category_based = rp_get_individual_repairs_based_on_repair_category($mid);
$categoriesCount = 0;
if( !empty( $category_based ) ) {
$categoriesCount = count($category_based);
foreach( $category_based as $cb_key => $repairCategory ) {
$repairCategory->c_name = rp_get_static_translations_of_repair_category('category_name', $repairCategory->c_uq_id, $mid);
$table_rows = array();
$c_repair_all = $repairCategory->repairs;
if(!empty($c_repair_all)) {
$last_index = count($c_repair_all) - 1;
if( $default_listing_range > ($last_index + 1) ) {
$default_listing_range = $last_index + 1;
}
if( 0 == $default_listing_range && $last_index !== -1 && $categoriesCount < 2 ){
$seprator_tr = array();
$seprator_tr['listing_range'] = $default_listing_range;
$table_rows[] = $seprator_tr;
}
foreach ($c_repair_all as $i => $c_repair) {
if( isset( $rp_location_based_price_id ) && !empty( $rp_location_based_price_id ) ) {
$c_repair = apply_filters('rp_overwrite_individual_repair_row', $c_repair, $rp_location_based_price_id);
}
$tr = array();
$tr['is_active'] = $c_repair->is_active;
$tr['is_free'] = $c_repair->is_free;
$tr['r_duration_measure'] = ( !empty( $c_repair->r_duration_measure ) ? $c_repair->r_duration_measure : '' );
$tr['m_id'] = $mid;
$tr['r_id'] = $c_repair->r_id;
$tr['r_img'] = $c_repair->r_img;
$tr['r_uq_id'] = $c_repair->r_uq_id;
$tr['repair_title'] = rp_get_static_translations_of_repair('repair_name', $c_repair->r_uq_id, $c_repair->m_id_fk);
$tr['repair_min'] = $c_repair->r_duration;
$tr['repair_info'] = rp_get_static_translations_of_repair('repair_desc', $c_repair->r_uq_id, $c_repair->m_id_fk);
$tr['repair_badge'] = rp_get_static_translations_of_repair('repair_badge', $c_repair->r_uq_id, $c_repair->m_id_fk);
$tr['r_uq_id_with_device_type'] = $c_repair->r_uq_id.'_'.rp_get_model_cached_category_by_mid($mid);
$tr['repair_read_more'] = rp_get_static_translations_of_repair_individually_editable('repair_read_more', $c_repair->r_uq_id.'_'.rp_get_model_cached_category_by_mid($mid), $c_repair->m_id_fk);
$tr['repair_readmore_text'] = rp_get_static_translations_of_repair_individually_editable('repair_readmore_text', $c_repair->r_uq_id.'_'.rp_get_model_cached_category_by_mid($mid), $c_repair->m_id_fk);
$tr['repair_price'] = $c_repair->r_price;
$tr['is_fully_unchanged'] = (rp_is_fully_unchanged_default_repair_individually($c_repair->r_id, $mid) === TRUE ? '1' : '0');
$tr = rp_sanitize_output($tr);
$tr['attrs'] = array();
$repair_attrs = $rpQuery->get_results("SELECT * FROM $rs_repair_attr WHERE `r_id_fk` = '".rp_escape_sql($c_repair->r_id)."' ORDER BY `ra_position` ASC");
$repair_attrs = rp_fix_default_repair_attr_sorting($repair_attrs, $mid);
if(!empty($repair_attrs)) {
foreach ($repair_attrs as $x => $c_attr) {
if( isset( $rp_location_based_price_id ) && !empty( $rp_location_based_price_id ) ) {
$c_attr = apply_filters('rp_overwrite_individual_repair_attr_row', $c_attr, $rp_location_based_price_id);
}
$attr = array();
$attr['a_id'] = $c_attr->a_id;
$attr['a_name'] = rp_get_static_translations_of_attr('attr_name', $c_attr->a_uq_id, $c_attr->r_id_fk);
$attr['attr_min'] = $c_attr->a_duration;
$attr['a_duration_measure'] = ( !empty( $c_attr->a_duration_measure ) ? $c_attr->a_duration_measure : '' );
$attr['a_desc'] = rp_get_static_translations_of_attr('attr_desc', $c_attr->a_uq_id, $c_attr->r_id_fk);
$attr['a_badge'] = rp_get_static_translations_of_attr('attr_badge', $c_attr->a_uq_id, $c_attr->r_id_fk);
$attr['a_readmore'] = rp_get_static_translations_of_attr_individually_editable('attr_read_more', $c_attr->a_uq_id, $c_attr->r_id_fk);
$attr['a_readmoretext'] = rp_get_static_translations_of_attr_individually_editable('attr_readmore_text', $c_attr->a_uq_id, $c_attr->r_id_fk);
$attr['a_price'] = $c_attr->a_price;
$attr['is_active'] = $c_attr->is_active;
$attr['a_uq_id'] = $c_attr->a_uq_id;
$attr = rp_sanitize_output($attr);
$attr = apply_filters('rp_before_returning_individual_repair_attr', $attr, $c_attr);
$tr['attrs'][] = $attr;
}
$tr['repair_price'] = rp_get_lowest_repair_attribute_price( $c_repair->r_id );
}
$tr = apply_filters('rp_before_returning_individual_repair_tr', $tr, $c_repair);
$table_rows[] = $tr;
if( $i+1 == $default_listing_range && $categoriesCount < 2 ){
$seprator_tr = array();
$seprator_tr['listing_range'] = $default_listing_range;
$table_rows[] = $seprator_tr;
}
}
}
$repairCategory->repairs = $table_rows;
$category_based[$cb_key] = $repairCategory;
}
}
return array( $category_based, $categoriesCount );
}
//-------------------------------------------------------------------update default repair
function update_unchanged_repair_attr_name($da_row_old = NULL) {
global $rpQuery;
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$rs_default_repair_attr = $rpQuery->prefix . "rs_default_repair_attr";
$dr_category = $_POST['dr_category'] ?? 0;
$new_row = $rpQuery->get_results("SELECT * FROM $rs_default_repair_attr WHERE da_id = '".rp_escape_sql($da_row_old->da_id)."' AND dr_category = '".rp_escape_sql($dr_category)."' LIMIT 1;");
$is_changed = FALSE;
if(!empty($new_row)) {
$columns_check = array('name');
foreach ($columns_check as $col_check) {
$the_col = 'da_'.$col_check;
if(trim($new_row[0]->{$the_col}) !== trim($da_row_old->{$the_col})) {
$is_changed = TRUE;
}
}
}
if($is_changed === TRUE) {
$r_ids = rp_get_all_repair_ids_related_to_category( $dr_category );
if(!empty($r_ids)) {
$r_ids = join(',', $r_ids);
$unchanged = $rpQuery->get_results("SELECT a_id FROM $rs_repair_attr WHERE a_uq_id = '".rp_escape_sql($da_row_old->da_uq_id)."' AND a_name LIKE '".rp_escape_sql($da_row_old->da_name)."' AND r_id_fk IN (".rp_escape_sql($r_ids).")");
if(!empty($unchanged)) {
$new_row = $new_row[0];
$allIds = array();
foreach ($unchanged as $key => $row) {
$allIds[] = $row->a_id;
}
$all_ids_str = '(' . join(', ', $allIds) . ')';
$updated_on = date('Y-m-d H:i:s');
$rpQuery->query("UPDATE $rs_repair_attr SET a_name = '".rp_escape_sql($new_row->da_name)."', updated_on = '".rp_escape_sql($updated_on)."' WHERE a_id IN $all_ids_str");
}
}
}
}
function rp_convert_to_object_if_not_already( $da_row_old = NULL ) {
if( !is_object( $da_row_old ) && !is_bool( $da_row_old ) && is_array( $da_row_old ) ) {
$da_row_old = (object) $da_row_old;
}
return $da_row_old;
}
function rp_convert_array_items_to_object_if_not_already( $rows = array() ) {
foreach( $rows as $key => $row ) {
$rows[ $key ] = rp_convert_to_object_if_not_already( $row );
}
return $rows;
}
function rp_update_matching_repair_name_in_row($key = '', $uqid = '', $old_dr_row = null, $new_value = '', $dr_category = 0) {
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$what_info = 'r_name';
$what_info_2 = 'dr_name';
if($key === 'repair_name') {
$what_info = 'r_name';
$what_info_2 = 'dr_name';
}
if($key === 'repair_desc') {
$what_info = 'r_discription';
$what_info_2 = 'dr_discription';
}
if($key === 'repair_badge') {
$what_info = 'r_badge';
$what_info_2 = 'dr_badge';
}
if($key === 'repair_read_more') {
$what_info = 'r_readmore';
$what_info_2 = 'dr_readmore';
}
if($key === 'repair_readmore_text') {
$what_info = 'r_readmoretext';
$what_info_2 = 'dr_readmoretext';
}
// Improvement in Query Logic!
$oldValue = $old_dr_row->{$what_info_2} ?? '';
$m_ids = rp_get_all_m_ids_by_category( $dr_category );
if( empty( $m_ids ) ) {
return;
}
$m_ids = join(',', $m_ids);
$sqlQuery = "UPDATE $rs_repair SET `$what_info` = '".rp_escape_sql($new_value)."' WHERE m_id_fk IN (".rp_escape_sql($m_ids).") AND r_uq_id = '".rp_escape_sql($uqid)."' AND ";
if( empty( $oldValue ) ) {
$oldValueQuerySQL = "(`$what_info` = '' OR `$what_info` IS NULL)";
} else {
$oldValueQuerySQL = "`$what_info` = '".rp_escape_sql($oldValue)."'";
}
$sqlQuery .= $oldValueQuerySQL;
$rpQuery->query( $sqlQuery );
}
function rp_update_matching_repair_category_name_in_row($key = '', $uqid = '', $old_dr_row = null, $new_value = '') {
global $rpQuery;
$rs_repairs_category = $rpQuery->prefix . "rs_repairs_category";
$what_info = 'c_name';
$what_info_2 = 'dc_name';
$oldValue = $old_dr_row->{$what_info_2} ?? '';
$sqlQuery = "UPDATE $rs_repairs_category SET `$what_info` = '".rp_escape_sql($new_value)."' WHERE c_uq_id = '".rp_escape_sql($uqid)."' AND ";
if( empty( $oldValue ) ) {
$oldValueQuerySQL = "(`$what_info` = '' OR `$what_info` IS NULL)";
} else {
$oldValueQuerySQL = "`$what_info` = '".rp_escape_sql($oldValue)."'";
}
$sqlQuery .= $oldValueQuerySQL;
$rpQuery->query( $sqlQuery );
}
function rp_update_matching_attr_name_in_row($key = '', $uqid = '', $old_dr_row = null, $new_value = '') {
global $rpQuery;
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$what_info = 'a_name';
$what_info_2 = 'da_name';
if($key === 'attr_name') {
$what_info = 'a_name';
$what_info_2 = 'da_name';
}
if($key === 'attr_desc') {
$what_info = 'a_desc';
$what_info_2 = 'da_desc';
}
if($key === 'attr_badge') {
$what_info = 'a_badge';
$what_info_2 = 'da_badge';
}
if($key === 'attr_read_more') {
$what_info = 'a_readmore';
$what_info_2 = 'da_readmore';
}
if($key === 'attr_readmore_text') {
$what_info = 'a_readmoretext';
$what_info_2 = 'da_readmoretext';
}
$oldValue = $old_dr_row->{$what_info_2} ?? '';
$sqlQuery = "UPDATE `$rs_repair_attr` SET `$what_info` = '".rp_escape_sql($new_value)."' WHERE a_uq_id = '".rp_escape_sql($uqid)."' AND ";
if( empty( $oldValue ) ) {
$oldValueQuerySQL = "(`$what_info` = '' OR `$what_info` IS NULL)";
} else {
$oldValueQuerySQL = "`$what_info` = '".rp_escape_sql($oldValue)."'";
}
$sqlQuery .= $oldValueQuerySQL;
$rpQuery->query( $sqlQuery );
}
if(!function_exists('rp_get_total_counts_of_used_repairs')) {
function rp_get_total_counts_of_used_repairs($dr_uq_id = null, $dr_category = 0) {
if(empty($dr_uq_id)) {
return 0;
}
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$rs_model = $rpQuery->prefix . "rs_model";
$total = $rpQuery->get_var("SELECT COUNT(m_id) FROM `$rs_model` WHERE m_id IN (SELECT m_id_fk FROM `$rs_repair` WHERE `r_uq_id` LIKE '".rp_escape_sql($dr_uq_id)."') AND device_type = '".rp_escape_sql($dr_category)."'");
if(empty($total)) {
return 0;
} else {
return $total;
}
}
}
function rp_user_can_manage_this_order( $o_id = 0 ) {
if( empty( $o_id ) ) {
return FALSE;
}
if( !rp_current_user_has_full_access() ) {
$selected_location_id = intval( rp_get_location_id_of_order( (int) $o_id ) );
if( rp_is_enabled_pricing_based_on_location() == FALSE ) {
return FALSE;
}
$selectable_locations = rp_get_allowed_locations_of_current_user();
if( empty( $selected_location_id ) || !in_array( $selected_location_id, $selectable_locations ) ) {
return FALSE;
}
}
return TRUE;
}
function rp_verify_selected_location_id_by_location_head() {
if( !rp_current_user_has_full_access() ) {
$selected_location_id = intval( $_POST['selected_location_id'] ?? 0 );
if( rp_is_enabled_pricing_based_on_location() == FALSE ) {
echo json_encode(Array('status' => false, 'rp_validation_error' => 'Looks like you do not have permission to do this action.'));
exit;
}
$selectable_locations = rp_get_allowed_locations_of_current_user();
if( empty( $selected_location_id ) || !in_array( $selected_location_id, $selectable_locations ) ) {
echo json_encode(Array('status' => false, 'rp_validation_error' => 'The selected location is either invalid or you are not assigned as the manager of this location.'));
exit;
}
}
}
function update_default_repair(){
rp_verify_csrf_token_for_ajax('default_repairs');
rp_block_more_actions_when_processing_pending_jobs();
rp_verify_selected_location_id_by_location_head();
$rp_current_user_has_full_access = rp_current_user_has_full_access();
global $rpQuery; $repairs = array(); $r_attrs = array();$s= array();
list( $selected_location_id, $rp_location_based_price_id ) = rp_must_verify_selected_location_if_needed_ajax();
$rs_repair = $rpQuery->prefix . "rs_default_repair";
$rs_repairs_category = $rpQuery->prefix . "rs_default_repairs_category";
$rs_repair_attr = $rpQuery->prefix . "rs_default_repair_attr";
$rs_model = $rpQuery->prefix . "rs_model";
$planning = $rpQuery->prefix . "rs_planning_and_discount";
$planning_result = $rpQuery->get_results("SELECT * FROM $planning");
$default_repair_length = 30;
if(!empty($planning_result)) {
$lengthD = $planning_result[0]->booking_slots_length;
if(!empty(trim($lengthD))) {
$lengthD = trim(explode(' ', trim($lengthD))[0]);
if(!empty($lengthD)) {
$default_repair_length = (float) $lengthD;
}
}
}
$mid = $_POST['mid'];
$rid = $_POST['rid'] ?? array();
$title = $_POST['title'] ?? array();
$mins = $_POST['mins'] ?? array();
$duration_measure = $_POST['duration_measure'] ?? array();
$info = $_POST['info'] ?? array();
$badge = $_POST['badge'] ?? array();
$readmore = $_POST['readmore'] ?? array();
$readmoretext = $_POST['readmoretext'] ?? array();
$rprice = $_POST['rprice'] ?? array();
$rmargin = $_POST['rmargin'] ?? array();
$rfree = $_POST['rfree'] ?? array();
$status = $_POST['status'] ?? array();
$attr_status = $_POST['attr_status'] ?? array();
$img_link = $_POST['img_link'] ?? array();
$rcid = $_POST['rcid'] ?? array();
$rcname = $_POST['rcname'] ?? array();
$rcexpand = $_POST['rcexpand'] ?? array();
$rc_img_link = $_POST['rc_img_link'] ?? array();
$rcstatus = $_POST['rcstatus'] ?? array();
$category_repairs_count = $_POST['category_repairs_count'] ?? array();
$dr_category = $_POST['dr_category'] ?? 0;
$create_attr_later = array();
$skipped_index = array();
$rc_skipped_index = array();
$old_rows = array();
$old_rows_category = array();
$old_rows_attr = array();
$newly_created_repair = array();
$newly_created_category = array();
$rpQuery->query('START TRANSACTION');
$saveRepairReadMoreLinks = FALSE;
$saveAttrReadMoreLinks = FALSE;
if( rp_get_option('rp_enable_read_more_link_for_repairs', '0') == '1' ) {
$saveRepairReadMoreLinks = TRUE;
}
if( rp_get_option('rp_enable_read_more_link_for_attributes', '0') == '1' ) {
$saveAttrReadMoreLinks = TRUE;
}
// Update/Create Repairs of Model
foreach($rid as $i => $r){
if(preg_match('/,/',$rprice[$i])) {
$price = str_replace(',','.',$rprice[$i]);
}else{
$price = $rprice[$i];
}
if(empty(trim($price))) {
$price = 0;
}
$marginPrice = FALSE;
if( !empty( $rmargin ) ) {
if(preg_match('/,/',$rmargin[$i])) {
$marginPrice = str_replace(',','.',$rmargin[$i]);
}else{
$marginPrice = $rmargin[$i];
}
if(empty(trim($marginPrice))) {
$marginPrice = 0;
}
}
if( array_search( ($duration_measure[$i] ?? '' ) , array('minutes', 'hours', 'days') ) === FALSE ) {
$duration_measure[$i] = 'minutes';
}
$is_free = $rfree[$i] ?? 0;
if(empty(trim($mins[$i]))) {
$mins[$i] = $default_repair_length;
}
if(trim(strtoupper($r)) === 'NEW') {
if( $rp_current_user_has_full_access == false ) {
$skipped_index[] = $i;
continue;
}
// Create
if(!empty(trim($title[$i]))) {
$r_uq_id = uniqid('repair_');
$r_date_time = date('Y-m-d H:i:s');
$updated_on = date('Y-m-d H:i:s');
$dr_readmore_col = '';
$dr_readmore_value = '';
if( $saveRepairReadMoreLinks == TRUE ) {
$dr_readmore_col = ', dr_readmore';
$dr_readmore_value = ", '".rp_escape_sql($readmore[$i])."'";
$dr_readmore_col .= ', dr_readmoretext';
$dr_readmore_value .= ", '".rp_escape_sql($readmoretext[$i])."'";
}
if( !empty( $selected_location_id ) ) {
// Price based on location
$dr_price_db_col = ', dr_price';
$dr_price_db_value = ", '0'";
$dr_margin = ', dr_margin';
$dr_margin_value = ", '0'";
$dr_is_free_col = ', is_free';
$dr_is_free_value = ", '0'";
} else {
$dr_price_db_col = ', dr_price';
$dr_price_db_value = ", '".rp_escape_sql($price)."'";
if( $marginPrice !== FALSE ) {
$dr_margin = ', dr_margin';
$dr_margin_value = ", '".rp_escape_sql($marginPrice)."'";
} else {
$dr_margin = '';
$dr_margin_value = '';
}
$dr_is_free_col = ', is_free';
$dr_is_free_value = ", '".rp_escape_sql($is_free)."'";
}
$rpQuery->query("INSERT INTO $rs_repair (dr_name, dr_duration, dr_discription, dr_badge, dr_uq_id, dr_img, dr_date_time, updated_on, dr_category, dr_duration_measure $dr_readmore_col $dr_margin $dr_price_db_col $dr_is_free_col) VALUES ('".rp_escape_sql($title[$i])."', '".rp_escape_sql($mins[$i])."', '".rp_escape_sql($info[$i])."', '".rp_escape_sql($badge[$i])."', '".rp_escape_sql($r_uq_id)."', '".rp_escape_sql($img_link[$i])."', '".rp_escape_sql($r_date_time)."', '".rp_escape_sql($updated_on)."', '".rp_escape_sql($dr_category)."', '".rp_escape_sql($duration_measure[$i])."' $dr_readmore_value $dr_margin_value $dr_price_db_value $dr_is_free_value);");
$rid[$i] = $rpQuery->insert_id;
$newly_created_repair[] = $rpQuery->insert_id;
} else {
$skipped_index[] = $i;
}
} else {
// Update
$old_row = $rpQuery->get_results("SELECT * FROM $rs_repair WHERE dr_id='".rp_escape_sql($r)."' AND dr_category='".rp_escape_sql($dr_category)."';");
if( !empty( $selected_location_id ) ) {
$old_row = $old_row[0];
// price based on location
list( $lb_price, $lb_margin, $lb_is_free ) = rp_get_repair_price_based_on_location_and_connection( 'dr', $old_row->dr_id, $selected_location_id );
$old_row->dr_price = $lb_price;
$old_row->dr_margin = $lb_margin;
$old_row->is_free = $lb_is_free;
$old_row = array( $old_row );
}
$old_rows[$r] = $old_row[0];
if( !empty( $selected_location_id ) ) {
// Price based on location
$dr_price_db = '';
$dr_margin = '';
$dr_is_free = '';
} else {
$dr_price_db = ', dr_price = "'.rp_escape_sql($price).'"';
if( $marginPrice !== FALSE ) {
$dr_margin = ', dr_margin = "'.rp_escape_sql($marginPrice).'"';
} else {
$dr_margin = '';
}
$dr_is_free = ', is_free = "'.rp_escape_sql($is_free).'"';
}
$updated_on = date('Y-m-d H:i:s');
if( $rp_current_user_has_full_access == true ) {
$rpQuery->query("UPDATE $rs_repair SET dr_duration='".rp_escape_sql($mins[$i])."',dr_img='".rp_escape_sql($img_link[$i])."',updated_on='".rp_escape_sql($updated_on)."',is_free='".rp_escape_sql($is_free)."',dr_duration_measure='".rp_escape_sql($duration_measure[$i])."' $dr_margin $dr_price_db $dr_is_free WHERE dr_id='".rp_escape_sql($r)."' AND dr_category='".rp_escape_sql($dr_category)."';");
}
}
}
if( !empty( $selected_location_id ) ) {
foreach($rid as $i => $r){
if(!in_array($i, $skipped_index)) {
if(preg_match('/,/',$rprice[$i])) {
$price = str_replace(',','.',$rprice[$i]);
}else{
$price = $rprice[$i];
}
if(empty(trim($price))) {
$price = 0;
}
$marginPrice = FALSE;
if( !empty( $rmargin ) ) {
if(preg_match('/,/',$rmargin[$i])) {
$marginPrice = str_replace(',','.',$rmargin[$i]);
}else{
$marginPrice = $rmargin[$i];
}
if(empty(trim($marginPrice))) {
$marginPrice = 0;
}
}
$is_free = $rfree[$i] ?? 0;
rp_update_default_repair_price_based_on_location( $r, $selected_location_id, $price, $marginPrice, $is_free );
}
}
}
if( $rp_current_user_has_full_access == true ) {
// Update/Create Repairs of Model
foreach($rcid as $i => $rc){
$is_expand = $rcexpand[$i] ?? 0;
if(trim(strtoupper($rc)) === 'NEW') {
// Create
if(!empty(trim($rcname[$i]))) {
$c_uq_id = uniqid('rcat_');
$c_date_time = date('Y-m-d H:i:s');
$updated_on = date('Y-m-d H:i:s');
$rpQuery->query("INSERT INTO $rs_repairs_category (dc_name, dc_uq_id, dc_img, dc_date_time, updated_on, dc_category, `expand`) VALUES ('".rp_escape_sql($rcname[$i])."', '".rp_escape_sql($c_uq_id)."', '".rp_escape_sql($rc_img_link[$i])."', '".rp_escape_sql($c_date_time)."', '".rp_escape_sql($updated_on)."', '".rp_escape_sql($dr_category)."', '".rp_escape_sql($is_expand)."');");
$rcid[$i] = $rpQuery->insert_id;
$newly_created_category[] = $rpQuery->insert_id;
} else {
$rc_skipped_index[] = $i;
}
} else {
// Update
$old_row = $rpQuery->get_results("SELECT * FROM $rs_repairs_category WHERE dc_id='".rp_escape_sql($rc)."' AND dc_category='".rp_escape_sql($dr_category)."';");
$old_rows_category[$rc] = $old_row[0];
$updated_on = date('Y-m-d H:i:s');
$rpQuery->query("UPDATE $rs_repairs_category SET dc_img='".rp_escape_sql($rc_img_link[$i])."',`expand`='".rp_escape_sql($is_expand)."',updated_on='".rp_escape_sql($updated_on)."' WHERE dc_id='".rp_escape_sql($rc)."' AND dc_category='".rp_escape_sql($dr_category)."';");
}
}
}
// Update/Create Repair Attrs of Model
$raid = $_POST['raid'] ?? array();
foreach ($raid as $i => $arr) {
if(!in_array($i, $skipped_index)) {
$a_id = $_POST['raid'][$i];
$a_name = $_POST['raname'][$i];
$a_duration = $_POST['raduration'][$i];
$a_duration_measure = $_POST['radurationmeasure'][$i];
$a_desc = $_POST['radesc'][$i];
$a_badge = $_POST['rabadge'][$i];
$a_readmore = $_POST['rareadmore'][$i] ?? array();
$a_readmoretext = $_POST['rareadmoretext'][$i] ?? array();
$a_price = $_POST['raprice'][$i];
$a_margin = $_POST['ramargin'] ?? array();
if( !empty( $a_margin ) ) {
$a_margin = $_POST['ramargin'][$i] ?? array();
}
$a_is_active = $_POST['raactive'][$i] ?? array();
$skipped_a_index = array();
foreach($a_id as $x => $a){
if( empty( trim( $a_duration[$x] ?? '' ) ) ) {
$a_duration[$x] = $default_repair_length;
}
if(preg_match('/,/',$a_price[$x])) {
$a_price[$x] = str_replace(',','.',$a_price[$x]);
}
if(empty(trim($a_price[$x]))) {
$a_price[$x] = 0;
}
$attrMarginPrice = FALSE;
if( !empty( $a_margin ) ) {
if(preg_match('/,/',$a_margin[$x])) {
$attrMarginPrice = str_replace(',','.',$a_margin[$x]);
} else {
$attrMarginPrice = $a_margin[$x];
}
if(empty(trim($a_margin[$x]))) {
$attrMarginPrice = 0;
}
}
if(strtoupper($a_id[$x]) === 'NEW') {
if( $rp_current_user_has_full_access == false ) {
$skipped_a_index[] = $x;
continue;
}
if(!empty(trim($a_name[$x]))) {
$da_readmore_col = '';
$da_readmore_value = '';
if( $saveAttrReadMoreLinks == TRUE ) {
$da_readmore_col = ', da_readmore';
$da_readmore_value = ", '".rp_escape_sql($a_readmore[$x])."'";
$da_readmore_col .= ', da_readmoretext';
$da_readmore_value .= ", '".rp_escape_sql($a_readmoretext[$x])."'";
}
if( !empty( $selected_location_id ) ) {
// Price based on location
$da_price_db_col = ', `da_price`';
$da_price_db_val = ", '0'";
$da_margin = ', `da_margin`';
$da_margin_value = ", '0'";
} else {
$da_price_db_col = ', `da_price`';
$da_price_db_val = ", '".rp_escape_sql($a_price[$x])."'";
if( $attrMarginPrice !== FALSE ) {
$da_margin = ', `da_margin`';
$da_margin_value = ", '".rp_escape_sql($attrMarginPrice)."'";
} else {
$da_margin = '';
$da_margin_value = '';
}
}
$a_uq_id = uniqid('rattr_');
$rpQuery->query("INSERT INTO $rs_repair_attr (`da_name`, `da_duration`, `da_duration_measure`, `da_desc`, `da_badge`, `da_uq_id`, `dr_id_fk`, `dr_category` $da_readmore_col $da_margin $da_price_db_col) VALUES('".rp_escape_sql($a_name[$x])."', '".rp_escape_sql($a_duration[$x])."', '".rp_escape_sql($a_duration_measure[$x])."', '".rp_escape_sql($a_desc[$x])."', '".rp_escape_sql($a_badge[$x])."', '".rp_escape_sql($a_uq_id)."', '".rp_escape_sql($rid[$i])."', '".rp_escape_sql($dr_category)."' $da_readmore_value $da_margin_value $da_price_db_val)");
$a_id[$x] = $rpQuery->insert_id;
$create_attr_later[] = $a_id[$x];
} else {
$skipped_a_index[] = $x;
}
} else {
$old_row_attr = $rpQuery->get_results("SELECT * FROM $rs_repair_attr WHERE da_id='".rp_escape_sql($a_id[$x])."' AND dr_category='".rp_escape_sql($dr_category)."';");
if( !empty( $selected_location_id ) ) {
// Price based on location
$old_row_attr = $old_row_attr[0];
list( $lb_price, $lb_margin, $lb_is_free ) = rp_get_repair_price_based_on_location_and_connection( 'da', $old_row_attr->da_id, $selected_location_id );
$old_row_attr->da_price = $lb_price;
$old_row_attr->da_margin = $lb_margin;
$old_row_attr->is_free = 0;
$old_row_attr = array( $old_row_attr );
}
$old_rows_attr[$a_id[$x]] = $old_row_attr[0];
if( !empty( $selected_location_id ) ) {
// Price based on location
$da_price_db = '';
$da_margin = '';
} else {
$da_price_db = ', da_price = "'.rp_escape_sql($a_price[$x]).'"';
if( $attrMarginPrice !== FALSE ) {
$da_margin = ', da_margin = "'.rp_escape_sql($attrMarginPrice).'"';
} else {
$da_margin = '';
}
}
if( $rp_current_user_has_full_access == true ) {
$rpQuery->query("UPDATE $rs_repair_attr SET da_duration='".rp_escape_sql($a_duration[$x])."', da_duration_measure='".rp_escape_sql($a_duration_measure[$x])."' $da_margin $da_price_db WHERE da_id='".rp_escape_sql($a_id[$x])."' AND dr_category='".rp_escape_sql($dr_category)."'");
}
}
}
if( !empty( $selected_location_id ) ) {
foreach($a_id as $x => $a){
if(!in_array($x, $skipped_a_index)) {
if(preg_match('/,/',$a_price[$x])) {
$a_price[$x] = str_replace(',','.',$a_price[$x]);
}
if(empty(trim($a_price[$x]))) {
$a_price[$x] = 0;
}
$attrMarginPrice = FALSE;
if( !empty( $a_margin ) ) {
if(preg_match('/,/',$a_margin[$x])) {
$attrMarginPrice = str_replace(',','.',$a_margin[$x]);
} else {
$attrMarginPrice = $a_margin[$x];
}
if(empty(trim($a_margin[$x]))) {
$attrMarginPrice = 0;
}
}
rp_update_default_repair_attr_price_based_on_location( $a_id[$x], $selected_location_id, $a_price[$x], $attrMarginPrice, 0 );
}
}
}
if( $rp_current_user_has_full_access == true ) {
$a_i = 1;
foreach($a_id as $x => $a){
if(!in_array($x, $skipped_a_index)) {
$rpQuery->query("UPDATE $rs_repair_attr SET da_position='".rp_escape_sql($a_i)."' WHERE da_id='".rp_escape_sql($a_id[$x])."' AND dr_category='".rp_escape_sql($dr_category)."'");
$a_i++;
}
}
foreach($a_id as $x => $a){
if(!in_array($x, $skipped_a_index)) {
if( !empty($a_is_active[$x]) ) {
$_is_active = '1';
} else {
$_is_active = '0';
}
$rpQuery->query("UPDATE $rs_repair_attr SET is_active='".rp_escape_sql($_is_active)."' WHERE da_id='".rp_escape_sql($a_id[$x])."' AND dr_category='".rp_escape_sql($dr_category)."'");
$a_i++;
}
}
}
}
}
if( $rp_current_user_has_full_access == true ) {
// Update Repair Position
$r_i = 1;
foreach($rid as $i => $repairId){
if(!in_array($i, $skipped_index)) {
$rpQuery->query("UPDATE $rs_repair SET dr_position='".rp_escape_sql($r_i)."' WHERE dr_id='".rp_escape_sql($repairId)."' AND dr_category='".rp_escape_sql($dr_category)."'");
$r_i++;
}
}
// Update Repair Attr Position
// Update Repair Statuses
$rpQuery->query("UPDATE $rs_repair SET is_active= '0' WHERE dr_category='".rp_escape_sql($dr_category)."'");
foreach($status as $i => $s){
if(!in_array($i, $skipped_index)) {
if(!empty($s)) {
$rpQuery->query("UPDATE $rs_repair SET is_active='1' WHERE dr_id='".rp_escape_sql($rid[$i])."' AND dr_category='".rp_escape_sql($dr_category)."'");
}
}
}
}
// Update/Create Repairs of Model
foreach($rid as $i => $r){
if(!in_array($i, $skipped_index)) {
if(!in_array($r, $newly_created_repair)) {
// Update
$old_row = $old_rows[$r];
if( $rp_current_user_has_full_access == true ) {
update_unchanged_repair_COLUMNS($old_row, ($_POST['dr_category'] ?? 0), ($rp_location_based_price_id ?? 0));
}
if( isset( $rp_location_based_price_id ) && !empty( $rp_location_based_price_id ) ) {
// Need to Edit 1
update_unchanged_repair_price_loc_based($old_row, $create_attr_later, ($_POST['dr_category'] ?? 0), $rp_location_based_price_id, 'price');
update_unchanged_repair_price_loc_based($old_row, $create_attr_later, ($_POST['dr_category'] ?? 0), $rp_location_based_price_id, 'margin');
} else {
if( $rp_current_user_has_full_access == true ) {
// Need to Edit 2
update_unchanged_repair_price($old_row, $create_attr_later, ($_POST['dr_category'] ?? 0), 'price');
update_unchanged_repair_price($old_row, $create_attr_later, ($_POST['dr_category'] ?? 0), 'margin');
}
}
if( $rp_current_user_has_full_access == true ) {
update_unchanged_repair_img($old_row, ($_POST['dr_category'] ?? 0));
}
} else {
if( $rp_current_user_has_full_access == true ) {
create_default_repair_for_all_models($r, ($_POST['dr_category'] ?? 0));
}
}
}
}
// *****************
if( $rp_current_user_has_full_access == true ) {
// Update Repair Position
$c_i = 1;
foreach($rcid as $i => $catId){
if(!in_array($i, $rc_skipped_index)) {
$rpQuery->query("UPDATE $rs_repairs_category SET dc_position='".rp_escape_sql($c_i)."' WHERE dc_id='".rp_escape_sql($catId)."' AND dc_category='".rp_escape_sql($dr_category)."'");
$c_i++;
}
}
// Update Repair Attr Position
// Update Repair Statuses
$rpQuery->query("UPDATE $rs_repairs_category SET is_active= '0' WHERE dc_category='".rp_escape_sql($dr_category)."'");
foreach($rcstatus as $i => $s){
if(!in_array($i, $rc_skipped_index)) {
if(!empty($s)) {
$rpQuery->query("UPDATE $rs_repairs_category SET is_active='1' WHERE dc_id='".rp_escape_sql($rcid[$i])."' AND dc_category='".rp_escape_sql($dr_category)."'");
}
}
}
// Update/Create Repairs of Model
foreach($rcid as $i => $rc){
if(!in_array($i, $rc_skipped_index)) {
if(!in_array($rc, $newly_created_category)) {
// Update
$old_row = $old_rows_category[$rc];
update_unchanged_repair_category_COLUMNS($old_row, ($_POST['dr_category'] ?? 0));
update_unchanged_repair_category_img($old_row, ($_POST['dr_category'] ?? 0));
} else {
create_default_repair_category_for_all_models($rc, ($_POST['dr_category'] ?? 0));
}
}
}
$last_correct_category = null;
$addLaterToFirst = array();
$category_repairs_count_before = $category_repairs_count;
foreach( $category_repairs_count as $i => $cr_count ) {
if(!in_array($i, $rc_skipped_index)) {
$last_correct_category = $i;
if( !empty( $addLaterToFirst ) ) {
$category_repairs_count[ $last_correct_category ] += array_sum( $addLaterToFirst );
$addLaterToFirst = array();
}
} else {
if( $last_correct_category === null ) {
$addLaterToFirst[] = $cr_count;
} else {
$category_repairs_count[ $last_correct_category ] += $cr_count;
}
$category_repairs_count[ $i ] = 0;
}
}
if( !empty( $addLaterToFirst ) ) {
$category_repairs_count[ $last_correct_category ] += array_sum( $addLaterToFirst );
$addLaterToFirst = array();
}
$rid_copy = $rid;
$repairsByCategory = array();
foreach($rcid as $i => $catId){
if(!in_array($i, $rc_skipped_index)) {
$repairsByCategory[ $catId ] = array();
// total repairs in this category
$totalRepairs = $category_repairs_count[$i] ?? 0;
if( $totalRepairs > 0 ) {
$currentItem = 1;
foreach($rid_copy as $x => $repairId){
if( $currentItem > $totalRepairs ) {
break;
}
if(!in_array($x, $skipped_index)) {
$repairsByCategory[ $catId ][] = $repairId;
}
unset($rid_copy[$x]);
$currentItem++;
}
}
}
}
rp_update_repairs_by_category( $dr_category, $repairsByCategory );
}
//******************/
if( $rp_current_user_has_full_access == true ) {
foreach ($create_attr_later as $attr_id) {
if( isset( $rp_location_based_price_id ) && !empty( $rp_location_based_price_id ) ) {
// Price based on location
create_default_repair_attr_for_all_models_loc_based($attr_id, $create_attr_later, $old_rows, ( $_POST['dr_category'] ?? 0 ), $rp_location_based_price_id);
} else {
create_default_repair_attr_for_all_models($attr_id, $create_attr_later, $old_rows, ( $_POST['dr_category'] ?? 0 ));
}
}
}
$raid = $_POST['raid'] ?? array();
foreach ($raid as $i => $arr) {
if(!in_array($i, $skipped_index)) {
$a_id = $_POST['raid'][$i];
$a_name = $_POST['raname'][$i];
$skipped_a_index = array();
foreach($a_id as $x => $a){
if(strtoupper($a_id[$x]) === 'NEW') {
if(!empty(trim($a_name[$x]))) {
// New Create Here...
// Already Created in Above Similar Loop..
} else {
// Skip This...
}
} else {
// Old Update Here
$old_row = $old_rows_attr[$a_id[$x]];
if( isset( $rp_location_based_price_id ) && !empty( $rp_location_based_price_id ) ) {
// Price based on location
// Need to Edit 3
update_unchanged_repair_attr_price_loc_based($old_row, $old_rows, $create_attr_later, ( $_POST['dr_category'] ?? 0 ), $rp_location_based_price_id, 'price');
update_unchanged_repair_attr_price_loc_based($old_row, $old_rows, $create_attr_later, ( $_POST['dr_category'] ?? 0 ), $rp_location_based_price_id, 'margin');
} else {
if( $rp_current_user_has_full_access == true ) {
// Need to Edit 4
update_unchanged_repair_attr_price($old_row, $old_rows, $create_attr_later, ( $_POST['dr_category'] ?? 0 ), 'price');
update_unchanged_repair_attr_price($old_row, $old_rows, $create_attr_later, ( $_POST['dr_category'] ?? 0 ), 'margin');
}
}
if( $rp_current_user_has_full_access == true ) {
update_unchanged_repair_attr_COLUMNS($old_row, ( $_POST['dr_category'] ?? 0 ));
}
}
}
}
}
// Return Result Array
$rpQuery->query('COMMIT');
if( array_key_exists( 'default_listing_range', $_POST ) ) {
$default_listing_range = (int) ($_POST['default_listing_range'] ?? 6);
} else {
$default_listing_range = rp_get_option( 'rp_default_listing_index_' . ((int)$dr_category), 6 );
}
$default_listing_range = rp_round_to_even_number($default_listing_range);
list( $category_based, $categoriesCount ) = rp_get_default_repairs_again_after_update( $dr_category, $default_listing_range );
if( $rp_current_user_has_full_access == true ) {
if( $categoriesCount < 2 && count( $_POST['rcid'] ?? array() ) < 2 ) {
// get previous position
$previous_position = rp_get_option( 'rp_default_listing_index_' . ((int)$dr_category), FALSE );
if( $previous_position !== FALSE && $previous_position !== $default_listing_range ) {
rp_update_default_listing_index_individually( (int) $previous_position, (int) $default_listing_range, (int) $dr_category );
}
rp_update_option( 'rp_default_listing_index_' . ((int)$dr_category), $default_listing_range );
}
}
echo json_encode(Array('status' => true, 'message' => 'Successfully Updated', 'category_based' => $category_based));
exit();
}
function rp_get_default_repairs_again_after_update( $dr_category = 0, $default_listing_range = 0 ) {
global $rpQuery;
global $rp_location_based_price_id;
$rs_repair = $rpQuery->prefix . "rs_default_repair";
$rs_repair_attr = $rpQuery->prefix . "rs_default_repair_attr";
$mid = 999;
$category_based = rp_get_default_repairs_based_on_repair_category($dr_category);
$categoriesCount = 0;
if( !empty( $category_based ) ) {
$categoriesCount = count($category_based);
foreach( $category_based as $cb_key => $repairCategory ) {
$repairCategory->dc_name = rp_get_static_translations_of_drepair_category('category_name', $repairCategory->dc_uq_id);
$table_rows = array();
$c_repair_all = $repairCategory->repairs;
if(!empty($c_repair_all)) {
$last_index = count($c_repair_all) - 1;
if( $default_listing_range > ($last_index + 1) ) {
$default_listing_range = $last_index + 1;
}
if( 0 == $default_listing_range && $last_index !== -1 && $categoriesCount < 2 ){
$seprator_tr = array();
$seprator_tr['listing_range'] = 0;
$table_rows[] = $seprator_tr;
}
foreach ($c_repair_all as $i => $c_repair) {
if( isset( $rp_location_based_price_id ) && !empty( $rp_location_based_price_id ) ) {
$c_repair = apply_filters('rp_overwrite_default_repair_row', $c_repair, $rp_location_based_price_id);
}
$tr = array();
$tr['is_free'] = $c_repair->is_free;
$tr['is_active'] = $c_repair->is_active;
$tr['dr_duration_measure'] = ( !empty( $c_repair->dr_duration_measure ) ? $c_repair->dr_duration_measure : '' );
$tr['m_id'] = $mid;
$tr['total_used'] = rp_get_total_counts_of_used_repairs($c_repair->dr_uq_id, $dr_category);
$tr['r_id'] = $c_repair->dr_id;
$tr['r_img'] = $c_repair->dr_img;
$tr['dr_uq_id'] = $c_repair->dr_uq_id;
$tr['repair_title'] = rp_get_static_translations_of_drepair('repair_name', $c_repair->dr_uq_id . '_' .$dr_category);
$tr['repair_min'] = $c_repair->dr_duration;
$tr['repair_info'] = rp_get_static_translations_of_drepair('repair_desc', $c_repair->dr_uq_id . '_' .$dr_category);
$tr['repair_badge'] = rp_get_static_translations_of_drepair('repair_badge', $c_repair->dr_uq_id . '_' .$dr_category);
$tr['repair_read_more'] = rp_get_static_translations_of_drepair('repair_read_more', $c_repair->dr_uq_id . '_' .$dr_category);
$tr['repair_readmore_text'] = rp_get_static_translations_of_drepair('repair_readmore_text', $c_repair->dr_uq_id . '_' .$dr_category);
$tr['repair_price'] = $c_repair->dr_price;
$tr = rp_sanitize_output($tr);
$tr['attrs'] = array();
$repair_attrs = $rpQuery->get_results("SELECT * FROM $rs_repair_attr WHERE `dr_id_fk` = '".rp_escape_sql($c_repair->dr_id)."' AND dr_category = '".rp_escape_sql($dr_category)."' ORDER BY `da_position` ASC");
if(!empty($repair_attrs)) {
foreach ($repair_attrs as $x => $c_attr) {
if( isset( $rp_location_based_price_id ) && !empty( $rp_location_based_price_id ) ) {
$c_attr = apply_filters('rp_overwrite_default_repair_attr_row', $c_attr, $rp_location_based_price_id);
}
$attr = array();
$attr['a_id'] = $c_attr->da_id;
$attr['a_name'] = rp_get_static_translations_of_dattr('attr_name', $c_attr->da_uq_id);
$attr['attr_min'] = $c_attr->da_duration;
$attr['da_duration_measure'] = ( !empty( $c_attr->da_duration_measure ) ? $c_attr->da_duration_measure : '' );
$attr['a_desc'] = rp_get_static_translations_of_dattr('attr_desc', $c_attr->da_uq_id);
$attr['a_badge'] = rp_get_static_translations_of_dattr('attr_badge', $c_attr->da_uq_id);
$attr['a_readmore'] = rp_get_static_translations_of_dattr('attr_read_more', $c_attr->da_uq_id);
$attr['a_readmoretext'] = rp_get_static_translations_of_dattr('attr_readmore_text', $c_attr->da_uq_id);
$attr['a_price'] = $c_attr->da_price;
$attr['is_active'] = $c_attr->is_active;
$attr['da_uq_id'] = $c_attr->da_uq_id;
$attr = rp_sanitize_output($attr);
$attr = apply_filters('rp_before_returning_default_repair_attr', $attr, $c_attr);
$tr['attrs'][] = $attr;
}
$tr['repair_price'] = rp_get_lowest_default_repair_attribute_price( $c_repair->dr_id );
}
$tr = apply_filters('rp_before_returning_default_repair_tr', $tr, $c_repair);
$table_rows[] = $tr;
if( $i+1 == $default_listing_range && $categoriesCount < 2 ){
$seprator_tr = array();
$seprator_tr['listing_range'] = $default_listing_range;
$table_rows[] = $seprator_tr;
}
}
}
$repairCategory->repairs = $table_rows;
$category_based[$cb_key] = $repairCategory;
}
}
return array($category_based, $categoriesCount);
}
rp_ajax_for_admin('update_default_repair','update_default_repair');
function rp_update_default_listing_index_individually($previous_position = 0, $new_position = 0, $dr_category = 0) {
if( $dr_category === 0 || $previous_position === $new_position ) {
// dr category is not set or previous position and new position is same
return;
}
// steps to update default listing index individually
// 1. get all model ids(m_id) from rs_model table where device_type = $dr_category
// 2. get all options from wp_options table where option_name like 'rp_default_listing_index_model_%' AND option_value = $previous_position
// 3. loop through all options and replace rp_default_listing_index_model_ from option_name to get remaining part of option_name (m_id)
// 4. check if m_id is in array of model ids
// 5. if yes then update that option with new position
global $rpQuery;
$rs_model = $rpQuery->prefix . "rs_model";
$options_table = $rpQuery->prefix . "options";
$model_ids = $rpQuery->get_results("SELECT m_id FROM $rs_model WHERE device_type = '".rp_escape_sql($dr_category)."'");
$model_ids = wp_list_pluck($model_ids, 'm_id');
$options = $rpQuery->get_results("SELECT * FROM $options_table WHERE option_name LIKE 'rp_default_listing_index_model_%' AND option_value = '".rp_escape_sql($previous_position)."'");
if( !empty($options) ) {
foreach ($options as $key => $option) {
$option_name = $option->option_name;
$option_name = str_replace('rp_default_listing_index_model_', '', $option_name);
if( !empty($option_name) && is_numeric($option_name) ) {
$option_name = (int) $option_name;
if( in_array($option_name, $model_ids) ) {
// delete $option_name
rp_delete_option($option->option_name);
}
}
}
}
}
//-------------------------------------------------------------------update model
function update_model(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
global $rpQuery; $abc = array();
$rs_model = $rpQuery->prefix . "rs_model";
$rs_model_color = $rpQuery->prefix . "rs_model_color";
$mid = $_POST['mid'];
$m_name = $_POST['m_name'];
$m_code = $_POST['m_code'];
$r_date = $_POST['r_date'];
$status = $_POST['status'];
// if (isset($_POST['img'])){
// $file=$_POST['img'];
// list($type, $file) = explode(';', $file);
// list(, $file) = explode(',', $file);
// $file = base64_decode($file);
// $upload_overrides = array('test_form' => false);
// $movefile = wp_handle_upload($file, $upload_overrides);
// if($movefile["url"] != "" || $movefile["url"] != null ){
// $m_logo = $movefile['url'];
// $rpQuery->query("UPDATE $rs_model SET m_img='".rp_escape_sql($m_logo)."' WHERE m_id='".rp_escape_sql($mid)."'");
// }
// }
$rpQuery->query("UPDATE $rs_model SET m_name='".rp_escape_sql($m_name)."',is_active='".rp_escape_sql($status)."',m_code='".rp_escape_sql($m_code)."',release_date='".rp_escape_sql($r_date)."' WHERE m_id='".rp_escape_sql($mid)."'");
$mc_name = $_POST['mc_name'] ?? array();
$mc_code = $_POST['mc_code'] ?? array();
$mc_id = $_POST['mcid'] ?? array();
foreach($mc_id as $x => $mcid){
if(!empty(trim($mc_name[$x]))) {
if(strtoupper(trim($mcid)) === 'NEW') {
$mc_uq_id = uniqid('modelcolor_');
$rpQuery->query("INSERT INTO $rs_model_color(color_name,color_code,mc_uq_id,m_id_fk) VALUES('".rp_escape_sql($mc_name[$x])."','".rp_escape_sql($mc_code[$x])."','".rp_escape_sql($mc_uq_id)."','".rp_escape_sql($mid)."')");
$mc_id[$x] = $rpQuery->insert_id;
} else {
$rpQuery->query("UPDATE $rs_model_color SET color_name='".rp_escape_sql($mc_name[$x])."',color_code='".rp_escape_sql($mc_code[$x])."' WHERE mc_id='".rp_escape_sql($mcid)."'");
}
} else {
unset($mc_id[$x]);
}
}
$i = 1;
foreach($mc_id as $x => $mcid){
$rpQuery->query("UPDATE $rs_model_color SET mc_position='".rp_escape_sql($i)."' WHERE mc_id='".rp_escape_sql($mcid)."'");
$i++;
}
if(isset($_POST['m_sort'])) {
$m_sort = $_POST['m_sort'] ?? 0;
$m_sort = (int) $m_sort;
// get brand_id_fk of rs_model
$brand_id_fk = $rpQuery->get_row("SELECT brand_id_fk FROM $rs_model WHERE m_id='".rp_escape_sql($mid)."' LIMIT 1;");
if( !empty( $brand_id_fk ) ) {
$brand_id_fk = $brand_id_fk->brand_id_fk;
$all_model_info = $rpQuery->get_results("SELECT m_id, m_position, brand_id_fk FROM $rs_model WHERE brand_id_fk = {$brand_id_fk} ORDER BY m_position ASC, release_date DESC;");
$sortedModels = array();
if( !empty( $all_model_info ) ) {
foreach( $all_model_info as $theKey => $theValue ) {
$sortedModels[] = $theValue->m_id;
}
}
// remove $mid from $sortedModels
$sortedModels = array_diff( $sortedModels, array( $mid ) );
// array values
$sortedModels = array_values( $sortedModels );
$sort_pos = 1;
if( $m_sort > count( $sortedModels ) ) {
$m_sort = count( $sortedModels ) + 1;
}
foreach( $sortedModels as $theKey => $theValue ) {
if( $sort_pos === $m_sort ) {
// update m_position
$rpQuery->query("UPDATE $rs_model SET m_position='".rp_escape_sql($m_sort)."' WHERE m_id='".rp_escape_sql($mid)."'");
$sort_pos++;
}
// update m_position
$rpQuery->query("UPDATE $rs_model SET m_position='".rp_escape_sql($sort_pos)."' WHERE m_id='".rp_escape_sql($theValue)."'");
$sort_pos++;
if( $sort_pos === $m_sort ) {
// update m_position
$rpQuery->query("UPDATE $rs_model SET m_position='".rp_escape_sql($m_sort)."' WHERE m_id='".rp_escape_sql($mid)."'");
$sort_pos++;
}
}
}
}
if(isset($_POST['m_link'])) {
$m_link = $_POST['m_link'];
$rpQuery->query("UPDATE $rs_model SET m_img='".rp_escape_sql($m_link)."' WHERE m_id='".rp_escape_sql($mid)."'");
}
echo json_encode(
array(
'status' => true,
'message' => 'Successfully Updated',
'color_info' => array(
'mc_name' => $mc_name,
'mc_id' => $mc_id,
'mc_code' => $mc_code
)
)
);
exit();
}
rp_ajax_for_admin('update_model','update_model');
function update_model_img(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
global $rpQuery; $abc = array();
$rs_model = $rpQuery->prefix . "rs_model";
$rs_model_color = $rpQuery->prefix . "rs_model_color";
$logo = '';
if(isset($_FILES) && !empty($_FILES) && isset($_FILES['file']) && isset($_POST) && isset($_POST['mid']) && !empty($_POST['mid'])) {
$mid = $_POST['mid'];
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if(!empty($movefile["url"])){
$logo = $movefile["url"];
$rpQuery->query("UPDATE $rs_model SET m_img = '".rp_escape_sql($logo)."' WHERE m_id = '".rp_escape_sql($mid)."' LIMIT 1;");
}
}
echo json_encode(Array('status' => true, 'message' => 'Successfully Updated', 'logo' => $logo));
exit();
}
rp_ajax_for_admin('update_model_img','update_model_img');
// --------------------------------------------------------- add model
function rp_get_model_name_by_m_id( $m_id = 0 ) {
if( empty( $m_id ) ) {
return '';
}
global $rpQuery;
$rs_model = $rpQuery->prefix . "rs_model";
$rows = $rpQuery->get_results("SELECT `m_name` FROM $rs_model WHERE `m_id` = '".rp_escape_sql($m_id)."' LIMIT 1;");
if(!empty($rows)) {
return $rows[0]->m_name;
}
return '';
}
function wp_repair_get_brand_name_by_id($b_id = '') {
if(!empty($b_id)) {
global $rpQuery;
$rs_brand = $rpQuery->prefix . "rs_brand";
$rows = $rpQuery->get_results("SELECT `b_name` FROM $rs_brand WHERE `b_id` = '".rp_escape_sql($b_id)."' LIMIT 1;");
if(!empty($rows)) {
return $rows[0]->b_name;
} else {
return '';
}
}
return '';
}
function rp_get_brand_by_uqid( $uqid = '' ) {
if(!empty($uqid)) {
global $rpQuery;
$rs_brand = $rpQuery->prefix . "rs_brand";
$row = $rpQuery->get_row("SELECT * FROM `$rs_brand` WHERE `b_uq_id` = '".rp_escape_sql($uqid)."' LIMIT 1;");
if(!empty($row)) {
return $row;
} else {
return '';
}
}
return '';
}
function rp_get_category_id_by_c_id_fk($c_id_fk = '') {
if(!empty($c_id_fk)) {
global $rpQuery;
$rs_category = $rpQuery->prefix . "rs_category";
$row = $rpQuery->get_row("SELECT * FROM `$rs_category` WHERE `c_id` = '".rp_escape_sql($c_id_fk)."' LIMIT 1;");
if(!empty($row)) {
return $row;
} else {
return '';
}
}
return '';
}
function wp_repair_get_category_name_by_id($c_id = '') {
if(!empty($c_id)) {
global $rpQuery;
$rs_category = $rpQuery->prefix . "rs_category";
$rows = $rpQuery->get_results("SELECT `c_name` FROM $rs_category WHERE `c_id` = '".rp_escape_sql($c_id)."' LIMIT 1;");
if(!empty($rows)) {
return $rows[0]->c_name;
} else {
return '';
}
}
return '';
}
function wp_repair_add_model() {
rp_verify_csrf_token_for_ajax('manage_models');
rp_block_more_actions_when_processing_pending_jobs();
rp_verify_user_full_access_ajax();
global $rpQuery;
list( $selected_location_id, $rp_location_based_price_id ) = rp_must_verify_selected_location_if_needed_ajax();
$rs_model = $rpQuery->prefix . "rs_model";
$uploadedfile = $_FILES['m_img'] ?? FALSE;
if($uploadedfile !== FALSE) {
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
$m_img = $movefile["url"] ?? '';
} else {
$m_img = '';
}
$m_name = $_POST['mname'] ?? '';
$m_name = trim($m_name);
$m_code = $_POST['mcode'] ?? '';
$release_date = date('Y-m-d', strtotime($_POST['releasedate']));
$device_type = $_POST['device_type'];
$brand_id_fk = $_POST['brand_id_fk'];
$m_uq_id = uniqid('model_');
$exists = $rpQuery->get_results("SELECT * FROM $rs_model WHERE `device_type` = '".rp_escape_sql($device_type)."' AND `brand_id_fk` = '".rp_escape_sql($brand_id_fk)."' AND `m_name` = '".rp_escape_sql($m_name)."' LIMIT 1;");
if(!empty($exists)) {
echo json_encode(array('status' => false, 'message' => 'already_exists'));
exit();
}
$r_ids = rp_get_all_default_repair_ids_of_category($device_type, TRUE);
$rpQuery->query("INSERT INTO $rs_model(m_name,m_img,device_type,brand_id_fk,m_code,release_date,m_uq_id,repair_ids) VALUES('".rp_escape_sql($m_name)."','".rp_escape_sql($m_img)."','".rp_escape_sql($device_type)."','".rp_escape_sql($brand_id_fk)."','".rp_escape_sql($m_code)."','".rp_escape_sql($release_date)."','".rp_escape_sql($m_uq_id)."', '".rp_escape_sql($r_ids)."')");
$m_id = $rpQuery->insert_id;
rp_process_colors_and_repair_for_model( $m_id );
rp_force_needed_repairs_category_creation();
// rp_trigger_translations_update_for_all_dr_repairs();
list( $category_based, $categoriesCount ) = rp_get_model_related_repairs_for_admin_page( $m_id );
echo json_encode(Array('status' => true, 'message' => 'Successfully Created', 'added_model' => array(
'm_id' => $m_id,
'device_type' => wp_repair_get_category_name_by_id($device_type),
'brand' => wp_repair_get_brand_name_by_id($brand_id_fk),
'model_name' => $m_name,
'model_code' => $m_code,
'release_date' => $release_date,
'm_link' => $m_img,
'model_uq_id' => $m_uq_id,
'category_based' => $category_based,
'categories_count' => $categoriesCount
)));
exit();
}
rp_ajax_for_admin('wp_repair_add_model','wp_repair_add_model');
// --------------------------------------------------------- update repair image
function update_repair_img(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
global $rpQuery; $abc = array();
$rs_repair = $rpQuery->prefix . "rs_repair";
$logo = '';
if(isset($_FILES) && !empty($_FILES) && isset($_FILES['file'])) {
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if(!empty($movefile["url"])){
$logo = $movefile["url"];
}
if(isset($_POST) && !empty($_POST)) {
$rid = $_POST['rid'] ?? '';
if(!empty($rid) && !empty($logo) && trim(strtoupper($rid)) !== 'NEW') {
$rpQuery->query("UPDATE $rs_repair SET r_img = '".rp_escape_sql($logo)."' WHERE r_id = '".rp_escape_sql($rid)."' LIMIT 1;");
}
}
}
echo json_encode(Array('status' => true, 'message' => 'Successfully Updated', 'logo' => $logo));
exit();
}
rp_ajax_for_admin('update_repair_img','update_repair_img');
// --------------------------------------------------------- update repair category image
function update_repair_category_img(){
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
global $rpQuery; $abc = array();
$rs_repairs_category = $rpQuery->prefix . "rs_repairs_category";
$logo = '';
if(isset($_FILES) && !empty($_FILES) && isset($_FILES['file'])) {
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if(!empty($movefile["url"])){
$logo = $movefile["url"];
}
if(isset($_POST) && !empty($_POST)) {
$rcid = $_POST['rcid'] ?? '';
if(!empty($rcid) && !empty($logo) && trim(strtoupper($rcid)) !== 'NEW') {
$rpQuery->query("UPDATE $rs_repairs_category SET c_img = '".rp_escape_sql($logo)."' WHERE c_id = '".rp_escape_sql($rcid)."' LIMIT 1;");
}
}
}
echo json_encode(Array('status' => true, 'message' => 'Successfully Updated', 'logo' => $logo));
exit();
}
rp_ajax_for_admin('update_repair_category_img','update_repair_category_img');
// --------------------------------------------------------- update default repair image
function update_default_repair_img(){
rp_verify_csrf_token_for_ajax('default_repairs');
rp_verify_user_full_access_ajax();
global $rpQuery; $abc = array();
$rs_repair = $rpQuery->prefix . "rs_repair";
$rs_default_repair = $rpQuery->prefix . "rs_default_repair";
$logo = '';
if(isset($_FILES) && !empty($_FILES) && isset($_FILES['file'])) {
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if(!empty($movefile["url"])){
$logo = $movefile["url"];
}
if(isset($_POST) && !empty($_POST)) {
$rid = $_POST['rid'] ?? '';
$dr_category = $_POST['dr_category'] ?? 0;
if(!empty($rid) && !empty($logo) && trim(strtoupper($rid)) !== 'NEW') {
$result = $rpQuery->get_results("SELECT * FROM $rs_default_repair WHERE dr_id = '".rp_escape_sql($rid)."' AND dr_category = '".rp_escape_sql($dr_category)."' LIMIT 1;");
if(!empty($result)) {
$dr_uq_id = $result[0]->dr_uq_id;
$dr_img = $result[0]->dr_img;
$rpQuery->query("UPDATE $rs_default_repair SET dr_img = '".rp_escape_sql($logo)."' WHERE dr_id = '".rp_escape_sql($rid)."' AND dr_category = '".rp_escape_sql($dr_category)."' LIMIT 1;");
$m_ids = rp_get_all_m_ids_by_category( $dr_category );
if(!empty($m_ids)) {
$m_ids = join(',',$m_ids);
$rpQuery->query("UPDATE $rs_repair SET r_img = '".rp_escape_sql($logo)."' WHERE r_uq_id = '".rp_escape_sql($dr_uq_id)."' AND r_img = '".rp_escape_sql($dr_img)."' AND m_id_fk IN (".rp_escape_sql($m_ids).");");
}
}
}
}
}
echo json_encode(Array('status' => true, 'message' => 'Successfully Updated', 'logo' => $logo));
exit();
}
rp_ajax_for_admin('update_default_repair_img','update_default_repair_img');
// --------------------------------------------------------- update default repair image
function update_default_repair_category_img(){
rp_verify_csrf_token_for_ajax('default_repairs');
rp_verify_user_full_access_ajax();
global $rpQuery; $abc = array();
$rs_repairs_category = $rpQuery->prefix . "rs_repairs_category";
$rs_default_repairs_category = $rpQuery->prefix . "rs_default_repairs_category";
$logo = '';
if(isset($_FILES) && !empty($_FILES) && isset($_FILES['file'])) {
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if(!empty($movefile["url"])){
$logo = $movefile["url"];
}
if(isset($_POST) && !empty($_POST)) {
$cid = $_POST['cid'] ?? '';
$dc_category = $_POST['dc_category'] ?? 0;
if(!empty($cid) && !empty($logo) && trim(strtoupper($cid)) !== 'NEW') {
$result = $rpQuery->get_results("SELECT * FROM $rs_default_repairs_category WHERE dc_id = '".rp_escape_sql($cid)."' AND dc_category = '".rp_escape_sql($dc_category)."' LIMIT 1;");
if(!empty($result)) {
$dc_uq_id = $result[0]->dc_uq_id;
$dc_img = $result[0]->dc_img;
$rpQuery->query("UPDATE $rs_default_repairs_category SET dc_img = '".rp_escape_sql($logo)."' WHERE dc_id = '".rp_escape_sql($cid)."' AND dc_category = '".rp_escape_sql($dc_category)."' LIMIT 1;");
$m_ids = rp_get_all_m_ids_by_category( $dc_category );
if(!empty($m_ids)) {
$m_ids = join(',',$m_ids);
$rpQuery->query("UPDATE $rs_repairs_category SET c_img = '".rp_escape_sql($logo)."' WHERE c_uq_id = '".rp_escape_sql($dc_uq_id)."' AND c_img = '".rp_escape_sql($dc_img)."' AND m_id_fk IN (".rp_escape_sql($m_ids).");");
}
}
}
}
}
echo json_encode(Array('status' => true, 'message' => 'Successfully Updated', 'logo' => $logo));
exit();
}
rp_ajax_for_admin('update_default_repair_category_img','update_default_repair_category_img');
// --------------------------------------------------------- update upsales image
function update_upsales_img(){
rp_verify_csrf_token_for_ajax('manage_upsales');
global $rpQuery;
$abc = array();
$rs_upsales = $rpQuery->prefix . "rs_upsales";
$logo = '';
if(isset($_FILES) && !empty($_FILES) && isset($_FILES['file'])) {
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if(!empty($movefile["url"])){
$logo = $movefile["url"];
}
if(isset($_POST) && !empty($_POST)) {
$uid = $_POST['uid'] ?? '';
if(!empty($uid) && !empty($logo) && trim(strtoupper($uid)) !== 'NEW') {
$rpQuery->query("UPDATE $rs_upsales SET upsales_img = '".rp_escape_sql($logo)."' WHERE upsales_id = '".rp_escape_sql($uid)."' LIMIT 1;");
}
}
}
echo json_encode(Array('status' => true, 'success' => 'Successfully Updated', 'logo' => $logo));
exit();
}
rp_ajax_for_admin('update_upsales_img','update_upsales_img');
//-------------------------------------------------------------------update repair position
function update_repair_position(){
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$r_position = $_POST['r_position'];
$i = 1;
foreach($r_position as $rp){
$rpQuery->query("UPDATE $rs_repair SET r_position='".rp_escape_sql($i)."' WHERE r_id='".rp_escape_sql($rp)."'");
$i++;
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully updated'));
exit();
}
rp_ajax_for_admin('update_repair_position','update_repair_position');
//-------------------------------------------------------------------update upsales position
function update_upsales_order_and_changes(){
rp_verify_csrf_token_for_ajax('manage_upsales');
global $rpQuery;
$rs_upsales = $rpQuery->prefix . "rs_upsales";
$up_position = $_POST['up_position'] ?? array();
$i = 1;
foreach($up_position as $up){
$rpQuery->query("UPDATE $rs_upsales SET upsales_position='".rp_escape_sql($i)."' WHERE upsales_id='".rp_escape_sql($up)."'");
$i++;
}
// upsales_id: upsales_id,
// is_active: upsales_status,
// us_old_price: upsales_old_price,
// us_new_price: upsales_new_price
$upsales_id = $_POST['upsales_id'] ?? array();
$upsales_status = $_POST['upsales_status'] ?? array();
$upsales_old_price = $_POST['upsales_old_price'] ?? array();
$upsales_new_price = $_POST['upsales_new_price'] ?? array();
foreach($upsales_id as $x => $uid){
if( preg_match('/,/', $upsales_old_price[$x]) ) {
$upsales_old_price[$x] = str_replace(',', '.', $upsales_old_price[$x]);
}
if( preg_match('/,/', $upsales_new_price[$x]) ) {
$upsales_new_price[$x] = str_replace(',', '.', $upsales_new_price[$x]);
}
$rpQuery->query("UPDATE $rs_upsales SET is_active='".rp_escape_sql($upsales_status[$x])."',us_old_price='".rp_escape_sql($upsales_old_price[$x])."',us_new_price='".rp_escape_sql($upsales_new_price[$x])."' WHERE upsales_id='".rp_escape_sql($uid)."'");
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully updated'));
exit();
}
rp_ajax_for_admin('update_upsales_order_and_changes','update_upsales_order_and_changes');
//-------------------------------------------------------------------pdf
function show_dompdf_svg($which = '') {
if($which === 'location') {
$which = 'locationicon';
$svg = rp_fetch_image_from_base(WP_REPAIR_PLUGIN_PATH.'assets/images/'.$which.'.svg');
return '<div class="location-icon"><img src="data:image/svg+xml;base64,'.base64_encode($svg).'" width="12.8" height="16" /></div>';
}
if($which === 'phone') {
$svg = rp_fetch_image_from_base(WP_REPAIR_PLUGIN_PATH.'assets/images/'.$which.'.svg');
return '<div class="phone-icon"><img src="data:image/svg+xml;base64,'.base64_encode($svg).'" width="18" height="18" /></div>';
}
$svg = rp_fetch_image_from_base(WP_REPAIR_PLUGIN_PATH.'assets/images/'.$which.'.svg');
return '<div class="icon"><img src="data:image/svg+xml;base64,'.base64_encode($svg).'" width="16" height="16" /></div>';
}
function pretty_offer_id($offer_id = 0) {
$offer_id_length = strlen((string)$offer_id);
if($offer_id_length >= 4) {
return date('Y'). '-' . $offer_id;
} else if($offer_id_length === 3) {
return date('Y'). '-0' . $offer_id;
} else if($offer_id_length === 2) {
return date('Y'). '-00' . $offer_id;
} else if($offer_id_length === 1) {
return date('Y'). '-000' . $offer_id;
} else {
return date('Y'). '-000' . $offer_id;
}
}
function rp_get_m_img_width_height_attrs($width = 150, $height = 150) {
if((($height * 100) / $width) > 50) {
// Is More Squarish
$ratio = $height / $width;
$width = 70/$ratio;
return ' height="70" width="'.($width).'"';
} else {
// Is Perfect!
$ratio = $height / $width;
return ' width="70" height="'.(70*$ratio).'"';
}
}
function rp_get_company_logo_width_height_attrs($width = 200, $height = 200) {
if((($height * 100) / $width) > 50) {
// Is More Squarish
$ratio = $height / $width;
$width = 100/$ratio;
$padding = (200 - $width) / 2;
return ' height="100" width="'.($width).'"';
} else {
// Is Perfect!
$ratio = $height / $width;
return ' width="200" height="'.(200*$ratio).'"';
}
}
function rp_encode_img_base64($img_path = false) {
if($img_path && !empty($img_path)){
$path = str_replace((get_site_url(). '/'), rp_get_wp_abs_path(), $img_path);
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = rp_fetch_image_from_base($path);
return 'data:image/' . $type . ';base64,' . base64_encode($data);
}
return '';
}
function rp_get_where_query($tableName = '', $key = '', $value = '', $single = FALSE, $compare = '=', $prefix = TRUE) {
global $rpQuery;
if($prefix === TRUE) {
$tableName = $rpQuery->prefix . $tableName;
}
if($single === TRUE) {
return $rpQuery->get_row("SELECT * FROM `$tableName` WHERE `$key` $compare '$value' LIMIT 1;");
} else {
return $rpQuery->get_results("SELECT * FROM `$tableName` WHERE `$key` $compare '$value'");
}
}
function rp_get_repair_lock_price( $r_id = '' ) {
/* Added in V1.4.2 */
$related_repair = rp_get_where_query('rs_repair', 'r_id', $r_id, TRUE, '=');
if(!empty($related_repair)) {
global $rp_pre_selected_location;
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$related_repair = apply_filters('rp_overwrite_individual_repair_row', $related_repair, $rp_pre_selected_location);
}
$related_repair = apply_filters('rp_filter_before_adding_repair_to_cart', $related_repair);
return array($related_repair->r_name, $related_repair->r_price);
}
return array('', '');
}
function rp_insert_into_rs_order_repairs( $order_id_fk = '' , $r_id = '' ) {
/* Added in V1.4.2 */
global $rpQuery;
$rs_order_repairs = $rpQuery->prefix. "rs_order_repairs";
list( $relatedRepairName, $relatedRepairPrice ) = rp_get_repair_lock_price($r_id);
if( isset( $_POST['get_o_id_fk'] ) && !empty( $_POST['get_o_id_fk'] )) {
$locked_price = rp_get_locked_repair_price( $_POST['get_o_id_fk'], $r_id );
if( $locked_price !== NULL ) {
$relatedRepairPrice = $locked_price;
}
}
// make sure it doesn't exist already
$check = $rpQuery->get_row("SELECT * FROM $rs_order_repairs WHERE r_id_fk = '".rp_escape_sql($r_id)."' AND o_id_fk = '".rp_escape_sql($order_id_fk)."' LIMIT 1");
if( empty( $check ) ) {
$rpQuery->query("INSERT INTO $rs_order_repairs(r_id_fk,o_id_fk,repair_name,repair_price) VALUES('".rp_escape_sql($r_id)."','".rp_escape_sql($order_id_fk)."','".rp_escape_sql($relatedRepairName)."', '".rp_escape_sql($relatedRepairPrice)."')");
do_action('rp_inserted_row_in_rs_order_repairs', $rpQuery->insert_id, $order_id_fk, $r_id);
}
}
function rp_find_repair_attr_row_by_id( $a_id = '' ) {
global $rpQuery;
$rs_repair_attr = $rpQuery->prefix. "rs_repair_attr";
$result = $rpQuery->get_row("SELECT * FROM $rs_repair_attr WHERE a_id = '".rp_escape_sql($a_id)."' LIMIT 1;");
return $result ?? array();
}
// cbfast
function rp_get_all_repairs_for_m_id_fk_cached( $m_id = 0 ) {
static $rp_get_all_repairs_for_m_id_fk_cached = NULL;
if( $rp_get_all_repairs_for_m_id_fk_cached !== NULL && array_key_exists( $m_id, $rp_get_all_repairs_for_m_id_fk_cached ) ) {
return $rp_get_all_repairs_for_m_id_fk_cached[ $m_id ];
}
if( $rp_get_all_repairs_for_m_id_fk_cached === NULL ) {
$rp_get_all_repairs_for_m_id_fk_cached = array();
}
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$result = $rpQuery->get_results("SELECT * FROM `$rs_repair` WHERE `m_id_fk` = '".rp_escape_sql($m_id)."';");
$prepared = array();
if( !empty( $result ) ) {
foreach( $result as $row ) {
$prepared[] = $row;
}
}
$rp_get_all_repairs_for_m_id_fk_cached[ $m_id ] = $prepared;
return $prepared;
}
function rp_find_repair_row_by_id( $r_id = '' ) {
// global $rpQuery;
// $rs_repair = $rpQuery->prefix. "rs_repair";
// $result = $rpQuery->get_row("SELECT * FROM $rs_repair WHERE r_id = '".rp_escape_sql($r_id)."' LIMIT 1;");
// return $result ?? array();
$modelIdOfRepair = rp_get_model_id_of_individual_repair( $r_id );
$allRepairs = rp_get_all_repairs_for_m_id_fk_cached( $modelIdOfRepair );
if( !empty( $allRepairs ) ) {
foreach( $allRepairs as $theRepairRow ) {
if( $theRepairRow->r_id == $r_id ) {
return $theRepairRow;
}
}
}
return array();
}
function rp_get_repair_attr_lock_price( $a_id = '' ) {
/* Added in V1.4.2 */
global $rpQuery;
$related_repair_attr = rp_get_where_query('rs_repair_attr', 'a_id', $a_id, TRUE, '=');
if(!empty($related_repair_attr)) {
$repairRow = rp_find_repair_row_by_id( $related_repair_attr->r_id_fk );
global $rp_pre_selected_location;
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$repairRow = apply_filters('rp_overwrite_individual_repair_row', $repairRow, $rp_pre_selected_location);
$related_repair_attr = apply_filters('rp_overwrite_individual_repair_attr_row', $related_repair_attr, $rp_pre_selected_location);
}
$related_repair_attr = apply_filters('rp_filter_before_adding_repair_attr_to_cart', $related_repair_attr, $repairRow);
return array($related_repair_attr->a_name, $related_repair_attr->a_price, $related_repair_attr->r_id_fk);
}
return array('', '', '');
}
function rp_insert_into_rs_order_repair_attr( $order_id_fk = '' , $a_id = '' ) {
/* Added in V1.4.2 */
global $rpQuery;
$rs_order_repair_attr = $rpQuery->prefix. "rs_order_repair_attr";
list($relatedRepairAttrName, $relatedRepairAttrPrice, $relatedRepairId) = rp_get_repair_attr_lock_price($a_id);
if( isset( $_POST['get_o_id_fk'] ) && !empty( $_POST['get_o_id_fk'] )) {
$locked_price = rp_get_locked_repair_attr_price( $_POST['get_o_id_fk'], $relatedRepairId, $a_id );
if( $locked_price !== NULL ) {
$relatedRepairAttrPrice = $locked_price;
}
}
// make sure this doesn't already exist in the cart
$alreadyExists = $rpQuery->get_row("SELECT * FROM $rs_order_repair_attr WHERE ra_id_fk = '".rp_escape_sql($a_id)."' AND o_id_fk = '".rp_escape_sql($order_id_fk)."' LIMIT 1;");
if( empty( $alreadyExists ) ) {
$rpQuery->query("INSERT INTO $rs_order_repair_attr(ra_id_fk,o_id_fk,repair_attr_name,repair_attr_price,r_id_fk) VALUES('".rp_escape_sql($a_id)."','".rp_escape_sql($order_id_fk)."', '".rp_escape_sql($relatedRepairAttrName)."', '".rp_escape_sql($relatedRepairAttrPrice)."', '".rp_escape_sql($relatedRepairId)."')");
do_action('rp_inserted_row_in_rs_order_repair_attr', $rpQuery->insert_id, $order_id_fk, $a_id);
}
}
function rp_get_upsale_lock_price( $up_id = '' ) {
/* Added in V1.4.2 */
global $rpQuery;
$related_upsale = rp_get_where_query('rs_upsales', 'upsales_id', $up_id, TRUE, '=');
if(!empty($related_upsale)) {
return array($related_upsale->us_name, $related_upsale->us_new_price);
}
return array('', '');
}
function rp_insert_into_rs_order_upsales( $order_id_fk = '' , $up_id = '' ) {
/* Added in V1.4.2 */
global $rpQuery;
$rs_order_upsales = $rpQuery->prefix. "rs_order_upsales";
list($relatedUpsaleName, $relatedUpsalePrice) = rp_get_upsale_lock_price($up_id);
if( isset( $_POST['get_o_id_fk'] ) && !empty( $_POST['get_o_id_fk'] )) {
$locked_price = rp_get_locked_upsale_price( $_POST['get_o_id_fk'], $up_id );
if( $locked_price !== NULL ) {
$relatedUpsalePrice = $locked_price;
}
}
$rpQuery->query("INSERT INTO $rs_order_upsales(upsales_id_fk,o_id_fk,upsale_name,upsale_price) VALUES('".rp_escape_sql($up_id)."','".rp_escape_sql($order_id_fk)."', '".rp_escape_sql($relatedUpsaleName)."', '".rp_escape_sql($relatedUpsalePrice)."')");
}
function me_post_pdf(){
rp_verify_csrf_token_for_ajax('frontend');
if( rp_verify_google_recaptcha() === FALSE ) {
echo json_encode(
array(
'status'=> false,
'rp_validation_error' => 'Form submission blocked by Google ReCaptcha. Please refresh the page and try again after few seconds.'
)
);
exit();
}
_rp_set_default_tiemzone();
global $rp_pre_selected_location;
$rp_pre_selected_location = 0;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
echo json_encode(Array('status' => false, 'rp_validation_error' => 'Invalid location id'));
exit;
}
}
global $wp_repair_selected_language;
global $rpQuery;
global $wp_repair_lang;
$rs_localization = $rpQuery->prefix . "rs_localization";
$rs_model = $rpQuery->prefix. "rs_model";
$rs_brand = $rpQuery->prefix. "rs_brand";
$tax_row = $rpQuery->get_row("SELECT * FROM $rs_localization LIMIT 1;");
if( !empty( $tax_row ) ) {
$tax = $tax_row->tax;
} else {
$tax = 0;
}
$mid = $_POST['mid'] ?? 0;
$model_name = '';
if( !empty( $mid ) ) {
$model_row = $rpQuery->get_row("SELECT m_id, m_name FROM $rs_model WHERE m_id = ':m_id' LIMIT 1;", array(
'm_id' => $mid
));
if( empty( $model_row ) ) {
$mid = 0;
} else {
$model_name = $model_row->m_name;
}
}
if( empty( $mid ) ) {
$model_name = $_POST['model_name'] ?? '';
if( !empty( $model_name ) ) {
$model_name = str_replace('-', ' ', $model_name);
$model_name = str_replace('_', '-', $model_name);
$model_name = str_replace('plus', '+', $model_name);
$model_row = $rpQuery->get_row("SELECT m_id FROM `$rs_model` WHERE m_name = '".rp_escape_sql($model_name)."' LIMIT 1;");
if( !empty( $model_row ) ) {
$mid = $model_row->m_id;
}
}
}
if( empty( $mid ) ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid input provided.'
));
exit;
}
$pdf_location_id = 0;
if( rp_is_enabled_location_selection_pdf() === true && isset( $_POST ) && !empty( $_POST ) && isset( $_POST['pdf_location_id'] ) && !empty( $_POST['pdf_location_id'] ) ) {
$pdf_location_id = (int) trim( $_POST['pdf_location_id'] );
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$all_locations = $rpQuery->get_results("SELECT * FROM $rs_company_location;");
// loop through all locations and make sure the location id is valid
$found_location = FALSE;
foreach( $all_locations as $location ) {
if( $location->location_id == $pdf_location_id ) {
$found_location = TRUE;
break;
}
}
if( $found_location === FALSE ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid input provided.'
));
exit;
}
}
$rpCart = new RepairPluginPro\RP_Cart( $mid );
$rid = $_POST['rid'] ?? array();
foreach ($rid as $repair_id) {
$rpCart->add_repair( ((int) $repair_id) );
}
$aid = $_POST['aid'] ?? array();
foreach ($aid as $attr_id) {
$rpCart->add_repair_attr( ((int) $attr_id) );
}
$upid = $_POST['upid'] ?? array();
foreach ($upid as $upsale_id) {
$rpCart->add_upsale( ((int) $upsale_id) );
}
$coupon_id = $_POST['coupon_id'] ?? '';
$really_added_coupon = $rpCart->add_coupon( ((int) $coupon_id) );
if( $really_added_coupon == false ) {
$coupon_id = '';
}
$calculations = $rpCart->calculate();
$combo = $calculations['combo_discount'];
$coupon = $calculations['coupon_amount'];
$coupon_info_json = '';
if( !empty( $rpCart->get_coupon_info() ) ) {
$coupon_info_json = json_encode( $rpCart->get_coupon_info() );
}
$final_price = $calculations['total'];
$prepared_post_data = $rpCart->prepare_post_data( $rid, $upid );
list( $rid, $array_name, $array_price, $aid, $upid ) = $prepared_post_data;
$color_name = $_POST['color_name'] ?? '';
$first_name = $_POST['first_name'] ?? '';
$last_name = $_POST['last_name'] ?? '';
$user_name = $_POST['user_name'] ?? '';
$street_phone = $_POST['street_phone'] ?? '';
$house_no = $_POST['house_no'] ?? '';
$user_country = $_POST['user_country'] ?? '';
$user_phone = $_POST['user_phone'] ?? '';
$zipcode_city = $_POST['zipcode_city'] ?? '';
$zipcode_only = $_POST['zipcode_only'] ?? '';
$email = $_POST['user_email'] ?? '';
$notes = $_POST['notes'] ?? '';
if(!empty($mid)) {
$cmodel = $rpQuery->get_results("SELECT * FROM `$rs_model` WHERE m_id = '".rp_escape_sql($mid)."' LIMIT 1;");
} else {
$cmodel = $rpQuery->get_results("SELECT * FROM `$rs_model` WHERE m_name = '".rp_escape_sql($model_name)."' LIMIT 1;");
}
$rs_user_pdfs = $rpQuery->prefix. "rs_user_pdfs";
$rpQuery->query("INSERT INTO $rs_user_pdfs(user_name,streetname_phone,zipcode_city,zipcode_only,user_email,notes,house_no,user_country) VALUES('".rp_escape_sql($user_name)."','".rp_escape_sql($street_phone)."','".rp_escape_sql($zipcode_city)."','".rp_escape_sql($zipcode_only)."','".rp_escape_sql($email)."','".rp_escape_sql($notes)."','".rp_escape_sql($house_no)."','".rp_escape_sql($user_country)."')");
$offer_id = $rpQuery->insert_id;
$rs_customer = $rpQuery->prefix. "rs_customer";
$rpQuery->query("INSERT INTO $rs_customer(customer_first_name,customer_last_name,customer_name,customer_phone,customer_email,customer_house_no,customer_street_address,customer_city,customer_zipcode,customer_country) VALUES('".rp_escape_sql($first_name)."','".rp_escape_sql($last_name)."','".rp_escape_sql($user_name)."','".rp_escape_sql($user_phone)."','".rp_escape_sql($email)."','".rp_escape_sql($house_no)."','".rp_escape_sql($street_phone)."','".rp_escape_sql($zipcode_city)."','".rp_escape_sql($zipcode_only)."', '".rp_escape_sql($user_country)."')");
$customer_id_fk = $rpQuery->insert_id;
$etp = 1 + (($tax * 1) / 100);
$ex_tax_price = $final_price/$etp;
$ex_tax_price = number_format((float)$ex_tax_price, 2, '.', '');
$d_method = 'Pdf Offer';
$time = date("H:i");
$date = date("Y-m-d");
$rs_orders = $rpQuery->prefix. "rs_orders";
$rs_order_repairs = $rpQuery->prefix. "rs_order_repairs";
$rs_order_repair_attr = $rpQuery->prefix. "rs_order_repair_attr";
$rs_order_upsales = $rpQuery->prefix. "rs_order_upsales";
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$location_row = $rpQuery->get_row("SELECT * FROM `$rs_company_location` LIMIT 1;");
$loc_id = '1';
if( !empty($location_row) ) {
$loc_id = $location_row->location_id;
}
if( !empty( $pdf_location_id ) ) {
$loc_id = $pdf_location_id;
}
$rpQuery->query("INSERT INTO $rs_orders(customer_id_fk,notes,color,excluded_tax_price,combo_discount,coupon_id_fk,total_price,delivery_method,delivery_time,delivery_date,pdf_offer,m_id_fk,status_id_fk,location_id_fk, coupon_amount, locked_coupon_info ) VALUES('".rp_escape_sql($customer_id_fk)."','".rp_escape_sql($notes)."','".rp_escape_sql($color_name)."','".rp_escape_sql($ex_tax_price)."','".rp_escape_sql($combo)."','".rp_escape_sql($coupon_id)."','".rp_escape_sql($final_price)."','".rp_escape_sql($d_method)."','".rp_escape_sql($time)."','".rp_escape_sql($date)."','1','".rp_escape_sql($mid)."','2','".rp_escape_sql($loc_id)."', '".rp_escape_sql($coupon)."', '".rp_escape_sql($coupon_info_json)."')");
$order_id_fk = $rpQuery->insert_id;
rp_update_quotation_tracking( $order_id_fk, 'quote_generated' );
rp_set_session_id_and_converted_date( $order_id_fk );
rp_set_based_on_location( $order_id_fk );
rp_set_new_appointment_number($order_id_fk, date('Y-m-d H:i:s'));
rp_set_coupon_settings($order_id_fk);
rp_update_coupon_usage_for_order( $order_id_fk );
rp_save_order_related_language( $order_id_fk, $wp_repair_selected_language );
$customBaseURL = rp_get_search_box_redirect_link();
$customURLIsSet = FALSE;
if( !empty( $customBaseURL ) ) {
$customBaseURL = rtrim($customBaseURL, '/');
$_REQUEST['created_through_url'] = $customBaseURL;
$_POST['created_through_url'] = $customBaseURL;
$customURLIsSet = TRUE;
}
rp_save_cancel_link_by_order_id( $order_id_fk, ($_POST['created_through_url'] ?? '') );
$link = $_POST['link'];
$link = str_replace(' ','-',$link);
$link = str_replace('%20','-',$link);
if( $customURLIsSet == TRUE ) {
$positionOfSelectedFinalize = strpos($link, '?selected=finalize');
if( $positionOfSelectedFinalize === FALSE ) {
$positionOfSelectedFinalize = strpos($link, '?selected=shortcode_finalize_order');
}
// ignore everything before selected=finalize
$link = $_POST['created_through_url'] . '/' . substr($link, $positionOfSelectedFinalize);
$link = str_replace('selected=shortcode_finalize_order', 'selected=finalize', $link);
}
$link = str_replace('?selected=finalize', '?o_id_fk='.$order_id_fk.'&c_id='.$customer_id_fk.'&uid='.substr(md5($customer_id_fk), 0, 8).'&selected=finalize', $link);
$link = str_replace('?selected=shortcode_finalize_order', '?o_id_fk='.$order_id_fk.'&c_id='.$customer_id_fk.'&uid='.substr(md5($customer_id_fk), 0, 8).'&selected=shortcode_finalize_order', $link);
$rpQuery->query("UPDATE `$rs_user_pdfs` SET `o_id_fk` = '$order_id_fk', `finalize_link` = '".rp_escape_sql($link)."' WHERE `user_pdfs_id` = '$offer_id' LIMIT 1;");
if($rid != null){
foreach($rid as $r_id){
rp_insert_into_rs_order_repairs($order_id_fk, $r_id);
}
}
if($aid != null){
foreach($aid as $a_id){
rp_insert_into_rs_order_repair_attr($order_id_fk, $a_id);
}
}
if($upid != null){
foreach($upid as $up_id){
rp_insert_into_rs_order_upsales($order_id_fk, $up_id);
}
}
if( (!empty(rp_get_por_repairs_by_order_id( $order_id_fk )) || !empty(rp_get_por_repair_attr_by_order_id( $order_id_fk ))) ) {
// No matter what settings are configured for price on request, for PDF Offer, we should always have Price on request
// status when appointment contains any price on request repair
// update status_id_fk to 5
$rpQuery->query("UPDATE $rs_orders SET status_id_fk = '5' WHERE o_id = '".rp_escape_sql($order_id_fk)."' LIMIT 1;");
}
if( !empty( $order_id_fk ?? 0 ) ) {
rp_trigger_outgoing_webhook( 'pdf_offer_created', $order_id_fk );
}
$gtm_data = rp_get_order_summary_for_gtm( $order_id_fk, 'pdf_quote_created' );
if( rp_send_appointment_status_update_email( $order_id_fk, TRUE ) === TRUE ) {
echo json_encode(Array('status'=> true, 'message' => 'Successfully Sent', 'gtm_data' => $gtm_data));
} else {
echo json_encode(Array('status'=> true, 'message' => 'Successfully Updated', 'gtm_data' => $gtm_data));
}
exit();
}
rp_ajax_for_public('me_post_pdf','me_post_pdf');
function get_email_template_of_wp_repair($which = 'pending') {
$templates = array(
'pending' => array(
'Wachten op goedkeuring',
'<p>Beste $CustomerName$,</p> <p>Bedankt voor het maken van een afspraak bij $LocationName$ om jouw $Model$ te laten repareren. Deze afspraak dient eerst goedgekeurd te worden door ons team. </p> <h3 style="font-family: sans-serif; font-size: 24px; border-radius: 8px; padding: 6px 12px; margin-bottom: 10px; background-color: #d5e4f4; color: #000000; border: 1px solid #b5c6b6;">Jouw afspraak op $AppointmentDate$ wordt zo snel mogelijk verwerkt.</h3> <p> </p> <p>$OrderSummary$</p> <p> </p> <p><strong>Uw gegevens<br></strong>Naam: $CustomerName$<br>Email: $CustomerEmail$<br>Tel: $CustomerPhone$</p> <p> </p> <p>Tijdens de reparatie kun je wachten bij ons in de winkel. We hebben supersnelle Wi-fi en heerlijke koffie. Komt het toch niet uit en wil je de afspraak annuleren?<br /><br />Klik dan op de volgende link: $cancel$.</p> <p> </p> <p>Met vriendelijke groet,</p> <p><strong>$LocationName$<br /></strong>$LocationAddress$<br />$LocationZipcodeCity$</p> <p> </p> <p> </p> <footer style="margin-top: 20px; font-size: 80%; color: #888; clear: both;"> <p>Je krijgt deze e-mail omdat er een afspraak is gemaakt met dit emailadres op de website van $LocationName$. Deze afspraak dient eerst goedgekeurd te worden door ons team. Heb je deze afspraak niet zelf gemaakt, neem dan contact met ons op.</p> </footer>'
),
'approved' => array(
'Uw afspraak is goedgekeurd',
'<p>Beste $CustomerName$,</p> <p>Bedankt voor het maken van een afspraak bij $LocationName$ om jouw $Model$ te laten repareren.</p> <h3 style="font-family: sans-serif; font-size: 24px; border-radius: 8px; padding: 6px 12px; margin-bottom: 10px; background-color: #d5e4f4; color: #000000; border: 1px solid #b5c6b6;">De afspraak is op $AppointmentDate$, om $AppointmentTime$ uur.</h3> <p> </p> <p>$OrderSummary$</p> <p> </p> <p><strong>Uw gegevens<br></strong>Naam: $CustomerName$<br>Email: $CustomerEmail$<br>Tel: $CustomerPhone$</p> <p> </p> <p>Tijdens de reparatie kun je wachten bij ons in de winkel. We hebben supersnelle Wi-fi en heerlijke koffie. Komt het toch niet uit en wil je de afspraak annuleren?<br /><br />Klik dan op de volgende link: $cancel$.</p> <p> </p> <p>Met vriendelijke groet,</p> <p><strong>$LocationName$<br /></strong>$LocationAddress$<br />$LocationZipcodeCity$</p> <p> </p> <p> </p> <footer style="margin-top: 20px; font-size: 80%; color: #888; clear: both;"> <p>Je krijgt deze e-mail omdat er een afspraak is gemaakt met dit emailadres op de website van $LocationName$. Deze e-mail is een bevestiging van de gemaakte afspraak. Heb je deze afspraak niet zelf gemaakt, neem dan contact met ons op.</p> </footer>'
),
'offer' => array(
'Uw Prijsopgaaf',
'<p>Beste $CustomerName$,</p> <p>Bedankt voor aanvragen van een offerte voor de reparatie van jouw $Model$.</p> <h3 style="font-family: sans-serif; font-size: 24px; border-radius: 8px; padding: 6px 12px; margin-bottom: 10px; background-color: #d5e4f4; color: #000000; border: 1px solid #b5c6b6;">De offerte voor de reparatie vindt je in de bijlage.</h3> <p> </p> <p>$OrderSummary$</p> <p> </p> <p><strong>Uw gegevens<br></strong>Naam: $CustomerName$<br>Email: $CustomerEmail$<br>Tel: $CustomerPhone$</p> <p> </p> <p>Meestal veranderen de prijzen niet, maar in deze tijden zou het kunnen dat wij onderdelen duurder inkopen dan oorspronkelijk verwerkt in de genoemde prijzen. Vandaar dat de offerte maximaal 14 dagen geldig is vanaf de offerte datum.<br /><br />Wil je de reparatie laten uitvoeren? Druk dan op onderstaande knop om de afspraak te voltooien.<br /> </p> <p>Met vriendelijke groet,</p> <p><strong>$LocationName$</strong><br />$LocationAddress$<br />$LocationZipcodeCity$<br /><br />$FinalizeButton$<br /></p> <p> </p> <p> </p> <footer style="margin-top: 20px; font-size: 80%; color: #888; clear: both;"> <p>Je krijgt deze e-mail omdat er een offerte is aangevraagd met dit emailadres op de website van $LocationName$. Heb je deze offerte niet zelf aangevraagd, neem dan contact met ons op.</p> </footer>'
),
'cancelled' => array(
'Uw afspraak is geannuleerd',
'<p>Beste $CustomerName$,</p> <p>Hierbij bevestigen we dat de afspraak voor het repareren van de $Model$ is geannuleerd.</p> <h3 style="font-family: sans-serif; font-size: 24px; border-radius: 8px; padding: 6px 12px; margin-bottom: 10px; background-color: #dd1935; color: #ffffff; border: 1px solid #b5c6b6;">De afspraak op $AppointmentDate$ om $AppointmentTime$ is geannuleerd.</h3> <p> </p> <p>$OrderSummary$</p> <p> </p> <p><strong>Uw gegevens<br></strong>Naam: $CustomerName$<br>Email: $CustomerEmail$<br>Tel: $CustomerPhone$</p> <p> </p> <p>Wil je opnieuw een afspraak inplannen? Bezoek dan onze website.</p> <p>Met vriendelijke groet,</p> <p><strong>$LocationName$<br /></strong>$LocationAddress$<br />$LocationZipcodeCity$<br /><br /><strong><br /></strong></p> <p> </p> <footer style="margin-top: 20px; font-size: 80%; color: #888; clear: both;"> <p>Je krijgt deze e-mail omdat er een afspraak is geannuleerd met dit emailadres op de website van $LocationName$. Deze e-mail is een bevestiging van de geannuleerde afspraak. Heb je deze afspraak niet zelf gemaakt geannuleerd, neem dan contact met ons op.</p> </footer>'
)
);
return $templates[$which];
}
//--------------------------------------------------------------------------------------
require_once plugin_dir_path( WP_REPAIR_PLUGIN_FILE)."RepairpluginBase.php";
require_once plugin_dir_path( WP_REPAIR_PLUGIN_FILE)."RepairpluginDynamic.php";
require_once plugin_dir_path( WP_REPAIR_PLUGIN_FILE)."RepairpluginEnhanced.php";
require_once plugin_dir_path( WP_REPAIR_PLUGIN_FILE)."RP_DynamicPricingAddon.php";
require_once plugin_dir_path( WP_REPAIR_PLUGIN_FILE)."RP_EnhancedLocationsAddon.php";
class Repairplugin {
public $plugin_file=WP_REPAIR_PLUGIN_FILE;
public $responseObj;
public $licenseMessage;
public $showMessage=false;
public $slug="repair-plugin";
function __construct() {
rp_add_action( 'admin_print_styles', [ $this, 'SetAdminStyle' ] );
$licenseKey=rp_get_option("Repairplugin_lic_Key","");
$liceEmail=rp_get_option( "Repairplugin_lic_email","");
RepairpluginBase::addOnDelete(function(){
rp_delete_option("Repairplugin_lic_Key");
});
if( !empty( $licenseKey ) ) {
if(RepairpluginBase::CheckWPPlugin($licenseKey,$liceEmail,$this->licenseMessage,$this->responseObj,WP_REPAIR_PLUGIN_FILE)){
rp_add_action( 'admin_menu', [$this,'ActiveAdminMenu'],99999);
rp_add_action( 'admin_post_Repairplugin_el_deactivate_license', [ $this, 'action_deactivate_license' ] );
//$this->licenselMessage=$this->mess;
//***Write you plugin's code here***
} else{
define('WP_REPAIR_REQUIRE_LICENSE', TRUE);
if(!empty($licenseKey) && !empty($this->licenseMessage)){
$this->showMessage=true;
}
rp_update_option("Repairplugin_lic_Key","");
rp_add_action( 'admin_post_Repairplugin_el_activate_license', [ $this, 'action_activate_license' ] );
rp_add_action( 'admin_menu', [$this,'InactiveMenu']);
}
} else {
define('WP_REPAIR_REQUIRE_LICENSE', TRUE);
rp_add_action( 'admin_post_Repairplugin_el_activate_license', [ $this, 'action_activate_license' ] );
rp_add_action( 'admin_menu', [$this,'InactiveMenu']);
}
}
function SetAdminStyle() {
wp_register_style( "RepairpluginLic", plugin_dir_url( WP_REPAIR_PLUGIN_FILE)."_lic_style.css?v=".WP_REPAIR_ASSETS_CACHE_V);
wp_enqueue_style( "RepairpluginLic" );
}
function get_menu_name( $value = '' ) {
$all_menu_items = array(
'analytics' => 'Analytics',
'appointments' => 'Appointments',
'customers' => 'Customers',
'manage categories' => 'Categories',
'manage models' => 'Models & Repairs',
'manage upsales' => 'Upsales',
'download libraries' => 'Download',
'default repairs' => 'Default Repairs',
'settings' => 'Settings'
);
return $all_menu_items[ $value ];
}
function ActiveAdminMenu(){
$currentUserId = get_current_user_id();
$permissionRequired = 'manage_repairplugin_pro';
add_menu_page ("RepairPlugin", "WP Repair", "activate_plugins", $this->slug, [$this,"Activated"], " dashicons-star-filled " , 25);
add_submenu_page(
'RepairPlugin', // No parent menu = not visible in admin
'RepairPlugin Setup Wizard',
'RepairPlugin Setup Wizard',
'manage_options',
'rp-setup-wizard',
[$this, 'rp_render_wizard_page']
);
if( rp_check_if_user_has_capability( $currentUserId, 'manage_repairplugin_pro' ) ) {
$allPages = array('analytics', 'appointments', 'customers', 'manage categories', 'manage models', 'manage upsales', 'download libraries', 'default repairs', 'settings');
} else {
if( !empty( $currentUserId ) && rp_is_enabled_pricing_based_on_location() == TRUE && count( rp_get_allowed_locations_of_location_head( $currentUserId ) ) > 0 ) {
$allPages = array('analytics', 'appointments', 'customers', 'manage models', 'default repairs', 'settings');
$permissionRequired = 'repairplugin_location_head';
} else {
$allPages = array();
}
}
foreach ($allPages as $key => $value) {
$page = str_replace(' ', '_', strtolower($value));
$callback = 'wp_repair_admin_main_page_html';
if(function_exists('wp_repair_admin_'.$page.'_page_html')) {
$callback = 'wp_repair_admin_'.$page.'_page_html';
}
$menu_name = $this->get_menu_name( $value );
add_submenu_page(
$this->slug,
ucwords(strtolower($value)),
ucwords(strtolower($menu_name)),
$permissionRequired,
'wp_repair_'.$page,
$callback,
);
}
_rp_change_admin_submenu_first_time_name();
}
function rp_render_wizard_page() {
$instalationWizard = new \RepairPluginPro\InstallationWizard();
$instalationWizard->register_ajax_hooks();
$instalationWizard->render_wizard_page();
}
function InactiveMenu() {
add_menu_page( 'Repairplugin','WP Repair',"activate_plugins", $this->slug, [$this,"LicenseForm"], " dashicons-star-filled " ,25);
add_submenu_page(
'Repairplugin', // No parent menu = not visible in admin
'RepairPlugin Setup Wizard',
'RepairPlugin Setup Wizard',
'manage_options',
'rp-setup-wizard',
[$this, 'rp_render_wizard_page']
);
_rp_change_admin_submenu_first_time_name();
// $allPages = array('appointments', 'manage categories', 'manage models', 'manage repairs', 'manage upsales', 'download libraries', 'settings');
// foreach ($allPages as $key => $value) {
// $page = str_replace(' ', '_', strtolower($value));
// $callback = 'wp_repair_admin_main_page_html';
// if(function_exists('wp_repair_admin_'.$page.'_page_html')) {
// $callback = 'wp_repair_admin_'.$page.'_page_html';
// }
// add_submenu_page(
// $this->slug,
// ucwords(strtolower($value)),
// ucwords(strtolower($value)),
// 'manage_repairplugin_pro',
// 'wp_repair_'.$page,
// $callback,
// );
// }
}
function action_activate_license(){
check_admin_referer( 'el-license' );
$licenseKey=!empty($_POST['el_license_key'])?$_POST['el_license_key']:"";
$licenseKey = trim($licenseKey);
$licenseEmail=!empty($_POST['el_license_email'])?$_POST['el_license_email']:"";
$licenseEmail = trim($licenseEmail);
rp_update_option("Repairplugin_lic_Key",$licenseKey);
rp_update_option("Repairplugin_lic_email",$licenseEmail);
rp_update_option('_site_transient_update_plugins','');
wp_safe_redirect(admin_url( 'admin.php?page='.$this->slug));
exit;
}
function action_deactivate_license() {
check_admin_referer( 'el-license' );
$message="";
if(RepairpluginBase::RemoveLicenseKey(WP_REPAIR_PLUGIN_FILE,$message)){
}
rp_update_option("Repairplugin_lic_Key","");
rp_update_option('_site_transient_update_plugins','');
wp_safe_redirect(admin_url( 'admin.php?page='.$this->slug));
exit;
}
function Activated(){
rp_print_execution_time_json_code();
_rp_set_default_tiemzone();
rp_show_validation_error_message();
wp_repair_admin_setup_tour_nav_html();
?>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
<input type="hidden" name="action" value="Repairplugin_el_deactivate_license"/>
<div class="el-license-container">
<?php $this->licenseTitleHTML(TRUE); ?>
<br>
<div class="el-license-rounded-box">
<h2 class="license-info-heading">License Info</h2>
<ul class="el-license-info">
<li>
<div>
<span class="el-license-info-title"><?php _e("Status",$this->slug);?></span>
<?php if ( isset($this->responseObj->is_valid) && $this->responseObj->is_valid ) : ?>
<span class="el-license-valid"><?php _e("Valid",$this->slug);?></span>
<?php else : ?>
<span class="el-license-valid"><?php _e("Invalid",$this->slug);?></span>
<?php endif; ?>
</div>
</li>
<li>
<div>
<span class="el-license-info-title"><?php _e("License Type",$this->slug);?></span>
<?php echo $this->responseObj->license_title ?? ''; ?>
</div>
</li>
<li>
<div>
<span class="el-license-info-title"><?php _e("License Expired on",$this->slug);?></span>
<?php echo $this->responseObj->expire_date ?? '';
if(isset($this->responseObj->expire_renew_link) && !empty($this->responseObj->expire_renew_link)){
?>
<a target="_blank" class="el-blue-btn" href="<?php echo $this->responseObj->expire_renew_link; ?>">Renew</a>
<?php
}
?>
</div>
</li>
<li>
<div>
<span class="el-license-info-title"><?php _e("Support Expired on",$this->slug);?></span>
<?php
echo $this->responseObj->support_end ?? '';
if(isset($this->responseObj->support_renew_link) && !empty($this->responseObj->support_renew_link)){
?>
<a target="_blank" class="el-blue-btn" href="<?php echo $this->responseObj->support_renew_link; ?>">Renew</a>
<?php
}
?>
</div>
</li>
<li>
<div>
<span class="el-license-info-title"><?php _e("Your License Key",$this->slug);?></span>
<span class="el-license-key"><?php
$theLicense = $this->responseObj->license_key ?? '';
echo esc_attr( substr($theLicense,0,9)."XXXXXXXX-XXXXXXXX".substr($theLicense,-9) ); ?></span>
</div>
</li>
</ul>
<p style="margin-top: 25px; margin-bottom:0px;">
<?php
global $wp_repair_lang;
_e($wp_repair_lang['do_you_need_help'],$this->slug); ?>
</p>
<div class="el-license-active-btn">
<?php wp_nonce_field( 'el-license' ); ?>
<?php submit_button('Deactivate'); ?>
</div>
</div>
</div>
<?php
require_once WP_REPAIR_PLUGIN_PATH . 'html/system_status.php';
?>
</form>
<link rel='stylesheet' id='font-awesome-css-css' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css?ver=6.4.3' media='all' />
<?php
rp_end_page_render_time();
}
function licenseTitleHTML( $status = false ) {
?>
<div class="el-license-title">
<div class="rp-favicon-container">
<img class="rp-favicon" src="<?php echo WP_REPAIR_PLUGIN_URL ?>assets/images/rp-favicon.png" alt="<?php _e("RepairPlugin Pro",$this->slug);?>">
</div>
<div class="rp-plugin-name">
<h2>
<span class="light">Repairplugin</span>
<span class="bold">Pro</span>
<span class="badge badge-inactive <?php if( !empty( $status ) ) { echo 'badge-active'; }; ?>"><?php if( !empty( $status ) ) { echo 'Active'; } else { echo 'Inactive'; } ?></span>
</h2>
</div>
</div>
<p class="more-info">The Ultimate WordPress Plugin for Repair shops</p>
<?php
}
function LicenseForm() {
global $wp_repair_lang;
?>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
<input type="hidden" name="action" value="Repairplugin_el_activate_license"/>
<div class="el-license-container">
<?php $this->licenseTitleHTML(); ?>
<br>
<?php
if(!empty($this->showMessage) && !empty($this->licenseMessage)){
$licenseError = $this->licenseMessage;
$licenseErrorKey = strtolower(str_replace(' ', '_', $licenseError));
if(isset($wp_repair_lang[$licenseErrorKey])) {
$licenseError = $wp_repair_lang[$licenseErrorKey];
}
?>
<div class="notice notice-error is-dismissible">
<p><?php echo _e($licenseError,$this->slug); ?></p>
</div>
<?php
}
?>
<div class="el-license-rounded-box">
<h2 class="license-info-heading">Activate your license</h2>
<p><?php _e($wp_repair_lang['enter_your_license_key_here'],$this->slug);?></p>
<p><?php _e($wp_repair_lang['if_you_dont_have_license'],$this->slug);?></p>
<div class="el-license-field" style="margin-top: 25px;">
<label for="el_license_key">License Code</label>
<input type="text" class="regular-text code" name="el_license_key" size="50" placeholder="xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx" required="required">
</div>
<div class="el-license-field">
<label for="el_license_key">Email</label>
<?php
$purchaseEmail = rp_get_option( "Repairplugin_lic_email", get_bloginfo( 'admin_email' ));
?>
<input type="email" class="regular-text code" name="el_license_email" size="50" value="<?php echo $purchaseEmail; ?>" placeholder="Please enter your email address" required="required">
<div style="margin-top:10px;"><small><?php _e($wp_repair_lang['we_will_send_updated_news_of_this_product'],$this->slug);?></small></div>
</div>
<p style="margin-top: 25px; margin-bottom:0px;">
<?php _e($wp_repair_lang['do_you_need_help'],$this->slug); ?>
</p>
<div class="el-license-active-btn">
<?php wp_nonce_field( 'el-license' ); ?>
<?php submit_button('Activate'); ?>
</div>
</div>
</div>
</form>
<?php
}
}
function _rp_change_admin_submenu_first_time_name($file = '') {
/*Added in 1.4.2*/
global $menu, $submenu;
if(!empty($menu) && is_array($menu)) {
foreach ($menu as $key => $menu_item) {
if(is_array($menu_item) && isset($menu_item[0]) && $menu_item[0] === 'WP Repair') {
$menu_item[0] = "<span class='repairplugin-admin-menu-item'>RepairPlugin</span> Pro";
if(isset($menu_item[6])) {
$menu_item[6] = WP_REPAIR_PLUGIN_URL.'assets/images/rp-dasbhoard-icon-white.svg';
}
$menu[$key] = $menu_item;
}
}
}
if(isset($submenu['repair-plugin']) && isset($submenu['repair-plugin'][0]) && isset($submenu['repair-plugin'][0][0]) && trim($submenu['repair-plugin'][0][0]) === 'WP Repair') {
$submenu['repair-plugin'][0][0] = 'Status';
$currentUserId = get_current_user_id();
if( !rp_check_if_user_has_capability( $currentUserId, 'activate_plugins' ) ) {
unset( $submenu['repair-plugin'][0] );
$submenu['repair-plugin'] = array_values($submenu['repair-plugin']);
}
}
return $file;
}
add_filter('submenu_file', '_rp_change_admin_submenu_first_time_name', 10, 1);
function _rp_style_RepairPlugin_menu_item() {
/*Added in 1.4.2*/
?>
<style type="text/css">
#adminmenu li.menu-top:hover a.toplevel_page_repair-plugin .wp-menu-image img,
#adminmenu li.wp-has-current-submenu a.toplevel_page_repair-plugin .wp-menu-image img,
#adminmenu li a.toplevel_page_repair-plugin .wp-menu-image img {
padding: 7px 6px 2px 6px !important;
opacity: 1 !important;
width: 20px;
}
#adminmenu li a.toplevel_page_repair-plugin .repairplugin-admin-menu-item {
font-weight: 700 !important;
}
#adminmenu li a.toplevel_page_repair-plugin,
#adminmenu li.wp-has-current-submenu a.wp-has-current-submenu.toplevel_page_repair-plugin {
background: #0556a5 !important;
color: #fff !important;
}
#adminmenu li a.toplevel_page_repair-plugin.wp-not-current-submenu,
#adminmenu li.wp-has-current-submenu a.toplevel_page_repair-plugin.wp-not-current-submenu {
color: #f0f0f1 !important;
}
#adminmenu li a.toplevel_page_repair-plugin:hover,
#adminmenu li.wp-has-current-submenu a.wp-has-current-submenu.toplevel_page_repair-plugin:hover {
background: #2271b1 !important;
color: #fff !important;
}
</style>
<?php
}
rp_add_action('admin_head', '_rp_style_RepairPlugin_menu_item');
function rp_javascript_get_next_run_schedule() {
?>
<script type="text/javascript">
window.lastWpRepairCRONRan = null;
function getCurrentTime() {
let theTime = new Date().getTime() / 1000;
return parseFloat(theTime.toFixed(0));
}
window._getCurrentTime = function() {
return getCurrentTime();
}
function getNextSafeSchedule(rp_try_after) {
let newRun = getNextRun();
if((getCurrentTime() + rp_try_after) >= newRun) {
window.lastWpRepairCRONRan = getCurrentTime() + rp_try_after;
console.log(window.lastWpRepairCRONRan - getCurrentTime());
return (window.lastWpRepairCRONRan - getCurrentTime()) * 1000;
} else {
console.log(window.lastWpRepairCRONRan - getCurrentTime());
return (window.lastWpRepairCRONRan - getCurrentTime()) * 1000;
}
}
window._getNextSafeSchedule = function(rp_try_after) {
return getNextSafeSchedule(rp_try_after);
}
function getNextRun() {
if(window.lastWpRepairCRONRan === null || window.lastWpRepairCRONRan < getCurrentTime()) {
window.lastWpRepairCRONRan = getCurrentTime() + 3;
return window.lastWpRepairCRONRan;
}
window.lastWpRepairCRONRan = window.lastWpRepairCRONRan + 3;
return window.lastWpRepairCRONRan;
}
</script>
<?php
}
rp_add_action('admin_footer', 'rp_javascript_get_next_run_schedule');
rp_add_action('wp_footer', 'rp_javascript_get_next_run_schedule');
function download_libraries_from_server_ajax_handler() {
rp_verify_csrf_token_for_ajax('download_libraries');
rp_block_more_actions_when_processing_pending_jobs();
global $rpQuery;
if(!current_user_can( 'manage_repairplugin_pro' )) {
echo json_encode(array('error'=>'Something went wrong, please try again later.'));
exit();
}
if(isset($_POST['the_dl_form'])) {
$dl_class = new RepairPluginPro\Download_Libraries($rpQuery);
$c_id = isset($_POST['c_id']) ? $_POST['c_id'] : '';
$b_id = isset($_POST['b_id']) ? $_POST['b_id'] : '';
$m_id = isset($_POST['m_id']) ? $_POST['m_id'] : '';
if(empty($c_id) && empty($b_id) && empty($m_id)) {
echo json_encode(array('error' => 'You have not selected any items to download'));
exit();
}
$data = $dl_class->fetch_repair_base(TRUE);
$dl_class->save_handler($data);
exit();
} else {
echo json_encode(array('error'=>'Something went wrong, please try again later.'));
exit();
}
}
rp_ajax_for_admin('wp_repair_download_libraries','download_libraries_from_server_ajax_handler');
function download_languages_from_server_ajax_handler() {
rp_verify_csrf_token_for_ajax('download_languages');
rp_block_more_actions_when_processing_pending_jobs();
global $rpQuery;
if(!current_user_can( 'manage_repairplugin_pro' )) {
echo json_encode(array('error'=>'Something went wrong, please try again later.'));
exit();
}
if(isset($_POST['lang_ids'])) {
$lang_ids = $_POST['lang_ids'] ?? array();
if(empty($lang_ids)) {
echo json_encode(array('error' => 'You have not selected any items to download'));
exit();
}
$baselang_class = new RepairPluginPro\Download_Languages($rpQuery);
$alreadyDownloaded = \rp_get_uq_id_of_all_rs_languages();
foreach($lang_ids as $key => $lang_id) {
if(in_array($lang_id, $alreadyDownloaded)) {
unset($lang_ids[$key]);
}
}
$lang_ids = array_values($lang_ids);
if( empty( $lang_ids ) ) {
echo json_encode(array('success' => 'up_to_date_already'));
exit();
}
$_POST['lang_uq_ids'] = $lang_ids;
$response = $baselang_class->fetch_repair_base(TRUE, FALSE);
$baselang_class->save_handler($response);
exit();
} else {
echo json_encode(array('error'=>'Something went wrong, please try again later.'));
exit();
}
}
rp_ajax_for_admin('wp_repair_download_languages','download_languages_from_server_ajax_handler');
function rp_get_fixed_downloading_attributes( $a_uq_ids = array() ) {
if(empty($a_uq_ids)) {
return array( array() , array() );
}
$main_repairs = array();
$filtered_a_uq_ids = array();
foreach( $a_uq_ids as $key => $a_uq_id ) {
list( $cat_uqid, $repair_uqid, $attr_uqid ) = explode('|', $a_uq_id);
$filtered_a_uq_ids[] = $cat_uqid . '|' . $attr_uqid;
$main_repairs[] = $cat_uqid . '|' . $repair_uqid;
}
return array( $main_repairs , $filtered_a_uq_ids );
}
function download_repairs_from_server_ajax_handler() {
rp_verify_csrf_token_for_ajax('download_repairs');
rp_block_more_actions_when_processing_pending_jobs();
global $rpQuery;
if(!current_user_can( 'manage_repairplugin_pro' )) {
echo json_encode(array('error'=>'Something went wrong, please try again later.'));
exit();
}
if(isset($_POST['the_dl_form'])) {
$baserepair_class = new RepairPluginPro\Download_Repairs($rpQuery);
$r_uq_ids = $_POST['r_uq_ids'] ?? array();
$a_uq_ids = $_POST['a_uq_ids'] ?? array();
if(empty($r_uq_ids)) {
echo json_encode(array('error' => 'You have not selected any items to download'));
exit();
}
//rp_get_fixed_downloading_attributes
list( $main_repairs_of_attrs , $a_uq_ids ) = rp_get_fixed_downloading_attributes( $a_uq_ids );
$alreadyDownloaded = rp_get_all_dr_uq_id_and_c_uq_id();
$alreadyDownloadedAttrs = rp_get_all_da_uq_id_and_c_uq_id();
foreach($r_uq_ids as $key => $r_uqid) {
if(in_array($r_uqid, $alreadyDownloaded)) {
unset($r_uq_ids[$key]);
}
}
$r_uq_ids = array_values($r_uq_ids);
foreach($a_uq_ids as $akey => $a_uqid) {
if(in_array($a_uqid, $alreadyDownloadedAttrs)) {
unset($a_uq_ids[$akey]);
}
}
$a_uq_ids = array_values($a_uq_ids);
if( !empty( $a_uq_ids ) ) {
// re add to r_uq_ids
foreach( $main_repairs_of_attrs as $adding_attr_repair ) {
if( !in_array( $adding_attr_repair, $r_uq_ids ) ) {
$r_uq_ids[] = $adding_attr_repair;
}
}
}
if( empty( $r_uq_ids ) && empty( $a_uq_ids ) ) {
echo json_encode(array('success' => 'up_to_date_already'));
exit();
}
$_POST['r_uq_ids'] = $r_uq_ids;
$_POST['a_uq_ids'] = $a_uq_ids;
$response = $baserepair_class->fetch_repair_base(TRUE, FALSE);
$baserepair_class->save_handler($response);
exit();
} else {
echo json_encode(array('error'=>'Something went wrong, please try again later.'));
exit();
}
}
rp_ajax_for_admin('wp_repair_download_repairs','download_repairs_from_server_ajax_handler');
function rp_add_index_to_column_if_not_exists( $table_name = '', $column_name = '', $prefix = TRUE ){
// no longer needed after new code for handling database structure..
return;
global $rpQuery;
$table_name_org = $table_name;
if($prefix === TRUE) {
$table_name = $rpQuery->prefix . $table_name;
}
$option_key = 'rp_index_added_'.$table_name_org.'_'.$column_name;
$has_created_index = rp_get_option($option_key, FALSE);
if(empty($has_created_index)) {
if( rp_has_existing_index( $table_name, $column_name ) == FALSE ) {
rp_add_option($option_key, TRUE);
$sql = "ALTER TABLE `$table_name` ADD INDEX(`$column_name`);";
$rpQuery->query($sql);
return TRUE;
}
}
return FALSE;
}
function wp_repair_search_box_shortcode_handler( $atts ) {
$atts = array_change_key_case( ( array )$atts, CASE_LOWER );
$shortcode_attributes = shortcode_atts(
array(
'language' => '',
'location' => ''
),
$atts
);
// Accept both Location ID / Name ---- START
$shortcode_attributes = rp_get_final_location_id_for_shortcode( $shortcode_attributes );
// Accept both Location ID / Name ---- END
$location = esc_attr( $shortcode_attributes['location'] );
$GLOBALS['rp_search_bar_forced_location'] = 0;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
if ( !empty( trim($location ?? '') ) ) {
if( rp_verify_selected_location_frontend( (int) (trim( $location )) ) == TRUE ) {
$GLOBALS['rp_search_bar_forced_location'] = (int) (trim( $location ));
}
}
}
rp_handle_default_language_overwrite( $shortcode_attributes['language'] );
$content = wp_repair_show_alert_if_no_license();
if(!empty($content)) {
return $content;
}
ob_start();
$fileName = WP_REPAIR_PLUGIN_PATH.'html/front_end/search_box_shortcode.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
include $fileName;
$content = ob_get_clean();
return $content;
}
add_shortcode('Repair_Search_Box', 'wp_repair_search_box_shortcode_handler');
function download_libraries_images_to_local( $reallyNeedToRunJob = true, $pending_jobs = 0 ) {
global $rpQuery;
$response = array();
$pendingJobOrBackup = ( $pending_jobs > 0 || $reallyNeedToRunJob == false );
if( $pendingJobOrBackup == TRUE ) {
// This will prevent image downloads before pending background
// jobs are really completed..
// Or when backup is running
define('WP_REPAIR_HAS_PENDING_BACKGROUND_JOBS', TRUE);
}
if( $pendingJobOrBackup == FALSE ) {
// It means image download will work
// if there is anything
$rpQuery->query("START TRANSACTION");
}
$response = rp_actual_single_image_downloading();
if( $pendingJobOrBackup == FALSE ) {
// It means image download will work
// if there is anything
$rpQuery->query("COMMIT");
}
return $response;
}
function rp_process_pending_background_jobs( $reallyNeedToRunJob = true ) {
global $rpQuery;
$rs_background_jobs = $rpQuery->prefix . 'rs_background_jobs';
$pending_jobs = 1;
$time = 0;
$count = 0;
if( $reallyNeedToRunJob == true ) {
list( $pending_jobs, $time, $count ) = _run_actual_background_job_for_cron();
}
$total_rows = $rpQuery->get_var("SELECT COUNT(id) FROM `$rs_background_jobs`");
// count all pending jobs where processed = 0
$pending_jobs = $rpQuery->get_var("SELECT COUNT(id) FROM `$rs_background_jobs` WHERE `processed` = 0");
$response = array(
'total' => (int) $total_rows,
'remaining' => (int) $pending_jobs,
'count' => $count
);
$row = $rpQuery->get_row("SELECT * FROM `$rs_background_jobs` WHERE `processed` = 0 ORDER BY `id` ASC LIMIT 1;");
if( !empty( $row ) && $row->callback == 'rp_process_colors_and_repair_for_model' ) {
$rs_model = $rpQuery->prefix . 'rs_model';
$totalModels = $rpQuery->get_var("SELECT COUNT(`m_id`) AS count FROM `$rs_model`");
$remainingModels = $rpQuery->get_var("SELECT COUNT(`m_id`) AS count FROM `$rs_model` WHERE `repair_ids` != '' OR `color_ids` != '';");
$response['total'] += ( $totalModels - 1 );
$response['remaining'] += ( $remainingModels - 1 );
}
if( !empty( $row ) && !empty( $row->callback ?? '' ) ) {
$more_response = rp_get_tables_count_for_pending_jobs_progressbar( $row->callback );
if( !empty( $more_response ) ) {
$response['tables_count'] = $more_response;
}
}
return $response;
}
function rp_is_running_background_job_ajax() {
if( rp_get_option('rp_background_jobs_ajax_is_running', '0') == '1' ) {
$timeOfLastAjaxJob = rp_get_option('rp_background_jobs_ajax_is_running_time', '');
if( !empty($timeOfLastAjaxJob) && (time() - $timeOfLastAjaxJob) < ( WP_REPAIR_MAX_BACKGROUND_JOB_TIME + 30 ) ) {
// Already running
return TRUE;
} else {
// It seems to be stuck. No process should ever take this much time..
return FALSE;
}
}
// Not running
return FALSE;
}
function rp_mark_ajax_background_job_as_running() {
rp_update_option('rp_background_jobs_ajax_is_running', '1');
rp_update_option('rp_background_jobs_ajax_is_running_time', time());
$_REQUEST['rp_process_background_job'] = TRUE;
$_GET['rp_process_background_job'] = TRUE;
$_POST['rp_process_background_job'] = TRUE;
}
function rp_mark_ajax_background_job_as_not_running() {
rp_update_option('rp_background_jobs_ajax_is_running', '0');
}
function rp_block_more_actions_when_processing_pending_jobs() {
global $rpQuery;
$rs_background_jobs = $rpQuery->prefix . 'rs_background_jobs';
$not_in = array('rp_update_base_image_into_local_image', 'rp_flush_bj_memory_cache');
$pending_jobs = $rpQuery->get_var("SELECT COUNT(id) FROM `$rs_background_jobs` WHERE `processed` = 0 AND `callback` NOT IN ('".implode("','", $not_in)."')");
if( $pending_jobs > 0 ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Please wait for previous tasks to complete.'
));
exit;
}
}
function rp_new_background_job_ajax_handler() {
global $rpQuery;
$rpQuery->disable_smart_cache();
$rs_background_jobs = $rpQuery->prefix . 'rs_background_jobs';
$pending_jobs = $rpQuery->get_var("SELECT COUNT(id) FROM `$rs_background_jobs` WHERE `processed` = 0");
$reallyNeedToRunJob = TRUE;
if( rpbkp_is_running_any_process() == true || rp_is_running_background_job_ajax() == true ) {
$reallyNeedToRunJob = FALSE;
}
if( $reallyNeedToRunJob === TRUE ) {
rp_mark_ajax_background_job_as_running();
}
if( rp_get_option('rp_skip_quick_start_wizard', FALSE) === FALSE ) {
ob_start();
rp_keep_setup_tour_nav_uptodate_part();
$content = ob_get_clean();
} else {
$content = '';
}
$response = array();
$response['tour_nav_html'] = $content;
// image_download_response
$response['image_download_response'] = download_libraries_images_to_local( $reallyNeedToRunJob, $pending_jobs );
// background_jobs_response
$response['background_jobs_response'] = rp_process_pending_background_jobs( $reallyNeedToRunJob );
$response['status'] = 'success';
$response['refresh_time'] = 5000; // 5 seconds
if( ($response['background_jobs_response']['remaining'] ?? 0) > 0 ) {
$response['refresh_time'] = 300; // 0.3 seconds
}
if( $reallyNeedToRunJob === TRUE ) {
rp_mark_ajax_background_job_as_not_running();
}
echo json_encode($response);
exit();
}
rp_ajax_for_admin('rp_new_background_job_ajax_handler', 'rp_new_background_job_ajax_handler');
function rp_add_background_job_ajax_handler() {
$page = $_REQUEST['page'] ?? '';
$repairPluginPages = array(
'repair-plugin',
'wp_repair_analytics',
'wp_repair_appointments',
'wp_repair_customers',
'wp_repair_manage_categories',
'wp_repair_manage_models',
'wp_repair_manage_upsales',
'wp_repair_download_libraries',
'wp_repair_default_repairs',
'wp_repair_settings'
);
if( !in_array($page, $repairPluginPages) ) {
return;
}
?>
<script type="text/javascript">
(function(window, document, $, undefiend){
window.rp_current_tab_unique_id = '<?php echo 'tab_' . uniqid() . uniqid(); ?>';
window.localStorageReallyWorking = false;
window.setCurrentTabIdInLocalStorageTimeout = null;
function setCurrentTabIdInLocalStorage() {
if( window.setCurrentTabIdInLocalStorageTimeout != null ) {
window.clearTimeout( window.setCurrentTabIdInLocalStorageTimeout );
}
window.setCurrentTabIdInLocalStorageTimeout = window.setTimeout(function(){
window.localStorageReallyWorking = false;
try {
if( 'localStorage' in window ) {
localStorage.setItem('rp_focused_tab_id', window.rp_current_tab_unique_id);
window.localStorageReallyWorking = true;
}
} catch(e) {
// Error
window.localStorageReallyWorking = false;
}
}, 60);
}
function getFocusedTabIdFromLocalStorage() {
let focusedTabId = '';
window.localStorageReallyWorking = false;
try {
if( 'localStorage' in window ) {
focusedTabId = localStorage.getItem('rp_focused_tab_id');
window.localStorageReallyWorking = true;
}
} catch(e) {
// Error
window.localStorageReallyWorking = false;
}
return focusedTabId;
}
jQuery(window).on("load", function(){
setCurrentTabIdInLocalStorage();
});
jQuery(window).focus(function(){
setCurrentTabIdInLocalStorage();
});
jQuery(document).on('hover click',function(){
setCurrentTabIdInLocalStorage();
});
function rpCurrentTabSeemsActive() {
let localStroageId = getFocusedTabIdFromLocalStorage();
let reallyRunFunction = false;
if( window.localStorageReallyWorking == false ) {
reallyRunFunction = true;
} else if( localStroageId == window.rp_current_tab_unique_id ) {
reallyRunFunction = true;
} else {
reallyRunFunction = false;
}
return reallyRunFunction;
}
function rpRepititiveBackgroundJob( refreshTime = 5000 ) {
window.setTimeout(function(){
if( rpCurrentTabSeemsActive() == true && !('rpForceStopBackgroundJobs' in window && window.rpForceStopBackgroundJobs == true) ) {
let ajaxHandler = jQuery;
if( 'repairPluginUI' in window ) {
ajaxHandler = repairPluginUI;
}
ajaxHandler.ajax({
type: 'POST',
url: '<?php echo rp_get_admin_ajax_url_for_back_end(); ?>',
data: {
action: 'rp_new_background_job_ajax_handler',
page: '<?php echo trim($_REQUEST['page'] ?? ''); ?>',
rp_process_background_job: 'true'
},
success: function(response) {
try {
response = JSON.parse(response);
} catch (e) {
response = {};
}
if( response && response.tour_nav_html && jQuery(".wp-repair-setup-tour-nav").length > 0 ) {
let old_markup = jQuery(".wp-repair-setup-tour-nav");
old_markup.after(response.tour_nav_html);
old_markup.remove();
}
if( response && response.image_download_response && jQuery("#rp_downloading_libraries_images").length > 0 ) {
let data = response.image_download_response;
let total = data.total;
let remaining = data.remaining;
let done_images = total - remaining;
let percentRemaining = (remaining * 100) / total;
let percentDone = 100 - percentRemaining;
jQuery("#rp_downloading_libraries_images .done").text(done_images);
jQuery("#rp_downloading_libraries_images .total").text(total);
if(percentDone < 100) {
jQuery("#rp_downloading_libraries_images").show();
} else {
jQuery("#rp_downloading_libraries_images").hide();
}
jQuery("#rp_downloading_libraries_images .desc").show();
jQuery("#rp_downloading_libraries_images .myBar").css({'width':percentDone+'%'});
}
if( response && response.background_jobs_response && jQuery("#rp_processing_pending_jobs").length > 0 ) {
let data = response.background_jobs_response;
let total = data.total;
let remaining = data.remaining;
let done_images = total - remaining;
let percentRemaining = (remaining * 100) / total;
let percentDone = 100 - percentRemaining;
jQuery("#rp_processing_pending_jobs .done").text(done_images);
jQuery("#rp_processing_pending_jobs .total").text(total);
if(percentDone < 100) {
jQuery("#rp_processing_pending_jobs").show();
} else {
jQuery("#rp_processing_pending_jobs").hide();
}
jQuery("#rp_processing_pending_jobs .desc").show();
jQuery("#rp_processing_pending_jobs .myBar").css({'width':percentDone+'%'});
jQuery("#rp_processing_pending_jobs .tablesCount").remove();
jQuery("#rp_processing_pending_jobs .rp-show-table-count").remove();
if( 'tables_count' in data ) {
let allTablesCount = '';
for( let key in data.tables_count ) {
allTablesCount += '<p class="singleTableCount">'+key+': '+data.tables_count[key]+'</p>';
}
let showHidetext = 'Show more details';
if( jQuery("#rp_processing_pending_jobs").hasClass('show-table-count') ) {
showHidetext = 'Hide more details';
}
// print as json
jQuery("#rp_processing_pending_jobs .myProgress").after('<div class="tablesCount">'+allTablesCount+'</div><span class="rp-show-table-count">'+showHidetext+'</span>');
}
if(percentDone < 100) {
} else {
jQuery("#rp_processing_pending_jobs").hide();
}
}
if( response && response.refresh_time ) {
refreshTime = response.refresh_time;
}
rpRepititiveBackgroundJob( refreshTime );
},
error: function() {
// Error!
rpRepititiveBackgroundJob( refreshTime );
}
});
} else {
rpRepititiveBackgroundJob( refreshTime );
}
}, refreshTime);
}
jQuery(window).on("load", function(){
rpRepititiveBackgroundJob( 5000 );
});
jQuery(document).on('click', '.rp-show-table-count', function(){
jQuery(this).closest('#rp_processing_pending_jobs').toggleClass('show-table-count');
if( jQuery(this).closest('#rp_processing_pending_jobs').hasClass('show-table-count') ) {
jQuery(this).text('Hide more details');
} else {
jQuery(this).text('Show more details');
}
});
}(window, document, jQuery));
</script>
<?php
}
rp_add_action('admin_footer', 'rp_add_background_job_ajax_handler');
function trigger_wp_repair_js_doc_ready() {
?>
<script>
if(typeof jQuery == 'function') {
jQuery(document).trigger('wpRepairReady');
} else {
window.addEventListener("load", function(){
if(typeof jQuery == 'function') {
jQuery(document).trigger('wpRepairReady');
} else {
window.setTimeout(function(){
jQuery(document).trigger('wpRepairReady');
},300);
}
});
}
</script>
<?php
}
rp_add_action('wp_footer', 'trigger_wp_repair_js_doc_ready', 9999999999);
rp_add_action('admin_footer', 'trigger_wp_repair_js_doc_ready', 9999999999);
function wp_repair_list_sorting_button($styling = '', $more_class = '') {
if(!empty($styling)) {
$style_tag = 'style="'.$styling.'"';
} else {
$style_tag = '';
}
?>
<span <?php echo $style_tag; ?> class="repair-list-sort <?php echo $more_class; ?>">
<i class="fas fa-caret-up" data-which="up"></i>
<i class="fas fa-caret-down" data-which="down"></i>
</span>
<?php
}
// --------------------------------------------------------- get locations for front-end
function _rp_fe_get_locations() {
return _rp_fe_get_locations_actual();
}
function _rp_fe_get_locations_actual() {
global $rpQuery;
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$location_results = $rpQuery->get_results("SELECT * FROM $rs_company_location ORDER BY `location_order` ASC, `location_id` ASC");
if(empty($location_results)) {
$location_results = array();
}
$location_results = rp_sanitize_output($location_results);
return json_encode(array(
'status' => TRUE,
'results' => array(),
'which_page' => 'locations'
));
}
function rp_fe_get_locations(){
echo _rp_fe_get_locations();
exit();
}
rp_ajax_for_public('rp_fe_get_locations','rp_fe_get_locations');
function _rp_get_brand_ids_by_brand_name( $brand_name = '' ) {
global $rpQuery;
$rs_brand = $rpQuery->prefix . "rs_brand";
$results = $rpQuery->get_results("SELECT * FROM $rs_brand WHERE b_name LIKE '".rp_escape_sql($brand_name)."'");
$ids = array();
if(!empty($results)) {
foreach ($results as $key => $value) {
$ids[] = (int) $value->b_id;
}
}
return $ids;
}
function _rp_check_if_brand_name_exists( $brand_name = '' ) {
global $rpQuery;
$rs_brand = $rpQuery->prefix . "rs_brand";
$results = $rpQuery->get_row("SELECT * FROM $rs_brand WHERE b_name LIKE '".rp_escape_sql($brand_name)."'");
if(empty($results)) {
return FALSE;
}
return TRUE;
}
function _rp_get_all_categories_of_brand( $brand_name = '' ) {
global $rpQuery;
$rs_brand = $rpQuery->prefix . "rs_brand";
// select c_id_fk from $rs_brand where b_name = $brand_name
$results = $rpQuery->get_results("SELECT c_id_fk FROM $rs_brand WHERE b_name LIKE '".rp_escape_sql($brand_name)."'");
$c_ids = array();
if(!empty($results)) {
foreach ($results as $key => $value) {
$c_ids[] = $value->c_id_fk;
}
}
return $c_ids;
}
function _rp_filter_get_brands_before_return( $brands = array() ) {
$rp_shortcode_brand_name = $_REQUEST['rp_shortcode_brand_name'] ?? '';
if( empty( $rp_shortcode_brand_name ) || !_rp_check_if_brand_name_exists( $rp_shortcode_brand_name ) ) {
return $brands;
}
$b_ids = _rp_get_brand_ids_by_brand_name( $rp_shortcode_brand_name );
$filtered = array();
if( !empty( $b_ids ) ) {
foreach ($brands as $key => $value) {
if( in_array( (int) $value->b_id, $b_ids ) ) {
$filtered[] = $value;
}
}
}
return $filtered;
}
function _rp_filter_get_categories_before_return( $categories = array() ) {
$rp_shortcode_brand_name = $_REQUEST['rp_shortcode_brand_name'] ?? '';
if( empty( $rp_shortcode_brand_name ) || !_rp_check_if_brand_name_exists( $rp_shortcode_brand_name ) ) {
return $categories;
}
$c_ids = _rp_get_all_categories_of_brand( $rp_shortcode_brand_name );
$filtered = array();
if( !empty( $c_ids ) ) {
foreach ($categories as $key => $value) {
if( in_array( $value->c_id, $c_ids ) ) {
$filtered[] = $value;
}
}
}
return $filtered;
}
function _rp_track_used_option( $option_name = '' ) {
global $rp_track_used_options;
if( empty( $rp_track_used_options ) ) {
$rp_track_used_options = array();
}
if( !in_array( $option_name, $rp_track_used_options ) ) {
$rp_track_used_options[] = $option_name;
}
}
function rp_get_cached_front_end_step( $step_name = '', $step_data = array(), $callback = null ) {
$feCacheClass = new RepairPluginPro\RP_Front_End_Steps_Cache($step_name, $step_data);
$result = ( $feCacheClass )->callback($callback);
return $result;
// Below code when we need to debug used options / tables
// in the front-end step. Check system_status.php top lines
// for debug code related to this which can be uncommented
// to see used tables / used options that aren't registered..
global $rpQuery;
global $rp_track_used_options;
$rp_track_used_options = array();
add_action('rp_using_option_name', '_rp_track_used_option', 10, 1);
$rpQuery->start_tracking_tables();
$feCacheClass = new RepairPluginPro\RP_Front_End_Steps_Cache($step_name, $step_data);
$result = ( $feCacheClass )->callback($callback);
$rpQuery->stop_tracking_tables();
remove_action('rp_using_option_name', '_rp_track_used_option');
$existing = rp_get_option('rp_checking_used_tables', array());
if( empty( $existing ) ) {
$existing = array();
}
if( !isset( $existing[ $step_name ] ) ) {
$existing[ $step_name ] = array();
}
$tracked_tables = $rpQuery->get_tracked_tables();
foreach( $tracked_tables as $tracked_table ) {
// add to existing
if( !in_array( $tracked_table, $existing[ $step_name ] ) ) {
$existing[ $step_name ][] = $tracked_table;
}
}
$registered_steps = $feCacheClass->get_registered_steps()[ $step_name ] ?? array();
if( isset( $existing[ $step_name ] ) && !empty( $registered_steps ) ) {
foreach( $existing[ $step_name ] as $re_key => $existing_option ) {
foreach( $registered_steps as $registered_step ) {
if( strpos( $existing_option, $registered_step ) !== FALSE ) {
unset( $existing[ $step_name ][ $re_key ] );
}
}
}
$existing[ $step_name ] = array_values( $existing[ $step_name ] );
}
rp_update_option( 'rp_checking_used_tables', $existing );
$existing_used_options = rp_get_option( 'rp_checking_used_options', array() );
if( empty( $existing_used_options ) ) {
$existing_used_options = array();
}
if( !isset( $existing_used_options[ $step_name ] ) ) {
$existing_used_options[ $step_name ] = array();
}
foreach( $rp_track_used_options as $used_option ) {
if( !in_array( $used_option, $existing_used_options[ $step_name ] ) ) {
$existing_used_options[ $step_name ][] = $used_option;
}
}
$registered_options = $feCacheClass->get_registered_step_options()[ $step_name ] ?? array();
if( isset( $existing_used_options[ $step_name ] ) && !empty( $registered_options ) ) {
foreach( $existing_used_options[ $step_name ] as $eo_key => $existing_option ) {
foreach( $registered_options as $registered_option ) {
if( strpos( $existing_option, $registered_option ) !== FALSE ) {
unset( $existing_used_options[ $step_name ][ $eo_key ] );
}
}
}
$existing_used_options[ $step_name ] = array_values( $existing_used_options[ $step_name ] );
}
rp_update_option( 'rp_checking_used_options', $existing_used_options );
return $result;
}
function _rp_fe_get_categories() {
global $rp_pre_selected_location;
$rp_pre_selected_location = 0;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
return json_encode(Array('status' => false, 'message' => 'Invalid location id'));
}
}
$rp_shortcode_brand_name = $_REQUEST['rp_shortcode_brand_name'] ?? '';
return rp_get_cached_front_end_step('_rp_fe_get_categories', array( $rp_pre_selected_location, $rp_shortcode_brand_name ), function(){
return _rp_fe_get_categories_actual();
});
}
function _rp_fe_get_categories_actual() {
global $rpQuery;
global $rp_pre_selected_location;
$category_table = $rpQuery->prefix . "rs_category";
$c_result = $rpQuery->get_results("SELECT c_name, c_id, c_img FROM $category_table WHERE is_active = '1' ORDER BY c_position ASC");
if(empty($c_result)) {
$c_result = array();
}
$c_result = _rp_filter_get_categories_before_return( $c_result );
$c_result = _rp_optimize_image_links( $c_result, 'c_img' );
$c_result = rp_sanitize_output($c_result);
$rp_wp_uploads_base_url = rp_get_wp_uploads_base_url();
return json_encode(array(
'status' => TRUE,
'results' => $c_result,
'which_page' => 'types',
'rp_wp_uploads_base_url' => $rp_wp_uploads_base_url
));
}
function rp_fe_get_categories(){
if(!isset($_POST['via_back_button'])) {
$load_step = rp_get_front_end_firsttime_load_step();
if(!empty($load_step)) {
$selected = $load_step[0];
if($selected === 'repairs') {
$_POST['c_name'] = $load_step[1][0];
$_POST['b_name'] = $load_step[1][1];
$_POST['m_name'] = $load_step[1][2];
echo _rp_fe_get_repairs();
exit();
} else if($selected === 'models') {
$_POST['c_name'] = $load_step[1][0];
$_POST['b_name'] = $load_step[1][1];
echo _rp_fe_get_models();
exit();
} else if($selected === 'brands') {
$_POST['c_name'] = $load_step[1][0];
echo _rp_fe_get_brands();
exit();
} else {
echo _rp_fe_get_categories();
exit();
}
} else {
echo _rp_fe_get_categories();
exit();
}
} else {
echo _rp_fe_get_categories();
exit();
}
}
rp_ajax_for_public('rp_fe_get_categories','rp_fe_get_categories');
// -------------------------------
function rp_pre_load_fe_get_brands() {
global $rpQuery;
global $rp_pre_selected_location;
$rp_pre_selected_location = 0;
$is_enabled_enhanced_locations = rp_is_enabled_pricing_based_on_location();
if( $is_enabled_enhanced_locations == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'Invalid location id'));
exit;
}
}
$GLOBALS['rp_pre_loading_fe_get_repairs'] = array( $rp_pre_selected_location, $is_enabled_enhanced_locations );
$category_table = $rpQuery->prefix . "rs_category";
$c_result = $rpQuery->get_results("SELECT c_name, c_id, c_img FROM $category_table WHERE is_active = '1' ORDER BY c_position ASC");
if(empty($c_result)) {
$c_result = array();
}
if( count( $c_result ) <= 1 ) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'No preload available'));
exit;
}
$final_response = array();
$start_time = microtime( true );
$response_size = 0;
// 500KB limit
$responseLimit = 500 * 1024;
while( !empty( $c_result ) && ( microtime( true ) - $start_time ) < 0.2 && $response_size < $responseLimit ) {
$category = array_shift( $c_result );
$_POST['c_name'] = $category->c_name;
$theResult = _rp_fe_get_brands_pre_loaded();
$final_response[ $category->c_name ] = $theResult;
$response_size += strlen( $theResult );
}
echo json_encode( array( 'status' => TRUE, 'data' => $final_response ) );
exit;
}
rp_ajax_for_public('rp_pre_load_fe_get_brands','rp_pre_load_fe_get_brands');
function _rp_fe_get_brands_pre_loaded() {
if(!isset($_POST['via_back_button'])) {
$cname = $_POST['c_name'] ?? '';
$load_step = rp_get_front_end_firsttime_load_step($cname);
if(!empty($load_step)) {
$selected = $load_step[0];
if($selected === 'repairs') {
$_POST['c_name'] = $load_step[1][0];
$_POST['b_name'] = $load_step[1][1];
$_POST['m_name'] = $load_step[1][2];
return _rp_fe_get_repairs();
} else if($selected === 'models') {
$_POST['c_name'] = $load_step[1][0];
$_POST['b_name'] = $load_step[1][1];
return _rp_fe_get_models();
} else {
// Do nothing so it return brands by default..
}
}
}
return _rp_fe_get_brands();
}
// --------------------------------------------------------- get brands for front-end
function _rp_fe_get_brands() {
global $rp_pre_selected_location;
if( isset( $GLOBALS['rp_pre_loading_fe_get_repairs'] ) && !empty( $GLOBALS['rp_pre_loading_fe_get_repairs'] ) ) {
list( $rp_pre_selected_location, $is_enabled_enhanced_locations ) = $GLOBALS['rp_pre_loading_fe_get_repairs'];
} else {
$rp_pre_selected_location = 0;
$is_enabled_enhanced_locations = rp_is_enabled_pricing_based_on_location();
if( $is_enabled_enhanced_locations == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
return json_encode(Array('status' => false, 'message' => 'Invalid location id'));
}
}
}
$cname = $_POST['c_name'] ?? '';
$rp_shortcode_brand_name = $_REQUEST['rp_shortcode_brand_name'] ?? '';
return rp_get_cached_front_end_step('_rp_fe_get_brands', array( $rp_pre_selected_location, $is_enabled_enhanced_locations, $cname, $rp_shortcode_brand_name ), function(){
return _rp_fe_get_brands_actual();
});
}
function _rp_fe_get_brands_actual() {
global $rpQuery;
global $rp_pre_selected_location;
$brand_table = $rpQuery->prefix . "rs_brand";
$category_table = $rpQuery->prefix . "rs_category";
$cname = $_POST['c_name'] ?? '';
$brands = array();
if(!empty($cname)) {
$c_result = $rpQuery->get_results("SELECT * FROM $category_table WHERE c_name = '".rp_escape_sql($cname)."' ORDER BY c_position ASC");
$c_id = $c_result[0]->c_id;
$brands = $rpQuery->get_results("SELECT b_id, b_name, b_img FROM $brand_table WHERE c_id_fk = '".rp_escape_sql($c_id)."' AND is_active = '1' ORDER BY b_position ASC, b_name ASC");
}
if(empty($brands)) {
$brands = array();
}
$brands = _rp_filter_get_brands_before_return( $brands );
$brands = _rp_optimize_image_links( $brands, 'b_img' );
$rp_wp_uploads_base_url = rp_get_wp_uploads_base_url();
$brands = rp_sanitize_output($brands);
$cname = rp_sanitize_output($cname);
return json_encode(array(
'status' => TRUE,
'results' => $brands,
'which_page' => 'brands',
'c_name' => $cname,
'rp_wp_uploads_base_url' => $rp_wp_uploads_base_url
));
}
function rp_fe_get_brands(){
if(!isset($_POST['via_back_button'])) {
$cname = $_POST['c_name'] ?? '';
$load_step = rp_get_front_end_firsttime_load_step($cname);
if(!empty($load_step)) {
$selected = $load_step[0];
if($selected === 'repairs') {
$_POST['c_name'] = $load_step[1][0];
$_POST['b_name'] = $load_step[1][1];
$_POST['m_name'] = $load_step[1][2];
echo _rp_fe_get_repairs();
exit();
} else if($selected === 'models') {
$_POST['c_name'] = $load_step[1][0];
$_POST['b_name'] = $load_step[1][1];
echo _rp_fe_get_models();
exit();
} else {
echo _rp_fe_get_brands();
exit();
}
} else {
echo _rp_fe_get_brands();
exit();
}
} else {
echo _rp_fe_get_brands();
exit();
}
}
rp_ajax_for_public('rp_fe_get_brands','rp_fe_get_brands');
// -------------------------------
function rp_pre_load_fe_get_models() {
global $rpQuery;
global $rp_pre_selected_location;
$rp_pre_selected_location = 0;
$is_enabled_enhanced_locations = rp_is_enabled_pricing_based_on_location();
if( $is_enabled_enhanced_locations == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'Invalid location id'));
exit;
}
}
$GLOBALS['rp_pre_loading_fe_get_repairs'] = array( $rp_pre_selected_location, $is_enabled_enhanced_locations );
$cname = $_POST['c_name'] ?? '';
if( empty( $cname ) ) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'Invalid category name'));
exit;
}
$category_table = $rpQuery->prefix . "rs_category";
$brand_table = $rpQuery->prefix . "rs_brand";
$c_result = $rpQuery->get_row("SELECT * FROM $category_table WHERE c_name = '".rp_escape_sql($cname)."'");
if(empty($c_result)) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'Invalid category name'));
exit;
}
$c_id = $c_result->c_id;
$brands = $rpQuery->get_results("SELECT * FROM $brand_table WHERE c_id_fk = '".rp_escape_sql($c_id)."' ORDER BY b_position ASC, b_name ASC");
if( empty( $brands ) || count( $brands ) <= 1 ) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'No preload available'));
exit;
}
$final_response = array();
$start_time = microtime( true );
$response_size = 0;
// 500KB limit
$responseLimit = 500 * 1024;
while( !empty( $brands ) && ( microtime( true ) - $start_time ) < 0.2 && $response_size < $responseLimit ) {
$brand = array_shift( $brands );
$_POST['c_name'] = $c_result->c_name;
$_POST['b_name'] = $brand->b_name;
$theResult = _rp_fe_get_models_pre_loaded();
$final_response[ $c_result->c_name .'|'. $brand->b_name ] = $theResult;
$response_size += strlen( $theResult );
}
$back_btn_data = _rp_fe_get_categories();
echo json_encode( array( 'status' => TRUE, 'data' => $final_response, 'back_btn_data' => $back_btn_data ) );
exit;
}
rp_ajax_for_public('rp_pre_load_fe_get_models','rp_pre_load_fe_get_models');
function _rp_fe_get_models_pre_loaded() {
if(!isset($_POST['via_back_button'])) {
$cname = $_POST['c_name'] ?? '';
$bname = $_POST['b_name'] ?? '';
$load_step = rp_get_front_end_firsttime_load_step($cname, $bname);
if(!empty($load_step)) {
$selected = $load_step[0];
if($selected === 'repairs') {
$_POST['c_name'] = $load_step[1][0];
$_POST['b_name'] = $load_step[1][1];
$_POST['m_name'] = $load_step[1][2];
return _rp_fe_get_repairs();
}
}
}
return _rp_fe_get_models();
}
// --------------------------------------------------------- get models for front-end
function _rp_fe_get_models() {
global $rp_pre_selected_location;
if( isset( $GLOBALS['rp_pre_loading_fe_get_repairs'] ) && !empty( $GLOBALS['rp_pre_loading_fe_get_repairs'] ) ) {
list( $rp_pre_selected_location, $is_enabled_enhanced_locations ) = $GLOBALS['rp_pre_loading_fe_get_repairs'];
} else {
$rp_pre_selected_location = 0;
$is_enabled_enhanced_locations = rp_is_enabled_pricing_based_on_location();
if( $is_enabled_enhanced_locations == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
return json_encode(Array('status' => false, 'message' => 'Invalid location id'));
}
}
}
$cname = $_POST['c_name'] ?? '';
$bname = $_POST['b_name'] ?? '';
return rp_get_cached_front_end_step('_rp_fe_get_models', array( $rp_pre_selected_location, $is_enabled_enhanced_locations, $cname, $bname ), function(){
return _rp_fe_get_models_actual();
});
}
function _rp_fe_get_models_actual() {
global $rpQuery;
global $rp_pre_selected_location;
$brand_table = $rpQuery->prefix . "rs_brand";
$category_table = $rpQuery->prefix . "rs_category";
$model_table = $rpQuery->prefix . "rs_model";
$cname = $_POST['c_name'] ?? '';
$bname = $_POST['b_name'] ?? '';
$models = array();
$model_series = array();
if(!empty($cname) && !empty($bname)) {
$c_result = $rpQuery->get_results("SELECT * FROM $category_table WHERE c_name = '".rp_escape_sql($cname)."'");
$c_id = $c_result[0]->c_id;
$brands = $rpQuery->get_results("SELECT * FROM $brand_table WHERE b_name = '".rp_escape_sql($bname)."' AND c_id_fk = '".rp_escape_sql($c_id)."'");
$b_id = $brands[0]->b_id;
$models = $rpQuery->get_results("SELECT m_id, m_name, m_img, m_code, brand_id_fk FROM $model_table WHERE brand_id_fk = '".rp_escape_sql($b_id)."' AND device_type = '".rp_escape_sql($c_id)."' AND is_active = '1' ORDER BY m_position ASC, release_date DESC");
$model_series = rp_get_only_active_model_series_with_atleast_one_model( $b_id );
$model_series = rp_unset_associative_object_keys( $model_series, array( 'b_id_fk', 'c_date_time', 'id', 'is_active', 'position', 'm_id_fk', 'updated_on' ) );
}
if(empty($models)) {
$models = array();
}
$models = _rp_optimize_image_links( $models, 'm_img' );
$model_series = _rp_optimize_image_links( $model_series, 'm_img' );
$rp_wp_uploads_base_url = rp_get_wp_uploads_base_url();
list( $models, $models_keys ) = _rp_keys_compression_algorithm( $models );
list( $model_series, $model_series_keys ) = _rp_keys_compression_algorithm( $model_series );
$models = rp_sanitize_output($models);
$cname = rp_sanitize_output($cname);
$bname = rp_sanitize_output($bname);
$model_series = rp_sanitize_output($model_series);
return json_encode(array(
'status' => TRUE,
'results' => $models,
'models_keys' => $models_keys,
'model_series' => $model_series,
'model_series_keys' => $model_series_keys,
'which_page' => 'models',
'c_name' => $cname,
'b_name' => $bname,
'rp_wp_uploads_base_url' => $rp_wp_uploads_base_url
));
}
function rp_fe_get_models(){
if(!isset($_POST['via_back_button'])) {
$cname = $_POST['c_name'] ?? '';
$bname = $_POST['b_name'] ?? '';
$load_step = rp_get_front_end_firsttime_load_step($cname, $bname);
if(!empty($load_step)) {
$selected = $load_step[0];
if($selected === 'repairs') {
$_POST['c_name'] = $load_step[1][0];
$_POST['b_name'] = $load_step[1][1];
$_POST['m_name'] = $load_step[1][2];
echo _rp_fe_get_repairs();
exit();
} else {
echo _rp_fe_get_models();
exit();
}
} else {
echo _rp_fe_get_models();
exit();
}
} else {
echo _rp_fe_get_models();
exit();
}
}
rp_ajax_for_public('rp_fe_get_models','rp_fe_get_models');
// ------------------------------------------
function rp_set_coupon_settings( $order_id_fk = 0, $parent_order_id = 0 ) {
global $rpQuery;
if( !empty( $parent_order_id ) ) {
// get combo_dstatus, combo_damount, combo_dtype from rs_orders where o_id = $parent_order_id
// and then assign to rs_orders where o_id = $order_id_fk
$rs_orders = $rpQuery->prefix . 'rs_orders';
$parent_order = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '".rp_escape_sql($parent_order_id)."'");
if( !empty( $parent_order ) ) {
$rpQuery->query("UPDATE `$rs_orders` SET `combo_dstatus` = '".rp_escape_sql($parent_order->combo_dstatus)."', `combo_damount` = '".rp_escape_sql($parent_order->combo_damount)."', `combo_dtype` = '".rp_escape_sql($parent_order->combo_dtype)."' WHERE `o_id` = '".rp_escape_sql($order_id_fk)."'");
}
} else {
$planing_discount_table = $rpQuery->prefix . "rs_planning_and_discount";
$planning_discount = $rpQuery->get_results("SELECT * FROM `$planing_discount_table`");
$planning_discount = rp_fix_combo_discount_row( $planning_discount );
if( !empty( $planning_discount ) ) {
$planning_discount = $planning_discount[0];
$combo_dstatus = 0;
if( $planning_discount->is_combo_discount == '1' ) {
// Combo discount is enabled
$combo_dstatus = 1;
$combo_damount = $planning_discount->amount;
$combo_dtype = 'Fixed';
} else if( $planning_discount->is_combo_discount_percentage == '1' ) {
// Combo discount is enabled
$combo_dstatus = 1;
$combo_damount = $planning_discount->amount;
$combo_dtype = 'Percentage';
} else {
// Combo discount is disabled
}
if( $combo_dstatus == 1 ) {
// Update rs_order where o_id = $order_id_fk (combo_dstatus, combo_damount, combo_dtype)
$rs_orders = $rpQuery->prefix . 'rs_orders';
$rpQuery->query("UPDATE `$rs_orders` SET `combo_dstatus` = '".rp_escape_sql($combo_dstatus)."', `combo_damount` = '".rp_escape_sql($combo_damount)."', `combo_dtype` = '".rp_escape_sql($combo_dtype)."' WHERE `o_id` = '".rp_escape_sql($order_id_fk)."'");
}
}
}
}
// -------------------------------------------
function _rp_fix_combo_discount_row_order_related( $row = NULL, $o_id_fk = 0 ) {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$order_row = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '".rp_escape_sql($o_id_fk)."'");
if( empty( $order_row ) ) {
return $row;
}
if( $order_row->combo_dstatus == '1' ) {
if( strtolower( trim( $order_row->combo_dtype ) ) == 'fixed' ) {
// Fixed Discount
$row->is_combo_discount = '1';
$row->is_combo_discount_percentage = '0';
} else {
// Percentage Discount
$row->is_combo_discount = '0';
$row->is_combo_discount_percentage = '1';
}
$row->amount = $order_row->combo_damount;
} else {
$row->is_combo_discount = '0';
$row->is_combo_discount_percentage = '0';
}
return $row;
}
function _rp_fix_combo_discount_row( $row = NULL, $o_id_fk = 0 ) {
if( !empty( $o_id_fk ) ) {
return _rp_fix_combo_discount_row_order_related( $row, $o_id_fk );
}
if( $row->is_combo_discount == '1' ) {
$selected_opt = trim(rp_get_option('rp_combo_discount_type', 'Fixed'));
if( strtolower( $selected_opt ) == 'percentage' ) {
// Percentage Discount
$row->is_combo_discount = '0';
$row->is_combo_discount_percentage = '1';
} else {
// Fixed Discount
$row->is_combo_discount = '1';
$row->is_combo_discount_percentage = '0';
}
} else {
$row->is_combo_discount = '0';
$row->is_combo_discount_percentage = '0';
}
return $row;
}
function rp_fix_combo_discount_row( $planning_discount = NULL, $o_id_fk = 0 ) {
if( empty( $planning_discount ) ) {
return $planning_discount;
}
if( is_object( $planning_discount ) ) {
$row = $planning_discount;
$row = _rp_fix_combo_discount_row( $row, $o_id_fk );
$planning_discount = $row;
return $planning_discount;
} else if( is_array( $planning_discount ) ) {
$row = $planning_discount[0];
$row = _rp_fix_combo_discount_row( $row, $o_id_fk );
$planning_discount[0] = $row;
return $planning_discount;
} else {
return $planning_discount;
}
}
function _rp_check_indexes_of_table( $table = '' ) {
global $rpQuery;
$table = $rpQuery->prefix . $table;
$indexes = $rpQuery->get_results("SHOW INDEX FROM $table");
$indexes = rp_sanitize_output($indexes);
return $indexes;
}
// --------------------------------------------------------- get repairs for front-end
function rp_getUniqueQueriesRanSoFar() {
global $rpQuery;
$allQueries = $rpQuery->get_saved_queries();
$uniqueQueries = array();
$duplicateQueries = array();
foreach( $allQueries as $singleQuery ) {
if( !in_array( $singleQuery, $uniqueQueries ) ) {
$uniqueQueries[] = $singleQuery;
} else {
$duplicateQueries[] = $singleQuery;
}
}
return array( $duplicateQueries, $uniqueQueries );
}
function rp_sort_associative_array( $array = array(), $order_by = '' ) {
if( empty( $array ) || !is_array( $array ) || empty( $order_by ) ) {
return $array;
}
$order_by = explode(',', $order_by);
// trim
$order_by = array_map('trim', $order_by);
usort($array, function($a, $b) use ($order_by) {
$result = 0;
foreach( $order_by as $key => $value ) {
$value = explode(' ', $value);
$which_order = 'ASC';
if( isset( $value[ 1 ] ) && in_array( strtoupper( $value[ 1 ] ), array( 'ASC', 'DESC' ) ) ) {
$which_order = strtoupper( $value[ 1 ] );
}
$value = $value[0];
if( $a[$value] == $b[$value] ) {
continue;
}
if( $which_order == 'ASC' ) {
$result = $a[$value] - $b[$value];
} else {
$result = $b[$value] - $a[$value];
}
break;
}
return $result;
});
return $array;
}
function rp_filter_associative_array( $array = array(), $where = array() ) {
if( empty( $array ) || !is_array( $array ) || empty( $where ) || !is_array( $where ) ) {
return $array;
}
$filtered = array();
foreach( $array as $key => $value ) {
$isMatched = TRUE;
foreach( $where as $whereKey => $whereValue ) {
if( !isset( $value[ $whereKey ] ) || $value[ $whereKey ] != $whereValue ) {
$isMatched = FALSE;
break;
}
}
if( $isMatched ) {
$filtered[] = $value;
}
}
return $filtered;
}
function rp_unset_associative_object_keys( $objects_org = array(), $keys_to_unset = array() ) {
$objects = unserialize( serialize( $objects_org ) );
if( empty( $objects ) ) {
return $objects;
}
if( is_string( $keys_to_unset ) ) {
$keys_to_unset = array( $keys_to_unset );
}
if( !is_array( $keys_to_unset ) ) {
return $objects;
}
foreach( $objects as $key => $object ) {
foreach( $keys_to_unset as $key_to_unset ) {
if( isset( $object->$key_to_unset ) || property_exists( $object, $key_to_unset ) ) {
unset( $object->$key_to_unset );
}
}
$objects[ $key ] = $object;
}
return $objects;
}
function rp_get_wp_uploads_base_url() {
static $uploads = NULL;
if( $uploads !== NULL ) {
return $uploads;
}
$uploads = wp_get_upload_dir();
$uploads = $uploads['baseurl'] ?? '';
return $uploads;
}
function rp_remove_wp_uploads_folder_url( $url = '' ) {
if( empty( $url ) ) {
return $url;
}
$uploads = rp_get_wp_uploads_base_url();
$url = str_replace( $uploads, '$', $url );
return $url;
}
function _rp_optimize_image_links( $items = array(), $image_link_key = '' ) {
foreach( $items as $key => $objItem ) {
$items[ $key ]->{$image_link_key} = rp_remove_wp_uploads_folder_url( $objItem->{$image_link_key} );
}
return $items;
}
function rp_get_dynamic_pricing_hash( $b_name = '', $m_name = '', $is_dynamic_pricing_enabled = 0 ) {
if( empty( $m_name ) || empty( $is_dynamic_pricing_enabled ) ) {
return '';
}
global $rpQuery;
$brand_table = $rpQuery->prefix. "rs_brand";
$model_table = $rpQuery->prefix. "rs_model";
$all_brands = null;
if(!empty($b_name)) {
$all_brands = $rpQuery->get_results("SELECT * FROM $brand_table WHERE b_name = '".rp_escape_sql($b_name)."'");
}
$models = array();
if(!empty($all_brands) && !empty($b_name)) {
$search_brands = array();
foreach ($all_brands as $key => $value) {
$search_brands[] = $value->b_id;
}
$search_brands = '('.implode(',', $search_brands).')';
$models = $rpQuery->get_results("SELECT * FROM $model_table WHERE m_name = '".rp_escape_sql($m_name)."' AND brand_id_fk IN $search_brands");
} else {
$models = $rpQuery->get_results("SELECT * FROM $model_table WHERE m_name = '".rp_escape_sql($m_name)."'");
}
if( empty( $models ) ) {
return '';
}
$model = $models[0] ?? array();
$m_uq_id = $model->m_uq_id ?? '';
if( empty( $m_uq_id ) ) {
return '';
}
$enabled_suppliers = rp_dp_get_custom_configured_suppliers( $m_uq_id );
if( empty( $enabled_suppliers ) ) {
return '';
}
$sku = rp_get_all_rows_related_to_m_uq_id_and_suppliers( $m_uq_id, $enabled_suppliers );
$sku = rp_unset_associative_object_keys( $sku, array( 'id', 'updated_at' ) );
$hash = md5( json_encode( $sku ) );
return $hash;
}
// -------------------------------
function rp_pre_load_fe_get_repairs() {
global $wp_repair_selected_language;
global $rpQuery;
global $rp_pre_selected_location;
$is_enabled_enhanced_locations = rp_is_enabled_pricing_based_on_location();
$rp_pre_selected_location = 0;
if( $is_enabled_enhanced_locations == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'Invalid location id'));
exit;
}
}
$is_dynamic_pricing_enabled = rp_is_enabled_dynamic_pricing();
$GLOBALS['rp_pre_loading_fe_get_repairs'] = array( $rp_pre_selected_location, $is_enabled_enhanced_locations, $is_dynamic_pricing_enabled );
$cname = $_POST['c_name'] ?? '';
$bname = $_POST['b_name'] ?? '';
if( empty( $cname ) || empty( $bname ) ) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'Invalid input provided'));
exit;
}
$category_table = $rpQuery->prefix . "rs_category";
$brand_table = $rpQuery->prefix . "rs_brand";
$model_table = $rpQuery->prefix . "rs_model";
$c_result = $rpQuery->get_row("SELECT * FROM $category_table WHERE c_name = '".rp_escape_sql($cname)."'");
if(empty($c_result)) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'Invalid category name'));
exit;
}
$c_id = $c_result->c_id;
$brand = $rpQuery->get_row("SELECT * FROM $brand_table WHERE b_name = '".rp_escape_sql($bname)."' AND c_id_fk = '".rp_escape_sql($c_id)."'");
if( empty( $brand ) ) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'Invalid brand name'));
exit;
}
$b_id = $brand->b_id;
$models = $rpQuery->get_results("SELECT m_id, m_name, m_img, m_code, brand_id_fk FROM $model_table WHERE brand_id_fk = '".rp_escape_sql($b_id)."' AND device_type = '".rp_escape_sql($c_id)."' AND is_active = '1' ORDER BY m_position ASC, release_date DESC");
if( empty( $models ) || count( $models ) <= 1 ) {
echo json_encode(Array('status' => TRUE, 'data' => array(), 'message' => 'No preload available'));
exit;
}
$start_time = microtime( true );
$final_response = array();
$response_size = 0;
// 500KB limit
$responseLimit = 500 * 1024;
while( !empty( $models ) && ( microtime( true ) - $start_time ) < 0.2 && $response_size < $responseLimit ) {
$model = array_shift( $models );
$_POST['b_name'] = $brand->b_name;
$_POST['m_name'] = $model->m_name;
$theResult = _rp_fe_get_repairs();
$final_response[ $brand->b_name .'|'. $model->m_name ] = $theResult;
$response_size += strlen( $theResult );
}
$GLOBALS['rp_pre_loading_fe_get_repairs'] = array( $rp_pre_selected_location, $is_enabled_enhanced_locations );
$back_btn_data = _rp_fe_get_brands();
echo json_encode( array( 'status' => TRUE, 'data' => $final_response, 'back_btn_data' => $back_btn_data ) );
exit;
}
rp_ajax_for_public('rp_pre_load_fe_get_repairs','rp_pre_load_fe_get_repairs');
// ---------------------------------------
function _rp_fe_get_repairs() {
global $wp_repair_selected_language;
global $rp_pre_selected_location;
if( isset( $GLOBALS['rp_pre_loading_fe_get_repairs'] ) && !empty( $GLOBALS['rp_pre_loading_fe_get_repairs'] ) ) {
list( $rp_pre_selected_location, $is_enabled_enhanced_locations, $is_dynamic_pricing_enabled ) = $GLOBALS['rp_pre_loading_fe_get_repairs'];
} else {
$is_enabled_enhanced_locations = rp_is_enabled_pricing_based_on_location();
$rp_pre_selected_location = 0;
if( $is_enabled_enhanced_locations == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
return json_encode(Array('status' => false, 'message' => 'Invalid location id'));
}
}
$is_dynamic_pricing_enabled = rp_is_enabled_dynamic_pricing();
}
$m_name = $_POST['m_name'] ?? '';
$b_name = $_POST['b_name'] ?? '';
$c_name = '';
$m_name = trim($m_name);
$b_name = trim($b_name);
$dp_linking_hash = rp_get_dynamic_pricing_hash( $b_name, $m_name, $is_dynamic_pricing_enabled );
$result = rp_get_cached_front_end_step('_rp_fe_get_repairs', array( $wp_repair_selected_language, $is_enabled_enhanced_locations, $rp_pre_selected_location, $dp_linking_hash, $is_dynamic_pricing_enabled, $c_name, $b_name, $m_name ), function(){
return _rp_fe_get_repairs_actual_response();
});
$last_synced_date = rp_get_option('rp_dp_finished_cron_processing', '');
// format = 24/12/22
if( !empty( $last_synced_date ) ) {
$last_synced_date = date( rp_get_option('rp_dp_date_format_front_end', 'd/m/y'), $last_synced_date);
} else {
$last_synced_date = '';
}
$result['last_synced_date'] = $last_synced_date;
return json_encode($result);
}
function rp_find_model_by_m_uq_id( $m_uq_id = '' ) {
if( empty( trim( $m_uq_id ) ) ) {
return false;
}
global $rpQuery;
$models_table = $rpQuery->prefix . "rs_model";
return $rpQuery->get_row("SELECT * FROM $models_table WHERE `m_uq_id` = '".rp_escape_sql($m_uq_id)."'");
}
function rp_pricing_table_shortcode_handler( $atts ) {
global $rpQuery;
global $wp_repair_lang;
$atts = array_change_key_case( ( array )$atts, CASE_LOWER );
$shortcode_attributes = shortcode_atts(
array(
'code' => '', // m_uq_id
'location' => '',
'language' => ''
),
$atts
);
$code = esc_attr( $shortcode_attributes['code'] );
$model_id = false;
if( !empty( $model = rp_find_model_by_m_uq_id( $code ) ) ) {
$model_id = $model->m_id ?? false;
}
// Accept both Location ID / Name ---- START
$shortcode_attributes = rp_get_final_location_id_for_shortcode( $shortcode_attributes );
// Accept both Location ID / Name ---- END
$location_attr = esc_attr( $shortcode_attributes['location'] );
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
$location_id = false;
if( !empty( $found_location = rp_get_location_by_id( (int) $location_attr ) ) ) {
$location_id = $found_location->location_id ?? false;
}
} else {
$location_id = 0;
}
if( $model_id === false && $location_id === false ) {
return 'Please enter valid code and location attribute.';
} else if( $location_id === false ) {
return 'Please enter valid location attribute.';
} else if( $model_id === false ) {
return 'Please enter valid code attribute.';
} else {
// Good to render!
}
rp_handle_default_language_overwrite( $shortcode_attributes['language'] );
$content = wp_repair_show_alert_if_no_license();
if(!empty($content)) {
return '';
}
$prepared_data = _rp_get_data_for_repair_pricing_table( $model_id, $location_id );
$hasCategory = false;
foreach( $prepared_data as $prepared_row ) {
if( $prepared_row['type'] == 'category' ) {
$hasCategory = true;
}
}
$hasPrintedUpsaleCategory = false;
$count = 0;
$company_information = $rpQuery->prefix . "rs_company_information";
$rs_localization = $rpQuery->prefix . "rs_localization";
$company_results = $rpQuery->get_results("SELECT * FROM $company_information");
$theme_color = $company_results[0]->company_theme_color ?? '1275c2';
$localization = $rpQuery->get_row("SELECT * FROM $rs_localization");
ob_start();
?>
<style type="text/css" style="display:none">
<?php
if( !empty( $theme_color ) ) {
?>
:root {
--rp-theme-color: #<?php echo $theme_color;?>;
--rp-theme-color-10: #<?php echo $theme_color;?>1A;
}
<?php
}
?>
.repair-pricing-table-container {
display: block;
width: 100%;
}
.repair-pricing-table-container table th,
.repair-pricing-table-container table td {
text-align:left;
padding: 10px 15px;
}
.repair-pricing-table-container.no-category table tr.rp-odd {
background: var(--rp-theme-color-10);
}
.repair-pricing-table-container.no-category table {
border-color:transparent;
}
.repair-pricing-table-container.no-category table tr td,
.repair-pricing-table-container.no-category table tr th {
border-color:transparent;
}
.repair-pricing-table-container.has-category table tr.rp-heading-tr {
background: var(--rp-theme-color-10);
}
</style>
<div class="repair-pricing-table-container <?php if( $hasCategory === true ) { echo 'has-category'; } else { echo 'no-category'; } ?>">
<table class="repair-pricing-table">
<thead>
<tr>
<th><?php echo ($wp_repair_lang['item_name'] ?? 'Item Name'); ?></th>
<th><?php echo ($wp_repair_lang['price'] ?? 'Price'); ?></th>
</tr>
</thead>
<tbody>
<?php
foreach( $prepared_data as $prepared_row ) {
if( $prepared_row['type'] == 'category' ) {
if( $prepared_row['name'] == 'Uncategorised' ) {
$prepared_row['name'] = ($wp_repair_lang['uncategorised'] ?? 'Uncategorised');
}
?>
<tr class="rp-heading-tr">
<th colspan="2"><?php echo esc_html( $prepared_row['name'] ); ?></th>
</tr>
<?php
$count = 0;
} else {
if( $prepared_row['type'] == 'upsale' && $hasCategory == true ) {
if( $hasPrintedUpsaleCategory === false ) {
$hasPrintedUpsaleCategory = true;
?>
<tr class="rp-heading-tr">
<th colspan="2"><?php echo ($wp_repair_lang['upsales'] ?? 'Upsales'); ?></th>
</tr>
<?php
$count = 0;
}
}
$count++;
?>
<tr class="<?php echo ( $count % 2 == 0 ) ? 'rp-even' : 'rp-odd'; ?>">
<td><?php echo esc_html( $model->m_name ?? '' ); ?> <?php echo esc_html( $prepared_row['name'] ); ?></td>
<td><?php
if( ( $prepared_row['type'] ?? '' ) == 'item' && array_key_exists( 'is_free', $prepared_row ) ) {
if( ($prepared_row['is_free'] ?? 0) == 1 ) {
// Free
echo $wp_repair_lang['free_repair_text'];
} else if( ((float) ( $prepared_row['price'] ?? 0 )) > 0 ) {
// Normal price
echo rp_handle_currency_position($prepared_row['price'], ($localization->set_currency ?? ''), FALSE);
} else {
// Price on request
echo $wp_repair_lang['price_on_request_text'];
}
} else {
echo rp_handle_currency_position($prepared_row['price'], ($localization->set_currency ?? ''), FALSE);
}
?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
<?php
$content = ob_get_clean();
return $content;
}
add_shortcode( 'Repair_Pricing_Table', 'rp_pricing_table_shortcode_handler' );
function _rp_get_prepared_repair_data_for_pricing_table( $repairs = array(), $repair_attrs_from_db = array() ) {
$prepared_data = array();
if( empty( $repairs ) ) {
return $prepared_data;
}
foreach( $repairs as $repair_row ) {
$attrs = $repair_attrs_from_db[ $repair_row->r_id ] ?? array();
if( ($repair_row->is_free ?? 0) == 1 ) {
$attrs = array();
}
if( !empty( $attrs ) ) {
foreach( $attrs as $attr_row ) {
$prepared_data[] = array(
'type' => 'item',
'name' => trim( $repair_row->r_name ) . ' ' . trim( $attr_row->a_name ),
'price' => $attr_row->a_price,
'is_free' => 0
);
}
} else {
$prepared_data[] = array(
'type' => 'item',
'name' => trim( $repair_row->r_name ),
'price' => $repair_row->r_price,
'is_free' => ( $repair_row->is_free ?? 0 )
);
}
}
return $prepared_data;
}
function _rp_get_data_for_repair_pricing_table( $m_id = 0, $location_id = 0 ) {
list( $repairs, $category_based, $repair_attrs_from_db, $upsales ) = _rp_get_model_related_repairs_for_front_end( $m_id, $location_id );
$prepared_data = array();
if( count( $category_based ) < 2 ) {
// use $repairs
$prepared_repairs_data = _rp_get_prepared_repair_data_for_pricing_table( $repairs ?? array(), $repair_attrs_from_db );
foreach( $prepared_repairs_data as $prepared_data_row ) {
$prepared_data[] = $prepared_data_row;
}
} else {
foreach( $category_based as $repairCategory ) {
if( !empty( $repairCategory->repairs ?? array() ) ) {
$prepared_data[] = array(
'type' => 'category',
'name' => $repairCategory->c_name
);
$prepared_repairs_data = _rp_get_prepared_repair_data_for_pricing_table( $repairCategory->repairs ?? array(), $repair_attrs_from_db );
foreach( $prepared_repairs_data as $prepared_data_row ) {
$prepared_data[] = $prepared_data_row;
}
}
}
}
if( !empty( $upsales ) ) {
foreach( $upsales as $upsale_row ) {
$prepared_data[] = array(
'type' => 'upsale',
'name' => $upsale_row->us_name,
'price' => $upsale_row->us_new_price
);
}
}
return $prepared_data;
}
function _rp_handle_hiding_repairs_if_needed_when_search( $m_id = 0, $m_uq_id = '', $repairs_group = array(), $rp_pre_selected_location = 0 ) {
if( !empty($repairs_group) ) {
$repair_attrs_from_db = array();
foreach($repairs_group as $ar_index => $ar_row) {
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$ar_row = apply_filters('rp_overwrite_individual_repair_row', $ar_row, $rp_pre_selected_location);
}
$repairs_group[$ar_index] = $ar_row;
}
foreach($repairs_group as $ar_index => $r){
$n = $r->r_price;
// $repair_attr = $rpQuery->get_results("SELECT * FROM $r_attr_table WHERE r_id_fk = '".rp_escape_sql($r->r_id)."' AND is_active = '1' ORDER BY ra_position ASC");
$repair_attr = rp_get_all_attrs_of_repair_order_by_position( $r->r_id );
$repair_attr = rp_fix_default_repair_attr_sorting($repair_attr, $m_id);
if(!empty($repair_attr)) {
foreach($repair_attr as $ra_index => $ra_row) {
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$ra_row = apply_filters('rp_overwrite_individual_repair_attr_row', $ra_row, $rp_pre_selected_location);
}
$repair_attr[$ra_index] = $ra_row;
}
$repair_attr = apply_filters('rp_filter_all_repair_attr_before_return', $repair_attr, $m_uq_id);
// only append if not empty
if(!empty($repair_attr)) {
$repair_attrs_from_db[$r->r_id] = $repair_attr;
}
}
}
$repairs_group = apply_filters('rp_filter_all_repairs_before_return', $repairs_group, $m_uq_id, $repair_attrs_from_db);
if( !empty( $repairs_group ) ) {
return array( $repairs_group, $repair_attrs_from_db );
}
}
return array();
}
function _rp_quick_find_default_repair_translations( $only_needed_uq_ids_for_translations = array() ) {
global $rpQuery;
global $wp_repair_selected_language;
$rs_dr_translations = $rpQuery->prefix . "rs_dr_translations";
$translations = $rpQuery->get_results("SELECT `key`, `uq_id`, `value` FROM `$rs_dr_translations`
WHERE `language` LIKE '".rp_escape_sql($wp_repair_selected_language)."'");
$prepared = array();
foreach( $translations as $row ) {
if( !isset( $prepared[ $row->key ] ) ) {
$prepared[ $row->key ] = array();
}
// This is for keeping an array short for less memory consumption
// and faster search!
if( in_array( $row->uq_id, $only_needed_uq_ids_for_translations ) ) {
$prepared[ $row->key ][ $row->uq_id ] = $row->value;
}
}
return $prepared;
}
function rp_quick_find_default_repair_translations( $key = '', $uq_id = '', $default = '', $only_needed_uq_ids_for_translations = array() ) {
static $prepared_translations = NULL;
static $final_cache = array();
$cache_key = md5( $key . $uq_id . $default );
if( array_key_exists( $cache_key, $final_cache ) ) {
return $final_cache[ $cache_key ];
}
if( $prepared_translations === NULL ) {
$prepared_translations = _rp_quick_find_default_repair_translations( $only_needed_uq_ids_for_translations );
}
$result = FALSE;
if( array_key_exists( $key, $prepared_translations ) && array_key_exists( $uq_id, $prepared_translations[ $key ] ) ) {
$result = $prepared_translations[ $key ][ $uq_id ] ?? ( $default ?? '' );
} else if( rp_is_default_repair_or_attr( $uq_id ) ) {
// Default translation was expected!
// But isn't found. Simply return default
$result = $default;
} else {
// False = Try to find translation
// the usual way. It could be
// an individually created repair/attr
$result = FALSE;
}
$final_cache[ $cache_key ] = $result;
return $result;
}
function _rp_get_model_related_repairs_for_advance_search( $m_id = 0, $location_id = 0, $sorted_default_repairs = array() ) {
global $wp;
global $rpQuery;
global $wp_repair_lang;
global $rp_pre_selected_location;
_rp_set_default_tiemzone();
if( !empty( $location_id ) ) {
$rp_pre_selected_location = $location_id;
} else {
$rp_pre_selected_location = 0;
}
$model_table = $rpQuery->prefix. "rs_model";
$r_attr_table = $rpQuery->prefix. "rs_repair_attr";
$rs_repair = $rpQuery->prefix . "rs_repair";
$model = $rpQuery->get_row("SELECT * FROM $model_table WHERE m_id = '{$m_id}'");
$all_repairs = rp_get_model_related_repairs_front_end( $m_id, 'r_position ASC, r_id ASC', array( 'is_active' => '1' ) );
$need_to_handle_hiding_repair = !empty( rp_hide_repair_if() );
if( $need_to_handle_hiding_repair == TRUE ) {
$all_repairs = apply_filters( 'rp_handle_hiding_main_repair_if_needed', $all_repairs );
}
$count_repairs = 0;
$category_based = rp_get_individual_repairs_based_on_repair_category( $m_id, TRUE, TRUE );
$repairs = array();
$repair_attrs_from_db = array();
if( !empty( $category_based ) ) {
$all_repairs = array();
foreach( $category_based as $cb_key => $repairCategory ) {
if( $repairCategory->is_active != 1 ) {
continue; // skip...
}
$all_category_repairs = $repairCategory->repairs ?? array();
foreach( $all_category_repairs as $cr_index => $c_repair ) {
$c_repair->repair_category_id = $repairCategory->c_id ?? 0;
$all_category_repairs[ $cr_index ] = $c_repair;
}
if( $need_to_handle_hiding_repair == TRUE ) {
$result = _rp_handle_hiding_repairs_if_needed_when_search( $m_id, $model->m_uq_id, $all_category_repairs, $rp_pre_selected_location );
if( !empty( $result ) ) {
list( $all_category_repairs, $_repair_attrs_from_db ) = $result;
foreach( $all_category_repairs as $category_repair_row ) {
$all_repairs[] = $category_repair_row;
}
foreach( $_repair_attrs_from_db as $r_id => $repair_attrs ) {
$repair_attrs_from_db[ $r_id ] = $repair_attrs;
}
}
} else {
foreach( $all_category_repairs as $category_repair_row ) {
$all_repairs[] = $category_repair_row;
}
}
}
}
$count_repairs = count($all_repairs);
// now next is to only process filtered 3 repairs
$found_dr_repairs = array();
$found_repair_ids = array();
foreach( $sorted_default_repairs as $dr_row ) {
$found = false;
foreach( $all_repairs as $ar_row ) {
if( $model->device_type == $dr_row->dr_category && $ar_row->r_uq_id == $dr_row->dr_uq_id ) {
// If default repair is from same category
$found = true;
break;
}
}
if( $found == true ) {
if( $need_to_handle_hiding_repair == TRUE ) {
// Already modified in above loop
$found_dr_repairs[] = $ar_row;
$found_repair_ids[] = $ar_row->r_id;
} else {
$result = _rp_handle_hiding_repairs_if_needed_when_search( $m_id, $model->m_uq_id, array( $ar_row ), $rp_pre_selected_location );
if( !empty( $result ) ) {
list( $repairs_group, $_repair_attrs_from_db ) = $result;
foreach( $_repair_attrs_from_db as $r_id => $repair_attrs ) {
$repair_attrs_from_db[ $r_id ] = $repair_attrs;
}
$ar_row = $repairs_group[0];
$found_dr_repairs[] = $ar_row;
$found_repair_ids[] = $ar_row->r_id;
}
}
}
if( count( $found_dr_repairs ) >= 3 ) {
break;
}
}
if( count( $found_dr_repairs ) < 3 ) {
foreach( $all_repairs as $ar_row ) {
if( !in_array( $ar_row->r_id, $found_repair_ids ) ) {
if( $need_to_handle_hiding_repair == TRUE ) {
// Already modified in above loop
$found_dr_repairs[] = $ar_row;
} else {
$result = _rp_handle_hiding_repairs_if_needed_when_search( $m_id, $model->m_uq_id, array( $ar_row ), $rp_pre_selected_location );
if( !empty( $result ) ) {
list( $repairs_group, $_repair_attrs_from_db ) = $result;
foreach( $_repair_attrs_from_db as $r_id => $repair_attrs ) {
$repair_attrs_from_db[ $r_id ] = $repair_attrs;
}
$ar_row = $repairs_group[0];
$found_dr_repairs[] = $ar_row;
}
}
if( count( $found_dr_repairs ) >= 3 ) {
break;
}
}
}
}
$all_repairs = $found_dr_repairs;
$only_needed_uq_ids_for_translations = array();
foreach( $all_repairs as $ar_index => $ar_row ) {
$only_needed_uq_ids_for_translations[] = $ar_row->r_uq_id . '_' . $model->device_type;
}
foreach( $repair_attrs_from_db as $r_id => $repair_attrs ) {
foreach( $repair_attrs as $ra_index => $ra_row ) {
$only_needed_uq_ids_for_translations[] = $ra_row->a_uq_id;
}
}
foreach( $all_repairs as $ar_index => $ar_row ) {
// only repair name need to be translatable
$translated = rp_quick_find_default_repair_translations( 'repair_name', $ar_row->r_uq_id . '_' . $model->device_type, $ar_row->r_name, $only_needed_uq_ids_for_translations );
if( $translated !== FALSE ) {
$ar_row->r_name = $translated;
} else {
$ar_row->r_name = rp_get_static_translations_of_repair('repair_name', $ar_row->r_uq_id, $ar_row->m_id_fk, 'selected');
}
$all_repairs[$ar_index] = $ar_row;
}
foreach( $repair_attrs_from_db as $r_id => $repair_attrs ) {
foreach( $repair_attrs as $ra_index => $ra_row ) {
$translated_a_name = rp_quick_find_default_repair_translations('attr_name', $ra_row->a_uq_id, $ra_row->a_name, $only_needed_uq_ids_for_translations);
if( $translated_a_name !== FALSE ) {
$ra_row->a_name = $translated_a_name;
} else {
$ra_row->a_name = rp_get_static_translations_of_attr('attr_name', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
}
$translated_a_desc = rp_quick_find_default_repair_translations('attr_desc', $ra_row->a_uq_id, $ra_row->a_desc, $only_needed_uq_ids_for_translations);
if( $translated_a_desc !== FALSE ) {
$ra_row->a_desc = $translated_a_desc;
} else {
$ra_row->a_desc = rp_get_static_translations_of_attr('attr_desc', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
}
$translated_a_badge = rp_quick_find_default_repair_translations('attr_badge', $ra_row->a_uq_id, $ra_row->a_badge,$only_needed_uq_ids_for_translations);
if( $translated_a_badge !== FALSE ) {
$ra_row->a_badge = $translated_a_badge;
} else {
$ra_row->a_badge = rp_get_static_translations_of_attr('attr_badge', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
}
if( rp_get_option('rp_enable_read_more_link_for_attributes', '0') == '1' ) {
$ra_row->a_readmore = rp_get_static_translations_of_attr_individually_editable('attr_read_more', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_readmoretext = rp_get_static_translations_of_attr_individually_editable('attr_readmore_text', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_readmore_is_valid = (filter_var( $ra_row->a_readmore, FILTER_VALIDATE_URL ) && rp_get_option('rp_enable_read_more_link_for_attributes', '0') == '1') == TRUE ? '1' : '0';
} else {
$ra_row->a_readmore = '';
$ra_row->a_readmoretext = '';
$ra_row->a_readmore_is_valid = '0';
}
$repair_attrs[$ra_index] = $ra_row;
}
$repair_attrs = rp_unset_associative_object_keys( $repair_attrs, array( 'a_margin', 'ra_position', 'updated_on', 'r_id_fk' ) );
$repair_attrs_from_db[ $r_id ] = $repair_attrs;
}
if( !empty( $all_repairs ) ) {
$all_repairs = rp_unset_associative_object_keys( $all_repairs, array( 'm_id_fk', 'r_date_time', 'r_margin', 'r_position', 'updated_on', 'last_synced_date' ) );
$repairs = $all_repairs;
} else {
$repairs = array();
}
return (array(
'count_repairs' => $count_repairs,
'repairs' => $repairs,
'attrs' => $repair_attrs_from_db,
));
}
function _rp_get_model_related_repairs_for_front_end( $m_id = 0, $location_id = 0 ) {
global $wp;
global $rpQuery;
global $wp_repair_lang;
global $rp_pre_selected_location;
_rp_set_default_tiemzone();
if( !empty( $location_id ) ) {
$rp_pre_selected_location = $location_id;
} else {
$rp_pre_selected_location = 0;
}
$model_table = $rpQuery->prefix. "rs_model";
$r_attr_table = $rpQuery->prefix. "rs_repair_attr";
$rs_repair = $rpQuery->prefix . "rs_repair";
$upsales_models_table = $rpQuery->prefix . "rs_upsales_models";
$rs_upsales = $rpQuery->prefix . "rs_upsales";
$model = $rpQuery->get_row("SELECT * FROM $model_table WHERE m_id = '{$m_id}'");
$all_repairs = rp_get_model_related_repairs_front_end( $m_id, 'r_position ASC, r_id ASC', array( 'is_active' => '1' ) );
$need_to_handle_hiding_repair = !empty( rp_hide_repair_if() );
if( $need_to_handle_hiding_repair == TRUE ) {
$all_repairs = apply_filters( 'rp_handle_hiding_main_repair_if_needed', $all_repairs );
}
$count_repairs = count($all_repairs);
$category_based = rp_get_individual_repairs_based_on_repair_category( $m_id, TRUE, TRUE );
$categoriesCount = 0;
$repair_attrs_from_db = array();
$repairs = array();
if( !empty( $category_based ) ) {
$categoriesCount = count( $category_based );
foreach( $category_based as $cb_key => $repairCategory ) {
$repairCategory->c_name = rp_get_static_translations_of_repair_category('category_name', $repairCategory->c_uq_id, $repairCategory->m_id_fk, 'selected');
$all_repairs = $repairCategory->repairs ?? array();
if(!empty($all_repairs)) {
foreach($all_repairs as $ar_index => $ar_row) {
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$ar_row = apply_filters('rp_overwrite_individual_repair_row', $ar_row, $rp_pre_selected_location);
}
$ar_row->r_name = rp_get_static_translations_of_repair('repair_name', $ar_row->r_uq_id, $ar_row->m_id_fk, 'selected');
$ar_row->r_discription = rp_get_static_translations_of_repair('repair_desc', $ar_row->r_uq_id, $ar_row->m_id_fk, 'selected');
$ar_row->r_badge = rp_get_static_translations_of_repair('repair_badge', $ar_row->r_uq_id, $ar_row->m_id_fk, 'selected');
$ar_row->r_readmore = rp_get_static_translations_of_repair_individually_editable('repair_read_more', $ar_row->r_uq_id.'_'.rp_get_model_cached_category_by_mid($ar_row->m_id_fk), $ar_row->m_id_fk, 'selected');
$ar_row->r_readmoretext = rp_get_static_translations_of_repair_individually_editable('repair_readmore_text', $ar_row->r_uq_id.'_'.rp_get_model_cached_category_by_mid($ar_row->m_id_fk), $ar_row->m_id_fk, 'selected');
$ar_row->r_readmore_is_valid = (filter_var( $ar_row->r_readmore, FILTER_VALIDATE_URL ) && rp_get_option('rp_enable_read_more_link_for_repairs', '0') == '1' ) == TRUE ? '1' : '0';
$all_repairs[$ar_index] = $ar_row;
}
foreach($all_repairs as $ar_index => $r){
$n = $r->r_price;
// $repair_attr = $rpQuery->get_results("SELECT * FROM $r_attr_table WHERE r_id_fk = '".rp_escape_sql($r->r_id)."' AND is_active = '1' ORDER BY ra_position ASC");
$repair_attr = rp_get_all_attrs_of_repair_order_by_position( $r->r_id );
$repair_attr = rp_fix_default_repair_attr_sorting($repair_attr, $m_id);
if(!empty($repair_attr)) {
foreach($repair_attr as $ra_index => $ra_row) {
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$ra_row = apply_filters('rp_overwrite_individual_repair_attr_row', $ra_row, $rp_pre_selected_location);
}
$ra_row->a_name = rp_get_static_translations_of_attr('attr_name', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_desc = rp_get_static_translations_of_attr('attr_desc', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_badge = rp_get_static_translations_of_attr('attr_badge', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_readmore = rp_get_static_translations_of_attr_individually_editable('attr_read_more', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_readmoretext = rp_get_static_translations_of_attr_individually_editable('attr_readmore_text', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_readmore_is_valid = (filter_var( $ra_row->a_readmore, FILTER_VALIDATE_URL ) && rp_get_option('rp_enable_read_more_link_for_attributes', '0') == '1') == TRUE ? '1' : '0';
$repair_attr[$ra_index] = $ra_row;
}
$repair_attr = apply_filters('rp_filter_all_repair_attr_before_return', $repair_attr, $model->m_uq_id);
// only append if not empty
if(!empty($repair_attr)) {
$repair_attrs_from_db[$r->r_id] = $repair_attr;
}
}
}
$all_repairs = apply_filters('rp_filter_all_repairs_before_return', $all_repairs, $model->m_uq_id, $repair_attrs_from_db);
$count_repairs = count( $all_repairs );
if( $categoriesCount < 2 ) {
$repairs = $all_repairs;
} else {
$repairCategory->repairs = $all_repairs;
}
}
$category_based[$cb_key] = $repairCategory;
}
}
$upsales = $rpQuery->get_results("SELECT upm.*,up.* FROM $upsales_models_table AS upm JOIN $rs_upsales AS up ON upm.upsales_id_fk = up.upsales_id WHERE upm.m_id_fk = '".rp_escape_sql($m_id)."' AND up.is_active = '1' ORDER BY upsales_position");
foreach($upsales as $up_index => $up_row) {
$up_row->us_name = rp_get_static_translations_of_upsale_selected('us_name', $up_row->upsales_id, 'selected');
$up_row->us_text = rp_get_static_translations_of_upsale_selected('us_text', $up_row->upsales_id, 'selected');
$up_row->us_info = rp_get_static_translations_of_upsale_selected('us_info', $up_row->upsales_id, 'selected');
$upsales[$up_index] = $up_row;
}
return (array(
$repairs,
$category_based,
$repair_attrs_from_db,
$upsales
));
}
function _rp_fe_get_repairs_actual_response() {
$start_time = microtime(true);
global $wp;
global $rpQuery;
global $wp_repair_lang;
_rp_set_default_tiemzone();
$m_name = $_POST['m_name'] ?? '';
$b_name = $_POST['b_name'] ?? '';
$c_name = '';
$m_name = trim($m_name);
$b_name = trim($b_name);
global $rp_pre_selected_location;
$brand_table = $rpQuery->prefix. "rs_brand";
$model_table = $rpQuery->prefix. "rs_model";
$default_repair_table = $rpQuery->prefix. "rs_default_repair";
$dr_attr_table = $rpQuery->prefix. "rs_default_repair_attr";
$r_attr_table = $rpQuery->prefix. "rs_repair_attr";
$default_color_table = $rpQuery->prefix. "rs_default_color";
$modelcolor_table = $rpQuery->prefix. "rs_model_color";
$rs_repair = $rpQuery->prefix . "rs_repair";
$rs_localization = $rpQuery->prefix . "rs_localization";
$rs_coupons = $rpQuery->prefix . "rs_coupons";
$show_coupon_field = !empty($rpQuery->get_results("SELECT * FROM $rs_coupons WHERE is_active = '1' LIMIT 1;"));
$all_brands = null;
if(!empty($b_name)) {
$all_brands = $rpQuery->get_results("SELECT * FROM $brand_table WHERE b_name = '".rp_escape_sql($b_name)."'");
}
if(!empty($all_brands) && !empty($b_name)) {
$search_brands = array();
foreach ($all_brands as $key => $value) {
$search_brands[] = $value->b_id;
}
$search_brands = '('.implode(',', $search_brands).')';
$models = $rpQuery->get_results("SELECT * FROM $model_table WHERE m_name = '".rp_escape_sql($m_name)."' AND brand_id_fk IN $search_brands");
} else {
$models = $rpQuery->get_results("SELECT * FROM $model_table WHERE m_name = '".rp_escape_sql($m_name)."'");
}
$m_id = $models[0]->m_id;
if(!empty($models)) {
$brand_table = $rpQuery->prefix . "rs_brand";
$brands = $rpQuery->get_results("SELECT * FROM $brand_table WHERE b_id = '".rp_escape_sql($models[0]->brand_id_fk)."' LIMIT 1;");
if(!empty($brands) && !empty($models)) {
$models[0]->b_name = $brands[0]->b_name;
$b_name = $brands[0]->b_name;
}
}
$c_name = '';
if(!empty($models)) {
$category_table = $rpQuery->prefix . "rs_category";
$category = $rpQuery->get_results("SELECT * FROM $category_table WHERE c_id = '".rp_escape_sql($models[0]->device_type)."' LIMIT 1;");
if(!empty($category) && !empty($models)) {
$models[0]->c_name = $category[0]->c_name;
$c_name = $category[0]->c_name;
}
}
$model_colors = $rpQuery->get_results("SELECT * FROM $modelcolor_table WHERE m_id_fk = '".rp_escape_sql($m_id)."' ORDER BY mc_position ASC, color_name ASC");
$count_colors = $rpQuery->get_var("SELECT COUNT(*) FROM $modelcolor_table WHERE m_id_fk = '".rp_escape_sql($m_id)."'");
$model_colors = rp_unset_associative_object_keys( $model_colors, array( 'm_id_fk', 'mc_id', 'mc_position', 'mc_uq_id', 'updated_on' ) );
// $count_repairs = $rpQuery->get_var("SELECT COUNT(*) FROM $rs_repair WHERE m_id_fk = '".rp_escape_sql($m_id)."' AND is_active = '1'");
// $all_repairs = $rpQuery->get_results("SELECT * FROM $rs_repair WHERE m_id_fk = '".rp_escape_sql($m_id)."' AND is_active = '1' ORDER BY r_position ASC, r_id ASC;");
$all_repairs = rp_get_model_related_repairs_front_end( $m_id, 'r_position ASC, r_id ASC', array( 'is_active' => '1' ) );
$need_to_handle_hiding_repair = !empty( rp_hide_repair_if() );
if( $need_to_handle_hiding_repair == TRUE ) {
$all_repairs = apply_filters( 'rp_handle_hiding_main_repair_if_needed', $all_repairs );
}
$count_repairs = count($all_repairs);
$default_listing_range = rp_get_option( 'rp_default_listing_index_model_'. $m_id, FALSE );
if( $default_listing_range === FALSE ){
$default_listing_range = rp_get_option( 'rp_default_listing_index_'. strval( $models[0]->device_type ), 6 );
}
$default_listing_range = (int) $default_listing_range;
$default_listing_range = rp_round_to_even_number($default_listing_range);
$category_based = rp_get_individual_repairs_based_on_repair_category( $m_id, TRUE, TRUE );
$categoriesCount = 0;
$repair_attrs_from_db = array();
$limited_repairs = array();
$repairs = array();
if( !empty( $category_based ) ) {
$categoriesCount = count( $category_based );
foreach( $category_based as $cb_key => $repairCategory ) {
$repairCategory->c_name = rp_get_static_translations_of_repair_category('category_name', $repairCategory->c_uq_id, $repairCategory->m_id_fk, 'selected');
$all_repairs = $repairCategory->repairs ?? array();
if(!empty($all_repairs)) {
foreach($all_repairs as $ar_index => $ar_row) {
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$ar_row = apply_filters('rp_overwrite_individual_repair_row', $ar_row, $rp_pre_selected_location);
}
$ar_row->r_name = rp_get_static_translations_of_repair('repair_name', $ar_row->r_uq_id, $ar_row->m_id_fk, 'selected');
$ar_row->r_discription = rp_get_static_translations_of_repair('repair_desc', $ar_row->r_uq_id, $ar_row->m_id_fk, 'selected');
$ar_row->r_badge = rp_get_static_translations_of_repair('repair_badge', $ar_row->r_uq_id, $ar_row->m_id_fk, 'selected');
$ar_row->r_readmore = rp_get_static_translations_of_repair_individually_editable('repair_read_more', $ar_row->r_uq_id.'_'.rp_get_model_cached_category_by_mid($ar_row->m_id_fk), $ar_row->m_id_fk, 'selected');
$ar_row->r_readmoretext = rp_get_static_translations_of_repair_individually_editable('repair_readmore_text', $ar_row->r_uq_id.'_'.rp_get_model_cached_category_by_mid($ar_row->m_id_fk), $ar_row->m_id_fk, 'selected');
$ar_row->r_readmore_is_valid = (filter_var( $ar_row->r_readmore, FILTER_VALIDATE_URL ) && rp_get_option('rp_enable_read_more_link_for_repairs', '0') == '1' ) == TRUE ? '1' : '0';
$all_repairs[$ar_index] = $ar_row;
}
foreach($all_repairs as $ar_index => $r){
$n = $r->r_price;
// $repair_attr = $rpQuery->get_results("SELECT * FROM $r_attr_table WHERE r_id_fk = '".rp_escape_sql($r->r_id)."' AND is_active = '1' ORDER BY ra_position ASC");
$repair_attr = rp_get_all_attrs_of_repair_order_by_position( $r->r_id );
$repair_attr = rp_fix_default_repair_attr_sorting($repair_attr, $m_id);
if(!empty($repair_attr)) {
foreach($repair_attr as $ra_index => $ra_row) {
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$ra_row = apply_filters('rp_overwrite_individual_repair_attr_row', $ra_row, $rp_pre_selected_location);
}
$ra_row->a_name = rp_get_static_translations_of_attr('attr_name', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_desc = rp_get_static_translations_of_attr('attr_desc', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_badge = rp_get_static_translations_of_attr('attr_badge', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_readmore = rp_get_static_translations_of_attr_individually_editable('attr_read_more', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_readmoretext = rp_get_static_translations_of_attr_individually_editable('attr_readmore_text', $ra_row->a_uq_id, $ra_row->r_id_fk, 'selected');
$ra_row->a_readmore_is_valid = (filter_var( $ra_row->a_readmore, FILTER_VALIDATE_URL ) && rp_get_option('rp_enable_read_more_link_for_attributes', '0') == '1') == TRUE ? '1' : '0';
$repair_attr[$ra_index] = $ra_row;
}
$repair_attr = apply_filters('rp_filter_all_repair_attr_before_return', $repair_attr, $models[0]->m_uq_id);
// only append if not empty
if(!empty($repair_attr)) {
$repair_attrs_from_db[$r->r_id] = $repair_attr;
}
}
}
$all_repairs = apply_filters('rp_filter_all_repairs_before_return', $all_repairs, $models[0]->m_uq_id, $repair_attrs_from_db);
$count_repairs = count( $all_repairs );
$all_repairs = rp_unset_associative_object_keys( $all_repairs, array( 'm_id_fk', 'r_date_time', 'r_margin', 'r_position', 'updated_on', 'r_uq_id', 'last_synced_date' ) );
$all_repairs = _rp_optimize_image_links( $all_repairs, 'r_img' );
if( $categoriesCount < 2 ) {
$limited_repairs = array_slice($all_repairs, 0, $default_listing_range);
$limit = $count_repairs - $default_listing_range;
if(count($all_repairs) > $default_listing_range) {
$repairs = array_slice($all_repairs, $default_listing_range);
}
} else {
$repairCategory->repairs = $all_repairs;
}
}
$category_based[$cb_key] = $repairCategory;
}
}
$planing_discount_table = $rpQuery->prefix . "rs_planning_and_discount";
$planning_discount = $rpQuery->get_results("SELECT * FROM $planing_discount_table");
$planning_discount = rp_fix_combo_discount_row( $planning_discount );
$planning_discount = rp_unset_associative_object_keys( $planning_discount, array( 'booking_amount_per_slot', 'booking_slots_length', 'come_our_store', 'date_time', 'pd_id', 'pickup_service', 'repair_on_location', 'ship_device' ) );
$tax = $rpQuery->get_results("SELECT * FROM $rs_localization");
$upsales_models_table = $rpQuery->prefix . "rs_upsales_models";
$rs_upsales = $rpQuery->prefix . "rs_upsales";
$upsales = $rpQuery->get_results("SELECT upm.*,up.* FROM $upsales_models_table AS upm JOIN $rs_upsales AS up ON upm.upsales_id_fk = up.upsales_id WHERE upm.m_id_fk = '".rp_escape_sql($m_id)."' AND up.is_active = '1' ORDER BY upsales_position");
foreach($upsales as $up_index => $up_row) {
$up_row->us_name = rp_get_static_translations_of_upsale_selected('us_name', $up_row->upsales_id, 'selected');
$up_row->us_text = rp_get_static_translations_of_upsale_selected('us_text', $up_row->upsales_id, 'selected');
$up_row->us_info = rp_get_static_translations_of_upsale_selected('us_info', $up_row->upsales_id, 'selected');
$upsales[$up_index] = $up_row;
}
$upsales = rp_unset_associative_object_keys( $upsales, array( 'date_time', 'm_id_fk', 'up_model_id', 'upsales_id_fk', 'upsales_position' ) );
$upsales = _rp_optimize_image_links( $upsales, 'upsales_img' );
list( $upsales, $upsales_keys ) = _rp_keys_compression_algorithm( $upsales );
$company_information = $rpQuery->prefix . "rs_company_information";
$company_results = $rpQuery->get_results("SELECT * FROM $company_information");
$theme_color = $company_results[0]->company_theme_color;
$localization = $rpQuery->get_results("SELECT * FROM $rs_localization");
$localization = rp_unset_associative_object_keys( $localization, array( 'date_time', 'localization_id', 'set_language', 'show_decimals', 'show_even_price' ) );
$decimal = $localization[0]->set_decimals;
$offers_table = $rpQuery->prefix . "rs_notifications_and_offers";
$offers = $rpQuery->get_results("SELECT * FROM $offers_table");
$type_table = $rpQuery->prefix . "rs_notification_types";
$types = $rpQuery->get_results("SELECT * FROM $type_table");
$types = rp_unset_associative_object_keys( $types, array( 'date_time', 'noti_type', 'noti_type_id' ) );
$category_based_keys = array();
if( !empty( $category_based ) ) {
foreach( $category_based as $cb_key => $repairCategory ) {
$repairCategoryRepairs = $repairCategory->repairs ?? array();
list( $repairCategoryRepairs, $repairCategoryRepairs_keys ) = _rp_keys_compression_algorithm( $repairCategoryRepairs );
unset($repairCategory->repairs);
$sanitized_repairs = rp_sanitize_output($repairCategoryRepairs);
$sanitizedRepairCategory = rp_sanitize_output($repairCategory);
$sanitizedRepairCategory->repairs = $sanitized_repairs;
$sanitizedRepairCategory->repairs_keys = $repairCategoryRepairs_keys;
$category_based[$cb_key] = $sanitizedRepairCategory;
}
$category_based = rp_unset_associative_object_keys( $category_based, array( 'c_date_time', 'c_position', 'c_uq_id', 'updated_on', 'm_id_fk' ) );
if( count( $category_based ) === 1 ) {
$category_based = rp_unset_associative_object_keys( $category_based, array( 'repairs' ) );
}
$category_based = _rp_optimize_image_links( $category_based, 'c_img' );
list( $category_based, $category_based_keys ) = _rp_keys_compression_algorithm( $category_based );
}
$models = rp_unset_associative_object_keys( $models, array( 'color_ids', 'device_type', 'is_active', 'm_code', 'm_date_time', 'm_position', 'm_uq_id', 'release_date', 'repair_ids', 'updated_on' ) );
$last_synced_date = rp_get_option('rp_dp_finished_cron_processing', '');
// format = 24/12/22
if( !empty( $last_synced_date ) ) {
$last_synced_date = date( rp_get_option('rp_dp_date_format_front_end', 'd/m/y'), $last_synced_date);
} else {
$last_synced_date = '';
}
$rp_wp_uploads_base_url = rp_get_wp_uploads_base_url();
$m_name = rp_sanitize_output($m_name);
$c_name = rp_sanitize_output($c_name);
$b_name = rp_sanitize_output($b_name);
$models = rp_sanitize_output($models);
$model_colors = rp_sanitize_output($model_colors);
$count_repairs = rp_sanitize_output($count_repairs);
$limited_repairs = rp_sanitize_output($limited_repairs);
$repairs = rp_sanitize_output($repairs);
$localization = rp_sanitize_output($localization);
$upsales = rp_sanitize_output($upsales);
$decimal = rp_sanitize_output($decimal);
$tax = rp_sanitize_output($tax);
$types = rp_sanitize_output($types);
$ravalue_keys = array();
if( !empty($repair_attrs_from_db) && is_array($repair_attrs_from_db) ) {
foreach($repair_attrs_from_db as $rakey => $ravalue) {
$ravalue = rp_unset_associative_object_keys( $ravalue, array( 'a_margin', 'a_uq_id', 'ra_position', 'updated_on', 'r_id_fk' ) );
list( $ravalue, $ravalue_keys ) = _rp_keys_compression_algorithm( $ravalue );
$repair_attrs_from_db[$rakey] = rp_sanitize_output($ravalue);
}
}
$planning_discount = rp_sanitize_output($planning_discount);
$show_coupon_field = rp_sanitize_output($show_coupon_field);
$tracked_execution_time = (microtime(true) - $start_time);
return (array(
'status' => TRUE,
'm_name' => $m_name,
'c_name' => $c_name,
'b_name' => $b_name,
'models' => $models,
'model_colors' => $model_colors,
'count_repairs' => $count_repairs,
'limited_repairs' => $limited_repairs,
'remaining_repairs' => $repairs,
'last_synced_date' => $last_synced_date,
'rp_wp_uploads_base_url' => $rp_wp_uploads_base_url,
'category_based' => $category_based,
'category_based_keys' => $category_based_keys,
'ravalue_keys' => $ravalue_keys,
'upsales_keys' => $upsales_keys,
'categories_count' => $categoriesCount,
'localization' => $localization,
'upsales' => $upsales,
'decimal' => $decimal,
'tax' => $tax,
'types' => $types,
'repair_attrs_from_db' => $repair_attrs_from_db,
'planning_discount' => $planning_discount,
'show_coupon_field' => $show_coupon_field,
'which_page' => 'repairs',
'execution_time' => $tracked_execution_time
));
}
function rp_fe_get_repairs(){
echo _rp_fe_get_repairs();
exit();
}
rp_ajax_for_public('rp_fe_get_repairs','rp_fe_get_repairs');
// --------------------------------------------------------- get order summary
function rp_render_order_summary( $models = array(), $color_name = '', $_r_id = NULL, $o_id_fk = NULL, $a_id = NULL, $up_id = NULL, $coupon = NULL, $coupon_type = NULL, $coupon_info = NULL, $total_price = 0, $sub_total = 0, $opened = '0', $selected_dm = '', $dm_key = '', $dm_cost = 0, $rpCart = NULL, $combo = 0 ) {
global $rpQuery;
global $wp_repair_lang;
$planning_discount_table = $rpQuery->prefix . "rs_planning_and_discount";
$planning_discount = $rpQuery->get_results("SELECT * FROM `$planning_discount_table`");
if( !empty( $o_id_fk ) ) {
$planning_discount = rp_fix_combo_discount_row( $planning_discount, $o_id_fk );
} else {
$planning_discount = rp_fix_combo_discount_row( $planning_discount );
}
$localization_table = $rpQuery->prefix . "rs_localization";
$localization = $rpQuery->get_results("SELECT * FROM $localization_table");
$tax = $localization[0]->tax;
$decimal = $localization[0]->set_decimals;
$repair_table = $rpQuery->prefix . "rs_repair";
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$rs_upsales = $rpQuery->prefix . "rs_upsales";
ob_start();
include WP_REPAIR_PLUGIN_PATH . 'html/front_end/finalize_order_summary.php';
$content = ob_get_contents();
ob_end_clean();
return $content;
}
function rp_get_order_summary_markup() {
rp_verify_csrf_token_for_ajax('frontend');
global $rpQuery;
global $rp_pre_selected_location;
$p_method = $_REQUEST['payment_method'] ?? '';
$priority_box = $_REQUEST['priority_box'] ?? '';
$rp_pre_selected_location = 0;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
echo json_encode(Array('status' => false, 'message' => 'Invalid location id'));
exit;
}
}
$opened = $_POST['opened'] ?? '0';
$selected_dm = $_POST['id'] ?? '';
$model_table = $rpQuery->prefix . "rs_model";
$category_table = $rpQuery->prefix . "rs_category";
$brand_table = $rpQuery->prefix . "rs_brand";
$rs_coupons = $rpQuery->prefix . "rs_coupons";
$rs_customer = $rpQuery->prefix . "rs_customer";
$rs_customer_business = $rpQuery->prefix . "rs_customer_business";
$rs_orders = $rpQuery->prefix . "rs_orders";
if( !isset( $_SESSION ) || empty( $_SESSION ) || !isset( $_SESSION['finalize_booking_arr'] ) || empty( $_SESSION['finalize_booking_arr'] ) ) {
RepairPluginPro\RP_Session_Handler::read();
}
if( isset($_SESSION['finalize_booking_arr']) && !empty( $_SESSION['finalize_booking_arr'] ) ) {
$arr = $_SESSION['finalize_booking_arr'];
$m_name = $arr['m_name'];
$color_name = $arr['color_name'];
$m_id_fk = $arr['m_id_fk'];
$coupon_id = $arr['coupon_id'];
$b_id = $arr['b_id'];
$r_id = $arr['r_id'];
$a_id = $arr['a_id'];
$up_id = $arr['upid'];
$coupon_id = $arr['coupon_id'];
$get_c_id = $arr['get_c_id'] ?? '';
$get_uid = $arr['get_uid'] ?? '';
$get_o_id_fk = $arr['get_o_id_fk'] ?? '';
$reschedule = $arr['reschedule'] ?? '';
$models = array();
if(isset($m_id_fk)) {
if(!empty($b_id)) {
$models = $rpQuery->get_results("SELECT m.* ,b.b_name,c.c_name FROM $model_table AS m JOIN $brand_table AS b ON m.brand_id_fk = b.b_id JOIN $category_table AS c ON m.device_type = c.c_id WHERE m.m_name='".rp_escape_sql($m_name)."' AND m.brand_id_fk = '".rp_escape_sql($b_id)."'");
} else {
$models = $rpQuery->get_results("SELECT m.* ,b.b_name,c.c_name FROM $model_table AS m JOIN $brand_table AS b ON m.brand_id_fk = b.b_id JOIN $category_table AS c ON m.device_type = c.c_id WHERE m.m_name='".rp_escape_sql($m_name)."'");
}
if( !empty( $models ) ) {
$m_id_fk = $models[0]->m_id;
$brandQuery = $rpQuery->get_results("SELECT * FROM $brand_table WHERE b_id = '".rp_escape_sql($models[0]->brand_id_fk)."'");
if(!empty($brandQuery)) {
$b_name = $brandQuery[0]->b_name;
}
} else {
$m_id_fk = NULL;
}
} else {
$m_id_fk = NULL;
}
if( empty( $m_id_fk ) ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid input provided.'
));
exit;
}
$coupon = 0;
if( isset( $coupon_id ) && !empty( $coupon_id ) ) {
$coupon_detail = $rpQuery->get_row("SELECT * FROM `$rs_coupons` WHERE coupons_id = '".rp_escape_sql($coupon_id)."' LIMIT 1;");
if( empty( $coupon_detail ) ){
$coupon_id = '';
}
} else {
$coupon_id = '';
}
if(isset($get_c_id) && !empty($get_c_id)) {
$_GET['c_id'] = $get_c_id;
}
if(isset($get_uid) && !empty($get_uid)) {
$_GET['uid'] = $get_uid;
}
if(isset($reschedule) && !empty($reschedule)) {
$_GET['reschedule'] = $reschedule;
}
$o_id_fk = 0;
if(isset($_GET['c_id']) && isset($_GET['uid'])) {
if(!empty($_GET['c_id']) && !empty($_GET['uid'])) {
if(trim(strtolower($_GET['uid'])) === substr(md5($_GET['c_id']), 0, 8)) {
$_customer_details = $rpQuery->get_results("SELECT * FROM `$rs_customer` WHERE customer_id = '".rp_escape_sql($_GET['c_id'])."' LIMIT 1;");
if(!empty($_customer_details)) {
$o_id_fk = $get_o_id_fk ?? 0;
if(isset($_GET['reschedule']) && !empty($_GET['reschedule']) && !empty($o_id_fk)) {
// select notes from rs_orders table
$rp_order_details = $rpQuery->get_results("SELECT * FROM `$rs_orders` WHERE o_id = '".rp_escape_sql($o_id_fk)."' LIMIT 1;");
}
}
}
}
}
$delivery_method_key = '';
$delivery_method_cost = 0;
if( !empty( $o_id_fk ) ) {
rp_set_order_related_language($o_id_fk);
$_GET['o_id_fk'] = $o_id_fk;
$_POST['selected_dm_id'] = $selected_dm;
if( !empty( $priority_box ) ) {
$_REQUEST['rp_overwrite_priority_box'] = $priority_box;
}
if( !empty( $p_method ) ) {
$_REQUEST['rp_overwrite_payment_method'] = $p_method;
}
list( $rpCart, $calculations ) = rp_get_latest_order_calculations( $o_id_fk );
$combo = $calculations['combo_discount'];
$coupon = $calculations['coupon_amount'];
$total_price = $calculations['total'];
$sub_total = $calculations['sub_total'];
$delivery_method_key = $rpCart->delivery_method_translation_key();
$delivery_method_cost = $rpCart->delivery_method_cost();
$coupon_info = $rpCart->get_coupon_info();
if( !empty($coupon_info) ) {
$coupon_type = $coupon_info->coupons_type;
}
$rid = array();
$aid = array();
$upid = array();
foreach( $rpCart->repairs as $cartRow ) {
$rid[] = $cartRow->r_id;
}
foreach( $rpCart->repair_attrs as $cartRow ) {
$rid[] = $cartRow->r_id_fk;
$aid[] = $cartRow->a_id;
}
foreach( $rpCart->upsales as $cartRow ) {
$upid[] = $cartRow->upsales_id;
}
$prepared_post_data = $rpCart->prepare_post_data( $rid, $upid );
list( $rid, $array_name, $array_price, $aid, $upid ) = $prepared_post_data;
} else if( $m_id_fk !== NULL ) {
$rpCart = new RepairPluginPro\RP_Cart( $m_id_fk );
$rid = $r_id ?? array();
foreach ($rid as $repair_id) {
$rpCart->add_repair( ((int) $repair_id) );
}
$aid = $a_id ?? array();
foreach ($aid as $attr_id) {
$rpCart->add_repair_attr( ((int) $attr_id) );
}
$upid = $up_id ?? array();
foreach ($upid as $upsale_id) {
$rpCart->add_upsale( ((int) $upsale_id) );
}
if( !empty( $selected_dm ) ) {
$rpCart->add_delivery_method( $selected_dm );
}
if( !empty( $priority_box ) ) {
$rpCart->add_priority_box( $priority_box );
}
if( !empty( $p_method ) ) {
$rpCart->add_payment_method( $p_method );
}
if( !empty( $coupon_id ) ) {
$rpCart->add_coupon( ((int) $coupon_id) );
}
$calculations = $rpCart->calculate();
$combo = $calculations['combo_discount'];
$coupon = $calculations['coupon_amount'];
$total_price = $calculations['total'];
$sub_total = $calculations['sub_total'];
$delivery_method_key = $rpCart->delivery_method_translation_key();
$delivery_method_cost = $rpCart->delivery_method_cost();
$coupon_info = $rpCart->get_coupon_info();
if( !empty($coupon_info) ) {
$coupon_type = $coupon_info->coupons_type;
}
$prepared_post_data = $rpCart->prepare_post_data( $rid, $upid );
list( $r_id, $array_name, $array_price, $a_id, $up_id ) = $prepared_post_data;
} else {
}
$order_summary = rp_render_order_summary(
$models,
$color_name ?? '',
$r_id ?? NULL,
$o_id_fk ?? NULL,
$a_id ?? NULL,
$up_id ?? NULL,
$coupon ?? NULL,
$coupon_type ?? NULL,
$coupon_info ?? NULL,
$total_price ?? 0,
$sub_total ?? 0,
$opened ?? '0',
$selected_dm ?? '',
$delivery_method_key ?? '',
$delivery_method_cost ?? 0,
$rpCart,
$combo
);
$selected_dm_copy = str_replace('_by_', '_', $selected_dm);
$active_payment_methods = rp_get_supported_payment_methods_by_delivery_method( $selected_dm_copy, ( $total_price ?? 0 ) );
if( $total_price > 0 ) {
// Everything is good
} else {
$active_payment_methods = array();
}
$rp_order_summary_total_price = rp_get_total_amount_text( $total_price );
if( rp_need_to_show_payment_methods_on_price_on_request() == FALSE ) {
if( $rpCart->hasAnyRepairsWithZeroPrice() ) {
$active_payment_methods = array();
}
}
echo json_encode(array(
'status' => true,
'order_summary' => $order_summary,
'total_price' => $total_price,
'active_payment_methods' => $active_payment_methods,
'rp_order_summary_total_price' => $rp_order_summary_total_price
));
exit;
} else {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Something went wrong, please refresh the page and try agian.'
));
exit;
}
}
rp_ajax_for_public('rp_get_order_summary_markup','rp_get_order_summary_markup');
function rp_check_is_virtual_location( $location_id = 0 ) {
if( rp_is_enabled_virtual_location() == FALSE ) {
return FALSE;
}
global $rpQuery;
$company_location = $rpQuery->prefix . "rs_company_location";
$virtual_location = $rpQuery->get_row("SELECT * FROM $company_location WHERE `location_id` = '".rp_escape_sql($location_id)."' AND `is_virtual` = '1'");
return !empty( $virtual_location );
}
function rp_get_location_data_of_ship_device() {
global $rp_pre_selected_location;
$location_id = rp_get_default_location_id_of_delivery_method('ship_device');
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$location_id = $rp_pre_selected_location;
}
if( !empty( $location_id ) ) {
global $rpQuery;
$company_location = $rpQuery->prefix . "rs_company_location";
$dm_location = $rpQuery->get_results("SELECT * FROM $company_location WHERE `location_id` = '".rp_escape_sql($location_id)."'");
return $dm_location;
} else {
$newObject = new stdClass();
$newObject->location_name = '';
$newObject->location_address = '';
$newObject->location_city_district = '';
return array( $newObject );
}
}
function rp_get_locations_that_support_delivery_method( $delivery_method = '' ) {
global $rpQuery;
$company_location = $rpQuery->prefix . "rs_company_location";
$all_locations = $rpQuery->get_results("SELECT * FROM $company_location");
if( empty( $all_locations ) || rp_is_active_enhanced_locations_addon() == FALSE ) {
return $all_locations;
}
foreach( $all_locations as $locKey => $theLocation ) {
$supported_delivery_methods = rp_get_location_supported_delivery_methods( $theLocation->location_id );
if( !empty( $supported_delivery_methods ) && $supported_delivery_methods[ $delivery_method ] == 1 ) {
// This location support the required delivery method
} else {
unset( $all_locations[ $locKey ] );
}
}
if( !empty( $all_locations ) ) {
$all_locations = array_values( $all_locations );
} else {
$main_location_id = rp_get_main_location_id_of_company();
$all_locations = $rpQuery->get_results("SELECT * FROM $company_location WHERE `location_id` = '".rp_escape_sql($main_location_id)."'");
}
return $all_locations;
}
function rp_get_default_location_id_of_delivery_method( $delivery_method = '' ) {
// comebackfast
global $rpQuery;
$company_location = $rpQuery->prefix . "rs_company_location";
$all_locations = $rpQuery->get_results("SELECT * FROM $company_location");
if( $delivery_method == 'ship_device' ) {
$all_locations = rp_get_locations_that_support_delivery_method('ship_device');
}
if( $delivery_method == 'pickup_service' ) {
$all_locations = rp_get_locations_that_support_delivery_method('pickup_service');
}
if( $delivery_method == 'repair_on_your_location' || $delivery_method == 'repair_on_location' ) {
$all_locations = rp_get_locations_that_support_delivery_method('repair_on_your_location');
}
$default_location_row_org = NULL;
$default_location_row = NULL;
if( !empty( $all_locations ) ) {
$default_location_row = $all_locations[0];
$default_location_row_org = $all_locations[0];
}
$rp_dm_location_id = rp_get_option('wp_repair_'.$delivery_method.'_location_id', 1);
foreach( $all_locations as $locKey => $theLocation ) {
if( (int) $theLocation->location_id == (int) $rp_dm_location_id ) {
$default_location_row = $theLocation;
}
}
$enabled_virtual_location = rp_is_enabled_virtual_location();
if( $enabled_virtual_location !== FALSE ) {
if( !empty( $default_location_row ) && $delivery_method == 'ship_device' ) {
if( $default_location_row->is_virtual == '1' ) {
$default_location_row = $default_location_row_org;
}
}
}
if( !empty( $default_location_row ) ) {
return $default_location_row->location_id;
}
return 0;
}
// --------------------------------------------------------- get finalize repairs for front-end
function _rp_fe_finalize_repairs(){
global $rpQuery;
global $wp_repair_lang;
$m_name = $_POST['m_name'] ?? '';
$b_name = '';
$b_id = NULL;
global $rp_pre_selected_location;
global $rp_order_location_id;
$rp_pre_selected_location = 0;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
return json_encode(Array('status' => false, 'message' => 'Invalid location id'));
}
}
$company_information = $rpQuery->prefix . "rs_company_information";
$company_results = $rpQuery->get_results("SELECT * FROM $company_information");
$theme_color = $company_results[0]->company_theme_color;
$planning_discount_table = $rpQuery->prefix . "rs_planning_and_discount";
$planning_discount = $rpQuery->get_results("SELECT * FROM $planning_discount_table");
$planning_discount = rp_fix_combo_discount_row( $planning_discount );
$company_location = $rpQuery->prefix . "rs_company_location";
$location = $rpQuery->get_results("SELECT * FROM $company_location");
$localization_table = $rpQuery->prefix . "rs_localization";
$localization = $rpQuery->get_results("SELECT * FROM $localization_table");
$tax = $localization[0]->tax;
$decimal = $localization[0]->set_decimals;
$offer_table = $rpQuery->prefix . "rs_notifications_and_offers";
$offers = $rpQuery->get_results("SELECT * FROM $offer_table");
$type_table = $rpQuery->prefix . "rs_notification_types";
$type = $rpQuery->get_results("SELECT * FROM $type_table");
$uri_path = $_SERVER['REQUEST_URI'];
$uri_segments = explode('/', $uri_path);
$segment = count($uri_segments);
$pdf_offer = '';
if (isset($_POST['finalize_booking'])) {
$color_name = $_POST['color_name'] ?? '';
$total_price = $_POST['total_price'] ?? '';
$sub_total = $_POST['sub_total'] ?? '';
$pdf_offer = $_POST['pdf_offer'] ?? '';
$m_id_fk = $_POST['m_id_fk'] ?? '';
$c_id = $_POST['c_id'] ?? '';
$b_id = $_POST['b_id'] ?? '';
$r_id = $_POST['rid'] ?? array();
$a_id = $_POST['aid'] ?? array();
$coupon_id = $_POST['coupon_id'] ?? '';
$up_id = $_POST['upid'] ?? array();
}else if($segment > 6){
global $rpQuery;
$pdf_offer = '1';
$segment = end($uri_segments);
$secondKey = count($uri_segments) -2;
$thirdKey = count($uri_segments) -3;
$forthKey = count($uri_segments) -4;
$fifthKey = count($uri_segments) -5;
$sixKey = count($uri_segments) -6;
$sevenKey = count($uri_segments) -7;
$eightKey = count($uri_segments) -8;
$nineKey = count($uri_segments) -9;
$sub_total = explode('=', $segment)[1];
$second_segment = $uri_segments[$secondKey];
$coupon_id = explode('=', $second_segment)[1];
$third_segment = $uri_segments[$thirdKey];
$total_price = explode('=', $third_segment)[1];
$forth_segment = $uri_segments[$forthKey];
$r_id = explode('=', $forth_segment)[1];
$r_id = explode(',', $r_id);
$fifth_segment = $uri_segments[$fifthKey];
$a_id = explode('=', $fifth_segment)[1];
$a_id = explode(',', $a_id);
$six_segment = $uri_segments[$sixKey];
$up_id = explode('=', $six_segment)[1];
$up_id = explode(',', $up_id);
$seven_segment = $uri_segments[$sevenKey];
$color = explode('=', $seven_segment)[1];
$color = str_replace('-slash-', '/', $color);
$color_name = str_replace('-',' ',$color);
$eight_segment = $uri_segments[$eightKey];
$m_name = explode('=', $eight_segment)[1];
$m_name = str_replace('-',' ',$m_name);
$nine_segment = $uri_segments[$nineKey] ?? '';
if(!empty($nine_segment)) {
$b_id = explode('=', $nine_segment)[1];
} else {
$b_id = '';
}
$m_id_fk = TRUE;
}
if($b_id === 'shortcode_finalize_order' || $b_id === 'finalize') {
$b_id = '';
}
$model_table = $rpQuery->prefix . "rs_model";
$category_table = $rpQuery->prefix . "rs_category";
$brand_table = $rpQuery->prefix . "rs_brand";
$repair_table = $rpQuery->prefix . "rs_repair";
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$rs_customer = $rpQuery->prefix . "rs_customer";
$rs_customer_business = $rpQuery->prefix . "rs_customer_business";
$rs_orders = $rpQuery->prefix . "rs_orders";
$rs_order_repairs = $rpQuery->prefix . "rs_order_repairs";
$rs_order_repair_attr = $rpQuery->prefix . "rs_order_repair_attr";
$rs_order_upsales = $rpQuery->prefix . "rs_order_upsales";
$rs_upsales = $rpQuery->prefix . "rs_upsales";
$rs_coupons = $rpQuery->prefix . "rs_coupons";
$rs_company_schedules = $rpQuery->prefix . "rs_company_schedules";
if(isset($m_id_fk)) {
if(!empty($b_id)) {
$models = $rpQuery->get_results("SELECT m.* ,b.b_name,c.c_name FROM $model_table AS m JOIN $brand_table AS b ON m.brand_id_fk = b.b_id JOIN $category_table AS c ON m.device_type = c.c_id WHERE m.m_name='".rp_escape_sql($m_name)."' AND m.brand_id_fk = '".rp_escape_sql($b_id)."'");
} else {
$models = $rpQuery->get_results("SELECT m.* ,b.b_name,c.c_name FROM $model_table AS m JOIN $brand_table AS b ON m.brand_id_fk = b.b_id JOIN $category_table AS c ON m.device_type = c.c_id WHERE m.m_name='".rp_escape_sql($m_name)."'");
}
if( !empty( $models ) ) {
$m_id_fk = $models[0]->m_id;
$brandQuery = $rpQuery->get_results("SELECT * FROM $brand_table WHERE b_id = '".rp_escape_sql($models[0]->brand_id_fk)."'");
if(!empty($brandQuery)) {
$b_name = $brandQuery[0]->b_name;
}
} else {
$m_id_fk = NULL;
}
} else {
$m_id_fk = NULL;
}
if( empty( $m_id_fk ) ) {
return json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid input provided.'
));
}
$coupon = 0;
if( isset( $coupon_id ) && !empty( $coupon_id ) ) {
$coupon_detail = $rpQuery->get_row("SELECT * FROM $rs_coupons WHERE coupons_id = '".rp_escape_sql($coupon_id)."' LIMIT 1;");
if( empty( $coupon_detail ) ){
$coupon_id = '';
}
} else {
$coupon_id = '';
}
$_customer_first_name = '';
$_customer_last_name = '';
$_customer_name = '';
$_customer_phone = '';
$_customer_email = '';
$_customer_notes = '';
$_customer_business_name = '';
$_customer_house_no = '';
$_customer_street_address = '';
$_customer_city = '';
$_customer_zipcode = '';
$_customer_country = '';
if(isset($_POST['get_c_id'])) {
$_GET['c_id'] = $_POST['get_c_id'];
}
if(isset($_POST['get_uid'])) {
$_GET['uid'] = $_POST['get_uid'];
}
if(isset($_POST['rp_reschedule'])) {
$_GET['reschedule'] = $_POST['rp_reschedule'];
}
if(isset($_POST['rp_payment_cancel'])) {
$_GET['payment_cancel'] = $_POST['rp_payment_cancel'];
}
$o_id_fk = 0;
if(isset($_GET['c_id']) && isset($_GET['uid'])) {
if(!empty($_GET['c_id']) && !empty($_GET['uid'])) {
if(trim(strtolower($_GET['uid'])) === substr(md5($_GET['c_id']), 0, 8)) {
$_customer_details = $rpQuery->get_results("SELECT * FROM `$rs_customer` WHERE customer_id = '".rp_escape_sql($_GET['c_id'])."' LIMIT 1;");
if(!empty($_customer_details)) {
$_customer_first_name = $_customer_details[0]->customer_first_name;
$_customer_last_name = $_customer_details[0]->customer_last_name;
$_customer_name = $_customer_details[0]->customer_name;
if ( empty($_customer_first_name) && !empty($_customer_name) ) {
$name_parts = explode(' ', $_customer_name);
if ( count($name_parts) > 1 ) {
$_customer_first_name = $name_parts[0];
// Combine the rest as last name
$_customer_last_name = implode(' ', array_slice($name_parts, 1));
} else {
// If only one name is provided, assume it's the first name
$_customer_first_name = $_customer_name;
$_customer_last_name = '';
}
}
$_customer_phone = $_customer_details[0]->customer_phone;
$_customer_email = $_customer_details[0]->customer_email;
$_customer_house_no = trim($_customer_details[0]->customer_house_no ?? '');
$_customer_street_address = trim($_customer_details[0]->customer_street_address ?? '');
$_customer_city = trim($_customer_details[0]->customer_city ?? '');
$_customer_zipcode = trim($_customer_details[0]->customer_zipcode ?? '');
$_customer_country = trim($_customer_details[0]->customer_country ?? '');
$o_id_fk = $_POST['get_o_id_fk'] ?? 0;
if(isset($_GET['reschedule']) && !empty($_GET['reschedule']) && !empty($o_id_fk)) {
// select notes from rs_orders table
$rp_order_details = $rpQuery->get_results("SELECT * FROM `$rs_orders` WHERE o_id = '".rp_escape_sql($o_id_fk)."' LIMIT 1;");
if( !empty( $rp_order_details ) ) {
$_customer_notes = $rp_order_details[0]->notes;
$rp_order_location_id = $rp_order_details[0]->location_id_fk;
$based_on_loc = (int) ($rp_order_details[0]->based_on_location ?? 0);
if( !empty( $based_on_loc ) ) {
$rp_pre_selected_location = $rp_order_location_id;
}
}
} else if( !empty( $o_id_fk ) ) {
$rp_order_details = $rpQuery->get_results("SELECT * FROM `$rs_orders` WHERE o_id = '".rp_escape_sql($o_id_fk)."' LIMIT 1;");
if( !empty( $rp_order_details ) ) {
$rp_order_location_id = $rp_order_details[0]->location_id_fk;
$based_on_loc = (int) ($rp_order_details[0]->based_on_location ?? 0);
if( !empty( $based_on_loc ) ) {
$rp_pre_selected_location = $rp_order_location_id;
}
}
} else {
}
$rs_customer_business = $rpQuery->prefix . "rs_customer_business";
// select * from rs_customer_business table where customer_id_fk = $_GET['c_id']
$rp_customer_business_details = $rpQuery->get_results("SELECT * FROM `$rs_customer_business` WHERE customer_id_fk = '".rp_escape_sql($_GET['c_id'])."' LIMIT 1;");
if( !empty( $rp_customer_business_details ) ) {
$_customer_business_name = $rp_customer_business_details[0]->cb_name;
}
}
}
}
}
$delivery_method_key = '';
$delivery_method_cost = 0;
if( !empty( $o_id_fk ) && !empty( rp_get_single_order_row_by_o_id( $o_id_fk ) ) ) {
$planning_discount = rp_fix_combo_discount_row( $planning_discount, $o_id_fk );
rp_set_order_related_language($o_id_fk);
$_GET['o_id_fk'] = $o_id_fk;
list( $rpCart, $calculations ) = rp_get_latest_order_calculations( $o_id_fk );
$combo = $calculations['combo_discount'];
$coupon = $calculations['coupon_amount'];
$total_price = $calculations['total'];
$sub_total = $calculations['sub_total'];
$delivery_method_key = $rpCart->delivery_method_translation_key();
$delivery_method_cost = $rpCart->delivery_method_cost();
$coupon_info = $rpCart->get_coupon_info();
if( !empty($coupon_info) ) {
$coupon_type = $coupon_info->coupons_type;
}
$coupon_id = '';
if( !empty( $coupon_info->coupons_id ?? 0 ) ) {
$coupon_id = $coupon_info->coupons_id;
}
$rid = array();
$aid = array();
$upid = array();
foreach( $rpCart->repairs as $cartRow ) {
$rid[] = $cartRow->r_id;
}
foreach( $rpCart->repair_attrs as $cartRow ) {
$rid[] = $cartRow->r_id_fk;
$aid[] = $cartRow->a_id;
}
foreach( $rpCart->upsales as $cartRow ) {
$upid[] = $cartRow->upsales_id;
}
$prepared_post_data = $rpCart->prepare_post_data( $rid, $upid );
list( $rid, $array_name, $array_price, $aid, $upid ) = $prepared_post_data;
} else if( $m_id_fk !== NULL ) {
$o_id_fk = 0;
$rpCart = new RepairPluginPro\RP_Cart( $m_id_fk );
$rid = $r_id ?? array();
foreach ($rid as $repair_id) {
$rpCart->add_repair( ((int) $repair_id) );
}
$aid = $a_id ?? array();
foreach ($aid as $attr_id) {
$rpCart->add_repair_attr( ((int) $attr_id) );
}
$upid = $up_id ?? array();
foreach ($upid as $upsale_id) {
$rpCart->add_upsale( ((int) $upsale_id) );
}
if( !empty( $coupon_id ) ) {
$really_added_coupon = $rpCart->add_coupon( ((int) $coupon_id) );
if( $really_added_coupon == FALSE ) {
$coupon_id = '';
}
}
$calculations = $rpCart->calculate();
$combo = $calculations['combo_discount'];
$coupon = $calculations['coupon_amount'];
$total_price = $calculations['total'];
$sub_total = $calculations['sub_total'];
$coupon_info = $rpCart->get_coupon_info();
if( !empty($coupon_info) ) {
$coupon_type = $coupon_info->coupons_type;
}
$coupon_id = '';
if( !empty( $coupon_info->coupons_id ?? 0 ) ) {
$coupon_id = $coupon_info->coupons_id;
}
$prepared_post_data = $rpCart->prepare_post_data( $rid, $upid );
list( $r_id, $array_name, $array_price, $a_id, $up_id ) = $prepared_post_data;
} else {
}
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['finalize_booking_arr'] = array();
$_SESSION['finalize_booking_arr']['m_name'] = $m_name;
$_SESSION['finalize_booking_arr']['b_id'] = $b_id;
$_SESSION['finalize_booking_arr']['color_name'] = $color_name;
$_SESSION['finalize_booking_arr']['total_price'] = $total_price;
$_SESSION['finalize_booking_arr']['sub_total'] = $sub_total;
$_SESSION['finalize_booking_arr']['pdf_offer'] = $pdf_offer;
$_SESSION['finalize_booking_arr']['m_id_fk'] = $m_id_fk;
$_SESSION['finalize_booking_arr']['r_id'] = $r_id;
$_SESSION['finalize_booking_arr']['a_id'] = $a_id;
$_SESSION['finalize_booking_arr']['upid'] = $up_id;
$_SESSION['finalize_booking_arr']['coupon_id'] = $coupon_id;
if(isset($_GET['c_id']) && isset($_GET['uid'])) {
$_SESSION['finalize_booking_arr']['get_c_id'] = $_GET['c_id'];
$_SESSION['finalize_booking_arr']['get_uid'] = $_GET['uid'];
}
if( isset( $_GET['o_id_fk'] ) ) {
$_SESSION['finalize_booking_arr']['get_o_id_fk'] = $_GET['o_id_fk'];
}
if( isset( $_GET['reschedule'] ) ) {
$_SESSION['finalize_booking_arr']['reschedule'] = $_GET['reschedule'];
}
if( isset( $_GET['payment_cancel'] ) ) {
$_SESSION['finalize_booking_arr']['payment_cancel'] = $_GET['payment_cancel'];
}
$default_schedule_location = $location[0];
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
foreach( $location as $theLocObj ) {
if( (int) $theLocObj->location_id == (int) $rp_pre_selected_location ) {
$default_schedule_location = $theLocObj;
}
}
}
if( isset( $rp_order_location_id ) && !empty( $rp_order_location_id ) ) {
foreach( $location as $theLocObj ) {
if( (int) $theLocObj->location_id == (int) $rp_order_location_id ) {
$default_schedule_location = $theLocObj;
}
}
}
$ship_device_location = rp_get_location_data_of_ship_device();
RepairPluginPro\RP_Session_Handler::close();
if( isset( $o_id_fk ) && !empty( $o_id_fk ) ) {
$GLOBALS['rp_o_id_fk'] = $o_id_fk;
}
if( isset( $o_id_fk ) && !empty( $o_id_fk ) && isset( $_GET['payment_cancel'] ) ) {
$sql = "SELECT * FROM $rs_orders WHERE o_id = '".rp_escape_sql($o_id_fk)."' AND `payment_status` = 'Pending'
AND `payment_method` IN ('paypal', 'stripe', 'mollie', 'ideal_in3') LIMIT 1;";
$row_of_order = $rpQuery->get_row( $sql );
if( !empty( $row_of_order ) ) {
RepairPluginPro\RP_Session_Handler::start();
$priority_cost_uqid = '';
if( !empty( $row_of_order->priority_cost_info ?? '' ) ) {
$priority_cost_info = json_decode( $row_of_order->priority_cost_info, true );
if( !empty( $priority_cost_info ) ) {
$priority_cost_uqid = $priority_cost_info['uqid'] ?? '';
}
}
$_SESSION['payment_cancel_prefilled_data'] = array(
'notes' => $row_of_order->notes,
'location_id_fk' => $row_of_order->location_id_fk,
'based_on_location' => ((int) ($row_of_order->based_on_location ?? 0)),
'delivery_method' => $row_of_order->delivery_method,
'delivery_time' => str_replace('—', '--', $row_of_order->delivery_time),
'delivery_date' => $row_of_order->delivery_date,
'payment_method' => $row_of_order->payment_method,
'priority_cost_uqid' => $priority_cost_uqid
);
$parentOrderIdIfFound = rp_get_parent_order_id( $o_id_fk );
RepairPluginPro\RP_Session_Handler::close();
// delete the order
$sql = "DELETE FROM $rs_orders WHERE o_id = '".rp_escape_sql($o_id_fk)."'";
$rpQuery->query($sql);
RepairPluginPro\RP_Session_Handler::start();
if( !empty( $parentOrderIdIfFound ) ) {
$_SESSION['finalize_booking_arr']['get_o_id_fk'] = $parentOrderIdIfFound;
$GLOBALS['rp_o_id_fk'] = $parentOrderIdIfFound;
$o_id_fk = $parentOrderIdIfFound;
} else {
unset($_SESSION['finalize_booking_arr']['get_o_id_fk']);
}
RepairPluginPro\RP_Session_Handler::close();
}
if( isset( $_SESSION['payment_cancel_prefilled_data'] ) && !empty( $_SESSION['payment_cancel_prefilled_data'] ) ) {
$_customer_notes = $_SESSION['payment_cancel_prefilled_data']['notes'] ?? '';
$rp_order_location_id = $_SESSION['payment_cancel_prefilled_data']['location_id_fk'] ?? '';
$based_on_loc = $_SESSION['payment_cancel_prefilled_data']['based_on_location'] ?? '';
if( !empty( $based_on_loc ) ) {
$rp_pre_selected_location = $rp_order_location_id;
}
$GLOBALS['payment_cancel_delivery_method'] = rp_prettify_order_delivery_method( $_SESSION['payment_cancel_prefilled_data']['delivery_method'] ?? '' );
$delivery_date = $_SESSION['payment_cancel_prefilled_data']['delivery_date'] ?? '';
if( strpos( $delivery_date, '-' ) === 2 ) {
// convert d-m-Y to Y-m-d
$delivery_date_arr = explode('-', $delivery_date);
$delivery_date = $delivery_date_arr[2] . '-' . $delivery_date_arr[1] . '-' . $delivery_date_arr[0];
}
$GLOBALS['payment_cancel_delivery_date'] = $delivery_date;
$delivery_time = $_SESSION['payment_cancel_prefilled_data']['delivery_time'] ?? '';
$delivery_time = str_replace('--', '—', $delivery_time);
$GLOBALS['payment_cancel_delivery_time'] = $delivery_time;
$GLOBALS['payment_cancel_priority_cost_uqid'] = $_SESSION['payment_cancel_prefilled_data']['priority_cost_uqid'] ?? '';
}
}
ob_start();
include WP_REPAIR_PLUGIN_PATH.'html/front_end/finalize_repairs_html.php';
$content = ob_get_contents();
ob_end_clean();
$gtm_data = array();
if( isset($_POST['from_step_4_to_5']) ) {
$gtm_data = rp_get_select_repairs_summary_for_gtm();
}
return json_encode(array(
'gtm_data' => $gtm_data,
'localization' => $localization,
'planning_discount' => $planning_discount,
'rp_total_price' => $total_price,
'template' => $content,
'status' => true,
'm_name' => $m_name,
'b_name' => $b_name,
'o_id_is_set' => ( isset( $o_id_fk ) && !empty( $o_id_fk )) == TRUE ? '1' : '0',
'o_id_override' => $o_id_fk,
));
}
function rp_fe_finalize_repairs(){
echo _rp_fe_finalize_repairs();
exit();
}
rp_ajax_for_public('rp_fe_finalize_repairs','rp_fe_finalize_repairs');
function rp_get_delivery_method_translation_key( $delivery_method_name = '' ) {
$translation_key = '';
// remove one or more space with single space
$delivery_method_name = preg_replace('/\s+/', ' ', $delivery_method_name);
// trim
$delivery_method_name = trim( $delivery_method_name );
// strtolower
$delivery_method_name = strtolower( $delivery_method_name );
// replace space or - with _
$delivery_method_name = preg_replace('/\s+/', '_', $delivery_method_name);
$delivery_method_name = preg_replace('/-+/', '_', $delivery_method_name);
if( $delivery_method_name == 'come_our_store' || $delivery_method_name == 'come_by_our_store' ) {
$translation_key = 'come_by_our_store';
}
if( $delivery_method_name == 'ship_device' || $delivery_method_name == 'ship_your_device' ) {
$translation_key = 'ship_device';
}
if( $delivery_method_name == 'pickup_service' ) {
$translation_key = 'let_us_pickup_your_device';
}
if( $delivery_method_name == 'repair_on_location' || $delivery_method_name == 'repair_on_your_location' ) {
$translation_key = 'repair_on_your_location';
}
return $translation_key;
}
// --------------------------------------------------------- get finalize repairs for front-end
function rp_fe_finalize_booking_reschedule() {
global $wp_repair_selected_language;
global $rpQuery;
global $rp_pre_selected_location;
$company_location = $rpQuery->prefix . "rs_company_location";
$location = $rpQuery->get_results("SELECT * FROM $company_location");
$type_table = $rpQuery->prefix . "rs_notification_types";
$type = $rpQuery->get_results("SELECT * FROM $type_table");
$model_table = $rpQuery->prefix . "rs_model";
$category_table = $rpQuery->prefix . "rs_category";
$brand_table = $rpQuery->prefix . "rs_brand";
$repair_table = $rpQuery->prefix . "rs_repair";
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$rs_customer = $rpQuery->prefix . "rs_customer";
$rs_customer_business = $rpQuery->prefix . "rs_customer_business";
$rs_orders = $rpQuery->prefix . "rs_orders";
$rs_order_repairs = $rpQuery->prefix . "rs_order_repairs";
$rs_order_repair_attr = $rpQuery->prefix . "rs_order_repair_attr";
$rs_order_upsales = $rpQuery->prefix . "rs_order_upsales";
$rs_upsales = $rpQuery->prefix . "rs_upsales";
$rs_company_schedules = $rpQuery->prefix . "rs_company_schedules";
$m_id_fk = $_POST['m_id_fk'] ?? 0;
$model_info = $rpQuery->get_row("SELECT * FROM $model_table WHERE m_id = ':m_id_fk' LIMIT 1;", array( 'm_id_fk' => $m_id_fk ));
if( empty( $model_info ) ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid input provided.'
));
exit;
}
if (isset($_POST['confirm_booking'])) {
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'ship device') {
if( !rp_is_enabled_ship_device_location() ) {
$_POST['location_id'] = rp_get_default_location_id_of_delivery_method('ship_device');
}
$_POST['date'] = date('d-m-Y');
$_POST['time'] = '';
}
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'pickup service') {
$_POST['location_id'] = rp_get_default_location_id_of_delivery_method('pickup_service');
}
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'repair on location') {
$_POST['location_id'] = rp_get_default_location_id_of_delivery_method('repair_on_location');
}
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$_POST['location_id'] = $rp_pre_selected_location;
}
$theSelectedDeliveryMethod = '';
if( isset($_POST['d_method']) && !empty( $_POST['d_method'] ?? '' ) ) {
$theSelectedDeliveryMethod = strtolower( trim( $_POST['d_method'] ?? '' ) );
}
$user_name = $_POST['user_name'];
$business_name = $_POST['business_name'];
$user_email = $_POST['user_email'];
$user_phone = $_POST['user_phone'];
$color = $_POST['color_name'];
$notes = $_POST['notes'] ?? '';
$time = $_POST['time'] ?? '';
$date = $_POST['date'] ?? '';
$d_method = $_POST['d_method'] ?? '';
$payment_method = trim($_POST['payment_method'] ?? '');
$location_id = $_POST['location_id'] ?? '';
$pdf_offer = $_POST['pdf_offer'] ?? '';
$_POST['get_o_id_fk'] = $_POST['get_o_id_fk'] ?? 0;
$c_order_info = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE o_id = ':get_o_id_fk' LIMIT 1;", array( 'get_o_id_fk' => $_POST['get_o_id_fk'] ));
if( !empty($c_order_info) ) {
$customer_id_fk = $c_order_info->customer_id_fk;
} else {
$customer_id_fk = 0;
}
if( $theSelectedDeliveryMethod == 'pickup service' || $theSelectedDeliveryMethod == 'repair on location' ) {
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$nearest_location_id = $rp_pre_selected_location;
} else {
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'repair on location') {
rp_add_filter_repair_on_your_location_locations();
}
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'pickup service') {
rp_add_filter_pickup_service_locations();
}
$nearest_location_id = rp_get_nearest_location_for_customer( $customer_id_fk );
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'repair on location') {
rp_remove_filter_repair_on_your_location_locations();
}
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'pickup service') {
rp_remove_filter_pickup_service_locations();
}
}
if( !empty( $nearest_location_id ) ) {
$_POST['location_id'] = $nearest_location_id;
$location_id = $nearest_location_id;
}
}
$c_business_info = $rpQuery->get_row("SELECT * FROM `$rs_customer_business` WHERE customer_id_fk = ':customer_id_fk' LIMIT 1;", array( 'customer_id_fk' => $customer_id_fk ));
if( !empty($c_business_info) ) {
$business_name = $c_business_info->cb_name;
} else {
$business_name = '';
}
$m_id_fk = $_POST['m_id_fk'] ?? 0;
$sub_total = $_POST['sub_total'] ?? '';
$total_price = $_POST['total_price'] ?? '';
$coupon_id_fk = $_POST['coupons_id'] ?? 0;
$combo = $_POST['combo'] ?? '';
$r_id = $_POST['r_id'] ?? array();
$a_id = $_POST['a_id'] ?? array();
$up_id = $_POST['up_id'] ?? array();
$dm_cost = 0;
$coupon_info_json = '';
if( isset( $_POST['get_o_id_fk'] ) && !empty( $_POST['get_o_id_fk'] ) ) {
list( $rpCart, $calculations ) = rp_get_latest_order_calculations( $_POST['get_o_id_fk'] );
$combo = $calculations['combo_discount'];
$coupon = $calculations['coupon_amount'];
if( !empty( $rpCart->get_coupon_info() ) ) {
$coupon_info_json = json_encode( $rpCart->get_coupon_info() );
}
$total_price = $calculations['total'];
$sub_total = $calculations['sub_total'];
$dm_cost = $rpCart->delivery_method_cost();
$r_id = array();
$a_id = array();
$up_id = array();
foreach( $rpCart->repairs as $cartRow ) {
$r_id[] = $cartRow->r_id;
}
foreach( $rpCart->repair_attrs as $cartRow ) {
$r_id[] = $cartRow->r_id_fk;
$a_id[] = $cartRow->a_id;
}
foreach( $rpCart->upsales as $cartRow ) {
$up_id[] = $cartRow->upsales_id;
}
$prepared_post_data = $rpCart->prepare_post_data( $r_id, $up_id );
list( $r_id, $array_name, $array_price, $a_id, $up_id ) = $prepared_post_data;
} else {
$rpCart = new RepairPluginPro\RP_Cart( $m_id_fk );
$r_id = $_POST['r_id'] ?? array();
foreach ($r_id as $repair_id) {
$rpCart->add_repair( ((int) $repair_id) );
}
$a_id = $_POST['a_id'] ?? array();
foreach ($a_id as $attr_id) {
$rpCart->add_repair_attr( ((int) $attr_id) );
}
$up_id = $_POST['up_id'] ?? array();
foreach ($up_id as $upsale_id) {
$rpCart->add_upsale( ((int) $upsale_id) );
}
$rpCart->add_delivery_method( $d_method );
if( !empty( $payment_method ) ) {
$rpCart->add_payment_method( $payment_method );
}
$really_added_coupon = $rpCart->add_coupon( ((int) $coupon_id_fk) );
if( $really_added_coupon == FALSE ) {
$coupon_id_fk = 0;
}
$calculations = $rpCart->calculate();
$combo = $calculations['combo_discount'];
$coupon = $calculations['coupon_amount'];
if( !empty( $rpCart->get_coupon_info() ) ) {
$coupon_info_json = json_encode( $rpCart->get_coupon_info() );
}
$total_price = $calculations['total'];
$sub_total = $calculations['sub_total'];
$dm_cost = $rpCart->delivery_method_cost();
$prepared_post_data = $rpCart->prepare_post_data( $r_id, $up_id );
list( $r_id, $array_name, $array_price, $a_id, $up_id ) = $prepared_post_data;
}
$status = rp_get_auto_approve_booking_value( $d_method );
if($status == '1'){
$status = '3';
}else{
$status = '1';
}
$order_id_fk = $_POST['get_o_id_fk'] ?? 0;
$created_time = date('Y-m-d H:i:s');
// update location_id_fk, date, time column in orders table
$rpQuery->query("UPDATE $rs_orders SET `location_id_fk` = '".rp_escape_sql($location_id)."', `delivery_date` = '".rp_escape_sql($date)."', `delivery_time` = '".rp_escape_sql($time)."', `reminder` = '0', `aftersales` = '0' WHERE o_id = '".rp_escape_sql($order_id_fk)."'");
if($r_id){
$r_id_str = join(',', $r_id);
} else {
$r_id_str = '';
}
if($a_id){
$a_id_str = join(',', $a_id);
} else {
$a_id_str = '';
}
$up_id = $_POST['up_id'] ?? '';
if($up_id){
$up_id_str = join(',', $up_id);
} else {
$up_id_str = '';
}
$rs_timeslot = $rpQuery->prefix . 'rs_timeslot';
$rpQuery->query("DELETE FROM `$rs_timeslot` WHERE o_id = '".rp_escape_sql($order_id_fk)."' LIMIT 1;");
$rs_timeslot_dm = $rpQuery->prefix . 'rs_timeslot_dm';
$rpQuery->query("DELETE FROM `$rs_timeslot_dm` WHERE o_id = '".rp_escape_sql($order_id_fk)."' LIMIT 1;");
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'come by our store') {
rp_book_available_slot(array(
'loc_id' => $location_id,
'a_date' => $date,
'a_time' => $time,
'o_id' => $order_id_fk
));
}
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'pickup service') {
rp_book_available_slot_new_dm(array(
'method_id' => 'ps',
'a_date' => $date,
'a_time' => $time,
'o_id' => $order_id_fk
));
}
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'repair on location') {
rp_book_available_slot_new_dm(array(
'method_id' => 'rol',
'a_date' => $date,
'a_time' => $time,
'o_id' => $order_id_fk
));
}
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['o_id'] = $order_id_fk;
unset($_SESSION['finalize_booking_arr']);
RepairPluginPro\RP_Session_Handler::close();
}
if( !empty( $order_id_fk ?? 0 ) ) {
rp_trigger_outgoing_webhook( 'scheduled_appointment_updated', $order_id_fk );
}
rp_fe_thank_you_page();
exit();
}
function rp_get_auto_approve_booking_value( $delivery_method = '' ) {
if( empty( $delivery_method ) ) {
return 0;
}
// Come By Our Store
// Ship Device
// Pickup Service
// Repair On Your Location
$delivery_method = strtolower( trim( $delivery_method ) );
$delivery_method = str_replace(array(' by ', ' your '), ' ', $delivery_method);
$delivery_method = str_replace(array('_by_', '_your_'), ' ', $delivery_method);
$delivery_method = str_replace(' ', '_', $delivery_method);
$delivery_method = str_replace('__', '_', $delivery_method);
$delivery_method = trim( $delivery_method );
$key = 'rp_auto_approve_' . $delivery_method;
$value = rp_get_option( $key, '0' );
if( $value == '1' ) {
return 1;
}
return 0;
}
function rp_auto_approve_based_on_delivery_methods_first_time() {
if( rp_get_option('rp_auto_approve_based_on_dm_first_time', '0') == '1' ) {
return;
}
rp_update_option('rp_auto_approve_based_on_dm_first_time', '1');
$old_value = rp_get_auto_approve_booking_old_value();
$delivery_methods = array('come_our_store', 'ship_device', 'repair_on_location', 'pickup_service');
foreach( $delivery_methods as $theMethod ) {
$key = 'rp_auto_approve_' . $theMethod;
rp_update_option( $key, $old_value );
}
}
rp_add_action('init', 'rp_auto_approve_based_on_delivery_methods_first_time', 9999);
function rp_get_auto_approve_booking_old_value() {
global $rpQuery;
$table = $rpQuery->prefix . 'rs_notification_types';
$sql = "SELECT * FROM `$table` WHERE `noti_type_id` = 3";
$row = $rpQuery->get_row( $sql );
if( !empty( $row ) ) {
return ($row->is_active ?? 0);
}
return 0;
}
function rp_is_enabled_come_by_our_store_address_fields( $payment_method = '' ) {
if( rp_get_option('rp_come_our_store_customer_address_fields', '0') == '1' ) {
return '1';
}
if( $payment_method == 'ideal_in3' && rp_is_enabled_ideal_in3_for_come_by_our_store() !== FALSE ) {
return '1';
}
return '0';
}
function rp_fe_finalize_booking(){
if( isset( $_POST['get_o_id_fk'] ) && !empty( $_POST['get_o_id_fk'] ) ) {
if( empty( rp_get_single_order_row_by_o_id( $_POST['get_o_id_fk'] ) ) ) {
unset( $_POST['get_o_id_fk'] );
}
}
rp_verify_csrf_token_for_ajax('frontend');
if( rp_verify_google_recaptcha() === FALSE ) {
echo json_encode(
array(
'status'=> false,
'rp_validation_error' => 'Form submission blocked by Google ReCaptcha. Please refresh the page and try again after few seconds.'
)
);
exit();
}
_rp_set_default_tiemzone();
global $wp_repair_selected_language;
global $rpQuery;
global $rp_pre_selected_location;
$rp_pre_selected_location = 0;
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
do_action('rp_before_getting_fe_pre_selected_location');
$rp_pre_selected_location = intval( $_POST['rp_pre_selected_location'] ?? 0 );
if( empty( $rp_pre_selected_location ) ) {
echo json_encode(Array('status' => false, 'rp_validation_error' => 'Invalid location id'));
exit;
}
}
if( ($_POST['rp_reschedule'] ?? '') == '1' && !empty(($_POST['get_o_id_fk'] ?? '')) ) {
rp_fe_finalize_booking_reschedule();
exit;
}
rp_verify_customer_address_details_before_finalize( $rp_pre_selected_location );
$company_location = $rpQuery->prefix . "rs_company_location";
$location = $rpQuery->get_results("SELECT * FROM $company_location");
$type_table = $rpQuery->prefix . "rs_notification_types";
$type = $rpQuery->get_results("SELECT * FROM $type_table");
$model_table = $rpQuery->prefix . "rs_model";
$category_table = $rpQuery->prefix . "rs_category";
$brand_table = $rpQuery->prefix . "rs_brand";
$repair_table = $rpQuery->prefix . "rs_repair";
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
$rs_customer = $rpQuery->prefix . "rs_customer";
$rs_customer_business = $rpQuery->prefix . "rs_customer_business";
$rs_orders = $rpQuery->prefix . "rs_orders";
$rs_order_repairs = $rpQuery->prefix . "rs_order_repairs";
$rs_order_repair_attr = $rpQuery->prefix . "rs_order_repair_attr";
$rs_order_upsales = $rpQuery->prefix . "rs_order_upsales";
$rs_upsales = $rpQuery->prefix . "rs_upsales";
$rs_company_schedules = $rpQuery->prefix . "rs_company_schedules";
$rs_customer_meta = $rpQuery->prefix . "rs_customer_meta";
$m_id_fk = $_POST['m_id_fk'] ?? 0;
$model_info = $rpQuery->get_row("SELECT * FROM $model_table WHERE m_id = ':m_id_fk' LIMIT 1;", array( 'm_id_fk' => $m_id_fk ));
if( empty( $model_info ) ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid input provided.'
));
exit;
}
$selected_delivery_method = '';
$allowed_delivery_methods = array(
'come by our store',
'ship device',
'pickup service',
'repair on location'
);
if( !empty( $_POST['d_method'] ?? '' ) ) {
$selected_delivery_method = strtolower( trim( $_POST['d_method'] ?? '' ) );
}
if( empty( $selected_delivery_method ) || !in_array( $selected_delivery_method, $allowed_delivery_methods ) ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid delivery method.'
));
exit;
}
if( !empty( rp_get_all_priority_repairs() ) && $selected_delivery_method == 'come by our store' ) {
$priority_box = rp_get_priority_box_by_uqid($_REQUEST['priority_box'] ?? '');
if( empty( $priority_box ) ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Please select priority.'
));
exit;
}
$priority_box['text'] = rp_sanitize_output(rp_get_static_translations_of_priority_options_selected('priority_option_text', $priority_box['uqid'], 'selected'));
} else {
$priority_box = '';
}
if (isset($_POST['confirm_booking'])) {
$_delivery_method_short = '';
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'ship device') {
if( !rp_is_enabled_ship_device_location() ) {
$_POST['location_id'] = rp_get_default_location_id_of_delivery_method('ship_device');
}
$_POST['date'] = date('d-m-Y');
$_POST['time'] = '';
$_delivery_method_short = 'sd';
}
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'pickup service') {
$_POST['location_id'] = rp_get_default_location_id_of_delivery_method('pickup_service');
$_delivery_method_short = 'ps';
}
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'repair on location') {
$_POST['location_id'] = rp_get_default_location_id_of_delivery_method('repair_on_location');
$_delivery_method_short = 'rol';
}
if( rp_is_enabled_come_by_our_store_address_fields( trim($_POST['payment_method'] ?? '') ) == '1' && isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'come by our store' ) {
$_delivery_method_short = 'cos';
}
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$_POST['location_id'] = $rp_pre_selected_location;
}
$user_name = trim( ($_POST['first_name'] ?? '') . ' ' . ($_POST['last_name'] ?? '') );
$first_name = $_POST['first_name'] ?? '';
$last_name = $_POST['last_name'] ?? '';
$business_name = $_POST['business_name'] ?? '';
$customer_type = $_POST['customer_type'] ?? '';
$user_email = $_POST['user_email'] ?? '';
$user_phone = $_POST['user_phone'] ?? '';
$color = $_POST['color_name'] ?? '';
$notes = $_POST['notes'] ?? '';
$time = $_POST['time'] ?? '';
$date = $_POST['date'] ?? '';
$d_method = $_POST['d_method'] ?? '';
$payment_method = trim($_POST['payment_method'] ?? '');
$location_id = $_POST['location_id'] ?? '';
$pdf_offer = $_POST['pdf_offer'] ?? '';
if( !empty( $_delivery_method_short ) ) {
$house_no = $_POST[$_delivery_method_short.'_house_no'] ?? '';
$street_address = $_POST[$_delivery_method_short.'_street_address'] ?? '';
$city = $_POST[$_delivery_method_short.'_user_city'] ?? '';
$zipcode = $_POST[$_delivery_method_short.'_user_zipcode'] ?? '';
$country = $_POST[$_delivery_method_short.'_user_country'] ?? '';
$rpQuery->query("INSERT INTO $rs_customer(customer_first_name,customer_last_name,customer_name,customer_phone,customer_email,customer_house_no,customer_street_address,customer_city,customer_zipcode,customer_country) VALUES('".rp_escape_sql($first_name)."','".rp_escape_sql($last_name)."','".rp_escape_sql($user_name)."','".rp_escape_sql($user_phone)."','".rp_escape_sql($user_email)."','".rp_escape_sql($house_no)."','".rp_escape_sql($street_address)."','".rp_escape_sql($city)."','".rp_escape_sql($zipcode)."', '".rp_escape_sql($country)."')");
$customer_id_fk = $rpQuery->insert_id;
if( $_delivery_method_short == 'rol' || $_delivery_method_short == 'ps' ) {
if( isset( $rp_pre_selected_location ) && !empty( $rp_pre_selected_location ) ) {
$nearest_location_id = $rp_pre_selected_location;
} else {
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'repair on location') {
rp_add_filter_repair_on_your_location_locations();
}
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'pickup service') {
rp_add_filter_pickup_service_locations();
}
$nearest_location_id = rp_get_nearest_location_for_customer( $customer_id_fk );
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'repair on location') {
rp_remove_filter_repair_on_your_location_locations();
}
if(isset($_POST['d_method']) && strtolower($_POST['d_method']) === 'pickup service') {
rp_remove_filter_pickup_service_locations();
}
}
if( !empty( $nearest_location_id ) ) {
$_POST['location_id'] = $nearest_location_id;
$location_id = $nearest_location_id;
}
}
} else {
$rpQuery->query("INSERT INTO $rs_customer(customer_first_name,customer_last_name,customer_name,customer_phone,customer_email) VALUES('".rp_escape_sql($first_name)."','".rp_escape_sql($last_name)."','".rp_escape_sql($user_name)."','".rp_escape_sql($user_phone)."','".rp_escape_sql($user_email)."')");
$customer_id_fk = $rpQuery->insert_id;
}
if( !empty( $_POST['custom_fields'] ?? array() ) ) {
$custom_fields_db = rp_get_all_form_custom_fields();
foreach( $_POST['custom_fields'] as $custom_field_name => $custom_field_value ) {
if( empty( $custom_field_value ) ) {
continue;
}
$custom_field = null;
if( isset( $custom_fields_db[ $custom_field_name ] ) && !empty( $custom_fields_db[ $custom_field_name ] ) ) {
$custom_field = $custom_fields_db[ $custom_field_name ];
}
if( empty( $custom_field ) || $custom_field->status == '0' ) {
// Unexpected!!
continue;
}
if( $custom_field->field_type == 'radio' || $custom_field->field_type == 'checkbox' || $custom_field->field_type == 'dropdown' ) {
if( !is_string( $custom_field_value ) ) {
if( is_array( $custom_field_value ) ) {
// find option by uqid
$field_options = json_decode($custom_field->field_options, TRUE);
if( !empty( $field_options ) ) {
$filtered = array();
foreach( $custom_field_value as $custom_field_value_single ) {
$found = false;
foreach( $field_options as $field_option ) {
if( $field_option['uqid'] == $custom_field_value_single ) {
$custom_field_value_single = rp_get_static_translations_of_custom_form_fields_options_selected('option_text', $custom_field->id.'_'.$field_option['uqid'], 'selected');
$found = true;
}
}
if( $found == true ) {
$filtered[] = $custom_field_value_single;
}
}
if( !empty( $filtered ) ) {
$custom_field_value = json_encode( $filtered );
} else {
// Unexpected!!
$custom_field_value = '';
}
} else {
// Unexpected!!
$custom_field_value = '';
}
} else {
// Unexpected!!
$custom_field_value = '';
}
} else {
// find option by uqid
$field_options = json_decode($custom_field->field_options, TRUE);
if( !empty( $field_options ) ) {
$found = false;
foreach( $field_options as $field_option ) {
if( $field_option['uqid'] == $custom_field_value ) {
$custom_field_value = rp_get_static_translations_of_custom_form_fields_options_selected('option_text', $custom_field->id.'_'.$field_option['uqid'], 'selected');
$found = true;
}
}
if( $found == false ) {
// Unexpected!!
$custom_field_value = '';
}
} else {
// Unexpected!!
$custom_field_value = '';
}
}
} else {
if( !is_string( $custom_field_value ) ) {
// Unexpected!!
$custom_field_value = '';
}
}
$rpQuery->query("INSERT INTO $rs_customer_meta(meta_key,meta_value,customer_id) VALUES('".rp_escape_sql($custom_field_name)."','".rp_escape_sql($custom_field_value)."','".rp_escape_sql($customer_id_fk)."')");
}
}
if(!empty($business_name) && $customer_type == 'business' ){
$rpQuery->query("INSERT INTO $rs_customer_business(cb_name,customer_id_fk) VALUES('".rp_escape_sql($business_name)."','".rp_escape_sql($customer_id_fk)."')");
}
$m_id_fk = $_POST['m_id_fk'] ?? 0;
$sub_total = $_POST['sub_total'] ?? '';
$total_price = $_POST['total_price'] ?? '';
$coupon_id_fk = $_POST['coupons_id'] ?? 0;
$combo = $_POST['combo'] ?? '';
$r_id = $_POST['r_id'] ?? array();
$a_id = $_POST['a_id'] ?? array();
$up_id = $_POST['up_id'] ?? array();
$dm_cost = 0;
$parent_order_id = 0;
$coupon_info_json = '';
if( isset( $_POST['get_o_id_fk'] ) && !empty( $_POST['get_o_id_fk'] ) ) {
$parent_order_id = $_POST['get_o_id_fk'];
$_POST['selected_dm_id'] = $d_method;
if( !empty( $priority_box ) && !empty( $priority_box['uqid'] ?? '' ) ) {
$_REQUEST['rp_overwrite_priority_box'] = $priority_box['uqid'] ?? '';
}
if( !empty( $payment_method ) ) {
$_REQUEST['rp_overwrite_payment_method'] = $payment_method;
}
list( $rpCart, $calculations ) = rp_get_latest_order_calculations( $_POST['get_o_id_fk'] );
$combo = $calculations['combo_discount'];
$coupon = $calculations['coupon_amount'];
if( !empty( $rpCart->get_coupon_info() ) ) {
$coupon_info_json = json_encode( $rpCart->get_coupon_info() );
}
$total_price = $calculations['total'];
$sub_total = $calculations['sub_total'];
$dm_cost = $rpCart->delivery_method_cost();
$r_id = array();
$a_id = array();
$up_id = array();
foreach( $rpCart->repairs as $cartRow ) {
$r_id[] = $cartRow->r_id;
}
foreach( $rpCart->repair_attrs as $cartRow ) {
$r_id[] = $cartRow->r_id_fk;
$a_id[] = $cartRow->a_id;
}
foreach( $rpCart->upsales as $cartRow ) {
$up_id[] = $cartRow->upsales_id;
}
$prepared_post_data = $rpCart->prepare_post_data( $r_id, $up_id );
list( $r_id, $array_name, $array_price, $a_id, $up_id ) = $prepared_post_data;
} else {
$rpCart = new RepairPluginPro\RP_Cart( $m_id_fk );
$r_id = $_POST['r_id'] ?? array();
foreach ($r_id as $repair_id) {
$rpCart->add_repair( ((int) $repair_id) );
}
$a_id = $_POST['a_id'] ?? array();
foreach ($a_id as $attr_id) {
$rpCart->add_repair_attr( ((int) $attr_id) );
}
$up_id = $_POST['up_id'] ?? array();
foreach ($up_id as $upsale_id) {
$rpCart->add_upsale( ((int) $upsale_id) );
}
$rpCart->add_delivery_method( $d_method );
if( !empty( $priority_box ) ) {
$rpCart->add_priority_box( $priority_box['uqid'] );
}
if( !empty( $payment_method ) ) {
$rpCart->add_payment_method( $payment_method );
}
$really_added_coupon = $rpCart->add_coupon( ((int) $coupon_id_fk) );
if( $really_added_coupon == FALSE ) {
$coupon_id_fk = 0;
}
$calculations = $rpCart->calculate();
$combo = $calculations['combo_discount'];
$coupon = $calculations['coupon_amount'];
if( !empty( $rpCart->get_coupon_info() ) ) {
$coupon_info_json = json_encode( $rpCart->get_coupon_info() );
}
$total_price = $calculations['total'];
$sub_total = $calculations['sub_total'];
$dm_cost = $rpCart->delivery_method_cost();
$prepared_post_data = $rpCart->prepare_post_data( $r_id, $up_id );
list( $r_id, $array_name, $array_price, $a_id, $up_id ) = $prepared_post_data;
}
$status = rp_get_auto_approve_booking_value( $d_method );
if($status == '1'){
$status = '3';
}else{
$status = '1';
}
$created_time = date('Y-m-d H:i:s');
$priority_cost_info = '';
if( !empty( $priority_box ) ) {
$priority_cost_info = json_encode( $priority_box );
}
$rpQuery->query("INSERT INTO $rs_orders(customer_id_fk,notes,color,excluded_tax_price,combo_discount,coupon_id_fk,total_price,delivery_method,delivery_time,delivery_date,pdf_offer,m_id_fk,status_id_fk,location_id_fk,coupon_amount,created_time,dm_cost,locked_coupon_info,priority_cost_info) VALUES('".rp_escape_sql($customer_id_fk)."','".rp_escape_sql($notes)."','".rp_escape_sql($color)."','".rp_escape_sql($sub_total)."','".rp_escape_sql($combo)."','".rp_escape_sql($coupon_id_fk)."','".rp_escape_sql($total_price)."','".rp_escape_sql($d_method)."','".rp_escape_sql($time)."','".rp_escape_sql($date)."','".rp_escape_sql($pdf_offer)."','".rp_escape_sql($m_id_fk)."','".rp_escape_sql($status)."','".rp_escape_sql($location_id)."','".rp_escape_sql($coupon)."','".rp_escape_sql($created_time)."','".rp_escape_sql($dm_cost)."','".rp_escape_sql($coupon_info_json)."', '".rp_escape_sql($priority_cost_info)."')");
$order_id_fk = $rpQuery->insert_id;
rp_set_payment_method_cost_info( $order_id_fk, $payment_method );
rp_set_based_on_location( $order_id_fk, $parent_order_id );
rp_set_new_appointment_number($order_id_fk, $created_time);
rp_set_coupon_settings($order_id_fk, $parent_order_id);
rp_set_parent_order_id_on_order( $order_id_fk, $parent_order_id );
if($r_id){
$r_id_str = join(',', $r_id);
} else {
$r_id_str = '';
}
if($a_id){
$a_id_str = join(',', $a_id);
} else {
$a_id_str = '';
}
$up_id = $_POST['up_id'] ?? '';
if($up_id){
$up_id_str = join(',', $up_id);
} else {
$up_id_str = '';
}
$customBaseURL = rp_get_search_box_redirect_link();
if( !empty( $customBaseURL ) ) {
$customBaseURL = rtrim($customBaseURL, '/');
$_REQUEST['created_through_url'] = $customBaseURL;
$_POST['created_through_url'] = $customBaseURL;
}
$created_through_url = $_REQUEST['created_through_url'] ?? '';
$thanks_page = 'thanks';
if( ($_REQUEST['is_model_shortcode'] ?? '0') === '1' ) {
$action = 'shortcode_finalize_order';
$thanks_page = 'shortcode_thanks';
} else {
$action = 'finalize';
}
$reschedule_link = $created_through_url . '/?reschedule=1&o_id_fk=' . $order_id_fk . '&c_id=' . $customer_id_fk . '&uid=' . substr(md5($customer_id_fk), 0, 8) . '&selected='.$action.'/b_id='. $model_info->brand_id_fk .'/model_name=' . rp_encode_model_name_for_uri( $model_info->m_name ) . '/color=' . rp_encode_model_name_for_uri( $color ) . '/u=' . $up_id_str . '/a=' . $a_id_str . '/r=' . $r_id_str . '/finalprice=' . $total_price . '/coupon=' . ($coupon_id_fk ?? 0) . '/subtotal=' . $sub_total;
// update reschedule link in rs_orders table
$rpQuery->query("UPDATE `$rs_orders` SET `reschedule_link` = '".rp_escape_sql($reschedule_link)."' WHERE o_id = '".rp_escape_sql($order_id_fk)."' LIMIT 1;");
rp_save_order_related_language($order_id_fk, $wp_repair_selected_language);
rp_save_cancel_link_by_order_id( $order_id_fk, ($_POST['created_through_url'] ?? '') );
if($r_id){
foreach($r_id as $rid){
rp_insert_into_rs_order_repairs($order_id_fk, $rid);
}
}
if($a_id){
foreach($a_id as $aid){
rp_insert_into_rs_order_repair_attr($order_id_fk, $aid);
}
}
$up_id = $_POST['up_id'] ?? '';
if($up_id){
foreach($up_id as $upid){
rp_insert_into_rs_order_upsales($order_id_fk, $upid);
}
}
if( rp_which_action_when_por() == 'set_price' ) {
if( (!empty(rp_get_por_repairs_by_order_id( $order_id_fk )) || !empty(rp_get_por_repair_attr_by_order_id( $order_id_fk ))) ) {
// update status_id_fk to 5
$rpQuery->query("UPDATE $rs_orders SET status_id_fk = '5' WHERE o_id = '".rp_escape_sql($order_id_fk)."' LIMIT 1;");
}
}
$payment_method = trim($_POST['payment_method'] ?? '');
$payment_methods_by_dm = rp_get_supported_payment_methods_by_delivery_method( $selected_delivery_method, ( $total_price ?? 0 ) );
if( rp_need_to_show_payment_methods_on_price_on_request() == FALSE ) {
if( $rpCart->hasAnyRepairsWithZeroPrice() ) {
$payment_methods_by_dm = array();
}
}
if( empty( $payment_methods_by_dm ) || !($total_price > 0) ) {
$payment_method = '';
}
if( $total_price > 0 && !empty( $payment_methods_by_dm ) ) {
if( in_array( $payment_method, $payment_methods_by_dm ) == FALSE ) {
// Remove appointment...
$rpQuery->query("DELETE FROM `$rs_orders` WHERE o_id = '".rp_escape_sql($order_id_fk)."'");
$response = array(
'template' => 'Payment Failed',
'status' => true,
'payment_error' => 'Select payment method is not supported by selected delivery method'
);
echo json_encode($response);
exit();
}
}
if( !empty( $payment_method ) && rp_check_if_payment_method_is_active( $payment_method ) ) {
rp_set_order_payment_method( $order_id_fk, $payment_method, 'Pending' );
$redirect_payment_methods = array('paypal', 'stripe', 'mollie', 'ideal_in3');
if( in_array( $payment_method, $redirect_payment_methods ) == TRUE ) {
$payment_related_info = rp_get_payment_related_info( $order_id_fk, $created_through_url, $thanks_page );
$redirect_url = '';
$payment_cancel_url = '';
$payment_error = '';
$template = '';
try {
$redirect_url = rp_get_payment_redirect_url( $payment_related_info );
$payment_cancel_url = rp_get_payment_cancel_url( $payment_related_info );
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['o_id'] = $order_id_fk;
RepairPluginPro\RP_Session_Handler::close();
} catch( Exception|Error $e ) {
$template = 'Payment Failed';
$payment_error = $e->getMessage() . ' - ' . $e->getFile() . ' - ' . $e->getLine();
$redirect_url = '';
}
$response = array(
'template' => $template,
'status' => true,
// 'payment_related_info' => $payment_related_info
);
if( !empty( $redirect_url ) ) {
$response['payment_getway_url'] = $redirect_url;
}
if( !empty( $payment_cancel_url ) ) {
$response['payment_cancel_url'] = $payment_cancel_url;
}
if( !empty( $payment_error ) ) {
// Remove appointment...
$rpQuery->query("DELETE FROM `$rs_orders` WHERE o_id = '".rp_escape_sql($order_id_fk)."'");
$response['payment_error'] = $payment_error;
}
echo json_encode($response);
exit();
}
}
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['o_id'] = $order_id_fk;
unset($_SESSION['finalize_booking_arr']);
RepairPluginPro\RP_Session_Handler::close();
}
rp_fe_thank_you_page();
exit();
}
rp_ajax_for_public('rp_fe_finalize_booking','rp_fe_finalize_booking');
function rp_find_delivery_method_of_order( $order_id_fk = 0 ) {
if( empty( $order_id_fk ) ) {
return FALSE;
}
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$sql = "SELECT * FROM `$rs_orders` WHERE `o_id` = '{$order_id_fk}'";
$row = $rpQuery->get_row( $sql );
if( !empty( $row ) ) {
return strtolower(trim($row->delivery_method ?? ''));
}
return FALSE;
}
// --------------------------------------------------------- get thank you page for front-end
function rp_fe_thank_you_page(){
global $rpQuery;
global $wp_repair_lang;
$rs_orders = $rpQuery->prefix . "rs_orders";
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$rs_customer = $rpQuery->prefix . "rs_customer";
$rs_notifications_and_offers = $rpQuery->prefix . "rs_notifications_and_offers";
$company_information = $rpQuery->prefix ."rs_company_information";
$company_results = $rpQuery->get_results("SELECT * FROM $company_information");
$theme_color = $company_results[0]->company_theme_color;
RepairPluginPro\RP_Session_Handler::read();
$order_id = $_SESSION['o_id'] ?? '';
$gtm_data = array();
if(isset($order_id) && !empty($order_id)){
$order = $rpQuery->get_results("SELECT o.*, cl.*, cu.* FROM $rs_orders AS o LEFT JOIN $rs_company_location AS cl ON o.location_id_fk = cl.location_id LEFT JOIN $rs_customer as cu ON o.customer_id_fk = cu.customer_id WHERE o.o_id = '".rp_escape_sql($order_id)."'");
if( ($_POST['rp_reschedule'] ?? '') == '1' ) {
// Do nothing
} else {
rp_record_quote_converted($order_id);
rp_update_coupon_usage_for_order($order_id);
rp_start_funnel_tracking(6);
rp_set_session_id_and_converted_date( $order_id );
if(strtolower($order[0]->delivery_method ?? '') === 'come by our store') {
rp_book_available_slot(array(
'loc_id' => $order[0]->location_id_fk,
'a_date' => $order[0]->delivery_date,
'a_time' => $order[0]->delivery_time,
'o_id' => $order_id
));
}
if(strtolower($order[0]->delivery_method ?? '') === 'pickup service') {
rp_book_available_slot_new_dm(array(
'method_id' => 'ps',
'a_date' => $order[0]->delivery_date,
'a_time' => $order[0]->delivery_time,
'o_id' => $order_id
));
}
if(strtolower($order[0]->delivery_method ?? '') === 'repair on location') {
rp_book_available_slot_new_dm(array(
'method_id' => 'rol',
'a_date' => $order[0]->delivery_date,
'a_time' => $order[0]->delivery_time,
'o_id' => $order_id
));
}
if( !empty( $order_id ?? 0 ) ) {
$order_delivery_method = rp_find_delivery_method_of_order( $order_id );
if( !empty( $order_delivery_method ) && $order_delivery_method != 'ship device' ) {
rp_trigger_outgoing_webhook( 'scheduled_appointment_created', $order_id );
} else {
rp_trigger_outgoing_webhook( 'ship_device_appointment_created', $order_id );
}
}
$gtm_data = rp_get_order_summary_for_gtm( $order_id, 'booking_finalized' );
}
rp_send_appointment_status_update_email($order_id, TRUE);
}
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['c_name'] = '';
$_SESSION['b_name'] = '';
$_SESSION['m_name'] = '';
$_SESSION['o_id'] = '';
RepairPluginPro\RP_Session_Handler::close();
// Check for custom thank you page redirect
$custom_thank_you_page = rp_get_option('rp_thank_you_page_redirect', '');
if (!empty($custom_thank_you_page)) {
$redirect_url = get_permalink($custom_thank_you_page);
echo json_encode(array(
'redirect_url' => $redirect_url,
'status' => true,
'gtm_data' => $gtm_data
));
exit();
}
ob_start();
require_once WP_REPAIR_PLUGIN_PATH.'html/front_end/thank_you_html.php';
$content = ob_get_contents();
ob_end_clean();
echo json_encode(array(
'template' => $content,
'status' => true,
'gtm_data' => $gtm_data
));
exit();
}
rp_ajax_for_public('rp_fe_thank_you_page','rp_fe_thank_you_page');
// --------------------------------------------------------- get cancel page for front-end
function _rp_fe_cancel_page(){
global $rpQuery;
global $wp_repair_lang;
$rs_orders = $rpQuery->prefix . "rs_orders";
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$rs_customer = $rpQuery->prefix . "rs_customer";
$rs_notifications_and_offers = $rpQuery->prefix . "rs_notifications_and_offers";
$company_information = $rpQuery->prefix ."rs_company_information";
$company_results = $rpQuery->get_results("SELECT * FROM $company_information");
$theme_color = $company_results[0]->company_theme_color;
$order_id = $_POST['id'] ?? '';
$secret_key = $_POST['secret_key'] ?? '';
$really_cancel = $_POST['really_cancel'] ?? '0';
if(isset($order_id) && !empty($order_id)){
$order = $rpQuery->get_results("SELECT o.*, cl.*, cu.* FROM $rs_orders AS o LEFT JOIN $rs_company_location AS cl ON o.location_id_fk = cl.location_id LEFT JOIN $rs_customer as cu ON o.customer_id_fk = cu.customer_id WHERE o.o_id = '".rp_escape_sql($order_id)."'");
if(!empty($order)) {
include_once WP_REPAIR_PLUGIN_PATH.'html/order_emails.php';
if(md5($order[0]->o_id . $order[0]->customer_id_fk) === $secret_key) {
rp_set_order_related_language($order_id);
if( $really_cancel == '1' ) {
$status = $order[0]->status_id_fk;
$offers = $rpQuery->get_results("SELECT * FROM $rs_notifications_and_offers");
if($status != '4') {
$rpQuery->query("UPDATE $rs_orders SET `status_id_fk`='4' WHERE `o_id` = '".rp_escape_sql($order[0]->o_id)."'");
$order_delivery_method = rp_find_delivery_method_of_order( $order[0]->o_id );
if( !empty( $order_delivery_method ) && $order_delivery_method != 'ship device' && $order_delivery_method != 'pdf offer' ) {
rp_trigger_outgoing_webhook( 'scheduled_appointment_cancelled', $order[0]->o_id );
} else if( !empty( $order_delivery_method ) && $order_delivery_method == 'ship device' ) {
rp_trigger_outgoing_webhook( 'ship_device_appointment_cancelled', $order[0]->o_id );
} else if( !empty( $order_delivery_method ) && $order_delivery_method == 'pdf offer' ) {
rp_trigger_outgoing_webhook( 'pdf_offer_cancelled', $order[0]->o_id );
} else {
// Do nothing!
}
$status = '4';
$pending = $offers[0]->is_active;
$offer = $offers[1]->is_active;
$approved = $offers[2]->is_active;
$cancel = $offers[3]->is_active;
$user_name = $order[0]->customer_name;
$user_email = $order[0]->customer_email;
$configure_email = $rpQuery->prefix . "rs_configure_mail";
$settings_detail = $rpQuery->get_results("SELECT * FROM $configure_email");
$to = $user_email;
$rp_location_id = rp_get_location_id_of_order( $order_id );
$bcc_email = rp_get_bcc_email_of_location( $rp_location_id );
if(($status == '1') && ($pending == '1')){
$email_translation_key = get_translation_key_by_noti_type_id($offers[0]->noti_type_id_fk);
$subject = $wp_repair_lang[$email_translation_key.'_email_subject'];
$message_template = $wp_repair_lang[$email_translation_key.'_email_template'];
$message = wp_repair_prepare_order_email($order_id, $subject, $message_template);
$subject = wp_repair_prepare_order_email_subject($order_id, $subject);
wp_repair_send_mail($to, $subject, $message);
$duplicate_email = wp_repair_admin_duplicate_email('1', $rp_location_id);
if(!empty($duplicate_email)) {
rp_wp_mail_change_sender_info($user_email, $user_name);
$message = wp_repair_prepare_order_email_for_admin($order_id, $subject, $message_template);
wp_repair_send_mail($duplicate_email, $subject, $message, $bcc_email);
}
}else if(($status == '2') && ($offer == '1')){
$email_translation_key = get_translation_key_by_noti_type_id($offers[1]->noti_type_id_fk);
$subject = $wp_repair_lang[$email_translation_key.'_email_subject'];
$message_template = $wp_repair_lang[$email_translation_key.'_email_template'];
$message = wp_repair_prepare_order_email($order_id, $subject, $message_template);
$subject = wp_repair_prepare_order_email_subject($order_id, $subject);
wp_repair_send_mail($to, $subject, $message);
$duplicate_email = wp_repair_admin_duplicate_email('2', $rp_location_id);
if(!empty($duplicate_email)) {
rp_wp_mail_change_sender_info($user_email, $user_name);
$message = wp_repair_prepare_order_email_for_admin($order_id, $subject, $message_template);
wp_repair_send_mail($duplicate_email, $subject, $message, $bcc_email);
}
}else if(($status == '3') && ($approved == '1')){
$email_translation_key = get_translation_key_by_noti_type_id($offers[2]->noti_type_id_fk);
$subject = $wp_repair_lang[$email_translation_key.'_email_subject'];
$message_template = $wp_repair_lang[$email_translation_key.'_email_template'];
$message = wp_repair_prepare_order_email($order_id, $subject, $message_template);
$subject = wp_repair_prepare_order_email_subject($order_id, $subject);
wp_repair_send_mail($to, $subject, $message);
$duplicate_email = wp_repair_admin_duplicate_email('3', $rp_location_id);
if(!empty($duplicate_email)) {
rp_wp_mail_change_sender_info($user_email, $user_name);
$message = wp_repair_prepare_order_email_for_admin($order_id, $subject, $message_template);
wp_repair_send_mail($duplicate_email, $subject, $message, $bcc_email);
}
}else if(($status == '4') && ($cancel == '1')){
$email_translation_key = get_translation_key_by_noti_type_id($offers[3]->noti_type_id_fk);
$subject = $wp_repair_lang[$email_translation_key.'_email_subject'];
$message_template = $wp_repair_lang[$email_translation_key.'_email_template'];
$message = wp_repair_prepare_order_email($order_id, $subject, $message_template);
$subject = wp_repair_prepare_order_email_subject($order_id, $subject);
wp_repair_send_mail($to, $subject, $message);
$duplicate_email = wp_repair_admin_duplicate_email('4', $rp_location_id);
if(!empty($duplicate_email)) {
rp_wp_mail_change_sender_info($user_email, $user_name);
$message = wp_repair_prepare_order_email_for_admin($order_id, $subject, $message_template);
wp_repair_send_mail($duplicate_email, $subject, $message, $bcc_email);
}
}
}
}
} else {
$order = NULL;
}
}
}
ob_start();
include WP_REPAIR_PLUGIN_PATH.'html/front_end/cancel_html.php';
$content = ob_get_contents();
ob_end_clean();
return json_encode(array(
'template' => $content,
'status' => true
));
}
function rp_fe_cancel_page(){
echo _rp_fe_cancel_page();
exit();
}
rp_ajax_for_public('rp_fe_cancel_page','rp_fe_cancel_page');
// --------------------------------------------------------- get approve page for front-end
function _rp_fe_approve_page(){
global $rpQuery;
global $wp_repair_lang;
$rs_orders = $rpQuery->prefix . "rs_orders";
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$rs_customer = $rpQuery->prefix . "rs_customer";
$rs_notifications_and_offers = $rpQuery->prefix . "rs_notifications_and_offers";
$company_information = $rpQuery->prefix ."rs_company_information";
$company_results = $rpQuery->get_results("SELECT * FROM $company_information");
$theme_color = $company_results[0]->company_theme_color;
$order_id = $_POST['id'] ?? '';
$secret_key = $_POST['secret_key'] ?? '';
$really_approve = $_POST['really_approve'] ?? '0';
if(isset($order_id) && !empty($order_id)){
$order = $rpQuery->get_results("SELECT o.*, cl.*, cu.* FROM $rs_orders AS o LEFT JOIN $rs_company_location AS cl ON o.location_id_fk = cl.location_id LEFT JOIN $rs_customer as cu ON o.customer_id_fk = cu.customer_id WHERE o.o_id = '".rp_escape_sql($order_id)."'");
if(!empty($order)) {
if(md5($order[0]->o_id . $order[0]->customer_id_fk."approve") === $secret_key) {
rp_set_order_related_language($order_id);
if( $really_approve == '1' ) {
// If status is pending
if( ( $order[0]->status_id_fk ?? 0 ) != 3 ) {
$rpQuery->query("UPDATE $rs_orders SET `status_id_fk` = 3 WHERE o_id = '".rp_escape_sql( $order[0]->o_id ?? 0 )."'");
rp_send_appointment_status_update_email( $order[0]->o_id ?? 0 );
}
}
} else {
$order = NULL;
}
}
}
ob_start();
include WP_REPAIR_PLUGIN_PATH.'html/front_end/approve_html.php';
$content = ob_get_contents();
ob_end_clean();
return json_encode(array(
'template' => $content,
'status' => true
));
}
function rp_fe_approve_page(){
echo _rp_fe_approve_page();
exit();
}
rp_ajax_for_public('rp_fe_approve_page','rp_fe_approve_page');
/*
UPSALES RESET / SINGLE DELETE
*/
function handle_upsale_single_delete() {
rp_verify_csrf_token_for_ajax('manage_upsales');
global $rpQuery;
$upsales_models_tables = $rpQuery->prefix . "rs_upsales_models";
$model_id = $_POST['up_model_id'] ?? '' ;
if(!empty($model_id)){
$rpQuery->query("DELETE FROM $upsales_models_tables WHERE `up_model_id` = '".rp_escape_sql($model_id)."' ");
echo json_encode(array(
'success' => 'Successfully deleted.'
));
exit();
}
echo json_encode(array(
'error' => 'Something went wrong, please try again later.'
));
exit();
}
rp_ajax_for_admin('delete_upsales_model', 'handle_upsale_single_delete');
// RESET UPSALES QUERY
function rp_upsale_reset() {
rp_verify_csrf_token_for_ajax('manage_upsales');
global $rpQuery;
$upsales_reset_table = $rpQuery->prefix . "rs_upsales_models";
$upsales_reset_id = $_POST['upsales_reset_id'] ?? '' ;
if(!empty($upsales_reset_id)) {
$rpQuery->query("DELETE FROM $upsales_reset_table WHERE `upsales_id_fk` = '".rp_escape_sql($upsales_reset_id)."'; ");
echo json_encode(array(
'success' => 'Selected uspale successfully reset.'
));
exit();
}
echo json_encode(array(
'error' => 'Something went wrong, please try again later.'
));
exit();
}
rp_ajax_for_admin('reset_upsales', 'rp_upsale_reset');
function rp_wp_mail_change_sender_info($sender_email = '', $sender_name = '') {
if(rp_get_option('rp_use_customer_info_for_duplicate_email', '0') === '1') {
if(!empty($sender_email)) {
$GLOBALS['rp_sender_email'] = $sender_email;
add_filter('wp_mail', function($atts = NULL){
if(!empty($atts)) {
if(!isset($atts['headers'])) {
$atts['headers'] = array();
}
if(is_array($atts['headers']) !== FALSE) {
$atts['headers'][] = 'Reply-To: '. $GLOBALS['rp_sender_email'];
} else if(is_string($atts['headers'])) {
$atts['headers'] .= "\nReply-To: ". $GLOBALS['rp_sender_email'];
} else {
}
}
return $atts;
}, 999);
}
if(!empty($sender_name)) {
$GLOBALS['rp_sender_name'] = $sender_name;
add_filter('wp_mail_from_name', function(){
return $GLOBALS['rp_sender_name'];
}, 999);
}
}
}
function rp_get_default_repair_attr_by_category_cached( $dr_category = 0 ) {
static $default_repair_attr_by_category = NULL;
if( $default_repair_attr_by_category !== NULL && array_key_exists( $dr_category, $default_repair_attr_by_category ) ) {
return $default_repair_attr_by_category[ $dr_category ];
}
global $rpQuery;
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$result = $rpQuery->get_results("SELECT * FROM `$rs_default_repair_attr` WHERE dr_category = '".rp_escape_sql( $dr_category )."'");
$default_repair_attr_by_category[ $dr_category ] = $result;
return $result;
}
function rp_get_model_row_device_type_by_m_id_cached( $m_id = 0 ) {
static $model_row_device_type_by_m_id = NULL;
if( $model_row_device_type_by_m_id !== NULL && array_key_exists( $m_id, $model_row_device_type_by_m_id ) ) {
return $model_row_device_type_by_m_id[ $m_id ];
}
global $rpQuery;
$rs_model = $rpQuery->prefix . 'rs_model';
$m_id = (int) $m_id;
$model_info = $rpQuery->get_results("SELECT device_type FROM `$rs_model` WHERE m_id = '".rp_escape_sql($m_id)."'");
$model_row_device_type_by_m_id[ $m_id ] = $model_info;
return $model_info;
}
function rp_fix_default_repair_attr_sorting($current_rows = array(), $m_id = '') {
global $rpQuery;
$rs_model = $rpQuery->prefix . 'rs_model';
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$m_id = (int) $m_id;
$model_info = rp_get_model_row_device_type_by_m_id_cached( $m_id );
if(!empty($model_info)) {
$result = rp_get_default_repair_attr_by_category_cached( $model_info[0]->device_type );
} else {
$result = $rpQuery->get_results("SELECT * FROM `$rs_default_repair_attr`");
}
if(!empty($result)) {
$key_value_pair = array();
$default_repairs = array();
foreach ($result as $key => $value) {
$key_value_pair[$value->da_uq_id] = $value->da_position;
$default_repairs[] = $value->da_uq_id;
}
$not_default = 1;
foreach ($current_rows as $key => $value) {
if(!in_array($value->a_uq_id, $default_repairs)) {
$value->ra_position = $not_default;
$current_rows[$key] = $value;
$not_default++;
} else {
if(($value->ra_position == '0' || $value->ra_position == '') && isset($key_value_pair[$value->a_uq_id])) {
// Skip..
} else {
$value->ra_position = $not_default;
$current_rows[$key] = $value;
$not_default++;
}
}
}
foreach ($current_rows as $key => $value) {
if(!in_array($value->a_uq_id, $default_repairs)) {
// Skip..
} else {
if(($value->ra_position == '0' || $value->ra_position == '') && isset($key_value_pair[$value->a_uq_id])) {
$value->ra_position = $not_default+$key_value_pair[$value->a_uq_id];
$current_rows[$key] = $value;
}
}
}
}
$sort_position = array();
foreach ($current_rows as $key => $value) {
$sort_position[] = array('key'=>$key, 'position'=>$value->ra_position);
}
usort($sort_position, function ($item1, $item2) {
return $item1['position'] <=> $item2['position'];
});
$new_arr = array();
foreach ($sort_position as $row) {
$new_arr[] = $current_rows[$row['key']];
}
return $new_arr;
}
function rp_fix_default_repair_sorting($current_rows = array(), $m_id = '') {
global $rpQuery;
$rs_model = $rpQuery->prefix . 'rs_model';
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$m_id = (int) $m_id;
$model_info = rp_get_model_row_device_type_by_m_id_cached( $m_id );
if(!empty($model_info)) {
$result = $rpQuery->get_results("SELECT * FROM `$rs_default_repair` WHERE dr_category = '".rp_escape_sql($model_info[0]->device_type)."'");
} else {
$result = $rpQuery->get_results("SELECT * FROM `$rs_default_repair`");
}
if(!empty($result)) {
$key_value_pair = array();
$default_repairs = array();
foreach ($result as $key => $value) {
$key_value_pair[$value->dr_uq_id] = $value->dr_position;
$default_repairs[] = $value->dr_uq_id;
}
$not_default = 1;
foreach ($current_rows as $key => $value) {
if(!in_array($value->r_uq_id, $default_repairs)) {
$value->r_position = $not_default;
$current_rows[$key] = $value;
$not_default++;
} else {
if(($value->r_position == '0' || $value->r_position == '') && isset($key_value_pair[$value->r_uq_id])) {
// Skip...
} else {
$value->r_position = $not_default;
$current_rows[$key] = $value;
$not_default++;
}
}
}
foreach ($current_rows as $key => $value) {
if(!in_array($value->r_uq_id, $default_repairs)) {
// Skip..
} else {
if(($value->r_position == '0' || $value->r_position == '') && isset($key_value_pair[$value->r_uq_id])) {
$value->r_position = $not_default+$key_value_pair[$value->r_uq_id];
$current_rows[$key] = $value;
}
}
}
}
$sort_position = array();
foreach ($current_rows as $key => $value) {
$sort_position[] = array('key'=>$key, 'position'=>$value->r_position);
}
usort($sort_position, function ($item1, $item2) {
return $item1['position'] <=> $item2['position'];
});
$new_arr = array();
foreach ($sort_position as $row) {
$new_arr[] = $current_rows[$row['key']];
}
return $new_arr;
}
function rp_get_all_repair_ids_related_to_category( $dr_category = 0 ) {
$cache_key = 'rp_get_all_repair_ids_related_to_category|'.$dr_category;
$cached = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if(!empty($cached)) {
return $cached;
}
global $rpQuery;
$rs_repair = $rpQuery->prefix . 'rs_repair';
$m_ids = rp_get_all_m_ids_by_category( $dr_category );
$r_ids = array();
if( !empty( $m_ids ) ) {
$m_ids = join(',', $m_ids);
$related_repairs = $rpQuery->get_results("SELECT r_id FROM `$rs_repair` WHERE m_id_fk IN (".rp_escape_sql($m_ids).")");
if(!empty($related_repairs)) {
foreach ($related_repairs as $row) {
$r_ids[] = $row->r_id;
}
}
}
RepairPluginPro\RP_Memory_Cache::save($cache_key, $r_ids);
return $r_ids;
}
function rp_reset_default_repairs_order_everywhere() {
global $rpQuery;
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_repairs_category = $rpQuery->prefix . 'rs_repairs_category';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_default_repairs_category = $rpQuery->prefix . 'rs_default_repairs_category';
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$rs_repair_cat_linking = $rpQuery->prefix . 'rs_repair_cat_linking';
$dr_category = $_POST['dr_category'] ?? 0;
$rows = $rpQuery->get_results("SELECT dr_uq_id FROM $rs_default_repair WHERE dr_category = '".rp_escape_sql($dr_category)."'");
$all_uq_ids = array();
if(!empty($rows)) {
$m_ids = rp_get_all_m_ids_by_category( $dr_category );
if(!empty($m_ids)) {
$m_ids = join(',', $m_ids);
foreach ($rows as $key => $row) {
$all_uq_ids[] = $row->dr_uq_id;
}
$all_uq_ids_str = '(\'' . join('\', \'', $all_uq_ids) . '\')';
$rpQuery->query("UPDATE $rs_repair SET r_position = '0' WHERE r_uq_id IN ".($all_uq_ids_str)." AND m_id_fk IN (".rp_escape_sql($m_ids).")");
$rpQuery->query("DELETE FROM $rs_repair_cat_linking WHERE repair_uqid IN ".($all_uq_ids_str)." AND m_id_fk IN (".rp_escape_sql($m_ids).")");
}
}
$rows = $rpQuery->get_results("SELECT dc_uq_id FROM $rs_default_repairs_category WHERE dc_category = '".rp_escape_sql($dr_category)."'");
$all_uq_ids = array();
if(!empty($rows)) {
$m_ids = rp_get_all_m_ids_by_category( $dr_category );
if(!empty($m_ids)) {
$m_ids = join(',', $m_ids);
foreach ($rows as $key => $row) {
$all_uq_ids[] = $row->dc_uq_id;
}
$all_uq_ids_str = '(\'' . join('\', \'', $all_uq_ids) . '\')';
$rpQuery->query("UPDATE $rs_repairs_category SET c_position = '0' WHERE c_uq_id IN ".($all_uq_ids_str)." AND m_id_fk IN (".rp_escape_sql($m_ids).")");
$rpQuery->query("DELETE FROM $rs_repair_cat_linking WHERE rc_uq_id IN ".($all_uq_ids_str)." AND m_id_fk IN (".rp_escape_sql($m_ids).")");
}
}
$rows = $rpQuery->get_results("SELECT da_uq_id FROM $rs_default_repair_attr WHERE dr_category = '".rp_escape_sql($dr_category)."'");
$all_uq_ids = array();
if(!empty($rows)) {
$r_ids = rp_get_all_repair_ids_related_to_category($dr_category);
if(!empty($r_ids)) {
$r_ids = join(',', $r_ids);
foreach ($rows as $key => $row) {
$all_uq_ids[] = $row->da_uq_id;
}
$all_uq_ids_str = '(\'' . join('\', \'', $all_uq_ids) . '\')';
$rpQuery->query("UPDATE $rs_repair_attr SET ra_position = '0' WHERE a_uq_id IN ".($all_uq_ids_str)." AND r_id_fk IN (".rp_escape_sql($r_ids).")");
}
}
}
/* NOT NEEDED AFTER 1.4 UPDATE */
// function rp_reset_default_repair_sorting_first_time() {
// if(rp_get_option('rp_reset_default_repair_sorting_first_time', FALSE) === FALSE) {
// rp_reset_default_repairs_order_everywhere();
// rp_add_option('rp_reset_default_repair_sorting_first_time', TRUE);
// }
// }
// rp_add_action('init', 'rp_reset_default_repair_sorting_first_time', 99999);
function rp_reset_default_sorting() {
rp_verify_csrf_token_for_ajax('default_repairs');
rp_verify_user_full_access_ajax();
rp_reset_default_repairs_order_everywhere();
echo json_encode(array('success' => 'Default sorting has been reset.'));
exit();
}
rp_ajax_for_admin('reset_default_sorting', 'rp_reset_default_sorting');
function rp_reset_default_repair_ajax() {
rp_verify_csrf_token_for_ajax('default_repairs');
rp_verify_selected_location_id_by_location_head();
$rp_current_user_has_full_access = rp_current_user_has_full_access();
list( $selected_location_id, $rp_location_based_price_id ) = rp_must_verify_selected_location_if_needed_ajax();
global $rpQuery;
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_repair_cat_linking = $rpQuery->prefix . 'rs_repair_cat_linking';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$rs_location_prices = $rpQuery->prefix . 'rs_location_prices';
$dr_id = $_POST['dr_id'] ?? '';
$dr_category = $_POST['dr_category'] ?? 0;
$reset_margin_field = apply_filters('rp_reset_margin_field_while_default_reset', FALSE);
$reset_price_field = TRUE;
if(!empty($dr_id)) {
$default_repair = $rpQuery->get_results("SELECT * FROM $rs_default_repair WHERE `dr_id` = '".rp_escape_sql($dr_id)."' AND dr_category = '".rp_escape_sql($dr_category)."' LIMIT 1;");
if(!empty($default_repair)) {
$default_repair = $default_repair[0];
$dr_img = $default_repair->dr_img;
$dr_img = $dr_img;
$m_ids = rp_get_all_m_ids_by_category( $dr_category );
if(!empty($m_ids)) {
$m_ids = join(',', $m_ids);
if( $reset_margin_field === TRUE ) {
$margin_field_sql = "`r_margin` = '".rp_escape_sql($default_repair->dr_margin)."',";
} else {
$margin_field_sql = '';
}
if( $reset_price_field === TRUE ) {
$price_field_sql = "`r_price` = '".rp_escape_sql($default_repair->dr_price)."',";
} else {
$price_field_sql = '';
}
if( $rp_current_user_has_full_access == true ) {
$rpQuery->query("UPDATE $rs_repair SET $price_field_sql $margin_field_sql `r_name` = '".rp_escape_sql($default_repair->dr_name)."', `r_duration` = '".rp_escape_sql($default_repair->dr_duration)."', `r_duration_measure` = '".rp_escape_sql($default_repair->dr_duration_measure)."', `r_discription` = '".rp_escape_sql($default_repair->dr_discription)."', `r_badge` = '".rp_escape_sql($default_repair->dr_badge)."', `r_readmore` = '".rp_escape_sql($default_repair->dr_readmore)."', `r_readmoretext` = '".rp_escape_sql($default_repair->dr_readmoretext)."', `r_img` = '".rp_escape_sql($dr_img)."', is_free = '".rp_escape_sql($default_repair->is_free)."', is_active = '".rp_escape_sql($default_repair->is_active)."' WHERE `r_uq_id` LIKE '".rp_escape_sql($default_repair->dr_uq_id)."' AND m_id_fk IN (".rp_escape_sql($m_ids).")");
$rpQuery->query("DELETE FROM $rs_repair_cat_linking WHERE repair_uqid LIKE '".rp_escape_sql($default_repair->dr_uq_id)."' AND m_id_fk IN (".rp_escape_sql($m_ids).")");
_rp_remove_individual_repair_translations_because_reset_default( 'repair_read_more', ($default_repair->dr_uq_id .'_'. $dr_category), $m_ids );
_rp_remove_individual_repair_translations_because_reset_default( 'repair_readmore_text', ($default_repair->dr_uq_id .'_'. $dr_category), $m_ids );
}
if( !empty( $selected_location_id ) ) {
// delete from $rs_location_prices where type = 'r' and uqid = dr_uq_id and dr_category = dr_category
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'r' AND `uqid` = '".rp_escape_sql($default_repair->dr_uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."' AND `location_id_fk` = '".rp_escape_sql($selected_location_id)."'");
}
$default_repair_attr = $rpQuery->get_results("SELECT * FROM $rs_default_repair_attr WHERE `dr_id_fk` = '".rp_escape_sql($dr_id)."' AND dr_category = '".rp_escape_sql($dr_category)."';");
if(!empty($default_repair_attr)) {
$r_ids = rp_get_all_repair_ids_related_to_category($dr_category);
if(!empty($r_ids)) {
$r_ids = join(',', $r_ids);
foreach ($default_repair_attr as $dra_row) {
if( $reset_margin_field === TRUE ) {
$a_margin_sql = "`a_margin` = '".rp_escape_sql($dra_row->da_margin)."',";
} else {
$a_margin_sql = '';
}
if( $reset_price_field === TRUE ) {
$a_price_sql = "`a_price` = '".rp_escape_sql($dra_row->da_price)."',";
} else {
$a_price_sql = '';
}
if( $rp_current_user_has_full_access == true ) {
$rpQuery->query("UPDATE $rs_repair_attr SET $a_price_sql $a_margin_sql `a_name` = '".rp_escape_sql($dra_row->da_name)."', `a_duration` = '".rp_escape_sql($dra_row->da_duration)."', `a_duration_measure` = '".rp_escape_sql($dra_row->da_duration_measure)."', `a_desc` = '".rp_escape_sql($dra_row->da_desc)."', `a_badge` = '".rp_escape_sql($dra_row->da_badge)."', `a_readmore` = '".rp_escape_sql($dra_row->da_readmore)."', `a_readmoretext` = '".rp_escape_sql($dra_row->da_readmoretext)."', `is_active` = '".rp_escape_sql($dra_row->is_active)."' WHERE `a_uq_id` = '".rp_escape_sql($dra_row->da_uq_id)."' AND `r_id_fk` IN (".rp_escape_sql($r_ids).")");
_rp_remove_individual_attributes_translations_because_reset_default( 'attr_read_more', $r_ids );
_rp_remove_individual_attributes_translations_because_reset_default( 'attr_readmore_text', $r_ids );
}
if( !empty( $selected_location_id ) ) {
// delete from $rs_location_prices where type = 'a' and uqid = da_uq_id and dr_category = dr_category
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'a' AND `uqid` = '".rp_escape_sql($dra_row->da_uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."' AND `location_id_fk` = '".rp_escape_sql($selected_location_id)."'");
}
}
}
}
}
}
}
echo json_encode(array('status' => true, 'success' => 'Selected default repair has been reset.'));
exit();
}
rp_ajax_for_admin('reset_default_repair_ajax', 'rp_reset_default_repair_ajax');
function rp_create_apple_calendar_link($options = array()) {
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename=appointment.ics');
$start_time = new DateTime("{$options['start_time']}:00", new DateTimeZone(wp_timezone_string()));
$start_time->setTimezone(new DateTimeZone("UTC"));
$start_time = $start_time->format("Ymd-His");
$end_time = new DateTime("{$options['end_time']}:00", new DateTimeZone(wp_timezone_string()));
$end_time->setTimezone(new DateTimeZone("UTC"));
$end_time = $end_time->format("Ymd-His");
$ics = new RepairPluginPro\RP_ICS(array(
'location' => $options['location'],
'description' => $options['details'],
'dtstart' => str_replace('-', 'T', $start_time),
'dtend' => str_replace('-', 'T', $end_time),
'summary' => $options['text'],
'url' => get_site_url()
));
echo $ics->to_string();
exit();
}
function rp_create_google_calendar_link($options = array()) {
$start_time = new DateTime("{$options['start_time']}:00", new DateTimeZone(wp_timezone_string()));
$timezone = wp_timezone_string();
if(!empty($timezone) && strpos($timezone, '/') !== false) {
// Skip...
} else {
$timezone = "Europe/Amsterdam";
}
$start_time->setTimezone(new DateTimeZone($timezone));
$start_time = $start_time->format("Ymd-His");
$end_time = new DateTime("{$options['end_time']}:00", new DateTimeZone(wp_timezone_string()));
$end_time->setTimezone(new DateTimeZone($timezone));
$end_time = $end_time->format("Ymd-His");
$url = 'https://www.google.com/calendar/event';
$params = array(
'action' => 'TEMPLATE',
'dates' => str_replace('-', 'T', "$start_time/$end_time"),
'text' => $options['text'],
'details' => $options['details'],
'location' => $options['location'],
'trp' => 'false',
'ctz' => $timezone,
'sprop' => 'website:'.get_site_url()
);
$get_paramaters = array();
foreach ($params as $key => $value) {
$get_paramaters[] = $key.'='.urlencode($value);
}
$get_paramaters_str = join('&', $get_paramaters);
return $url.'?'.$get_paramaters_str;
}
function rp_handle_ics_file_download() {
if(isset($_REQUEST['rp_ics']) && $_REQUEST['rp_ics'] === 'true' && isset($_POST) && !empty($_POST)) {
rp_verify_csrf_token_for_apple_calendar();
rp_create_apple_calendar_link(array(
'text' => $_POST['text'],
'details' => $_POST['details'],
'location' => $_POST['location'],
'start_time' => $_POST['start_time'],
'end_time' => $_POST['end_time']
));
}
}
rp_add_action('init', 'rp_handle_ics_file_download');
function _rp_set_default_tiemzone() {
date_default_timezone_set(wp_timezone_string());
}
global $rp_check_if_table_already_exists_last_results;
$rp_check_if_table_already_exists_last_results;
function rp_check_if_table_already_exists($table_name = '') {
global $rp_check_if_table_already_exists_last_results;
$rp_check_if_table_already_exists_last_results;
if( isset( $rp_check_if_table_already_exists_last_results ) && is_array( $rp_check_if_table_already_exists_last_results ) && array_key_exists( $table_name, $rp_check_if_table_already_exists_last_results ) ) {
return $rp_check_if_table_already_exists_last_results[ $table_name ];
}
global $wpdb;
$result = $wpdb->get_results("SHOW TABLES LIKE '$table_name'");
$result = !empty($result);
$rp_check_if_table_already_exists_last_results[ $table_name ] = $result;
return $result;
}
function rp_db_delta( $sql = array() ) {
global $rp_check_if_table_already_exists_last_results;
$rp_check_if_table_already_exists_last_results;
require_once( ABSPATH .'wp-admin/includes/upgrade.php' );
if( !is_array( $sql ) ) {
$sql = array( $sql );
}
$filtered_sql = array();
foreach( $sql as $theSQL ) {
$table_name = str_replace('CREATE TABLE IF NOT EXISTS ', '', $theSQL);
$table_name = explode( ' ', trim( $table_name ) )[0];
$table_name = str_replace('`', '', $table_name);
if( !rp_check_if_table_already_exists( $table_name ) ) {
$rp_check_if_table_already_exists_last_results[ $table_name ] = TRUE;
$filtered_sql[] = $theSQL;
}
}
if( !empty( $filtered_sql ) ) {
dbDelta( $filtered_sql );
}
}
function rp_book_available_slot($data = array()) {
global $rpQuery;
$rs_timeslot = $rpQuery->prefix . 'rs_timeslot';
$insert_keys = array();
$insert_values = array();
foreach ($data as $key => $value) {
$insert_keys[] = $key;
if($key === 'a_time') {
$insert_values[] = rp_escape_sql(date('H:i:s', strtotime($value)));
} else if($key === 'a_date') {
$the_date = explode('-', $value);
$the_date = $the_date[2] . '-' . $the_date[1] . '-' . $the_date[0];
$insert_values[] = rp_escape_sql($the_date);
} else {
$insert_values[] = rp_escape_sql($value);
}
}
$insert_keys_str = '`'.join('`,`', $insert_keys).'`';
$insert_values_str = "'" . join("','", $insert_values) . "'";
$rpQuery->query("INSERT INTO `$rs_timeslot` ($insert_keys_str) VALUES ($insert_values_str)");
}
function rp_book_available_slot_new_dm($data = array()) {
global $rpQuery;
$rs_timeslot_dm = $rpQuery->prefix . 'rs_timeslot_dm';
$insert_keys = array();
$insert_values = array();
foreach ($data as $key => $value) {
$insert_keys[] = $key;
if($key === 'a_time') {
$time = explode(' — ', $value);
$time = date('H:i', strtotime($time[0])) . ' — ' . date('H:i', strtotime($time[1]));
$insert_values[] = rp_escape_sql($time);
} else if($key === 'a_date') {
$the_date = explode('-', $value);
$the_date = $the_date[2] . '-' . $the_date[1] . '-' . $the_date[0];
$insert_values[] = rp_escape_sql($the_date);
} else {
$insert_values[] = rp_escape_sql($value);
}
}
$insert_keys_str = '`'.join('`,`', $insert_keys).'`';
$insert_values_str = "'" . join("','", $insert_values) . "'";
$rpQuery->query("INSERT INTO `$rs_timeslot_dm` ($insert_keys_str) VALUES ($insert_values_str)");
}
function rp_is_available_slot($loc_id = NULL, $date = '', $time = '') {
if(empty($loc_id) || empty($date) || empty($time)) {
return FALSE;
}
$time = date('H:i:s', strtotime($time));
global $rpQuery;
$planning = $rpQuery->prefix . "rs_planning_and_discount";
$rs_timeslot = $rpQuery->prefix . 'rs_timeslot';
$rs_orders = $rpQuery->prefix . 'rs_orders';
$planning_result = $rpQuery->get_results("SELECT * FROM $planning");
$booking_amount_per_slot = trim($planning_result[0]->booking_amount_per_slot);
if(empty($booking_amount_per_slot)) {
$booking_amount_per_slot = 'unlimited';
}
if(strpos(strtolower($booking_amount_per_slot), 'unlimited') !== FALSE) {
return TRUE;
}
$booking_amount_per_slot = (int) $booking_amount_per_slot;
$rows = $rpQuery->get_results("SELECT * FROM `$rs_timeslot` WHERE `loc_id` = '".rp_escape_sql($loc_id)."' AND `a_date` LIKE '".rp_escape_sql($date)."' AND `a_time` LIKE '".rp_escape_sql($time)."'");
if(!empty($rows)) {
$o_ids = array();
foreach ($rows as $row) {
$o_ids[] = $row->o_id;
}
$o_ids_str = join(',', $o_ids);
$active_orders_count = $rpQuery->get_var("SELECT COUNT(o_id) FROM `$rs_orders` WHERE `o_id` IN (".rp_escape_sql($o_ids_str).") AND `status_id_fk` IN (1,3)");
return $booking_amount_per_slot > $active_orders_count;
}
return TRUE;
}
function rp_is_available_slot_new_delivery_methods($method = NULL, $date = '', $time = '') {
if(empty($method) || empty($date) || empty($time)) {
return FALSE;
}
if( $method === 'pickup_service' ) {
$_method = 'ps';
}
if( $method === 'repair_on_location' ) {
$_method = 'rol';
}
$time = explode(' — ', $time);
$time = date('H:i', strtotime($time[0])) . ' — ' . date('H:i', strtotime($time[1]));
global $rpQuery;
$rs_timeslot_dm = $rpQuery->prefix . 'rs_timeslot_dm';
$rs_orders = $rpQuery->prefix . 'rs_orders';
$booking_amount_per_slot = trim(rp_get_option('wp_repair_booking_amount_per_slot_'.$_method, 'Unlimited'));
if(empty($booking_amount_per_slot)) {
$booking_amount_per_slot = 'unlimited';
}
if(strpos(strtolower($booking_amount_per_slot), 'unlimited') !== FALSE) {
return TRUE;
}
$booking_amount_per_slot = (int) $booking_amount_per_slot;
$rows = $rpQuery->get_results("SELECT * FROM `$rs_timeslot_dm` WHERE `method_id` = '".rp_escape_sql($_method)."' AND `a_date` LIKE '".rp_escape_sql($date)."' AND `a_time` LIKE '".rp_escape_sql($time)."'");
if(!empty($rows)) {
$o_ids = array();
foreach ($rows as $row) {
$o_ids[] = $row->o_id;
}
$o_ids_str = join(',', $o_ids);
$active_orders_count = $rpQuery->get_var("SELECT COUNT(o_id) FROM `$rs_orders` WHERE `o_id` IN (".rp_escape_sql($o_ids_str).") AND `status_id_fk` IN (1,3)");
return $booking_amount_per_slot > $active_orders_count;
}
return TRUE;
}
function rp_get_front_end_results_count() {
global $rpQuery;
$categories_count = array();
$brands_count = array();
$models_count = array();
$rs_category = $rpQuery->prefix . "rs_category";
$rs_brand = $rpQuery->prefix . "rs_brand";
$rs_model = $rpQuery->prefix . "rs_model";
$c_results = $rpQuery->get_results("SELECT c_id FROM $rs_category WHERE is_active = '1';");
if(!empty($c_results)) {
foreach ($c_results as $c_row) {
$categories_count[] = $c_row->c_id;
$b_results = $rpQuery->get_results("SELECT b_id FROM $rs_brand WHERE c_id_fk = '".rp_escape_sql($c_row->c_id)."' AND is_active = '1';");
$brands_count[$c_row->c_id] = array();
if(!empty($b_results)) {
foreach ($b_results as $b_row) {
$brands_count[$c_row->c_id][] = $b_row->b_id;
$m_results = $rpQuery->get_results("SELECT m_id FROM $rs_model WHERE brand_id_fk = '".rp_escape_sql($b_row->b_id)."' AND is_active = '1';");
$models_count[$b_row->b_id] = array();
if(!empty($m_results)) {
foreach ($m_results as $m_row) {
$models_count[$b_row->b_id][] = $m_row->m_id;
}
}
}
}
}
}
return array($categories_count, $brands_count, $models_count);
}
function rp_get_b_id_by_c_name_and_b_name($c_name = '', $b_name = '') {
global $rpQuery;
$rs_category = $rpQuery->prefix . "rs_category";
$rs_brand = $rpQuery->prefix . "rs_brand";
$rows = $rpQuery->get_results("SELECT b.b_id FROM $rs_brand AS b
LEFT JOIN $rs_category AS c ON b.c_id_fk = c.c_id
WHERE b.b_name LIKE '".rp_escape_sql($b_name)."' AND c.c_name LIKE '".rp_escape_sql($c_name)."' LIMIT 1");
if(!empty($rows)) {
return $rows[0]->b_id;
}
return 0;
}
function rp_get_c_id_by_c_name($c_name = '') {
global $rpQuery;
$rs_category = $rpQuery->prefix . "rs_category";
$rows = $rpQuery->get_results("SELECT c_id FROM $rs_category WHERE c_name LIKE '".rp_escape_sql($c_name)."' LIMIT 1");
if(!empty($rows)) {
return $rows[0]->c_id;
}
return 0;
}
function rp_get_c_name_by_c_id($c_id = '') {
global $rpQuery;
$rs_category = $rpQuery->prefix . "rs_category";
$rows = $rpQuery->get_results("SELECT c_name FROM $rs_category WHERE c_id = '".rp_escape_sql($c_id)."' LIMIT 1");
if(!empty($rows)) {
return $rows[0]->c_name;
}
return '';
}
function rp_get_b_name_by_b_id($b_id = '') {
global $rpQuery;
$rs_brand = $rpQuery->prefix . "rs_brand";
$rows = $rpQuery->get_results("SELECT b_name FROM $rs_brand WHERE b_id = '".rp_escape_sql($b_id)."' LIMIT 1");
if(!empty($rows)) {
return $rows[0]->b_name;
}
return '';
}
function rp_get_m_name_by_m_id($m_id = '') {
global $rpQuery;
$rs_model = $rpQuery->prefix . "rs_model";
$rows = $rpQuery->get_results("SELECT m_name FROM $rs_model WHERE m_id = '".rp_escape_sql($m_id)."' LIMIT 1");
if(!empty($rows)) {
return $rows[0]->m_name;
}
return '';
}
function rp_get_front_end_firsttime_load_step($c_name = '', $b_name = '') {
if(rp_get_option('wp_repair_skip_steps', '1') != '1') {
return NULL;
}
global $rpQuery;
list($categories, $brands, $models) = rp_get_front_end_results_count();
if( !empty( $c_name ) && !empty( $_REQUEST['rp_shortcode_brand_name'] ?? '' ) ) {
if( empty( $b_name ) ) {
$b_name = ($_REQUEST['rp_shortcode_brand_name'] ?? '');
}
}
if(!empty($b_name)) {
$c_id = rp_get_c_id_by_c_name($c_name);
$categories = array( $c_id );
$b_id = rp_get_b_id_by_c_name_and_b_name($c_name, $b_name);
$brands[ $categories[0] ] = array( $b_id );
} else if(!empty($c_name)) {
$c_id = rp_get_c_id_by_c_name($c_name);
$categories = array($c_id);
} else {
// No Need To Do Anything!
}
if(count($categories) === 1) {
if(isset($brands[ $categories[0] ]) && count( $brands[ $categories[0] ] ) === 1) {
if(isset($models[ $brands[ $categories[0] ][0] ]) && count($models[ $brands[ $categories[0] ][0] ]) === 1) {
return array(
'repairs',
array(
rp_get_c_name_by_c_id( $categories[0] ),
rp_get_b_name_by_b_id( $brands[ $categories[0] ][0] ),
rp_get_m_name_by_m_id( $models[ $brands[ $categories[0] ][0] ][0] )
)
);
} else {
return array(
'models',
array(
rp_get_c_name_by_c_id( $categories[0] ),
rp_get_b_name_by_b_id( $brands[ $categories[0] ][0] )
)
);
}
} else {
return array(
'brands',
array(
rp_get_c_name_by_c_id( $categories[0] )
)
);
}
} else {
return array('types', array());
}
}
function rp_get_all_model_repair_ids($m_id = NULL) {
if(empty($m_id)) {
return array();
}
global $rpQuery;
$rs_repair = $rpQuery->prefix . 'rs_repair';
$repairs = $rpQuery->get_results("SELECT r_uq_id FROM `$rs_repair` WHERE m_id_fk = '".rp_escape_sql($m_id)."'");
$ids = array();
if(!empty($repairs)) {
foreach ($repairs as $repair) {
$ids[] = trim($repair->r_uq_id);
}
}
return $ids;
}
function rp_get_all_model_color_ids($m_id = NULL) {
if(empty($m_id)) {
return array();
}
global $rpQuery;
$rs_model_color = $rpQuery->prefix . 'rs_model_color';
$colors = $rpQuery->get_results("SELECT mc_uq_id FROM `$rs_model_color` WHERE m_id_fk = '".rp_escape_sql($m_id)."'");
$ids = array();
if(!empty($colors)) {
foreach ($colors as $color) {
$ids[] = trim($color->mc_uq_id);
}
}
return $ids;
}
function rp_get_information_schema_statistics() {
static $rp_get_information_schema_statistics = NULL;
if( $rp_get_information_schema_statistics !== NULL ) {
return $rp_get_information_schema_statistics;
}
global $rpQuery;
$prefixOfWp = $rpQuery->prefix;
$existing_indexes = $rpQuery->get_results("SELECT * FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = '".DB_NAME."' AND TABLE_NAME LIKE '{$prefixOfWp}rs_%'");
$prepared = array();
foreach( $existing_indexes as $existingIndex ) {
if( !isset( $prepared[ $existingIndex->TABLE_NAME ] ) ) {
$prepared[ $existingIndex->TABLE_NAME ] = array();
}
if( !empty( $existingIndex->INDEX_NAME ?? '' ) ) {
$prepared[ $existingIndex->TABLE_NAME ][] = $existingIndex->INDEX_NAME;
}
}
$rp_get_information_schema_statistics = $prepared;
return $prepared;
}
function rp_get_information_schema_columns() {
static $rp_get_information_schema_columns = NULL;
if( $rp_get_information_schema_columns !== NULL ) {
return $rp_get_information_schema_columns;
}
global $rpQuery;
$prefixOfWp = $rpQuery->prefix;
$existing_columns = $rpQuery->get_results("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".DB_NAME."' AND TABLE_NAME LIKE '{$prefixOfWp}rs_%'");
$prepared = array();
foreach( $existing_columns as $existingColumn ) {
if( !isset( $prepared[ $existingColumn->TABLE_NAME ] ) ) {
$prepared[ $existingColumn->TABLE_NAME ] = array();
}
$prepared[ $existingColumn->TABLE_NAME ][] = $existingColumn->COLUMN_NAME;
}
$rp_get_information_schema_columns = $prepared;
return $prepared;
}
function rp_has_existing_column( $table_name = '', $column_name = '' ) {
$existing_columns = rp_get_information_schema_columns();
$table_columns = $existing_columns[ $table_name ] ?? array();
if( !empty( $table_columns ) ) {
return in_array( $column_name, $table_columns );
}
return FALSE;
}
function rp_has_existing_index( $table_name = '', $index_name = '' ) {
$existing_indexes = rp_get_information_schema_statistics();
$table_indexes = $existing_indexes[ $table_name ] ?? array();
if( !empty( $table_indexes ) ) {
return in_array( $index_name, $table_indexes );
}
return FALSE;
}
/* Function to Easily Add Column To Table if not exists*/
function rp_add_column_to_table_if_not_exists( $table_name = '', $column_name = '', $dataType = '', $prefix = TRUE ) {
global $rpQuery;
if($prefix === TRUE) {
$table_name = $rpQuery->prefix . $table_name;
}
if( rp_has_existing_column( $table_name, $column_name ) == FALSE ) {
$rpQuery->query("ALTER TABLE `$table_name` ADD `$column_name` $dataType;");
return TRUE;
}
return FALSE;
}
/*
1. Add dr_category column to rs_default_repair table
2. Split Default Repairs Based on Category
*/
function rp_fix_default_repairs_based_on_category() {
global $rpQuery;
$rs_category = $rpQuery->prefix . 'rs_category';
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$categories = $rpQuery->get_results("SELECT * FROM $rs_category");
$categories_ids = array();
if(!empty($categories)) {
foreach ($categories as $category) {
$categories_ids[] = $category->c_id;
}
// Start Work From Here!!!! Need TO Migrate Default Repairs!!!
$org_default_repairs = $rpQuery->get_results("SELECT * FROM $rs_default_repair");
$org_default_repairs_attrs = $rpQuery->get_results("SELECT * FROM $rs_default_repair_attr");
if(!empty( $org_default_repairs )) {
foreach ($categories_ids as $cat_id) {
foreach ($org_default_repairs as $default_repair) {
$dr_id = $default_repair->dr_id;
$for_insert = array();
foreach ($default_repair as $key => $value) {
$for_insert[$key] = $value;
}
unset($for_insert['dr_id']);
$for_insert['dr_category'] = $cat_id;
$rpQuery->insert($rs_default_repair, $for_insert);
$new_dr_id = $rpQuery->insert_id;
$related_default_repairs_attrs = $rpQuery->get_results("SELECT * FROM $rs_default_repair_attr WHERE `dr_id_fk` = '".rp_escape_sql($dr_id)."'");
if( !empty( $related_default_repairs_attrs ) ) {
foreach ($related_default_repairs_attrs as $related_attr) {
$da_id = $related_attr->da_id;
$for_insert = array();
foreach ($related_attr as $key => $value) {
$for_insert[$key] = $value;
}
unset($for_insert['da_id']);
$for_insert['dr_id_fk'] = $new_dr_id;
$for_insert['dr_category'] = $cat_id;
$rpQuery->insert($rs_default_repair_attr, $for_insert);
}
}
}
}
}
if(!empty($org_default_repairs)) {
$delete_ids = array();
foreach ($org_default_repairs as $row) {
$delete_ids[] = $row->dr_id;
}
$delete_ids_str = join(',', $delete_ids);
$rpQuery->query("DELETE FROM $rs_default_repair WHERE dr_id IN (".rp_escape_sql($delete_ids_str).")");
}
if(!empty($org_default_repairs_attrs)) {
$delete_ids = array();
foreach ($org_default_repairs_attrs as $row) {
$delete_ids[] = $row->da_id;
}
$delete_ids_str = join(',', $delete_ids);
$rpQuery->query("DELETE FROM $rs_default_repair_attr WHERE da_id IN (".rp_escape_sql($delete_ids_str).")");
}
}
}
function rp_fix_images_in_default_repairs_table() {
global $rpQuery;
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$entries = $rpQuery->get_results("SELECT dr_uq_id FROM `$rs_default_repair` WHERE dr_img LIKE '%base.repairplugin.com%'");
if(!empty($entries)) {
foreach ($entries as $entry) {
$allReapirs = $rpQuery->get_results("SELECT r_img FROM `$rs_repair` WHERE r_uq_id = '".rp_escape_sql($entry->dr_uq_id)."'");
if(!empty($allReapirs)) {
$repeatitiveImage = array();
foreach ($allReapirs as $repair) {
if(!isset( $repeatitiveImage[ $repair->r_img ] )) {
$repeatitiveImage[ $repair->r_img ] = 0;
}
$repeatitiveImage[ $repair->r_img ]++;
}
arsort($repeatitiveImage);
$best_image = array_keys($repeatitiveImage)[0];
$best_image = $best_image;
$rpQuery->query("UPDATE `$rs_default_repair` SET `dr_img` = '".rp_escape_sql($best_image)."' WHERE dr_uq_id = '".rp_escape_sql($entry->dr_uq_id)."'");
$rpQuery->query("UPDATE `$rs_repair` SET `r_img` = '".rp_escape_sql($best_image)."' WHERE r_uq_id = '".rp_escape_sql($entry->dr_uq_id)."'");
}
}
}
}
function rp_get_lowest_repair_attribute_price($r_id = 0) {
global $rp_location_based_price_id;
global $rpQuery;
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$result = $rpQuery->get_results("SELECT * FROM `$rs_repair_attr` WHERE `r_id_fk` = '".rp_escape_sql($r_id)."'");
$prices = array();
foreach ($result as $row) {
if( isset( $rp_location_based_price_id ) && !empty( $rp_location_based_price_id ) ) {
$row = apply_filters('rp_overwrite_individual_repair_attr_row', $row, $rp_location_based_price_id);
}
$prices[] = (float) str_replace( ',', '.', $row->a_price );
}
if(empty($prices)) {
return 0;
}
return min($prices);
}
function rp_get_lowest_default_repair_attribute_price($dr_id = 0) {
global $rp_location_based_price_id;
global $rpQuery;
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$result = $rpQuery->get_results("SELECT * FROM `$rs_default_repair_attr` WHERE `dr_id_fk` = '".rp_escape_sql($dr_id)."'");
$prices = array();
foreach ($result as $row) {
if( isset( $rp_location_based_price_id ) && !empty( $rp_location_based_price_id ) ) {
$row = apply_filters('rp_overwrite_default_repair_attr_row', $row, $rp_location_based_price_id);
}
$prices[] = (float) str_replace( ',', '.', $row->da_price );
}
if(empty($prices)) {
return 0;
}
return min($prices);
}
function _rp_get_all_default_repair_ids_of_category( $category = '' ) {
$cache_key = 'rp_get_all_default_repair_ids_of_category|'.$category;
$cached = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if(!empty($cached)) {
return $cached;
}
global $rpQuery;
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$result = $rpQuery->get_results("SELECT dr_id FROM `$rs_default_repair` WHERE dr_category = '".rp_escape_sql($category)."'");
$dr_ids = array();
if(!empty($result)) {
foreach ($result as $drepair) {
$dr_ids[] = $drepair->dr_id;
}
}
RepairPluginPro\RP_Memory_Cache::save($cache_key, $dr_ids);
return $dr_ids;
}
function rp_get_all_default_repair_ids_of_category( $category = '', $join = FALSE ) {
$dr_ids = _rp_get_all_default_repair_ids_of_category( $category );
if($join === TRUE) {
if(empty($dr_ids)) {
return '';
}
$dr_ids = join(',',$dr_ids);
}
return $dr_ids;
}
function rp_setup_guide_meet_download_libraries_requirement() {
global $rpQuery;
$rs_category = $rpQuery->prefix . 'rs_category';
$rs_brand = $rpQuery->prefix . 'rs_brand';
$rs_model = $rpQuery->prefix . 'rs_model';
$required_tables = array( $rs_category, $rs_brand, $rs_model );
$meet_requirement = TRUE;
foreach ($required_tables as $table) {
if(empty($rpQuery->get_results("SELECT * FROM $table LIMIT 1;"))) {
$meet_requirement = FALSE;
}
}
return $meet_requirement;
}
function rp_setup_guide_meet_default_repairs_requirement() {
global $rpQuery;
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$required_tables = array( $rs_default_repair );
$meet_requirement = TRUE;
foreach ($required_tables as $table) {
if(empty($rpQuery->get_results("SELECT * FROM $table"))) {
$meet_requirement = FALSE;
}
}
return $meet_requirement;
}
function rp_setup_guide_meet_manage_upsales_requirement() {
global $rpQuery;
$rs_upsales = $rpQuery->prefix . 'rs_upsales';
$required_tables = array( $rs_upsales );
$meet_requirement = TRUE;
foreach ($required_tables as $table) {
if(empty($rpQuery->get_results("SELECT * FROM $table WHERE is_active = '1'"))) {
$meet_requirement = FALSE;
}
}
return $meet_requirement;
}
function rp_setup_guide_meet_configure_settings_requirement() {
global $rpQuery;
$rs_company_information = $rpQuery->prefix . 'rs_company_information';
$result = $rpQuery->get_results("SELECT * FROM $rs_company_information");
if(!empty($result)) {
if($result[0]->company_name === 'abc' || $result[0]->company_email === rp_get_settings_placeholder_email()) {
return FALSE;
}
return TRUE;
}
return FALSE;
}
function rp_keep_setup_tour_nav_uptodate_part() {
$fileName = WP_REPAIR_PLUGIN_PATH.'html/setup_tour_nav_uptodate.php';
$fileName = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $fileName);
require_once $fileName;
}
function rp_keep_setup_tour_nav_uptodate() {
rp_keep_setup_tour_nav_uptodate_part();
exit;
}
rp_ajax_for_admin('rp_keep_setup_tour_nav_uptodate', 'rp_keep_setup_tour_nav_uptodate');
function rp_skip_quick_start_wizard() {
if( rp_get_option('rp_skip_quick_start_wizard', FALSE) === FALSE ) {
rp_add_option('rp_skip_quick_start_wizard', TRUE);
}
echo json_encode( array( 'status' => 'success', 'message' => 'Successfully skipped.' ) );
exit;
}
rp_ajax_for_admin('rp_skip_quick_start_wizard', 'rp_skip_quick_start_wizard');
function rp_quick_search_database($selectWhat = '', $tableName = '', $columnName = '', $searchWith = '=', $searchFor = '', $prefix = TRUE) {
global $rpQuery;
if($prefix === TRUE) {
$tableName = $rpQuery->prefix . $tableName;
}
return $rpQuery->get_results("SELECT $selectWhat FROM `$tableName` WHERE `$columnName` $searchWith '$searchFor'");
}
function rp_add_default_upsales_rows() {
/* Added in V1.4.2 */
global $rpQuery;
// If NOT Already Added!
if(rp_get_option('rp_added_default_upsales_rows', FALSE) === FALSE) {
$default_upsales_img_directory = WP_REPAIR_PLUGIN_URL . 'assets/images/upsales/';
// 100% Confirm If NOT Already Added!
if( empty( rp_quick_search_database('upsales_id', 'rs_upsales', 'upsales_img', 'LIKE', '%'.rp_escape_sql( $default_upsales_img_directory ).'%') ) ) {
$upsales = array();
$upsale_row = array();
$upsale_row['us_name'] = 'Mobile Safety Glass';
$upsale_row['us_info'] = 'Bescherm het scherm met deze keiharde screen protector.';
$upsale_row['us_text'] = 'Bescherm het scherm met deze keiharde screen protector.';
$upsale_row['us_old_price'] = '0';
$upsale_row['us_new_price'] = '19.95';
$upsale_row['is_active'] = '0';
$upsale_row['date_time'] = date('Y-m-d H:i:s');
$upsale_row['upsales_position'] = '1';
$upsale_row['upsales_img'] = $default_upsales_img_directory . 'glassprotector.jpg';
$upsales[] = $upsale_row;
$upsale_row = array();
$upsale_row['us_name'] = 'Apple oplaad kabel';
$upsale_row['us_info'] = 'De nieuwe standaard aansluiting, speciaal voor deze iPhone.';
$upsale_row['us_text'] = 'De nieuwe standaard aansluiting, speciaal voor deze iPhone.';
$upsale_row['us_old_price'] = '0';
$upsale_row['us_new_price'] = '25';
$upsale_row['is_active'] = '0';
$upsale_row['date_time'] = date('Y-m-d H:i:s');
$upsale_row['upsales_position'] = '2';
$upsale_row['upsales_img'] = $default_upsales_img_directory . 'usb-c-1.jpg';
$upsales[] = $upsale_row;
$upsale_row = array();
$upsale_row['us_name'] = 'Apple 20w oplaad adapter';
$upsale_row['us_info'] = 'Apple 20w oplaad adapter';
$upsale_row['us_text'] = 'Laadt je toestel razendsnel op met deze 20W adapter.';
$upsale_row['us_old_price'] = '0';
$upsale_row['us_new_price'] = '25';
$upsale_row['is_active'] = '0';
$upsale_row['date_time'] = date('Y-m-d H:i:s');
$upsale_row['upsales_position'] = '3';
$upsale_row['upsales_img'] = $default_upsales_img_directory . 'Apple_USB_C_lichtnetadapter_20w.jpg';
$upsales[] = $upsale_row;
foreach ($upsales as $single_upsale_row) {
$rpQuery->insert($rpQuery->prefix . 'rs_upsales', $single_upsale_row);
}
}
rp_add_option('rp_added_default_upsales_rows', '1');
}
}
rp_add_action('init', 'rp_add_default_upsales_rows', 999);
function rp_first_time_update_rs_order_repairs($order_id = 0) {
/* Added in V1.4.2 */
global $rpQuery;
$rs_order_repairs = $rpQuery->prefix . 'rs_order_repairs';
$related_repairs = rp_get_where_query('rs_order_repairs', 'o_id_fk', $order_id);
foreach ($related_repairs as $order_repair) {
if(!empty($order_repair->repair_name)) {
//Already Set
continue;
}
list( $relatedRepairName, $relatedRepairPrice ) = rp_get_repair_lock_price($order_repair->r_id_fk);
$rpQuery->query("UPDATE `$rs_order_repairs` SET `repair_name` = '".rp_escape_sql($relatedRepairName)."', `repair_price` = '".rp_escape_sql($relatedRepairPrice)."' WHERE `or_id` = '".rp_escape_sql($order_repair->or_id)."'");
}
}
function rp_first_time_update_rs_order_repair_attr($order_id = 0) {
/* Added in V1.4.2 */
global $rpQuery;
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
$related_repair_attrs = rp_get_where_query('rs_order_repair_attr', 'o_id_fk', $order_id);
foreach ($related_repair_attrs as $order_repair_attr) {
if(!empty($order_repair_attr->repair_attr_name)) {
//Already Set
continue;
}
list($relatedRepairAttrName, $relatedRepairAttrPrice, $relatedRepairId) = rp_get_repair_attr_lock_price($order_repair_attr->ra_id_fk);
$rpQuery->query("UPDATE `$rs_order_repair_attr` SET `repair_attr_name` = '".rp_escape_sql($relatedRepairAttrName)."', `repair_attr_price` = '".rp_escape_sql($relatedRepairAttrPrice)."', `r_id_fk` = '".rp_escape_sql($relatedRepairId)."' WHERE `ora_id` = '".rp_escape_sql($order_repair_attr->ora_id)."'");
}
}
function rp_first_time_update_rs_order_upsales($order_id = 0) {
/* Added in V1.4.2 */
global $rpQuery;
$rs_order_upsales = $rpQuery->prefix . 'rs_order_upsales';
$related_upsales = rp_get_where_query('rs_order_upsales', 'o_id_fk', $order_id);
foreach ($related_upsales as $order_upsale) {
if(!empty($order_upsale->upsale_name)) {
//Already Set
continue;
}
list( $relatedUpsaleName, $relatedUpsalePrice ) = rp_get_upsale_lock_price($order_upsale->upsales_id_fk);
$rpQuery->query("UPDATE `$rs_order_upsales` SET `upsale_name` = '".rp_escape_sql($relatedUpsaleName)."', `upsale_price` = '".rp_escape_sql($relatedUpsalePrice)."' WHERE `ou_id` = '".rp_escape_sql($order_upsale->ou_id)."'");
}
}
function rp_lazy_lock_first_time_repair_price() {
/* Added in V1.4.2 */
global $rpQuery;
$lock_previous_appointments = array();
$lock = rp_get_option('rp_lock_previous_appointments_prices', FALSE);
$added_just_now = FALSE;
if($lock === FALSE) {
// Need To Lock Previous Appointments...
$rs_orders = $rpQuery->prefix . 'rs_orders';
$orders = $rpQuery->get_results("SELECT o_id FROM `$rs_orders`");
$order_ids = array();
foreach ($orders as $order) {
$order_ids['order_id_'.$order->o_id] = '0';
}
$lock_previous_appointments = $order_ids;
$added_just_now = TRUE;
rp_add_option('rp_lock_previous_appointments_prices', $order_ids);
} else {
if(!empty($lock)) {
$lock_previous_appointments = $lock;
}
}
if($added_just_now === FALSE) {
$unprocessed = array();
foreach ($lock_previous_appointments as $key => $value) {
if($value == '0') {
$unprocessed[] = $key;
}
}
if(!empty($unprocessed)) {
$unprocessed = $unprocessed[ (count($unprocessed) - 1) ]; // Last Item
$order_id = (int) str_replace('order_id_', '', $unprocessed);
// Process the row here!
// Lock Repairs Price
rp_first_time_update_rs_order_repairs($order_id);
// Lock Repair Attributes Price
rp_first_time_update_rs_order_repair_attr($order_id);
// Lock Upsales Price
rp_first_time_update_rs_order_upsales($order_id);
// Mark Item as Proccessed!
$lock_previous_appointments[$unprocessed] = '1';
// Update The Option!
rp_update_option('rp_lock_previous_appointments_prices', $lock_previous_appointments);
}
}
}
rp_add_action('init', 'rp_lazy_lock_first_time_repair_price', 999);
function rp_curl_get_with_curl_class( $url = '', $timeout = 5 ) {
$curl = new RepairPluginPro\RP_Curl_Request_Wrapper();
$curl->set_url( $url );
return array( $curl, $curl->get( $timeout ) );
}
function rp_curl_get( $url = '', $timeout = 5 ) {
$curl = new RepairPluginPro\RP_Curl_Request_Wrapper();
$curl->set_url( $url );
return $curl->get( $timeout );
}
function rp_curl_post( $url = '', $payload = array(), $timeout = 5 ) {
$curl = new RepairPluginPro\RP_Curl_Request_Wrapper();
$curl->set_url( $url );
$curl->set_payload( $payload );
return $curl->post( $timeout );
}
function rp_find_and_fix_duplicated_model_colors() {
$rpPages = array(
'wp_repair_download_libraries',
'wp_repair_manage_models'
);
if( !is_admin() || !in_array( $_REQUEST['page'] ?? '', $rpPages ) ) {
return;
}
$start_time = microtime( true );
global $rpQuery;
$rs_model_color = $rpQuery->prefix . 'rs_model_color';
$rows = $rpQuery->get_results("SELECT * FROM
(SELECT m_id_fk, mc_uq_id, color_name, COUNT(CONCAT(m_id_fk, mc_uq_id, color_name)) AS count FROM $rs_model_color GROUP BY m_id_fk, mc_uq_id, color_name) AS subquery
WHERE subquery.count > 1;");
if( !empty( $rows ) ) {
while( !empty( $rows ) && ( microtime( true ) - $start_time ) < 1 ) {
$row = $rows[0];
$delete_limit = ((int) $row->count) - 1; // 2 - 1 = 1
$rpQuery->query( "DELETE FROM $rs_model_color WHERE m_id_fk = {$row->m_id_fk} AND mc_uq_id = '{$row->mc_uq_id}' AND color_name = '{$row->color_name}' ORDER BY mc_id DESC LIMIT $delete_limit" );
unset( $rows[0] );
$rows = array_values( $rows );
}
}
}
rp_add_action('init', 'rp_find_and_fix_duplicated_model_colors');
/*
Get uq_id of all rs_languages
*/
function rp_get_uq_id_of_all_rs_languages() {
global $rpQuery;
$rs_languages = $rpQuery->prefix . 'rs_languages';
$results = $rpQuery->get_results("SELECT `uq_id` FROM `$rs_languages`");
$all_uq_ids = array();
if( !empty( $results ) ) {
foreach( $results as $row ) {
$all_uq_ids[] = $row->uq_id;
}
}
return $all_uq_ids;
}
/*
Add Default Languages in Languages Table
*/
function repair_plugin_add_languages_in_table(){
/* Added in V1.4.4 */
/* Revised in V1.5.0 */
global $rpQuery;
$table_rs_languages = $rpQuery->prefix . "rs_languages";
if( rp_get_option('rp_added_first_time_languages_rows', FALSE) === FALSE ) {
rp_add_option('rp_added_first_time_languages_rows', '1');
$row = $rpQuery->get_row("SELECT id FROM `$table_rs_languages` WHERE `key` = 'english_united_states' LIMIT 1;");
if( empty( $row ) ) {
$rpQuery->query("INSERT INTO `$table_rs_languages` (`key`, `name`, `alt_name`, `image`, `position`) VALUES('english_united_states', 'English (United States)', 'English (US)', 'assets/images/english_united_states.png', '2')");
}
$row = $rpQuery->get_row("SELECT id FROM `$table_rs_languages` WHERE `key` = 'dutch_netherlands' LIMIT 1;");
if( empty( $row ) ) {
$rpQuery->query("INSERT INTO `$table_rs_languages` (`key`, `name`, `alt_name`, `image`, `position`) VALUES('dutch_netherlands', 'Dutch (Netherlands)', 'Netherlands', 'assets/images/dutch_netherlands.png', '1')");
}
$rpQuery->query("UPDATE `$table_rs_languages` SET `alt_name` = 'English (US)' WHERE `alt_name` LIKE 'English (United States)';");
$rpQuery->query("UPDATE `$table_rs_languages` SET `alt_name` = 'Netherlands' WHERE `alt_name` LIKE 'Dutch (Netherlands)';");
}
}
rp_add_action('init', 'repair_plugin_add_languages_in_table', 999);
function rp_get_all_languages(){
/* Added in V1.4.4 */
global $rpQuery;
$table_rs_languages = $rpQuery->prefix . "rs_languages";
return $rpQuery->get_results("SELECT * FROM `$table_rs_languages` ORDER BY `position`;");
}
function rp_get_enabled_languages_old() {
/* Added in V1.4.4 */
$all_languages = rp_get_all_languages();
$all_languages_name = array();
foreach ($all_languages as $lang_row) {
$all_languages_name[] = $lang_row->name;
}
return rp_get_option('rp_get_enabled_languages', $all_languages_name);
}
function rp_get_enabled_languages() {
/* REVISED in V1.5.0 */
$all_languages = rp_get_all_languages();
$enabled_languages_names = array();
$all_languages_name = array();
foreach ($all_languages as $lang_row) {
if( $lang_row->is_active == '1' ) {
$enabled_languages_names[] = $lang_row->name;
}
$all_languages_name[] = $lang_row->name;
}
if( !empty($enabled_languages_names) ) {
return $enabled_languages_names;
}
return $all_languages_name;
}
function rp_get_rows_of_enabled_languages() {
/* Added in V1.4.4 */
$enabled_languages = rp_get_enabled_languages();
global $rpQuery;
$table_rs_languages = $rpQuery->prefix . "rs_languages";
$where_in = array();
foreach ($enabled_languages as $lang_name) {
$where_in[] = rp_escape_sql( $lang_name );
}
$where_in_str = "'". join("', '", $where_in) . "'";
return $rpQuery->get_results("SELECT * FROM `$table_rs_languages` WHERE `name` IN ($where_in_str) ORDER BY position ASC;");
}
function rp_change_pre_selected_location() {
$id = $_POST['id'] ?? '';
$step_after_location = trim($_POST['step_after_location'] ?? '');
$step_after_location_data = $_POST['step_after_location_data'] ?? array();
$valid_step_after_location = array( 'types', 'brands', 'models', 'repairs' );
if( !in_array( $step_after_location, $valid_step_after_location ) ) {
$step_after_location = 'types';
}
if( !empty( $id ) ) {
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['rp_pre_selected_enhanced_location'] = $id;
$_POST['rp_pre_selected_location'] = $id;
RepairPluginPro\RP_Session_Handler::close();
}
$data = array();
if( $step_after_location == 'brands' && !empty( $step_after_location_data ) && is_array( $step_after_location_data ) ) {
$_POST['c_name'] = $step_after_location_data[0] ?? '';
$data = _rp_fe_get_brands();
} else if( $step_after_location == 'models' && !empty( $step_after_location_data ) && is_array( $step_after_location_data ) ) {
$_POST['c_name'] = $step_after_location_data[0] ?? '';
$_POST['b_name'] = $step_after_location_data[1] ?? '';
$data = _rp_fe_get_models();
} else if( $step_after_location == 'repairs' && !empty( $step_after_location_data ) && is_array( $step_after_location_data ) ) {
$_POST['c_name'] = $step_after_location_data[0] ?? '';
$_POST['b_name'] = $step_after_location_data[1] ?? '';
$_POST['m_name'] = $step_after_location_data[2] ?? '';
$data = _rp_fe_get_repairs();
} else {
$data = _rp_fe_get_categories();
}
global $rp_pre_selected_location;
$rp_pre_selected_location = $_SESSION['rp_pre_selected_enhanced_location'] ?? 0;
if( rp_is_enabled_location_selection_pdf() ) {
ob_start();
rp_el_location_markup('','',true);
$rp_el_location_markup = ob_get_clean();
} else {
$rp_el_location_markup = '';
}
$locationName = (rp_get_location_by_id( (int) ($_POST['id'] ?? 0) )->location_name ?? '');
echo json_encode( array( 'status' => true, 'message' => 'Location successfully selected!', 'data' => $data, 'html' => $rp_el_location_markup, 'selected_location_name' => rp_sanitize_output( $locationName ) ) );
exit;
}
rp_ajax_for_public('rp_change_pre_selected_location', 'rp_change_pre_selected_location');
function rp_change_frontend_language() {
$selected_language = $_POST['selected_language'] ?? '';
if( !empty( $selected_language ) ) {
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['rp_selected_language'] = $selected_language;
RepairPluginPro\RP_Session_Handler::close();
}
echo json_encode( array( 'status' => true, 'message' => 'Language successfully selected!' ) );
exit;
}
rp_ajax_for_public('rp_change_frontend_language', 'rp_change_frontend_language');
function rp_fix_addon_switch_settings_on_backend() {
RepairPluginPro\RP_Session_Handler::read();
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['rp_filter_is_active_enhanced_locations_addon'] = '1';
$_SESSION['rp_filter_is_enabled_dynamic_pricing'] = '1';
RepairPluginPro\RP_Session_Handler::close();
}
function rp_get_shortcode_page_link() {
global $rpQuery;
$shortcode_page = $rpQuery->get_results("SELECT * FROM {$rpQuery->posts} WHERE `post_type` = 'page' AND (`post_content` LIKE '%[Repair_All]%' OR `post_content` LIKE '%[Repair_All %') AND `post_status` = 'publish'");
if(!empty($shortcode_page)) {
return get_permalink($shortcode_page[0]->ID);
} else {
$shortcode_page_childs = $rpQuery->get_results("SELECT * FROM {$rpQuery->posts} WHERE `post_type` = 'revision' AND (`post_content` LIKE '%[Repair_All]%' OR `post_content` LIKE '%[Repair_All %') AND `post_status` = 'inherit'");
if(!empty($shortcode_page_childs)) {
$post_ids = array();
foreach ($shortcode_page_childs as $child) {
if(array_search($child->post_parent, $post_ids) === FALSE) {
$post_ids[] = $child->post_parent;
}
}
$post_ids_str = join(',', $post_ids);
$shortcode_page = $rpQuery->get_results("SELECT * FROM {$rpQuery->posts} WHERE `ID` IN (".rp_escape_sql($post_ids_str).") AND `post_type` = 'page' AND `post_status` = 'publish'");
if(!empty($shortcode_page)) {
return get_permalink($shortcode_page[0]->ID);
}
}
}
return '';
}
function rp_get_specific_shortcode_page_link( $m_uq_id = '' ) {
global $rpQuery;
$shortcode_page = $rpQuery->get_results("SELECT * FROM {$rpQuery->posts} WHERE `post_type` = 'page' AND (`post_content` LIKE '%[models code=$m_uq_id]%' OR ( `post_content` LIKE '%[models %' AND `post_content` LIKE '%code=$m_uq_id%' ) ) AND `post_status` = 'publish'");
if(!empty($shortcode_page)) {
return get_permalink($shortcode_page[0]->ID);
} else {
$shortcode_page_childs = $rpQuery->get_results("SELECT * FROM {$rpQuery->posts} WHERE `post_type` = 'revision' AND (`post_content` LIKE '%[models code=$m_uq_id]%' OR ( `post_content` LIKE '%[models %' AND `post_content` LIKE '%code=$m_uq_id%' ) ) AND `post_status` = 'inherit'");
if(!empty($shortcode_page_childs)) {
$post_ids = array();
foreach ($shortcode_page_childs as $child) {
if(array_search($child->post_parent, $post_ids) === FALSE) {
$post_ids[] = $child->post_parent;
}
}
$post_ids_str = join(',', $post_ids);
$shortcode_page = $rpQuery->get_results("SELECT * FROM {$rpQuery->posts} WHERE `ID` IN (".rp_escape_sql($post_ids_str).") AND `post_type` = 'page' AND `post_status` = 'publish'");
if(!empty($shortcode_page)) {
return get_permalink($shortcode_page[0]->ID);
}
}
}
return '';
}
function rp_get_por_repairs_by_order_id( $order_id = '' ) {
/* Added in V1.4.4 */
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$rs_order_repairs = $rpQuery->prefix . 'rs_order_repairs';
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
$rs_repair = $rpQuery->prefix . 'rs_repair';
$order_repairs = $rpQuery->get_results("SELECT * FROM `$rs_order_repairs` WHERE `o_id_fk` = '{$order_id}';");
if( !empty( $order_repairs ) ) {
$r_id_fk = array();
foreach( $order_repairs as $row ) {
$repair_attrs = $rpQuery->get_results("SELECT * FROM `$rs_order_repair_attr` WHERE `o_id_fk` = '{$order_id}' AND `r_id_fk` = '".rp_escape_sql($row->r_id_fk)."';");
if( empty( $repair_attrs ) && ((float) $row->repair_price) <= 0 ) {
$r_id_fk[] = $row->r_id_fk;
}
}
if( !empty( $r_id_fk ) ) {
$r_id_fk = join(',', $r_id_fk);
$price_on_request = $rpQuery->get_results("SELECT * FROM `$rs_repair` WHERE `r_id` IN ({$r_id_fk});");
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
$order_row = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '".rp_escape_sql( $order_id )."' LIMIT 1;");
$price_on_request = $rpQuery->get_results("SELECT * FROM `$rs_repair` WHERE `r_id` IN ({$r_id_fk});");
if( !empty( $order_row ) && !empty( $price_on_request ) ) {
$selected_location_id = $order_row->location_id_fk;
foreach( $price_on_request as $por_key => $por_row ) {
$por_row = apply_filters('rp_overwrite_individual_repair_row', $por_row, $selected_location_id);
if( (float) $por_row->r_price > 0 || $por_row->is_free == '1' ) {
unset( $price_on_request[$por_key] );
}
$price_on_request[$por_key] = $por_row;
}
}
} else {
$price_on_request = $rpQuery->get_results("SELECT * FROM `$rs_repair` WHERE `r_id` IN ({$r_id_fk}) AND `r_price` = '0' AND `is_free` != '1';");
}
return apply_filters('returning_por_repairs', $price_on_request, $order_id);
}
}
return apply_filters('returning_por_repairs', array(), $order_id);
}
function rp_check_is_por_repair( $needle = '', $haystack = array() ) {
if(empty($haystack)) {
return FALSE;
}
/* Added in V1.4.4 */
foreach( $haystack as $row ) {
if( ((int) $row->r_id) === ((int) $needle) ) {
return TRUE;
}
}
return FALSE;
}
function rp_get_por_repair_attr_by_order_id( $order_id = '' ) {
/* Added in V1.4.4 */
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$order_repairs = $rpQuery->get_results("SELECT * FROM `$rs_order_repair_attr` WHERE `o_id_fk` = '{$order_id}';");
if( !empty( $order_repairs ) ) {
$ra_id_fk = array();
foreach( $order_repairs as $row ) {
if( ((float) $row->repair_attr_price) <= 0 ) {
$ra_id_fk[] = $row->ra_id_fk;
}
}
if( !empty( $ra_id_fk ) ) {
$ra_id_fk = join(',', $ra_id_fk);
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
$order_row = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '".rp_escape_sql( $order_id )."' LIMIT 1;");
$price_on_request = $rpQuery->get_results("SELECT * FROM `$rs_repair_attr` WHERE `a_id` IN ({$ra_id_fk});");
if( !empty( $order_row ) && !empty( $price_on_request ) ) {
$selected_location_id = $order_row->location_id_fk;
foreach( $price_on_request as $por_key => $por_row ) {
$por_row = apply_filters('rp_overwrite_individual_repair_attr_row', $por_row, $selected_location_id);
if( (float) $por_row->a_price > 0 ) {
unset( $price_on_request[$por_key] );
}
$price_on_request[$por_key] = $por_row;
}
}
} else {
$price_on_request = $rpQuery->get_results("SELECT * FROM `$rs_repair_attr` WHERE `a_id` IN ({$ra_id_fk}) AND `a_price` = '0';");
}
return apply_filters('returning_por_repair_attrs', $price_on_request, $order_id);
}
}
return apply_filters('returning_por_repair_attrs', array(), $order_id);
}
function rp_check_is_por_repair_attr( $needle = '', $haystack = array() ) {
if(empty($haystack)) {
return FALSE;
}
/* Added in V1.4.4 */
foreach( $haystack as $row ) {
if( ((int) $row->a_id) === ((int) $needle) ) {
return TRUE;
}
}
return FALSE;
}
function rp_get_dynamic_pricing_por_repair_attr( $o_id = '' ) {
global $rpQuery;
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
// select * where o_id_fk = $o_id
$repair_attrs = $rpQuery->get_results("SELECT * FROM `$rs_order_repair_attr` WHERE `o_id_fk` = '{$o_id}';");
$a_ids = array();
if( !empty( $repair_attrs ) ) {
foreach( $repair_attrs as $attrRow ) {
if( property_exists( $attrRow, 'pricing_method' ) && $attrRow->pricing_method === 'price_on_request' ) {
$a_ids[] = $attrRow->ra_id_fk;
}
}
}
return $a_ids;
}
function rp_get_dynamic_pricing_por_repairs( $o_id = '' ) {
global $rpQuery;
$rs_order_repairs = $rpQuery->prefix . 'rs_order_repairs';
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
// select * where o_id_fk = $o_id
$order_repairs = $rpQuery->get_results("SELECT * FROM `$rs_order_repairs` WHERE `o_id_fk` = '{$o_id}';");
$r_ids = array();
if( !empty( $order_repairs ) ) {
// loop through all order repairs and check if $order_repairs->r_id_fk AND $o_id matches in rs_order_repair_attr
foreach( $order_repairs as $oRepairRow ) {
// select * where o_id_fk = $o_id AND r_id_fk = $order_repairs->r_id_fk
$repair_attrs = $rpQuery->get_results("SELECT * FROM `$rs_order_repair_attr` WHERE `o_id_fk` = '{$o_id}' AND `r_id_fk` = '".rp_escape_sql($oRepairRow->r_id_fk)."';");
if( empty( $repair_attrs ) ) {
if( property_exists( $oRepairRow, 'pricing_method' ) && $oRepairRow->pricing_method === 'price_on_request' ) {
$r_ids[] = $oRepairRow->r_id_fk;
}
}
}
}
return $r_ids;
}
function rp_update_por_repairs_price() {
rp_verify_csrf_token_for_ajax('appointments');
/* Added in V1.4.4 */
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$rs_order_repairs = $rpQuery->prefix . 'rs_order_repairs';
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
$rs_repair = $rpQuery->prefix . 'rs_repair';
$oid = $_POST['appointment_id'] ?? '';
$where_to_set = $_POST['where_to_set'] ?? '';
if( $where_to_set != 'current' ) {
$where_to_set = 'globally';
}
$all_rids = $_POST['rid'] ?? array();
$all_aids = $_POST['aid'] ?? array();
$r_price = $_POST['r_price'] ?? array();
$exists_order_row = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '".rp_escape_sql( $oid )."' LIMIT 1;");
if( empty( $exists_order_row ) ) {
echo json_encode( array( 'error' => true ) );
exit;
}
$_POST['selected_location_id'] = rp_get_location_id_of_order( $exists_order_row->o_id );
rp_verify_selected_location_id_by_location_head();
$enabled_price_based_on_location = rp_is_enabled_pricing_based_on_location();
$order_location_id = $exists_order_row->location_id_fk ?? 0;
if( !empty( $oid ) && !empty( $all_rids ) && !empty( $all_aids ) && !empty( $r_price ) && is_array( $all_rids ) && is_array( $r_price ) && count( $all_rids ) > 0 && count($all_rids) === count( $r_price ) ) {
$appointment_por_repairs = rp_get_por_repairs_by_order_id( $oid );
$appointment_por_repair_attrs = rp_get_por_repair_attr_by_order_id( $oid );
$dynamic_pricing_por_repairs = rp_get_dynamic_pricing_por_repairs( $oid );
$dynamic_pricing_por_repair_attr = rp_get_dynamic_pricing_por_repair_attr( $oid );
$affected_orders = array();
foreach( $all_rids as $index => $rid ) {
if( !empty( $all_aids[ $index ] ) ) {
// Is repair attribute
continue;
}
$the_price = $r_price[ $index ];
if( preg_match('/,/', $the_price) ) {
$the_price = str_replace(',', '.', $the_price);
}
$order_ids = array();
if( rp_check_is_por_repair( $rid, $appointment_por_repairs ) ) {
$order_ids[] = $oid;
if( !in_array( $rid, $dynamic_pricing_por_repairs ) ) {
$current_less_7_days = date('Y-m-d H:i:s', strtotime( date('Y-m-d H:i:s') . ' -7 days' ));
$location_where_str = "";
if( $enabled_price_based_on_location == TRUE ) {
$location_where_str = " AND rs_o.location_id_fk = '".rp_escape_sql( $order_location_id )."' ";
}
$related_rows = $rpQuery->get_results("SELECT rs_o.o_id FROM `$rs_order_repairs` AS rs_or JOIN `$rs_orders` AS rs_o ON rs_or.o_id_fk = rs_o.o_id WHERE rs_or.r_id_fk = '$rid' AND rs_o.o_date_time >= '$current_less_7_days' AND rs_or.repair_price = '0' $location_where_str;");
if( !empty( $related_rows ) ) {
foreach( $related_rows as $r_row ) {
if( array_search( $r_row->o_id, $order_ids ) === FALSE ) {
$order_ids[] = $r_row->o_id;
}
}
}
}
}
if( !empty( $order_ids ) ) {
if( $where_to_set == 'current' ) {
$order_ids = array( $oid );
}
$order_ids_str = join(',', $order_ids);
if( !in_array( $rid, $dynamic_pricing_por_repairs ) ) {
if( $where_to_set == 'globally' ) {
if( $enabled_price_based_on_location == TRUE ) {
// Update based on location
rp_update_individual_repair_price_only_based_on_loc( $rid, $order_location_id, $the_price );
} else {
// Update Model Related Price
$rpQuery->query("UPDATE `$rs_repair` SET `r_price` = '{$the_price}' WHERE `r_id` = '$rid';");
}
}
}
// Update Locked Prices
$rpQuery->query("UPDATE `$rs_order_repairs` SET `repair_price` = '{$the_price}' WHERE `r_id_fk` = '$rid' AND `o_id_fk` IN ({$order_ids_str})");
foreach( $order_ids as $_o_id ) {
if( array_search( $_o_id, $affected_orders ) === FALSE ) {
$affected_orders[] = $_o_id;
}
}
}
}
foreach( $all_aids as $index => $a_id ) {
if( empty( $a_id ) ) {
continue;
}
$the_price = $r_price[ $index ];
if( preg_match('/,/', $the_price) ) {
$the_price = str_replace(',', '.', $the_price);
}
$order_ids = array();
if( rp_check_is_por_repair_attr( $a_id, $appointment_por_repair_attrs ) ) {
$order_ids[] = $oid;
if( !in_array( $a_id, $dynamic_pricing_por_repair_attr ) ) {
$current_less_7_days = date('Y-m-d H:i:s', strtotime( date('Y-m-d H:i:s') . ' -7 days' ));
$location_where_str = "";
if( $enabled_price_based_on_location == TRUE ) {
$location_where_str = " AND rs_o.location_id_fk = '".rp_escape_sql( $order_location_id )."' ";
}
$related_rows = $rpQuery->get_results("SELECT rs_o.o_id FROM `$rs_order_repair_attr` AS rs_or JOIN `$rs_orders` AS rs_o ON rs_or.o_id_fk = rs_o.o_id WHERE rs_or.ra_id_fk = '$a_id' AND rs_o.o_date_time >= '$current_less_7_days' AND rs_or.repair_attr_price = '0' $location_where_str;");
if( !empty( $related_rows ) ) {
foreach( $related_rows as $r_row ) {
if( array_search( $r_row->o_id, $order_ids ) === FALSE ) {
$order_ids[] = $r_row->o_id;
}
}
}
}
}
if( !empty( $order_ids ) ) {
if( $where_to_set == 'current' ) {
$order_ids = array( $oid );
}
$order_ids_str = join(',', $order_ids);
if( !in_array( $a_id, $dynamic_pricing_por_repair_attr ) ) {
if( $where_to_set == 'globally' ) {
if( $enabled_price_based_on_location == TRUE ) {
// Update based on location
rp_update_individual_repair_attr_price_only_based_on_loc( $a_id, $order_location_id, $the_price );
} else {
// Update Model Related Price
$rpQuery->query("UPDATE `$rs_repair_attr` SET `a_price` = '{$the_price}' WHERE `a_id` = '$a_id';");
}
}
}
// Update Locked Prices
$rpQuery->query("UPDATE `$rs_order_repair_attr` SET `repair_attr_price` = '{$the_price}' WHERE `ra_id_fk` = '$a_id' AND `o_id_fk` IN ({$order_ids_str})");
foreach( $order_ids as $_o_id ) {
if( array_search( $_o_id, $affected_orders ) === FALSE ) {
$affected_orders[] = $_o_id;
}
}
}
}
foreach( $affected_orders as $order_id ) {
rp_calculate_and_set_appointment_total( $order_id );
// Only send email if there is no price on request
// repair left!
if( empty( rp_get_por_repairs_by_order_id( $order_id ) ) && empty( rp_get_por_repair_attr_by_order_id( $order_id ) ) ) {
rp_set_appointment_status_after_setting_price( $order_id );
rp_send_appointment_status_update_email( $order_id );
}
}
echo json_encode( array( 'success' => true ) );
exit;
}
echo json_encode( array( 'error' => true ) );
exit;
}
function rp_set_appointment_status_after_setting_price( $order_id = 0 ) {
global $rpQuery;
// get order row
$rs_orders = $rpQuery->prefix . 'rs_orders';
$row = $rpQuery->get_row("SELECT * FROM $rs_orders WHERE o_id = '".rp_escape_sql($order_id)."' LIMIT 1");
if( empty( $row ) ) {
return;
}
$status_id_fk = $row->status_id_fk;
$order_delivery_method = rp_find_delivery_method_of_order( $order_id );
if( $status_id_fk != 4 ) {
// If status is not cancelled..
if( !empty( $order_delivery_method ) && $order_delivery_method != 'ship device' && $order_delivery_method != 'pdf offer' ) {
rp_trigger_outgoing_webhook( 'scheduled_appointment_updated', $order_id );
} else if( !empty( $order_delivery_method ) && $order_delivery_method == 'ship device' ) {
rp_trigger_outgoing_webhook( 'ship_device_appointment_updated', $order_id );
} else if( !empty( $order_delivery_method ) && $order_delivery_method == 'pdf offer' ) {
rp_trigger_outgoing_webhook( 'pdf_offer_updated', $order_id );
} else {
// Do nothing!
}
}
if( $status_id_fk != 5 ) {
// It is not price on request, so no need to worry
return;
}
if( $order_delivery_method == 'pdf offer' ) {
// Set status to Offered/Quoted
$rpQuery->query("UPDATE $rs_orders SET status_id_fk = '2' WHERE o_id = '".rp_escape_sql($order_id)."' LIMIT 1");
} else {
$auto_approve = rp_get_auto_approve_booking_value( $row->delivery_method ?? '' );
if( $auto_approve == '1' ){
$new_status = '3'; // Approved Status
} else{
$new_status = '1'; // Pending Status
}
// Set status to $new_status (Pending / Approved)
$rpQuery->query("UPDATE $rs_orders SET status_id_fk = '$new_status' WHERE o_id = '".rp_escape_sql($order_id)."' LIMIT 1");
}
}
function rp_get_latest_order_calculations( $order_id = '' ) {
/* Added in V1.4.4 */
global $rpQuery;
$rpCart = new RepairPluginPro\RP_Cart_Recalc( $order_id );
$rs_orders = $rpQuery->prefix . 'rs_orders';
$rs_order_repairs = $rpQuery->prefix . 'rs_order_repairs';
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
$rs_order_upsales = $rpQuery->prefix . 'rs_order_upsales';
$rows = $rpQuery->get_results("SELECT r_id_fk FROM `$rs_order_repairs` WHERE `o_id_fk` = '$order_id';");
if( !empty( $rows ) ) {
foreach( $rows as $row ) {
$rpCart->add_repair( $row->r_id_fk );
}
}
$rows = $rpQuery->get_results("SELECT ra_id_fk FROM `$rs_order_repair_attr` WHERE `o_id_fk` = '$order_id';");
if( !empty( $rows ) ) {
foreach( $rows as $row ) {
$rpCart->add_repair_attr( $row->ra_id_fk );
}
}
$rows = $rpQuery->get_results("SELECT upsales_id_fk FROM `$rs_order_upsales` WHERE `o_id_fk` = '$order_id';");
if( !empty( $rows ) ) {
foreach( $rows as $row ) {
$rpCart->add_upsale( $row->upsales_id_fk );
}
}
$row = $rpQuery->get_row("SELECT `delivery_method`, `dm_cost` FROM `$rs_orders` WHERE o_id = '$order_id' LIMIT 1;");
if( !empty( $row ) ) {
if( empty( $row->delivery_method ) || strtolower(trim(str_replace(' ', '_', $row->delivery_method))) == 'pdf_offer' ) {
$dm_cost = 0;
if( !empty( $_POST['selected_dm_id'] ?? '' ) ) {
$rpCart->add_delivery_method( $_POST['selected_dm_id'], 0, TRUE );
$dm_cost = (float) $rpCart->delivery_method_cost();
}
} else {
$dm_cost = (float) ($row->dm_cost ?? 0);
$rpCart->add_delivery_method( $row->delivery_method, $dm_cost );
}
}
$row = $rpQuery->get_row("SELECT `delivery_method`, `priority_cost_info` FROM `$rs_orders` WHERE o_id = '$order_id' LIMIT 1;");
if( !empty( $row ) ) {
if( empty( $row->delivery_method ) || strtolower(trim(str_replace(' ', '_', $row->delivery_method))) == 'pdf_offer' ) {
if( !empty( $_REQUEST['rp_overwrite_priority_box'] ?? '' ) ) {
$rpCart->add_priority_box_overwrite( $_REQUEST['rp_overwrite_priority_box'] );
}
} else {
$rpCart->add_priority_box();
}
}
if( !isset( $_GET['payment_cancel'] ) ) {
if( isset( $_REQUEST['rp_overwrite_payment_method'] ) ) {
$rpCart->add_payment_method_overwrite( $_REQUEST['rp_overwrite_payment_method'] );
} else {
$rpCart->add_payment_method();
}
}
$row = $rpQuery->get_row("SELECT coupon_id_fk FROM `$rs_orders` WHERE o_id = '$order_id' LIMIT 1;");
if( !empty( $row ) ) {
$rpCart->add_coupon( $row->coupon_id_fk );
}
return array( $rpCart, $rpCart->calculate() );
}
function rp_calculate_and_set_appointment_total( $order_id = '' ) {
_rp_set_default_tiemzone();
/* Added in V1.4.4 */
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$old_row = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '$order_id' LIMIT 1;");
list( $rpCart, $calculations ) = rp_get_latest_order_calculations( $order_id );
$combo = $calculations['combo_discount'];
$coupon_amount = $calculations['coupon_amount'];
$final_price = $calculations['total'];
$sub_total = $calculations['sub_total'];
$last_edited = date('Y-m-d H:i:s');
$rpQuery->query("UPDATE `$rs_orders` SET `excluded_tax_price` = '$sub_total', `coupon_amount` = '$coupon_amount', `combo_discount` = '$combo', `total_price` = '$final_price', `last_edited` = '".rp_escape_sql($last_edited)."' WHERE `o_id` = '$order_id';");
$old_row_total = round( (float) ($old_row->total_price ?? 0), 2 );
$new_row_total = round( (float) $final_price, 2 );
if( $old_row_total != $new_row_total ) {
// update price_edited
$rpQuery->query("UPDATE `$rs_orders` SET `price_edited` = 1 WHERE `o_id` = '$order_id';");
}
}
rp_ajax_for_admin('rp_update_por_repairs_price', 'rp_update_por_repairs_price');
function rp_get_locked_repair_price( $order_id = '', $r_id = '' ) {
if( empty( $order_id ) || empty( $r_id ) ) {
return NULL;
}
global $rpQuery;
$rs_order_repairs = $rpQuery->prefix . 'rs_order_repairs';
$row = $rpQuery->get_row("SELECT * FROM `$rs_order_repairs` WHERE `o_id_fk` = '$order_id' AND `r_id_fk` = '$r_id' LIMIT 1;");
if( !empty( $row ) ) {
return $row->repair_price;
}
return NULL;
}
function rp_get_locked_repair_attr_price( $order_id = '', $r_id = '', $a_id = '' ) {
if( empty( $order_id ) || empty( $r_id ) || empty( $a_id ) ) {
return NULL;
}
global $rpQuery;
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
$row = $rpQuery->get_row("SELECT * FROM `$rs_order_repair_attr` WHERE `o_id_fk` = '$order_id' AND `r_id_fk` = '$r_id' AND `ra_id_fk` = '$a_id' LIMIT 1;");
if( !empty( $row ) ) {
return $row->repair_attr_price;
}
return NULL;
}
function rp_get_locked_upsale_price( $order_id = '', $u_id = '' ) {
if( empty( $order_id ) || empty( $u_id ) ) {
return NULL;
}
global $rpQuery;
$rs_order_upsales = $rpQuery->prefix . 'rs_order_upsales';
$row = $rpQuery->get_row("SELECT * FROM `$rs_order_upsales` WHERE `o_id_fk` = '$order_id' AND `upsales_id_fk` = '$u_id' LIMIT 1;");
if( !empty( $row ) ) {
return $row->upsale_price;
}
return NULL;
}
// add 'Price On Request' in noti_type column of rs_notification_types table
function add_price_on_request_in_rs_notification_types() {
/* Added in V1.4.4 */
global $rpQuery;
$rs_notification_types = $rpQuery->prefix . 'rs_notification_types';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notification_types` WHERE `noti_type` = 'Price On Request' LIMIT 1;");
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notification_types` (`noti_type`, `is_active`) VALUES ('Price On Request', '1');");
}
}
rp_add_action('init', 'add_price_on_request_in_rs_notification_types', 999);
// insert into all columns from rs_notifications_and_offers table if noti_type_id_fk 5 doesn't exist
function insert_por_markup_in_rs_notifications_and_offers() {
/* Added in V1.4.4 */
global $rpQuery;
$rs_notifications_and_offers = $rpQuery->prefix . 'rs_notifications_and_offers';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notifications_and_offers` WHERE `noti_type_id_fk` = '5' LIMIT 1;");
$subject = 'Bedankt voor het aanvragen van een prijs voor uw $Model$';
$message = '<p>Geachte $CustomerName$,</p> <p>Bedankt voor het aanvragen van een prijs voor uw $Model$. Wij waarderen uw belangstelling voor ons bedrijf.</p> <p>Wij zullen u binnen 2 uur op dezelfde werkdag antwoord geven met een offerte. Mocht u intussen nog vragen hebben of meer informatie nodig hebben, aarzel dan niet om contact met ons op te nemen.</p> <p>Nogmaals bedankt voor uw aanvraag. Wij kijken ernaar uit om u te helpen de problemen op te lossen.</p> <p>Met vriendelijke groet, $ShopName$</p>';
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notifications_and_offers` (`noti_subject`, `noti_message`, `noti_type_id_fk`, `is_active`, `date_time`) VALUES ('$subject', '$message', '5', '1', '".date('Y-m-d H:i:s')."');");
}
}
rp_add_action('init', 'insert_por_markup_in_rs_notifications_and_offers', 999);
/*
Add parent_order column to rs_user_pdfs table
*/
function rp_get_parent_order_id( $o_id = 0 ) {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$o_id = (int) $o_id;
$row = $rpQuery->get_row("SELECT parent_order FROM $rs_orders WHERE o_id = {$o_id}");
if( !empty( $row ) ) {
return $row->parent_order ?? 0;
}
return 0;
}
function rp_set_parent_order_id_on_order( $o_id = 0, $parent_order = 0 ) {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$o_id = (int) $o_id;
$parent_order = (int) $parent_order;
$rpQuery->query("UPDATE $rs_orders SET parent_order = {$parent_order} WHERE o_id = {$o_id} LIMIT 1;");
}
/*
Get cancel_link by order id from rs_orders table
*/
function rp_get_cancel_link_by_order_id( $order_id = '' ) {
if( empty( $order_id ) ) {
return NULL;
}
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$row = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '$order_id' LIMIT 1;");
if( !empty( $row ) ) {
return $row->cancel_link . '/';
}
return NULL;
}
/*
Save cancel_link by order id in rs_orders table
*/
function rp_save_cancel_link_by_order_id( $order_id = '', $cancel_link = '' ) {
if( empty( $order_id ) || empty( $cancel_link ) ) {
return NULL;
}
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$rpQuery->query("UPDATE `$rs_orders` SET `cancel_link` = '".rp_escape_sql($cancel_link)."' WHERE `o_id` = '$order_id';");
}
/* RepairPlugin Get selected currency with backward compatibility */
function rp_get_selected_currency_letters() {
$selected_currency = rp_get_selected_currency();
return strtoupper( trim( explode( ' ', $selected_currency )[1] ?? '' ) );
}
function rp_get_plugin_decimal_separator() {
global $rpQuery;
$localization = $rpQuery->prefix . "rs_localization";
$row = $rpQuery->get_row("SELECT * FROM $localization");
if( !empty( $row ) ) {
return ( $row->set_decimals ?? '' );
}
return 'comma';
}
function rp_get_selected_currency_symbol() {
global $rpQuery;
$localization = $rpQuery->prefix . "rs_localization";
$row = $rpQuery->get_row("SELECT * FROM $localization");
if( !empty( $row ) ) {
return ( $row->set_currency ?? '' );
}
return '';
}
function rp_get_selected_currency() {
/* Added in v1.5.0 */
$currency = rp_get_option('rp_localization_selected_currency', NULL);
if( empty( $currency ) ) {
global $rpQuery;
$localization = $rpQuery->prefix . "rs_localization";
$row = $rpQuery->get_row("SELECT * FROM $localization");
if( !empty( $row ) ) {
$symbol = $row->set_currency;
if( $symbol === '$' ) {
$currency = '$ USD (United States Dollar)';
} else if( $symbol === '£' ) {
$currency = '£ GBP (United Kingdom Pound)';
} else {
$currency = '€ EUR (Euro Member Countries)';
}
} else {
$currency = '€ EUR (Euro Member Countries)';
}
}
return $currency;
}
/* RepairPlugin Available Currencies */
function rp_get_all_currencies() {
/* Added in v1.5.0 */
$currencies = array(
'Lek ALL (Albania Lek)' => 'Lek',
'؋ AFN (Afghanistan Afghani)' => '؋',
'$ ARS (Argentina Peso)' => '$',
'ƒ AWG (Aruba Guilder)' => 'ƒ',
'$ AUD (Australia Dollar)' => '$',
'₼ AZN (Azerbaijan Manat)' => '₼',
'$ BSD (Bahamas Dollar)' => '$',
'$ BBD (Barbados Dollar)' => '$',
'Br BYN (Belarus Ruble)' => 'Br',
'BZ$ BZD (Belize Dollar)' => 'BZ$',
'$ BMD (Bermuda Dollar)' => '$',
'$b BOB (Bolivia Bolíviano)' => '$b',
'KM BAM (Bosnia and Herzegovina Convertible Mark)' => 'KM',
'P BWP (Botswana Pula)' => 'P',
'лв BGN (Bulgaria Lev)' => 'лв',
'R$ BRL (Brazil Real)' => 'R$',
'$ BND (Brunei Darussalam Dollar)' => '$',
'៛ KHR (Cambodia Riel)' => '៛',
'$ CAD (Canada Dollar)' => '$',
'$ KYD (Cayman Islands Dollar)' => '$',
'$ CLP (Chile Peso)' => '$',
'¥ CNY (China Yuan Renminbi)' => '¥',
'$ COP (Colombia Peso)' => '$',
'₡ CRC (Costa Rica Colon)' => '₡',
'kn HRK (Croatia Kuna)' => 'kn',
'₱ CUP (Cuba Peso)' => '₱',
'Kč CZK (Czech Republic Koruna)' => 'Kč',
'kr DKK (Denmark Krone)' => 'kr',
'RD$ DOP (Dominican Republic Peso)' => 'RD$',
'$ XCD (East Caribbean Dollar)' => '$',
'£ EGP (Egypt Pound)' => '£',
'$ SVC (El Salvador Colon)' => '$',
'€ EUR (Euro Member Countries)' => '€',
'£ FKP (Falkland Islands (Malvinas) Pound)' => '£',
'$ FJD (Fiji Dollar)' => '$',
'¢ GHS (Ghana Cedi)' => '¢',
'£ GIP (Gibraltar Pound)' => '£',
'Q GTQ (Guatemala Quetzal)' => 'Q',
'£ GGP (Guernsey Pound)' => '£',
'$ GYD (Guyana Dollar)' => '$',
'L HNL (Honduras Lempira)' => 'L',
'$ HKD (Hong Kong Dollar)' => '$',
'Ft HUF (Hungary Forint)' => 'Ft',
'kr ISK (Iceland Krona)' => 'kr',
'₹ INR (India Rupee)' => '₹',
'Rp IDR (Indonesia Rupiah)' => 'Rp',
'ریال IRR (Iran Rial)' => 'ریال',
'£ IMP (Isle of Man Pound)' => '£',
'₪ ILS (Israel Shekel)' => '₪',
'J$ JMD (Jamaica Dollar)' => 'J$',
'¥ JPY (Japan Yen)' => '¥',
'£ JEP (Jersey Pound)' => '£',
'лв KZT (Kazakhstan Tenge)' => 'лв',
'₩ KPW (Korea (North) Won)' => '₩',
'₩ KRW (Korea (South) Won)' => '₩',
'лв KGS (Kyrgyzstan Som)' => 'лв',
'₭ LAK (Laos Kip)' => '₭',
'£ LBP (Lebanon Pound)' => '£',
'$ LRD (Liberia Dollar)' => '$',
'ден MKD (Macedonia Denar)' => 'ден',
'RM MYR (Malaysia Ringgit)' => 'RM',
'₨ MUR (Mauritius Rupee)' => '₨',
'$ MXN (Mexico Peso)' => '$',
'₮ MNT (Mongolia Tughrik)' => '₮',
'د.إ MNT (Moroccan-dirham)' => 'د.إ',
'MT MZN (Mozambique Metical)' => 'MT',
'$ NAD (Namibia Dollar)' => '$',
'₨ NPR (Nepal Rupee)' => '₨',
'ƒ ANG (Netherlands Antilles Guilder)' => 'ƒ',
'$ NZD (New Zealand Dollar)' => '$',
'C$ NIO (Nicaragua Cordoba)' => 'C$',
'₦ NGN (Nigeria Naira)' => '₦',
'kr NOK (Norway Krone)' => 'kr',
'ریال OMR (Oman Rial)' => 'ریال',
'₨ PKR (Pakistan Rupee)' => '₨',
'B/. PAB (Panama Balboa)' => 'B/.',
'Gs PYG (Paraguay Guarani)' => 'Gs',
'S/. PEN (Peru Sol)' => 'S/.',
'₱ PHP (Philippines Peso)' => '₱',
'zł PLN (Poland Zloty)' => 'zł',
'ریال QAR (Qatar Riyal)' => 'ریال',
'lei RON (Romania Leu)' => 'lei',
'₽ RUB (Russia Ruble)' => '₽',
'£ SHP (Saint Helena Pound)' => '£',
'ریال SAR (Saudi Arabia Riyal)' => 'ریال',
'Дин. RSD (Serbia Dinar)' => 'Дин.',
'₨ SCR (Seychelles Rupee)' => '₨',
'$ SGD (Singapore Dollar)' => '$',
'$ SBD (Solomon Islands Dollar)' => '$',
'S SOS (Somalia Shilling)' => 'S',
'₩ KRW (South Korean Won)' => '₩',
'R ZAR (South Africa Rand)' => 'R',
'₨ LKR (Sri Lanka Rupee)' => '₨',
'kr SEK (Sweden Krona)' => 'kr',
'CHF CHF (Switzerland Franc)' => 'CHF',
'$ SRD (Suriname Dollar)' => '$',
'£ SYP (Syria Pound)' => '£',
'NT$ TWD (Taiwan New Dollar)' => 'NT$',
'฿ THB (Thailand Baht)' => '฿',
'TT$ TTD (Trinidad and Tobago Dollar)' => 'TT$',
'₺ TRY (Turkey Lira)' => '₺',
'$ TVD (Tuvalu Dollar)' => '$',
'₴ UAH (Ukraine Hryvnia)' => '₴',
'د.إ AED (UAE-Dirham)' => 'د.إ',
'£ GBP (United Kingdom Pound)' => '£',
'$ USD (United States Dollar)' => '$',
'$U UYU (Uruguay Peso)' => '$U',
'лв UZS (Uzbekistan Som)' => 'лв',
'Bs VEF (Venezuela Bolívar)' => 'Bs',
'₫ VND (Viet Nam Dong)' => '₫',
'ریال YER (Yemen Rial)' => 'ریال',
'Z$ ZWD (Zimbabwe Dollar)' => 'Z$',
);
return $currencies;
}
// Update is_active column of rs_languages table based on enabled languages
function rp_update_is_active_based_on_enabled_languages() {
/* Added in V1.5.0 */
global $rpQuery;
$rs_languages = $rpQuery->prefix . 'rs_languages';
$rp_enabled_languages = rp_get_enabled_languages_old();
$rp_languages = rp_get_all_languages();
foreach ($rp_languages as $row) {
if(array_search($row->name, $rp_enabled_languages) !== FALSE) {
$rpQuery->query("UPDATE `$rs_languages` SET `is_active` = '1' WHERE `name` = '".rp_escape_sql($row->name)."'");
} else {
$rpQuery->query("UPDATE `$rs_languages` SET `is_active` = '0' WHERE `name` = '".rp_escape_sql($row->name)."'");
}
}
}
function rp_fix_language_image( $link = '' ) {
if( empty( $link ) ) {
return WP_REPAIR_PLUGIN_URL . 'assets/images/circle-64.png';
}
/* Added in v1.5.0 for Backward Compatibility */
if( strpos($link, 'assets') === 0 ) {
return WP_REPAIR_PLUGIN_URL . $link;
} else {
return $link;
}
}
function rp_update_default_language( $new = '' ) {
/* Added in V1.5.0 */
global $rpQuery;
$localization = $rpQuery->prefix . "rs_localization";
$result = $rpQuery->get_row("SELECT * FROM $localization LIMIT 1;");
if( !empty( $result ) ) {
// update set_language column where localization_id matches $result->localization_id
$rpQuery->query("UPDATE `$localization` SET `set_language` = '".rp_escape_sql($new)."' WHERE `localization_id` = '".rp_escape_sql($result->localization_id)."' LIMIT 1;");
}
}
function rp_get_default_language() {
/* Added in V1.5.0 */
global $rpQuery;
$localization = $rpQuery->prefix . "rs_localization";
$result = $rpQuery->get_row("SELECT * FROM $localization LIMIT 1;");
return trim($result->set_language);
}
function rp_get_language_row_by_id( $id = '' ) {
/* Added in V1.5.0 */
global $rpQuery;
$table_rs_languages = $rpQuery->prefix . "rs_languages";
if( !empty( $id ) ) {
$row = $rpQuery->get_row("SELECT * FROM `$table_rs_languages` WHERE `id` = '".rp_escape_sql($id)."' LIMIT 1;");
if( !empty($row) ) {
return $row;
}
}
return array();
}
function rp_get_default_language_id() {
/* Added in V1.5.0 */
global $rpQuery;
$default_language = rp_get_default_language();
$table_rs_languages = $rpQuery->prefix . "rs_languages";
if( !empty( $default_language ) ) {
$row = $rpQuery->get_row("SELECT id FROM `$table_rs_languages` WHERE `name` = '".rp_escape_sql($default_language)."' LIMIT 1;");
if( !empty($row) ) {
return $row->id;
}
}
return 0;
}
function rp_delete_language() {
rp_verify_csrf_token_for_ajax('localization');
(new RepairPluginPro\RP_Languages())->rp_delete_language();
}
rp_ajax_for_admin('rp_delete_language', 'rp_delete_language');
function rp_update_language_image() {
rp_verify_csrf_token_for_ajax('localization');
(new RepairPluginPro\RP_Languages())->rp_update_language_image();
}
rp_ajax_for_admin('rp_update_language_image', 'rp_update_language_image');
function rp_update_languages() {
rp_verify_csrf_token_for_ajax('localization');
rp_block_more_actions_when_processing_pending_jobs();
(new RepairPluginPro\RP_Languages())->rp_update_languages();
}
rp_ajax_for_admin('rp_update_languages', 'rp_update_languages');
/*
check if have any pending background jobs
*/
function rp_get_pending_background_jobs() {
/* Added in V1.5.9 */
global $rpQuery;
$table_rs_background_jobs = $rpQuery->prefix . "rs_background_jobs";
$row = $rpQuery->get_row("SELECT * FROM `$table_rs_background_jobs` WHERE `processed` = 0 ORDER BY `id` ASC LIMIT 1;");
if( !empty($row) ) {
return TRUE;
}
return FALSE;
}
function rp_need_to_add_tables_count( $callback = '' ) {
$add_tables_count_callbacks = array('rp_add_this_default_repair_to_all_models', 'rp_add_this_new_default_repair_attr_to_all_models', 'rp_process_colors_and_repair_for_model', 'rp_process_colors_and_repair_for_model_enhanced', 'rp_add_this_new_default_repair_attr_to_all_models_without_check', 'rp_handle_need_to_add_colors_insert_queries', 'rp_handle_need_to_add_repairs_insert_queries');
return !empty($callback) && in_array($callback, $add_tables_count_callbacks);
}
function rp_get_tables_count_for_pending_jobs_progressbar( $callback = '' ) {
if( !rp_need_to_add_tables_count( $callback ) ) {
return array();
}
global $rpQuery;
$tables_to_count = array(
'rs_model',
'rs_model_color',
'rs_default_repair',
'rs_default_repair_attr',
'rs_repair',
'rs_repair_attr'
);
$alternative_names = array(
'rs_model' => 'Models',
'rs_model_color' => 'Colors',
'rs_default_repair' => 'Default Repairs',
'rs_default_repair_attr' => 'Default Attributes',
'rs_repair' => 'Repairs',
'rs_repair_attr' => 'Attributes'
);
$primary_keys = array(
'rs_model' => 'm_id',
'rs_model_color' => 'mc_id',
'rs_default_repair' => 'dr_id',
'rs_default_repair_attr' => 'da_id',
'rs_repair' => 'r_id',
'rs_repair_attr' => 'a_id'
);
$prepared = array();
foreach( $tables_to_count as $tableName ) {
$prefixed_tableName = $rpQuery->prefix . $tableName;
$primary_key = $primary_keys[ $tableName ];
$count = $rpQuery->get_var("SELECT COUNT($primary_key) FROM `$prefixed_tableName`");
$prepared[ $alternative_names[ $tableName ] ] = $count;
}
return $prepared;
}
/*
Get language from rs_order_language table by order id
*/
function rp_get_language_by_order_id($order_id = 0) {
/* Added in V1.5.0 */
global $rpQuery;
$table_rs_order_language = $rpQuery->prefix . "rs_order_language";
$sql = "SELECT * FROM `$table_rs_order_language` WHERE `o_id_fk` = '$order_id'";
$result = $rpQuery->get_row($sql);
if( !empty($result) ) {
return $result->language;
}
return '';
}
/*
Save language in rs_order_language table
*/
function rp_save_order_related_language( $o_id = '', $language = '' ) {
global $rpQuery;
$table_rs_order_language = $rpQuery->prefix . "rs_order_language";
$sql = "SELECT * FROM `$table_rs_order_language` WHERE `o_id_fk` = '$o_id'";
$result = $rpQuery->get_row($sql);
if( !empty( $result ) ) {
// Update
$rpQuery->query("UPDATE `$table_rs_order_language` SET `language` = '".rp_escape_sql($language)."' WHERE `o_id_fk` = '".rp_escape_sql($o_id)."'");
} else {
// Create
$rpQuery->query("INSERT INTO `$table_rs_order_language` (`o_id_fk`, `language`) VALUES ('".rp_escape_sql($o_id)."', '".rp_escape_sql($language)."')");
}
}
/*
Use this function to insert multiple rows in a table
*/
function rp_insert_multiple_rows($table_name = '', $data = array(), $start_transaction = TRUE) {
if( empty( $data ) ) {
return FALSE;
}
/* Added in V1.5.0 */
global $rpQuery;
if( $start_transaction === TRUE ) {
$rpQuery->query('START TRANSACTION');
}
$table_name = $rpQuery->prefix . $table_name;
$keys = array_keys($data[0]);
$keys_str = "`" . implode('`, `', $keys) . "`";
$sql = "INSERT INTO `$table_name` ({$keys_str}) VALUES ";
$values = array();
foreach ($data as $row) {
$row_values = array();
foreach($keys as $key) {
if( !isset($row[$key]) ) {
$row[$key] = '';
}
$row_values[] = "'".rp_escape_sql($row[$key])."'";
}
$values[] = '('.implode(', ', $row_values).')';
}
$sql .= implode(', ', $values);
$rpQuery->query($sql);
if( $start_transaction === TRUE ) {
$rpQuery->query('COMMIT');
}
}
/*
Add Default Translation Rows First Time
*/
function rp_add_default_translation_rows() {
if( rp_get_option('rp_added_default_translation_rows', FALSE) === '1' ) {
return;
}
rp_add_option('rp_added_default_translation_rows', '1');
global $rpQuery;
$english_translations = rp_get_static_translations_of_language('English (United States)');
$dutch_translations = rp_get_static_translations_of_language('Dutch (Netherlands)');
// Check if rs_translations table is empty
$table_rs_translations = $rpQuery->prefix . "rs_translations";
$result = $rpQuery->get_row("SELECT * FROM $table_rs_translations LIMIT 1;");
if( empty( $result ) ) {
$rows = array();
$added = array();
foreach( $english_translations as $key => $value ) {
if( !in_array($key, $added) ) {
$rows[] = array(
'language' => 'English (United States)',
'key' => $key,
'value' => $value
);
$added[] = $key;
}
}
rp_insert_multiple_rows('rs_translations', $rows);
$rows = array();
$added = array();
foreach( $dutch_translations as $key => $value ) {
if( !in_array($key, $added) ) {
$rows[] = array(
'language' => 'Dutch (Netherlands)',
'key' => $key,
'value' => $value
);
$added[] = $key;
}
}
rp_insert_multiple_rows('rs_translations', $rows);
}
}
rp_add_action('init', 'rp_add_default_translation_rows', 999);
/*
Get related translations in all languages by key
*/
function rp_get_related_translations() {
(new RepairPluginPro\RP_Languages())->rp_get_related_translations();
}
rp_ajax_for_admin('rp_get_related_translations', 'rp_get_related_translations');
/*
Get related translations in all languages by key
*/
function rp_update_translations() {
rp_verify_csrf_token_for_ajax(array(
'styling',
'planning_discount',
'notification_offer',
'localization',
'display_opening_hours'
));
(new RepairPluginPro\RP_Languages())->rp_update_translations();
}
rp_ajax_for_admin('rp_update_translations', 'rp_update_translations');
/*
Get related repair translations in all languages by key
*/
function rp_get_r_translations_individually_editable() {
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_get_r_translations_individually_editable();
}
rp_ajax_for_admin('rp_get_r_translations_individually_editable', 'rp_get_r_translations_individually_editable');
function rp_get_r_translations() {
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_get_r_translations();
}
rp_ajax_for_admin('rp_get_r_translations', 'rp_get_r_translations');
/*
Get related repair translations in all languages by key
*/
function rp_get_rcat_translations() {
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_get_rcat_translations();
}
rp_ajax_for_admin('rp_get_rcat_translations', 'rp_get_rcat_translations');
/*
Get related repair translations in all languages by key
*/
function rp_get_dr_translations() {
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_get_dr_translations();
}
rp_ajax_for_admin('rp_get_dr_translations', 'rp_get_dr_translations');
/*
Get related upsale translations in all languages by key
*/
function rp_get_upsale_translations() {
(new RepairPluginPro\RP_Upsale_Translations())->rp_get_upsale_translations();
}
rp_ajax_for_admin('rp_get_upsale_translations', 'rp_get_upsale_translations');
/*
Get related Checklist translations in all languages by key
*/
function rp_get_checklist_translations() {
(new RepairPluginPro\RP_Checklist_Translations())->rp_get_checklist_translations();
}
rp_ajax_for_admin('rp_get_checklist_translations', 'rp_get_checklist_translations');
/*
Get related Special date translations in all languages by key
*/
function rp_get_special_date_translations() {
(new RepairPluginPro\RP_Special_Date_Translations())->rp_get_special_date_translations();
}
rp_ajax_for_admin('rp_get_special_date_translations', 'rp_get_special_date_translations');
/*
Get related form fields translations in all languages by key
*/
function rp_get_form_fields_translations() {
(new RepairPluginPro\RP_Form_Fields_Translations())->rp_get_form_fields_translations();
}
rp_ajax_for_admin('rp_get_form_fields_translations', 'rp_get_form_fields_translations');
/*
Get related form fields options translations in all languages by key
*/
function rp_get_form_fields_options_translations() {
(new RepairPluginPro\RP_Form_Fields_Options_Translations())->rp_get_form_fields_options_translations();
}
rp_ajax_for_admin('rp_get_form_fields_options_translations', 'rp_get_form_fields_options_translations');
/*
Get related priority options translations in all languages by key
*/
function rp_get_priority_options_translations() {
(new RepairPluginPro\RP_Priority_Options_Translations())->rp_get_priority_options_translations();
}
rp_ajax_for_admin('rp_get_priority_options_translations', 'rp_get_priority_options_translations');
/*
Get related repair attr translations in all languages by key
*/
function rp_get_rattr_translations_individually_editable() {
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_get_rattr_translations_individually_editable();
}
rp_ajax_for_admin('rp_get_rattr_translations_individually_editable', 'rp_get_rattr_translations_individually_editable');
function rp_get_rattr_translations() {
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_get_rattr_translations();
}
rp_ajax_for_admin('rp_get_rattr_translations', 'rp_get_rattr_translations');
/*
Get related default repair attr translations in all languages by key
*/
function rp_get_drattr_translations() {
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_get_drattr_translations();
}
rp_ajax_for_admin('rp_get_drattr_translations', 'rp_get_drattr_translations');
/*
Get related default repair category translations in all languages by key
*/
function rp_get_drcat_translations() {
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_get_drcat_translations();
}
rp_ajax_for_admin('rp_get_drcat_translations', 'rp_get_drcat_translations');
/*
Get static translation of repair
*/
function rp_get_static_translations_of_repair_category( $key = '', $uqid = '', $connection_id = '', $use_language = 'default' ) {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$table_rs_repairs_category = $rpQuery->prefix . "rs_repairs_category";
$org_key = $key;
if( $key === 'category_name' ) {
$key = 'c_name';
}
// select $key from rs_repairs_category where r_uq_id = $uqid and m_id_fk = $connection_id
//cbfast
$result = $rpQuery->get_row("SELECT `$key` FROM `$table_rs_repairs_category` WHERE `c_uq_id` = '".rp_escape_sql($uqid)."' AND m_id_fk = '".rp_escape_sql($connection_id)."' LIMIT 1;");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
if( $use_language === 'selected' ) {
global $wp_repair_selected_language;
$default_language = $wp_repair_selected_language;
} else {
global $rp_use_order_related_language;
if( isset( $rp_use_order_related_language ) && !empty( $rp_use_order_related_language ) ) {
$default_language = $rp_use_order_related_language;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
}
// select value from rs_r_translations where key = $key and uq_id = $uqid and m_id_fk = $connection_id
// $result = $rpQuery->get_row("SELECT `value` FROM `$table_rs_r_translations` WHERE `key` = '".rp_escape_sql($org_key)."' AND `uq_id` = '".rp_escape_sql($uqid)."' AND m_id_fk = '".rp_escape_sql($connection_id)."' AND `language` = '".rp_escape_sql($default_language)."' LIMIT 1;");
$d_result = rp_get_static_translations_of_drepair_category($org_key, $uqid, $default_language);
if( !empty($d_result) ) {
$final_result = $d_result;
} else {
$result = rp_get_dynamic_translations_of_repair_category($connection_id, $default_language);
if( is_array( $result ) && isset( $result[$uqid.$org_key] ) ) {
$final_result = $result[$uqid.$org_key];
}
}
return $final_result ?? '';
}
function rp_associative_object_to_array( $items = array() ) {
if( empty( $items ) ) {
return $items;
}
$prepared = array();
foreach( $items as $item ) {
if( is_object( $item ) ) {
$item = (array) $item;
}
$prepared[] = $item;
}
return $prepared;
}
function rp_associative_array_to_object( $items = array() ) {
if( empty( $items ) ) {
return $items;
}
$prepared = array();
foreach( $items as $item ) {
if( is_array( $item ) ) {
$item = (object) $item;
}
$prepared[] = $item;
}
return $prepared;
}
function rp_get_model_related_repairs_front_end( $m_id = 0, $order_by = '', $where = array() ) {
static $cached_result = NULL;
$m_id = (int) $m_id;
if( $cached_result !== NULL && array_key_exists( $m_id, $cached_result ) ) {
$result = $cached_result[ $m_id ];
} else {
global $rpQuery;
$table_rs_repair = $rpQuery->prefix . "rs_repair";
$result = $rpQuery->get_results("SELECT * FROM `$table_rs_repair` WHERE m_id_fk = {$m_id}");
if( $cached_result === NULL ) {
$cached_result = array();
}
$cached_result[ $m_id ] = $result;
}
if( !empty( $result ) && ( !empty( $order_by ) || !empty( $where ) ) ) {
$result = rp_associative_object_to_array( $result );
if( !empty( $where ) && is_array( $where ) ) {
$result = rp_filter_associative_array( $result, $where );
}
if( !empty( $order_by ) && is_string( $order_by ) ) {
$result = rp_sort_associative_array( $result, $order_by );
}
$result = rp_associative_array_to_object( $result );
return $result;
}
return $result;
}
function rp_get_all_prepared_repairs_of_model_using_uqid( $key = '', $uqid = '', $m_id = '' ) {
$cache_key = md5( __FUNCTION__ . $m_id );
$exists = RepairPluginPro\RP_Memory_Cache::exists( $cache_key );
if( $exists == TRUE ) {
$result = RepairPluginPro\RP_Memory_Cache::last_result( $cache_key );
if( !empty( $result ) && isset( $result[$uqid.$key] ) ) {
return $result[$uqid.$key] ?? '';
}
return '';
}
global $rpQuery;
$table_rs_repair = $rpQuery->prefix . "rs_repair";
$keys = array( 'r_name', 'r_discription', 'r_badge', 'r_readmore', 'r_readmoretext' );
$imploded_keys = implode('`, `', $keys);
$result = rp_get_model_related_repairs_front_end( $m_id );
$prepared = array();
if( !empty( $result ) ) {
foreach( $keys as $theKey ) {
if( !isset( $prepared[ $uqid . $theKey ] ) ) {
$prepared[ $uqid . $theKey ] = array();
}
}
foreach( $result as $row ) {
foreach( $keys as $theKey ) {
$newObj = new stdClass();
$newObj->{$theKey} = $row->{$theKey};
$newObj->r_uq_id = $row->r_uq_id;
$prepared[ $uqid . $theKey ][] = $newObj;
}
}
}
RepairPluginPro\RP_Memory_Cache::save( $cache_key, $prepared );
if( !empty( $prepared ) && isset( $prepared[$uqid.$key] ) ) {
return $prepared[$uqid.$key] ?? array();
}
return '';
}
function rp_get_cached_r_name_by_model_id( $key = '', $uqid = '', $m_id = '' ) {
global $rpQuery;
$table_rs_repair = $rpQuery->prefix . "rs_repair";
$cache_key = md5( __FUNCTION__ . $key . $m_id );
$exists = RepairPluginPro\RP_Memory_Cache::exists( $cache_key );
if( $exists == TRUE ) {
$result = RepairPluginPro\RP_Memory_Cache::last_result( $cache_key );
if( !empty( $result ) && isset( $result[$uqid] ) ) {
return $result[$uqid] ?? '';
}
return '';
}
// $result = $rpQuery->get_results("SELECT `$key`, `r_uq_id` FROM `$table_rs_repair` WHERE m_id_fk = '".rp_escape_sql($m_id)."'");
$result = rp_get_all_prepared_repairs_of_model_using_uqid( $key, $uqid, $m_id );
$key_value_pair = array();
if( !empty( $result ) ) {
foreach( $result as $_key => $row ) {
$key_value_pair[ $row->r_uq_id ] = $row->{$key};
}
}
RepairPluginPro\RP_Memory_Cache::save( $cache_key, $key_value_pair );
$result = $key_value_pair;
if( !empty( $result ) && isset( $result[$uqid] ) ) {
return $result[$uqid] ?? '';
}
return '';
}
function rp_get_static_translations_of_repair_individually_editable($key = '', $uqid = '', $connection_id = '', $use_language = 'default') {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$table_rs_repair = $rpQuery->prefix . "rs_repair";
$org_key = $key;
if( $key === 'repair_name' ) {
$key = 'r_name';
}
if( $key === 'repair_desc' ) {
$key = 'r_discription';
}
if( $key === 'repair_badge' ) {
$key = 'r_badge';
}
if( $key === 'repair_read_more' ) {
$key = 'r_readmore';
}
if( $key === 'repair_readmore_text' ) {
$key = 'r_readmoretext';
}
$actual_uqid = $uqid;
if( $key == 'r_readmore' || $key == 'r_readmoretext' ) {
$exploded_uqid = explode('_', $uqid);
// get last part
$last_part = end($exploded_uqid);
// re-implode uqid except for last part
$actual_uqid = implode('_', array_slice($exploded_uqid, 0, -1));
}
$final_result = rp_get_cached_r_name_by_model_id( $key, $actual_uqid, $connection_id );
if( $use_language === 'selected' ) {
global $wp_repair_selected_language;
$default_language = $wp_repair_selected_language;
} else {
global $rp_use_order_related_language;
if( isset( $rp_use_order_related_language ) && !empty( $rp_use_order_related_language ) ) {
$default_language = $rp_use_order_related_language;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
}
// If individual translation is found, return individual
// Else, return default
$result = rp_get_dynamic_translations_of_repair($connection_id, $default_language);
if( is_array( $result ) && isset( $result[$uqid.$org_key] ) ) {
$final_result = $result[$uqid.$org_key] ?? '';
} else {
$d_result = rp_get_static_translations_of_drepair($org_key, $uqid, $default_language);
if( !empty($d_result) ) {
$final_result = $d_result;
}
}
return $final_result ?? '';
}
function rp_get_static_translations_of_repair($key = '', $uqid = '', $connection_id = '', $use_language = 'default') {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$table_rs_repair = $rpQuery->prefix . "rs_repair";
$org_key = $key;
if( $key === 'repair_name' ) {
$key = 'r_name';
}
if( $key === 'repair_desc' ) {
$key = 'r_discription';
}
if( $key === 'repair_badge' ) {
$key = 'r_badge';
}
if( $key === 'repair_read_more' ) {
$key = 'r_readmore';
}
if( $key === 'repair_readmore_text' ) {
$key = 'r_readmoretext';
}
$final_result = rp_get_cached_r_name_by_model_id( $key, $uqid, $connection_id );
if( $use_language === 'selected' ) {
global $wp_repair_selected_language;
$default_language = $wp_repair_selected_language;
} else {
global $rp_use_order_related_language;
if( isset( $rp_use_order_related_language ) && !empty( $rp_use_order_related_language ) ) {
$default_language = $rp_use_order_related_language;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
}
// select value from rs_r_translations where key = $key and uq_id = $uqid and m_id_fk = $connection_id
// $result = $rpQuery->get_row("SELECT `value` FROM `$table_rs_r_translations` WHERE `key` = '".rp_escape_sql($org_key)."' AND `uq_id` = '".rp_escape_sql($uqid)."' AND m_id_fk = '".rp_escape_sql($connection_id)."' AND `language` = '".rp_escape_sql($default_language)."' LIMIT 1;");
$d_result = rp_get_static_translations_of_drepair($org_key, $uqid.'_'.rp_get_model_cached_category_by_mid($connection_id), $default_language);
if( !empty($d_result) ) {
$final_result = $d_result;
} else {
$result = rp_get_dynamic_translations_of_repair($connection_id, $default_language);
if( is_array( $result ) && isset( $result[$uqid.$org_key] ) ) {
$final_result = $result[$uqid.$org_key];
}
}
return $final_result ?? '';
}
/*
Get static translation of upsale
*/
function rp_get_static_translations_of_upsale_selected($key = '', $uqid = '', $use_language = 'default') {
global $rpQuery;
$rs_upsale_translations = $rpQuery->prefix . "rs_upsale_translations";
$rs_upsales = $rpQuery->prefix . "rs_upsales";
$nm_key = $key;
$org_key = $key;
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `$nm_key` FROM `$rs_upsales` WHERE `upsales_id` = '".rp_escape_sql($uqid)."' LIMIT 1;");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$nm_key};
}
if( $use_language === 'selected' ) {
global $wp_repair_selected_language;
$default_language = $wp_repair_selected_language;
} else {
global $rp_use_order_related_language;
if( isset( $rp_use_order_related_language ) && !empty( $rp_use_order_related_language ) ) {
$default_language = $rp_use_order_related_language;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
}
$d_result = rp_get_static_translations_of_upsale($org_key, $uqid, $default_language);
if( !empty($d_result) ) {
$final_result = $d_result;
}
return $final_result;
}
/*
Get static translation of special date
*/
function rp_get_static_translations_of_special_date_name_selected($key = '', $uqid = '', $use_language = 'default') {
global $rpQuery;
$rs_general_translations = $rpQuery->prefix . "rs_general_translations";
$rs_special_timing = $rpQuery->prefix . "rs_special_timing";
$nm_key = $key;
$org_key = $key;
$result = $rpQuery->get_row("SELECT `$nm_key` FROM `$rs_special_timing` WHERE `cs_id` = '".rp_escape_sql($uqid)."' LIMIT 1;");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$nm_key};
}
if( $use_language === 'selected' ) {
global $wp_repair_selected_language;
$default_language = $wp_repair_selected_language;
} else {
global $rp_use_order_related_language;
if( isset( $rp_use_order_related_language ) && !empty( $rp_use_order_related_language ) ) {
$default_language = $rp_use_order_related_language;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
}
$d_result = rp_get_static_translations_of_special_date_name($org_key, $uqid, $default_language);
if( !empty($d_result) ) {
$final_result = $d_result;
}
return $final_result;
}
/*
Get static translation of appointment checklist
*/
function rp_get_static_translations_of_checklist_selected($key = '', $uqid = '', $use_language = 'default') {
global $rpQuery;
$rs_general_translations = $rpQuery->prefix . "rs_general_translations";
$rs_appointment_checklist = $rpQuery->prefix . "rs_appointment_checklist";
$nm_key = $key;
if( $key == 'li_name' ) {
$nm_key = 'title';
}
$org_key = $key;
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `$nm_key` FROM `$rs_appointment_checklist` WHERE `id` = '".rp_escape_sql($uqid)."' LIMIT 1;");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$nm_key};
}
if( $use_language === 'selected' ) {
global $wp_repair_selected_language;
$default_language = $wp_repair_selected_language;
} else {
global $rp_use_order_related_language;
if( isset( $rp_use_order_related_language ) && !empty( $rp_use_order_related_language ) ) {
$default_language = $rp_use_order_related_language;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
}
$d_result = rp_get_static_translations_of_checklist($org_key, $uqid, $default_language);
if( !empty($d_result) ) {
$final_result = $d_result;
}
return $final_result;
}
/*
Get static translation of repair by language
*/
function rp_get_static_translations_of_repair_by_language_individually_editable($key = '', $uqid = '', $connection_id = '', $language = '') {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$table_rs_repair = $rpQuery->prefix . "rs_repair";
$org_key = $key;
if( $key === 'repair_name' ) {
$key = 'r_name';
}
if( $key === 'repair_desc' ) {
$key = 'r_discription';
}
if( $key === 'repair_badge' ) {
$key = 'r_badge';
}
if( $key === 'repair_read_more' ) {
$key = 'r_readmore';
}
if( $key === 'repair_readmore_text' ) {
$key = 'r_readmoretext';
}
$actual_uqid = $uqid;
if( $key == 'r_readmore' || $key == 'r_readmoretext' ) {
$exploded_uqid = explode('_', $uqid);
// get last part
$last_part = end($exploded_uqid);
// re-implode uqid except for last part
$actual_uqid = implode('_', array_slice($exploded_uqid, 0, -1));
}
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `$key` FROM `$table_rs_repair` WHERE `r_uq_id` = '".rp_escape_sql($actual_uqid)."' AND m_id_fk = '".rp_escape_sql($connection_id)."' LIMIT 1;");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
$default_language = $language;
$result = rp_get_dynamic_translations_of_repair($connection_id, $default_language);
if( is_array( $result ) && isset( $result[$uqid.$org_key] ) ) {
$final_result = $result[$uqid.$org_key];
} else {
$d_result = rp_get_static_translations_of_drepair($org_key, $uqid, $default_language);
if( !empty($d_result) ) {
$final_result = $d_result;
}
}
return $final_result;
}
function rp_get_static_translations_of_repair_by_language($key = '', $uqid = '', $connection_id = '', $language = '') {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$table_rs_repair = $rpQuery->prefix . "rs_repair";
$org_key = $key;
if( $key === 'repair_name' ) {
$key = 'r_name';
}
if( $key === 'repair_desc' ) {
$key = 'r_discription';
}
if( $key === 'repair_badge' ) {
$key = 'r_badge';
}
if( $key === 'repair_read_more' ) {
$key = 'r_readmore';
}
if( $key === 'repair_readmore_text' ) {
$key = 'r_readmoretext';
}
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `$key` FROM `$table_rs_repair` WHERE `r_uq_id` = '".rp_escape_sql($uqid)."' AND m_id_fk = '".rp_escape_sql($connection_id)."' LIMIT 1;");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
$default_language = $language;
$d_result = rp_get_static_translations_of_drepair($org_key, $uqid, $default_language);
if( !empty($d_result) ) {
$final_result = $d_result;
} else {
$result = rp_get_dynamic_translations_of_repair($connection_id, $default_language);
if( is_array( $result ) && isset( $result[$uqid.$org_key] ) ) {
$final_result = $result[$uqid.$org_key];
}
}
return $final_result;
}
/*
Get static translation of repair category by language
*/
function rp_get_static_translations_of_repair_category_by_language($key = '', $uqid = '', $connection_id = '', $language = '') {
global $rpQuery;
$table_rs_repairs_category = $rpQuery->prefix . "rs_repairs_category";
$org_key = $key;
if( $key === 'category_name' ) {
$key = 'c_name';
}
// select $key from rs_repairs_category where r_uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `$key` FROM `$table_rs_repairs_category` WHERE `c_uq_id` = '".rp_escape_sql($uqid)."' AND m_id_fk = '".rp_escape_sql($connection_id)."' LIMIT 1;");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
$default_language = $language;
$d_result = rp_get_static_translations_of_drepair_category($org_key, $uqid, $default_language);
if( !empty($d_result) ) {
$final_result = $d_result;
} else {
$result = rp_get_dynamic_translations_of_repair_category($connection_id, $default_language);
if( is_array( $result ) && isset( $result[$uqid.$org_key] ) ) {
$final_result = $result[$uqid.$org_key];
}
}
return $final_result;
}
function rp_get_dynamic_translations_of_repair_category($connection_id = '', $default_language = '') {
$cache_key = md5('rp_get_dynamic_translations_of_repair_category_' . $connection_id . $default_language);
$cache = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if( $cache !== NULL && is_array( $cache ) ) {
return $cache;
}
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$result = $rpQuery->get_results("SELECT * FROM `$table_rs_r_translations` WHERE m_id_fk = '".rp_escape_sql($connection_id)."' AND `language` = '".rp_escape_sql($default_language)."';");
$prepared = array();
if( !empty( $result ) ) {
foreach( $result as $row ) {
$prepared[$row->uq_id.$row->key] = $row->value;
}
}
RepairPluginPro\RP_Memory_Cache::save($cache_key, $prepared);
return $prepared;
}
function rp_get_dynamic_translations_of_repair($connection_id = '', $default_language = '') {
$cache_key = md5('rp_get_dynamic_translations_of_repair_' . $connection_id . $default_language);
$cache = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if( $cache !== NULL && is_array( $cache ) ) {
return $cache;
}
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_r_translations";
$result = $rpQuery->get_results("SELECT * FROM `$table_rs_r_translations` WHERE m_id_fk = '".rp_escape_sql($connection_id)."' AND `language` = '".rp_escape_sql($default_language)."';");
$prepared = array();
if( !empty( $result ) ) {
foreach( $result as $row ) {
$prepared[$row->uq_id.$row->key] = $row->value;
}
}
RepairPluginPro\RP_Memory_Cache::save($cache_key, $prepared);
return $prepared;
}
/*
Get static translation of default repair category
*/
function rp_get_static_translations_of_drepair_category($key = '', $uqid = '', $lang = '') {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_dr_translations";
$rs_default_repairs_category = $rpQuery->prefix . "rs_default_repairs_category";
$org_key = $key;
if( $key === 'category_name' ) {
$key = 'dc_name';
}
// select $key from rs_default_repairs_category where r_uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `$key` FROM `$rs_default_repairs_category` WHERE `dc_uq_id` = '".rp_escape_sql($uqid)."';");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
if(!empty($lang)) {
$default_language = $lang;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
// select value from rs_r_translations where key = $key and uq_id = $uqid and m_id_fk = $connection_id
// $result = $rpQuery->get_row("SELECT `value` FROM `$table_rs_r_translations` WHERE `key` = '".rp_escape_sql($org_key)."' AND `uq_id` = '".rp_escape_sql($uqid)."' AND `language` = '".rp_escape_sql($default_language)."';");
$result = rp_get_default_repair_translation_key_uqid_lang_cached( $org_key, $uqid, $default_language );
if( !empty( $result ) ) {
$final_result = $result->value;
}
return $final_result ?? '';
}
/*
Get static translation of default repair
*/
function rp_get_default_repairs_based_on_ud_id_cached( $uqid = '' ) {
static $rp_get_default_repairs_based_on_ud_id_cached = NULL;
if( $rp_get_default_repairs_based_on_ud_id_cached !== NULL && array_key_exists( $uqid, $rp_get_default_repairs_based_on_ud_id_cached ) ) {
return $rp_get_default_repairs_based_on_ud_id_cached[ $uqid ];
}
global $rpQuery;
$table_rs_repair = $rpQuery->prefix . "rs_default_repair";
$result = $rpQuery->get_results("SELECT * FROM `$table_rs_repair`");
$rp_get_default_repairs_based_on_ud_id_cached = array();
foreach( $result as $repairRow ) {
$rp_get_default_repairs_based_on_ud_id_cached[ $repairRow->dr_uq_id ] = $repairRow;
}
if( $rp_get_default_repairs_based_on_ud_id_cached !== NULL && array_key_exists( $uqid, $rp_get_default_repairs_based_on_ud_id_cached ) ) {
return $rp_get_default_repairs_based_on_ud_id_cached[ $uqid ];
}
return array();
}
function rp_get_all_default_translations_for_language( $lang = '' ) {
static $rp_get_all_default_translations_for_language = NULL;
if( $rp_get_all_default_translations_for_language !== NULL && array_key_exists( $lang, $rp_get_all_default_translations_for_language ) ) {
return $rp_get_all_default_translations_for_language[ $lang ];
}
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_dr_translations";
$result = $rpQuery->get_results("SELECT * FROM `$table_rs_r_translations` WHERE `language` = '".rp_escape_sql($lang)."';");
$rp_get_all_default_translations_for_language[ $lang ] = $result;
return $result;
}
function rp_get_default_repair_translation_key_uqid_lang_cached( $key = '', $uqid = '', $lang = '' ) {
$hash = md5( $key.$uqid );
static $rp_get_default_repair_translation_key_uqid_lang_cached = NULL;
if( $rp_get_default_repair_translation_key_uqid_lang_cached !== NULL && array_key_exists( $lang, $rp_get_default_repair_translation_key_uqid_lang_cached ) && array_key_exists( $hash, $rp_get_default_repair_translation_key_uqid_lang_cached[ $lang ] ) ) {
return $rp_get_default_repair_translation_key_uqid_lang_cached[ $lang ][ $hash ];
}
$result = rp_get_all_default_translations_for_language( $lang );
if( empty( $rp_get_default_repair_translation_key_uqid_lang_cached ) ) {
$rp_get_default_repair_translation_key_uqid_lang_cached = array();
}
if( !isset( $rp_get_default_repair_translation_key_uqid_lang_cached[ $lang ] ) ) {
$rp_get_default_repair_translation_key_uqid_lang_cached[ $lang ] = array();
}
foreach( $result as $translationRow ) {
$rp_get_default_repair_translation_key_uqid_lang_cached[ $lang ][ md5( $translationRow->key.$translationRow->uq_id ) ] = $translationRow;
}
if( $rp_get_default_repair_translation_key_uqid_lang_cached !== NULL && array_key_exists( $lang, $rp_get_default_repair_translation_key_uqid_lang_cached ) && array_key_exists( $hash, $rp_get_default_repair_translation_key_uqid_lang_cached[ $lang ] ) ) {
return $rp_get_default_repair_translation_key_uqid_lang_cached[ $lang ][ $hash ];
}
return array();
}
function rp_fix_uq_id_if_needed( $uqid = '' ) {
if( empty( $uqid ) || strpos( $uqid, 'repair_' ) === FALSE ) {
return $uqid;
}
$u_cache_key = md5( __FUNCTION__ . $uqid );
$cache_exists = RepairPluginPro\RP_Memory_Cache::exists($u_cache_key);
if( $cache_exists == TRUE ) {
return RepairPluginPro\RP_Memory_Cache::last_result($u_cache_key);
}
$exploded = explode('_', $uqid);
if( count( $exploded ) == 3 ) {
// all looks good!
return $uqid;
}
global $rpQuery;
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$row = $rpQuery->get_row("SELECT * FROM $rs_default_repair WHERE dr_uq_id = '".rp_escape_sql($uqid)."' LIMIT 1");
if( !empty( $row ) && !empty( $row->dr_category ?? 0 ) ) {
$uqid = $uqid.'_'.$row->dr_category;
}
RepairPluginPro\RP_Memory_Cache::save($u_cache_key, $uqid);
return $uqid;
}
function rp_get_static_translations_of_drepair($key = '', $uqid = '', $lang = '') {
$uqid = rp_fix_uq_id_if_needed( $uqid );
$u_cache_key = md5( __FUNCTION__ . $key . $uqid . $lang );
$cache_exists = RepairPluginPro\RP_Memory_Cache::exists($u_cache_key);
if( $cache_exists == TRUE ) {
return RepairPluginPro\RP_Memory_Cache::last_result($u_cache_key);
}
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_dr_translations";
$table_rs_repair = $rpQuery->prefix . "rs_default_repair";
$org_key = $key;
if( $key === 'repair_name' ) {
$key = 'dr_name';
}
if( $key === 'repair_desc' ) {
$key = 'dr_discription';
}
if( $key === 'repair_badge' ) {
$key = 'dr_badge';
}
if( $key === 'repair_read_more' ) {
$key = 'dr_readmore';
}
if( $key === 'repair_readmore_text' ) {
$key = 'dr_readmoretext';
}
$actual_uqid = $uqid;
// if( $key == 'dr_readmore' || $key == 'dr_readmoretext' ) {
$exploded_uqid = explode('_', $uqid);
// get last part
$last_part = end($exploded_uqid);
// re-implode uqid except for last part
$actual_uqid = implode('_', array_slice($exploded_uqid, 0, -1));
// }
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
// $result = $rpQuery->get_row("SELECT `$key` FROM `$table_rs_repair` WHERE `dr_uq_id` = '".rp_escape_sql($uqid)."';");
$result = rp_get_default_repairs_based_on_ud_id_cached( $actual_uqid );
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
if(!empty($lang)) {
$default_language = $lang;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
// select value from rs_r_translations where key = $key and uq_id = $uqid and m_id_fk = $connection_id
// $result = $rpQuery->get_row("SELECT `value` FROM `$table_rs_r_translations` WHERE `key` = '".rp_escape_sql($org_key)."' AND `uq_id` = '".rp_escape_sql($uqid)."' AND `language` = '".rp_escape_sql($default_language)."';");
$result = rp_get_default_repair_translation_key_uqid_lang_cached( $org_key, $uqid, $default_language );
if( !empty( $result ) ) {
$final_result = $result->value;
}
RepairPluginPro\RP_Memory_Cache::save($u_cache_key, ($final_result ?? ''));
return $final_result ?? '';
}
/*
Get static general translation of appointment_checklist
*/
function rp_get_static_translations_of_checklist($key = '', $uqid = '', $lang = '') {
global $rpQuery;
$rs_general_translations = $rpQuery->prefix . "rs_general_translations";
$rs_appointment_checklist = $rpQuery->prefix . "rs_appointment_checklist";
$nm_key = $key;
if( $key == 'li_name' ) {
$nm_key = 'title';
}
$key = $uqid.'_'.$key;
$org_key = $key;
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `$nm_key` FROM `$rs_appointment_checklist` WHERE `id` = '".rp_escape_sql($uqid)."';");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$nm_key};
}
if(!empty($lang)) {
$default_language = $lang;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
// select value from rs_general_translations where key = $key and uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `value` FROM `$rs_general_translations` WHERE `key` = '".rp_escape_sql($org_key)."' AND `language` = '".rp_escape_sql($default_language)."';");
if( !empty( $result ) ) {
$final_result = $result->value;
}
return $final_result;
}
/*
Get static general translation of rs_special_timing
*/
function rp_get_static_translations_of_special_date_name($key = '', $uqid = '', $lang = '') {
global $rpQuery;
$rs_general_translations = $rpQuery->prefix . "rs_general_translations";
$rs_special_timing = $rpQuery->prefix . "rs_special_timing";
$nm_key = $key;
$key = $uqid.'_'.$key;
$org_key = $key;
$result = $rpQuery->get_row("SELECT `$nm_key` FROM `$rs_special_timing` WHERE `cs_id` = '".rp_escape_sql($uqid)."';");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$nm_key};
}
if(!empty($lang)) {
$default_language = $lang;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
// select value from rs_general_translations where key = $key and uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `value` FROM `$rs_general_translations` WHERE `key` = '".rp_escape_sql($org_key)."' AND `language` = '".rp_escape_sql($default_language)."';");
if( !empty( $result ) ) {
$final_result = $result->value;
}
return $final_result;
}
/*
Get static translation of upsale
*/
function rp_get_static_translations_of_upsale($key = '', $uqid = '', $lang = '') {
global $rpQuery;
$rs_upsale_translations = $rpQuery->prefix . "rs_upsale_translations";
$rs_upsales = $rpQuery->prefix . "rs_upsales";
$nm_key = $key;
$key = $uqid.'_'.$key;
$org_key = $key;
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `$nm_key` FROM `$rs_upsales` WHERE `upsales_id` = '".rp_escape_sql($uqid)."';");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$nm_key};
}
if(!empty($lang)) {
$default_language = $lang;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
// select value from rs_r_translations where key = $key and uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `value` FROM `$rs_upsale_translations` WHERE `key` = '".rp_escape_sql($org_key)."' AND `language` = '".rp_escape_sql($default_language)."';");
if( !empty( $result ) ) {
$final_result = $result->value;
}
return $final_result;
}
/*
Get static translation of attr
*/
function rp_get_all_rids_for_m_id_fk( $m_id = 0 ) {
static $rp_get_all_rids_for_m_id_fk = NULL;
if( $rp_get_all_rids_for_m_id_fk !== NULL && array_key_exists( $m_id, $rp_get_all_rids_for_m_id_fk ) ) {
return $rp_get_all_rids_for_m_id_fk[ $m_id ];
}
if( $rp_get_all_rids_for_m_id_fk === NULL ) {
$rp_get_all_rids_for_m_id_fk = array();
}
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
// $result = $rpQuery->get_results("SELECT `r_id` FROM `$rs_repair` WHERE `m_id_fk` = '".rp_escape_sql($m_id)."';");
$result = rp_get_model_related_repairs_front_end( $m_id );
$prepared = array();
if( !empty( $result ) ) {
foreach( $result as $row ) {
$prepared[] = $row->r_id;
}
}
$rp_get_all_rids_for_m_id_fk[ $m_id ] = $prepared;
return $prepared;
}
function rp_get_model_id_of_individual_repair( $r_id = 0 ) {
static $rp_get_model_id_of_individual_repair = NULL;
if( $rp_get_model_id_of_individual_repair !== NULL && array_key_exists( $r_id, $rp_get_model_id_of_individual_repair ) ) {
return $rp_get_model_id_of_individual_repair[ $r_id ];
}
if( $rp_get_model_id_of_individual_repair === NULL ) {
$rp_get_model_id_of_individual_repair = array();
}
global $rpQuery;
$rs_repair = $rpQuery->prefix . 'rs_repair';
$result = $rpQuery->get_row("SELECT `m_id_fk` FROM `$rs_repair` WHERE `r_id` = '".rp_escape_sql($r_id)."' LIMIT 1;");
if( !empty( $result ) ) {
$rp_get_model_id_of_individual_repair[ $r_id ] = $result->m_id_fk;
$allRids = rp_get_all_rids_for_m_id_fk( $result->m_id_fk );
// Cache Initially Fast
foreach( $allRids as $rid ) {
$rp_get_model_id_of_individual_repair[ $rid ] = $result->m_id_fk;
}
return $result->m_id_fk;
}
$rp_get_model_id_of_individual_repair[ $r_id ] = 0;
return 0;
}
function rp_get_all_attributes_of_model_id( $m_id = 0 ) {
static $rp_get_all_attributes_of_model_id = NULL;
if( $rp_get_all_attributes_of_model_id !== NULL && array_key_exists( $m_id, $rp_get_all_attributes_of_model_id ) ) {
return $rp_get_all_attributes_of_model_id[ $m_id ];
}
if( $rp_get_all_attributes_of_model_id === NULL ) {
$rp_get_all_attributes_of_model_id = array();
}
$allRepairIdsOfModel = rp_get_all_rids_for_m_id_fk( $m_id );
if( empty( $allRepairIdsOfModel ) ) {
$rp_get_all_attributes_of_model_id[ $m_id ] = array();
return array();
}
global $rpQuery;
$table_rs_repair = $rpQuery->prefix . "rs_repair_attr";
$repair_ids_string = implode(',', $allRepairIdsOfModel);
$result = $rpQuery->get_results("SELECT * FROM `$table_rs_repair` WHERE `r_id_fk` IN ($repair_ids_string);");
$prepared = array();
if( !empty( $result ) ) {
foreach( $result as $row ) {
$prepared[] = $row;
}
}
$rp_get_all_attributes_of_model_id[ $m_id ] = $prepared;
return $prepared;
}
function rp_get_all_attributes_of_model_id_order_by_position( $m_id = 0 ) {
static $rp_get_all_attributes_of_model_id_order_by_position = NULL;
if( $rp_get_all_attributes_of_model_id_order_by_position !== NULL && array_key_exists( $m_id, $rp_get_all_attributes_of_model_id_order_by_position ) ) {
return $rp_get_all_attributes_of_model_id_order_by_position[ $m_id ];
}
if( $rp_get_all_attributes_of_model_id_order_by_position === NULL ) {
$rp_get_all_attributes_of_model_id_order_by_position = array();
}
$allRepairIdsOfModel = rp_get_all_rids_for_m_id_fk( $m_id );
if( empty( $allRepairIdsOfModel ) ) {
$rp_get_all_attributes_of_model_id_order_by_position[ $m_id ] = array();
return array();
}
global $rpQuery;
$table_rs_repair = $rpQuery->prefix . "rs_repair_attr";
$repair_ids_string = implode(',', $allRepairIdsOfModel);
$result = $rpQuery->get_results("SELECT * FROM `$table_rs_repair` WHERE `r_id_fk` IN ($repair_ids_string) AND `is_active` = '1' ORDER BY ra_position ASC");
$prepared = array();
if( !empty( $result ) ) {
foreach( $result as $row ) {
$prepared[] = $row;
}
}
$rp_get_all_attributes_of_model_id_order_by_position[ $m_id ] = $prepared;
return $prepared;
}
function rp_get_all_attrs_of_repair_order_by_position( $r_id_fk = 0 ) {
$modelIdOfRepair = rp_get_model_id_of_individual_repair( $r_id_fk );
$allAttributesOfModel = rp_get_all_attributes_of_model_id_order_by_position( $modelIdOfRepair );
$filtered = array();
if( !empty( $allAttributesOfModel ) ) {
foreach( $allAttributesOfModel as $attrRow ) {
if( $attrRow->r_id_fk == $r_id_fk ) {
$filtered[] = $attrRow;
}
}
}
return $filtered;
}
function rp_get_repair_attr_row_by_uqid_and_r_id_fk_cached( $uqid = '', $r_id_fk = 0 ) {
$modelIdOfRepair = rp_get_model_id_of_individual_repair( $r_id_fk );
$allAttributesOfModel = rp_get_all_attributes_of_model_id( $modelIdOfRepair );
// loop through all and return where a_uq_id and r_id_fk matches
foreach( $allAttributesOfModel as $attrRow ) {
if( $attrRow->a_uq_id == $uqid && $attrRow->r_id_fk == $r_id_fk ) {
return $attrRow;
}
}
return array();
}
function rp_get_static_translations_of_attr_individually_editable($key = '', $uqid = '', $connection_id = '', $use_language = 'default') {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_rattr_translations";
$table_rs_repair = $rpQuery->prefix . "rs_repair_attr";
$org_key = $key;
if( $key === 'attr_name' ) {
$key = 'a_name';
}
if( $key === 'attr_desc' ) {
$key = 'a_desc';
}
if( $key === 'attr_badge' ) {
$key = 'a_badge';
}
if( $key === 'attr_read_more' ) {
$key = 'a_readmore';
}
if( $key === 'attr_readmore_text' ) {
$key = 'a_readmoretext';
}
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
// $result = $rpQuery->get_row("SELECT `$key` FROM `$table_rs_repair` WHERE `a_uq_id` = '".rp_escape_sql($uqid)."' AND r_id_fk = '".rp_escape_sql($connection_id)."' LIMIT 1;");
$result = rp_get_repair_attr_row_by_uqid_and_r_id_fk_cached( $uqid, $connection_id );
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
if( $use_language === 'selected' ) {
global $wp_repair_selected_language;
$default_language = $wp_repair_selected_language;
} else {
global $rp_use_order_related_language;
if( isset( $rp_use_order_related_language ) && !empty( $rp_use_order_related_language ) ) {
$default_language = $rp_use_order_related_language;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
}
// If individual translation is found, return individual translation
// else return default translation
$result = rp_get_dynamic_translations_of_attr($connection_id, $default_language);
if( is_array( $result ) && isset( $result[$uqid.$org_key] ) ) {
$final_result = $result[$uqid.$org_key] ?? '';
} else {
$d_result = rp_get_static_translations_of_dattr($org_key, $uqid, $default_language);
if( !empty( $d_result ) ) {
$final_result = $d_result;
}
}
return $final_result ?? '';
}
function rp_get_static_translations_of_attr($key = '', $uqid = '', $connection_id = '', $use_language = 'default') {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_rattr_translations";
$table_rs_repair = $rpQuery->prefix . "rs_repair_attr";
$org_key = $key;
if( $key === 'attr_name' ) {
$key = 'a_name';
}
if( $key === 'attr_desc' ) {
$key = 'a_desc';
}
if( $key === 'attr_badge' ) {
$key = 'a_badge';
}
if( $key === 'attr_read_more' ) {
$key = 'a_readmore';
}
if( $key === 'attr_readmore_text' ) {
$key = 'a_readmoretext';
}
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
// $result = $rpQuery->get_row("SELECT `$key` FROM `$table_rs_repair` WHERE `a_uq_id` = '".rp_escape_sql($uqid)."' AND r_id_fk = '".rp_escape_sql($connection_id)."' LIMIT 1;");
$result = rp_get_repair_attr_row_by_uqid_and_r_id_fk_cached( $uqid, $connection_id );
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
if( $use_language === 'selected' ) {
global $wp_repair_selected_language;
$default_language = $wp_repair_selected_language;
} else {
global $rp_use_order_related_language;
if( isset( $rp_use_order_related_language ) && !empty( $rp_use_order_related_language ) ) {
$default_language = $rp_use_order_related_language;
} else {
$cache = RepairPluginPro\RP_Memory_Cache::get('rp_get_default_language');
if( empty( $cache ) ) {
$default_language = rp_get_default_language();
RepairPluginPro\RP_Memory_Cache::save('rp_get_default_language', $default_language);
} else {
$default_language = $cache;
}
}
}
// select value from rs_r_translations where key = $key and uq_id = $uqid and m_id_fk = $connection_id
// $result = $rpQuery->get_row("SELECT `value` FROM `$table_rs_r_translations` WHERE `key` = '".rp_escape_sql($org_key)."' AND `uq_id` = '".rp_escape_sql($uqid)."' AND r_id_fk = '".rp_escape_sql($connection_id)."' AND `language` = '".rp_escape_sql($default_language)."' LIMIT 1;");
$d_result = rp_get_static_translations_of_dattr($org_key, $uqid, $default_language);
if( !empty( $d_result ) ) {
$final_result = $d_result;
} else {
$result = rp_get_dynamic_translations_of_attr($connection_id, $default_language);
if( is_array( $result ) && isset( $result[$uqid.$org_key] ) ) {
$final_result = $result[$uqid.$org_key];
}
}
return $final_result ?? '';
}
/*
Get static translation of attr by language
*/
function rp_get_static_translations_of_attr_by_language_individually_editable($key = '', $uqid = '', $connection_id = '', $language = '') {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_rattr_translations";
$table_rs_repair = $rpQuery->prefix . "rs_repair_attr";
$org_key = $key;
if( $key === 'attr_name' ) {
$key = 'a_name';
}
if( $key === 'attr_desc' ) {
$key = 'a_desc';
}
if( $key === 'attr_badge' ) {
$key = 'a_badge';
}
if( $key === 'attr_read_more' ) {
$key = 'a_readmore';
}
if( $key === 'attr_readmore_text' ) {
$key = 'a_readmoretext';
}
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `$key` FROM `$table_rs_repair` WHERE `a_uq_id` = '".rp_escape_sql($uqid)."' AND r_id_fk = '".rp_escape_sql($connection_id)."' LIMIT 1;");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
$default_language = $language;
$result = rp_get_dynamic_translations_of_attr($connection_id, $default_language);
if( is_array( $result ) && isset( $result[$uqid.$org_key] ) ) {
$final_result = $result[$uqid.$org_key];
} else {
$d_result = rp_get_static_translations_of_dattr($org_key, $uqid, $default_language);
if( !empty( $d_result ) ) {
$final_result = $d_result;
}
}
return $final_result;
}
function rp_get_static_translations_of_attr_by_language($key = '', $uqid = '', $connection_id = '', $language = '') {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_rattr_translations";
$table_rs_repair = $rpQuery->prefix . "rs_repair_attr";
$org_key = $key;
if( $key === 'attr_name' ) {
$key = 'a_name';
}
if( $key === 'attr_desc' ) {
$key = 'a_desc';
}
if( $key === 'attr_badge' ) {
$key = 'a_badge';
}
if( $key === 'attr_read_more' ) {
$key = 'a_readmore';
}
if( $key === 'attr_readmore_text' ) {
$key = 'a_readmoretext';
}
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
$result = $rpQuery->get_row("SELECT `$key` FROM `$table_rs_repair` WHERE `a_uq_id` = '".rp_escape_sql($uqid)."' AND r_id_fk = '".rp_escape_sql($connection_id)."' LIMIT 1;");
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
$default_language = $language;
$d_result = rp_get_static_translations_of_dattr($org_key, $uqid, $default_language);
if( !empty( $d_result ) ) {
$final_result = $d_result;
} else {
$result = rp_get_dynamic_translations_of_attr($connection_id, $default_language);
if( is_array( $result ) && isset( $result[$uqid.$org_key] ) ) {
$final_result = $result[$uqid.$org_key];
}
}
return $final_result;
}
function rp_get_dynamic_translations_of_attr($connection_id = '', $default_language = '') {
$cache_key = md5('rp_get_dynamic_translations_of_attr' . $connection_id . $default_language);
$cache = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if( $cache !== NULL && is_array( $cache ) ) {
return $cache;
}
global $rpQuery;
$table_rs_rattr_translations = $rpQuery->prefix . "rs_rattr_translations";
$result = $rpQuery->get_results("SELECT * FROM `$table_rs_rattr_translations` WHERE r_id_fk = '".rp_escape_sql($connection_id)."' AND `language` = '".rp_escape_sql($default_language)."';");
$prepared = array();
if( !empty( $result ) ) {
foreach( $result as $row ) {
$prepared[$row->uq_id.$row->key] = $row->value;
}
}
RepairPluginPro\RP_Memory_Cache::save($cache_key, $prepared);
return $prepared;
}
/*
Get static translation of default attr
*/
function rp_get_default_attrs_based_on_ud_id_cached( $uqid = '' ) {
static $rp_get_default_attrs_based_on_ud_id_cached = NULL;
if( $rp_get_default_attrs_based_on_ud_id_cached !== NULL && array_key_exists( $uqid, $rp_get_default_attrs_based_on_ud_id_cached ) ) {
return $rp_get_default_attrs_based_on_ud_id_cached[ $uqid ];
}
global $rpQuery;
$table_rs_repair = $rpQuery->prefix . "rs_default_repair_attr";
$result = $rpQuery->get_results("SELECT * FROM `$table_rs_repair`");
$rp_get_default_attrs_based_on_ud_id_cached = array();
foreach( $result as $repairRow ) {
$rp_get_default_attrs_based_on_ud_id_cached[ $repairRow->da_uq_id ] = $repairRow;
}
if( $rp_get_default_attrs_based_on_ud_id_cached !== NULL && array_key_exists( $uqid, $rp_get_default_attrs_based_on_ud_id_cached ) ) {
return $rp_get_default_attrs_based_on_ud_id_cached[ $uqid ];
}
return array();
}
function rp_get_static_translations_of_dattr($key = '', $uqid = '', $lang = '') {
global $rpQuery;
$table_rs_r_translations = $rpQuery->prefix . "rs_dr_translations";
$table_rs_repair = $rpQuery->prefix . "rs_default_repair_attr";
$org_key = $key;
if( $key === 'attr_name' ) {
$key = 'da_name';
}
if( $key === 'attr_desc' ) {
$key = 'da_desc';
}
if( $key === 'attr_badge' ) {
$key = 'da_badge';
}
if( $key === 'attr_read_more' ) {
$key = 'da_readmore';
}
if( $key === 'attr_readmore_text' ) {
$key = 'da_readmoretext';
}
// select $key from rs_repair where r_uq_id = $uqid and m_id_fk = $connection_id
// $result = $rpQuery->get_row("SELECT `$key` FROM `$table_rs_repair` WHERE `da_uq_id` = '".rp_escape_sql($uqid)."';");
$result = rp_get_default_attrs_based_on_ud_id_cached( $uqid );
$final_result = '';
if( !empty( $result ) ) {
$final_result = $result->{$key};
}
if(!empty($lang)) {
$default_language = $lang;
} else {
$default_language = rp_get_default_language();
}
// select value from rs_r_translations where key = $key and uq_id = $uqid and m_id_fk = $connection_id
// $result = $rpQuery->get_row("SELECT * FROM `$table_rs_r_translations` WHERE `key` = '".rp_escape_sql($org_key)."' AND `uq_id` = '".rp_escape_sql($uqid)."' AND `language` = '".rp_escape_sql($default_language)."';");
$result = rp_get_default_repair_translation_key_uqid_lang_cached( $org_key, $uqid, $default_language );
if( !empty( $result ) ) {
$final_result = $result->value;
}
return $final_result ?? '';
}
/*
Update related repair translations in all languages by key
*/
function rp_update_r_translations_individually_editable() {
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_update_r_translations_individually_editable();
}
rp_ajax_for_admin('rp_update_r_translations_individually_editable', 'rp_update_r_translations_individually_editable');
function rp_update_r_translations() {
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_update_r_translations();
}
rp_ajax_for_admin('rp_update_r_translations', 'rp_update_r_translations');
/*
Update related repair translations in all languages by key
*/
function rp_update_rcat_translations() {
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_update_rcat_translations();
}
rp_ajax_for_admin('rp_update_rcat_translations', 'rp_update_rcat_translations');
/*
Update related attr translations in all languages by key
*/
function rp_update_rattr_translations_individually_editable() {
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_update_rattr_translations_individually_editable();
}
rp_ajax_for_admin('rp_update_rattr_translations_individually_editable', 'rp_update_rattr_translations_individually_editable');
function rp_update_rattr_translations() {
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_update_rattr_translations();
}
rp_ajax_for_admin('rp_update_rattr_translations', 'rp_update_rattr_translations');
/*
Update related default repair translations in all languages by key
*/
function rp_update_dr_translations() {
rp_verify_csrf_token_for_ajax('default_repairs');
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_update_dr_translations();
}
rp_ajax_for_admin('rp_update_dr_translations', 'rp_update_dr_translations');
/*
Update related default repair category translations in all languages by key
*/
function rp_update_drcat_translations() {
rp_verify_csrf_token_for_ajax('default_repairs');
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_update_drcat_translations();
}
rp_ajax_for_admin('rp_update_drcat_translations', 'rp_update_drcat_translations');
/*
Update related upsale translations in all languages by key
*/
function rp_update_upsale_translations() {
rp_verify_csrf_token_for_ajax('manage_upsales');
(new RepairPluginPro\RP_Upsale_Translations())->rp_update_upsale_translations();
}
rp_ajax_for_admin('rp_update_upsale_translations', 'rp_update_upsale_translations');
/*
Update related upsale translations in all languages by key
*/
function rp_update_checklist_translations() {
rp_verify_csrf_token_for_ajax('styling');
(new RepairPluginPro\RP_Checklist_Translations())->rp_update_checklist_translations();
}
rp_ajax_for_admin('rp_update_checklist_translations', 'rp_update_checklist_translations');
/*
Update related special date translations in all languages by key
*/
function rp_update_special_date_translations() {
rp_verify_csrf_token_for_ajax('special_opening_times');
(new RepairPluginPro\RP_Special_Date_Translations())->rp_update_special_date_translations();
}
rp_ajax_for_admin('rp_update_special_date_translations', 'rp_update_special_date_translations');
/*
Update related form fields translations in all languages by key
*/
function rp_update_form_fields_translations() {
rp_verify_csrf_token_for_ajax('planning_discount');
(new RepairPluginPro\RP_Form_Fields_Translations())->rp_update_form_fields_translations();
}
rp_ajax_for_admin('rp_update_form_fields_translations', 'rp_update_form_fields_translations');
/*
Update related form fields options translations in all languages by key
*/
function rp_update_form_fields_options_translations() {
rp_verify_csrf_token_for_ajax('planning_discount');
(new RepairPluginPro\RP_Form_Fields_Options_Translations())->rp_update_form_fields_options_translations();
}
rp_ajax_for_admin('rp_update_form_fields_options_translations', 'rp_update_form_fields_options_translations');
/*
Update related priority options translations in all languages by key
*/
function rp_update_priority_options_translations() {
rp_verify_csrf_token_for_ajax('planning_discount');
(new RepairPluginPro\RP_Priority_Options_Translations())->rp_update_priority_options_translations();
}
rp_ajax_for_admin('rp_update_priority_options_translations', 'rp_update_priority_options_translations');
/*
Update related default attr translations in all languages by key
*/
function rp_update_drattr_translations() {
rp_verify_csrf_token_for_ajax('default_repairs');
rp_verify_user_full_access_ajax();
(new RepairPluginPro\RP_Repair_Translations())->rp_update_drattr_translations();
}
rp_ajax_for_admin('rp_update_drattr_translations', 'rp_update_drattr_translations');
/* Translate repairs and attributes */
function rp_translate_locked_repairs_and_attributes( $repairs = array(), $attrs = array() ) {
global $rpQuery;
$rs_repair = $rpQuery->prefix . "rs_repair";
$rs_repair_attr = $rpQuery->prefix . "rs_repair_attr";
if( !empty( $repairs ) ) {
foreach($repairs as $index => $repair_row) {
if( isset($repair_row->repair_name) && !empty($repair_row->repair_name) ) {
$row = $rpQuery->get_row("SELECT * FROM `$rs_repair` WHERE `r_id` = '".rp_escape_sql($repair_row->r_id_fk)."';");
if( !empty( $row ) ) {
$translated = rp_get_static_translations_of_repair('repair_name', $row->r_uq_id, $row->m_id_fk);
if( !empty( $translated ) ) {
$repair_row->repair_name = $translated;
}
}
$repairs[$index] = $repair_row;
} else {
unset($repair_row->repair_name);
}
if( isset($repair_row->r_name) ) {
$translated = rp_get_static_translations_of_repair('repair_name', $repair_row->r_uq_id, $repair_row->m_id_fk);
if( !empty( $translated ) ) {
$repair_row->r_name = $translated;
}
$repairs[$index] = $repair_row;
} else {
$repair_row->r_name = '';
}
}
}
if( !empty( $attrs ) ) {
foreach($attrs as $index => $attr_row) {
if( isset( $attr_row->repair_attr_name ) && !empty( $attr_row->repair_attr_name ) ) {
$row = $rpQuery->get_row("SELECT * FROM `$rs_repair_attr` WHERE `a_id` = '".rp_escape_sql($attr_row->ra_id_fk)."';");
if( !empty( $row ) ) {
$translated = rp_get_static_translations_of_attr('attr_name', $row->a_uq_id, $row->r_id_fk);
if( !empty( $translated ) ) {
$attr_row->repair_attr_name = $translated;
}
$translated_attr = rp_get_static_translations_of_attr('attr_desc', $row->a_uq_id, $row->r_id_fk);
if( !empty( $translated_attr ) ) {
$attr_row->repair_attr_desc = $translated_attr;
}
$translated_badge = rp_get_static_translations_of_attr('attr_badge', $row->a_uq_id, $row->r_id_fk);
if( !empty( $translated_badge ) ) {
$attr_row->repair_attr_badge = $translated_badge;
}
}
$attrs[$index] = $attr_row;
} else {
unset($attr_row->repair_attr_name);
}
if( isset($attr_row->a_name) ) {
$translated = rp_get_static_translations_of_attr('attr_name', $attr_row->a_uq_id, $attr_row->r_id_fk);
if( !empty( $translated ) ) {
$attr_row->a_name = $translated;
}
$translated_attr = rp_get_static_translations_of_attr('attr_desc', $attr_row->a_uq_id, $attr_row->r_id_fk);
if( !empty( $translated_attr ) ) {
$attr_row->a_desc = $translated_attr;
}
$translated_badge = rp_get_static_translations_of_attr('attr_badge', $attr_row->a_uq_id, $attr_row->r_id_fk);
if( !empty( $translated_badge ) ) {
$attr_row->a_badge = $translated_badge;
}
$attrs[$index] = $attr_row;
} else {
$attr_row->a_name = '';
}
}
}
return array( $repairs, $attrs );
}
/* Translate upsales */
function rp_translate_locked_upsales( $upsales = array() ) {
global $rpQuery;
$rs_upsales = $rpQuery->prefix . "rs_upsales";
if( !empty( $upsales ) ) {
foreach($upsales as $index => $upsale_row) {
if( isset($upsale_row->upsale_name) && !empty($upsale_row->upsale_name) ) {
$row = $rpQuery->get_row("SELECT * FROM `$rs_upsales` WHERE `upsales_id` = '".rp_escape_sql($upsale_row->upsales_id_fk)."';");
if( !empty( $row ) ) {
$translated = rp_get_static_translations_of_upsale_selected('us_name', $row->upsales_id);
if( !empty( $translated ) ) {
$upsale_row->upsale_name = $translated;
}
}
$upsales[$index] = $upsale_row;
} else {
unset($upsale_row->upsale_name);
}
if( isset($upsale_row->us_name) ) {
$translated = rp_get_static_translations_of_upsale_selected('us_name', $upsale_row->upsales_id);
if( !empty( $translated ) ) {
$upsale_row->us_name = $translated;
}
$upsales[$index] = $upsale_row;
} else {
$upsale_row->us_name = '';
}
}
}
return $upsales;
}
function rp_set_order_related_language( $order_id ) {
global $rp_use_order_related_language;
$lang = trim(rp_get_language_by_order_id($order_id));
if( !empty( $lang ) ) {
$rp_use_order_related_language = $lang;
rp_set_new_plugin_language($lang);
}
}
function rp_unset_order_related_language() {
global $rp_use_order_related_language;
if( isset( $rp_use_order_related_language ) ) {
$rp_use_order_related_language = '';
unset( $rp_use_order_related_language );
}
rp_reset_plugin_language();
}
function rp_update_language_name_everywhere( $old_language_name = '', $new_language_name = '' ) {
global $rpQuery;
$rs_dr_translations = $rpQuery->prefix . 'rs_dr_translations';
$rs_rattr_translations = $rpQuery->prefix . 'rs_rattr_translations';
$rs_r_translations = $rpQuery->prefix . 'rs_r_translations';
$rs_translations = $rpQuery->prefix . 'rs_translations';
$rpQuery->query("UPDATE `$rs_dr_translations` SET `language` = '".rp_escape_sql($new_language_name)."' WHERE `language` = '".rp_escape_sql($old_language_name)."';");
$rpQuery->query("UPDATE `$rs_rattr_translations` SET `language` = '".rp_escape_sql($new_language_name)."' WHERE `language` = '".rp_escape_sql($old_language_name)."';");
$rpQuery->query("UPDATE `$rs_r_translations` SET `language` = '".rp_escape_sql($new_language_name)."' WHERE `language` = '".rp_escape_sql($old_language_name)."';");
$rpQuery->query("UPDATE `$rs_translations` SET `language` = '".rp_escape_sql($new_language_name)."' WHERE `language` = '".rp_escape_sql($old_language_name)."';");
}
function rp_create_unique_language_id( $language_name = '' ) {
/* Added in V1.5.0 */
if( trim($language_name) === 'English (United States)' ) {
return 'lang_dfb21ebmKgeS';
}
if( trim($language_name) === 'Dutch (Netherlands)' ) {
return 'lang_5cb71ecQxMIZ';
}
// create random and unique id with language name as prefix
$language_name = trim($language_name);
// limit language name to 10 characters
$language_name = md5($language_name);
$language_name = substr($language_name, 0, 6);
$language_name = $language_name . rp_generate_random_string(6);
return 'lang_' . $language_name;
}
function rp_generate_random_string( $length = 10 ) {
/* Added in V1.5.0 */
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function rp_update_languages_uq_id_for_first_time() {
/* Added in V1.5.0 */
global $rpQuery;
$table_rs_languages = $rpQuery->prefix . 'rs_languages';
$languages = $rpQuery->get_results("SELECT * FROM `$table_rs_languages` WHERE `uq_id` = '' OR `uq_id` IS NULL");
if( !empty($languages) ) {
foreach ($languages as $language) {
$uq_id = rp_create_unique_language_id($language->name);
$rpQuery->query("UPDATE `$table_rs_languages` SET `uq_id` = '".rp_escape_sql($uq_id)."' WHERE `id` = '".rp_escape_sql($language->id)."';");
}
}
}
// Get all dc_uq_id from rs_default_repairs_category table
function rp_get_all_dc_uq_id_from_rs_default_repairs_category() {
/* Added in V1.6.0 */
global $rpQuery;
$rs_default_repairs_category = $rpQuery->prefix . 'rs_default_repairs_category';
$dc_uq_ids = $rpQuery->get_results("SELECT `dc_uq_id` FROM `$rs_default_repairs_category` GROUP BY `dc_uq_id`");
if( !empty($dc_uq_ids) ) {
$dc_uq_ids = array_column($dc_uq_ids, 'dc_uq_id');
return $dc_uq_ids;
}
return array();
}
// Get all dr_uq_id from rs_default_repair table
function rp_get_all_dr_uq_id_from_rs_default_repair_table() {
/* Added in V1.5.0 */
global $rpQuery;
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$dr_uq_ids = $rpQuery->get_results("SELECT `dr_uq_id` FROM `$rs_default_repair` GROUP BY `dr_uq_id`");
if( !empty($dr_uq_ids) ) {
$dr_uq_ids = array_column($dr_uq_ids, 'dr_uq_id');
return $dr_uq_ids;
}
return array();
}
// Get all dr_uq_id from rs_default_repair table and c_uq_id from rs_category table where dr_category = c_id
function rp_get_all_dr_uq_id_and_c_uq_id() {
/* Added in V1.5.0 */
global $rpQuery;
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_category = $rpQuery->prefix . 'rs_category';
$dr_uq_ids = $rpQuery->get_results("SELECT `dr_uq_id`, `c_uq_id` FROM `$rs_default_repair` AS `dr` LEFT JOIN `$rs_category` AS `c` ON `dr`.`dr_category` = `c`.`c_id`");
if( !empty($dr_uq_ids) ) {
$new_arr = array();
foreach( $dr_uq_ids as $row ) {
$new_arr[] = $row->c_uq_id . '|' . $row->dr_uq_id;
}
return $new_arr;
}
return array();
}
// Get all da_uq_id from rs_default_repair_attr table and c_uq_id from rs_category table where dr_category = c_id
function rp_get_all_da_uq_id_and_c_uq_id() {
/* Added in V1.5.0 */
global $rpQuery;
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$rs_category = $rpQuery->prefix . 'rs_category';
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$da_uq_ids = $rpQuery->get_results("SELECT `da_uq_id`, `c_uq_id` FROM `$rs_default_repair_attr` AS `dr` LEFT JOIN `$rs_category` AS `c` ON `dr`.`dr_category` = `c`.`c_id` INNER JOIN `$rs_default_repair` AS `d` ON `dr`.`dr_id_fk` = `d`.`dr_id`"); // temp back
if( !empty($da_uq_ids) ) {
$new_arr = array();
foreach( $da_uq_ids as $row ) {
$new_arr[] = $row->c_uq_id . '|' . $row->da_uq_id;
}
return $new_arr;
}
return array();
}
// Get all uq_id from rs_languages table
function rp_get_all_uq_id_from_rs_languages_table() {
/* Added in V1.5.0 */
global $rpQuery;
$rs_languages = $rpQuery->prefix . 'rs_languages';
$uq_ids = $rpQuery->get_results("SELECT `uq_id` FROM `$rs_languages` GROUP BY `uq_id`");
if( !empty($uq_ids) ) {
$uq_ids = array_column($uq_ids, 'uq_id');
return $uq_ids;
}
return array();
}
// Get all da_uq_id from rs_default_repair_attr table
function rp_get_all_da_uq_id_from_rs_default_repair_attr_table() {
/* Added in V1.5.0 */
global $rpQuery;
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$da_uq_ids = $rpQuery->get_results("SELECT `da_uq_id` FROM `$rs_default_repair_attr` GROUP BY `da_uq_id`");
if( !empty($da_uq_ids) ) {
$da_uq_ids = array_column($da_uq_ids, 'da_uq_id');
return $da_uq_ids;
}
return array();
}
function rp_check_if_combined_index_exists( $table_name = '', $column_names = array(), $prefix = TRUE ) {
global $rpQuery;
if($prefix === TRUE) {
$table_name = $rpQuery->prefix . $table_name;
}
// explode column names by (
foreach ($column_names as $key => $value) {
$value = explode('(', $value);
$column_names[$key] = $value[0];
}
$index_name = implode(',', $column_names);
// show indexes from table
$found_index = $rpQuery->get_results("SELECT `table_name`, GROUP_CONCAT(column_name ORDER BY seq_in_index) AS `index_columns`
FROM information_schema.statistics
WHERE `table_schema` = '".DB_NAME."' AND `table_name` = '$table_name'
GROUP BY `table_name`, `index_name`;");
if( !empty( $found_index ) ) {
foreach ($found_index as $key => $value) {
if($value->index_columns === $index_name) {
return TRUE;
}
}
}
return FALSE;
}
function rp_add_combined_index( $table_name = '', $index_name = '', $column_names = array(), $prefix = TRUE ) {
global $rpQuery;
$table_name_org = $table_name;
if($prefix === TRUE) {
$table_name = $rpQuery->prefix . $table_name;
}
$option_key = 'rp_index_added_'.$table_name_org.'_'.$index_name;
$has_created_index = rp_get_option($option_key, FALSE);
if(empty($has_created_index)) {
$found_index = rp_check_if_combined_index_exists($table_name_org, $column_names, TRUE);
if($found_index === FALSE) {
rp_add_option($option_key, TRUE);
foreach ($column_names as $key => $value) {
$value = explode('(', $value);
$column_names[$key] = '`'.$value[0].'`';
if(isset($value[1])) {
// remove ) from the end
$value[1] = substr($value[1], 0, -1);
$column_names[$key] .= '('.$value[1].')';
}
}
$column_names = implode(',', $column_names);
$sql = "ALTER TABLE `$table_name` ADD INDEX($column_names);";
$rpQuery->query($sql);
return TRUE;
}
}
return FALSE;
}
function rp_add_combined_index_for_repair_used_count() {
rp_add_combined_index('rs_model_color', 'mid_uqid_color', array('m_id_fk', 'mc_uq_id', 'color_name'), TRUE);
rp_add_combined_index('rs_repair', 'r_uq_id_m_id_fk', array('r_uq_id', 'm_id_fk'), TRUE);
rp_add_combined_index('rs_repair_attr', 'a_uq_id_r_id_fk', array('a_uq_id', 'r_id_fk'), TRUE);
rp_add_combined_index('rs_r_translations', 'val_key_uqid_lang', array('key(48)', 'uq_id(48)', 'language(100)', 'value(255)'), TRUE);
rp_add_combined_index('rs_r_translations', 'key_uqid_lang', array('key(48)', 'uq_id(48)', 'language(100)'), TRUE);
rp_add_combined_index('rs_r_translations', 'mid_key_uqid_lang', array('key(48)', 'uq_id(48)', 'language(100)', 'm_id_fk'), TRUE);
rp_add_combined_index('rs_rattr_translations', 'val_key_uqid_lang', array('key(48)', 'uq_id(48)', 'language(100)', 'value(255)'), TRUE);
rp_add_combined_index('rs_rattr_translations', 'key_uqid_lang', array('key(48)', 'uq_id(48)', 'language(100)'), TRUE);
rp_add_combined_index('rs_rattr_translations', 'mid_key_uqid_lang', array('key(48)', 'uq_id(48)', 'language(100)', 'r_id_fk'), TRUE);
}
function rp_get_category_by_c_uq_id( $c_uq_id = '' ) {
global $rpQuery;
$rs_category = $rpQuery->prefix . 'rs_category';
$category_row = $rpQuery->get_row("SELECT * FROM `$rs_category` WHERE `c_uq_id` = '$c_uq_id' LIMIT 1;");
return ($category_row ?? array());
}
function rp_get_category_id_by_c_uq_id( $c_uq_id = '' ) {
global $rpQuery;
$rs_category = $rpQuery->prefix . 'rs_category';
$category_id = $rpQuery->get_var("SELECT `c_id` FROM `$rs_category` WHERE `c_uq_id` = '$c_uq_id' LIMIT 1;");
return ($category_id ?? '');
}
function rp_add_or_update_option( $key = '', $value = NULL ) {
if( rp_get_option($key, FALSE) === FALSE ) {
rp_add_option($key, $value);
} else {
rp_update_option($key, $value);
}
}
function rp_get_all_c_uq_ids_from_rs_category() {
global $rpQuery;
$rs_category = $rpQuery->prefix . 'rs_category';
$c_uq_ids = $rpQuery->get_results("SELECT `c_uq_id` FROM `$rs_category`;");
if( !empty( $c_uq_ids ) ) {
$c_uq_ids = array_column($c_uq_ids, 'c_uq_id');
return $c_uq_ids;
}
return array();
}
function download_languages_from_server_first_time() {
global $rpQuery;
if(isset($_POST['lang_ids'])) {
$lang_ids = $_POST['lang_ids'] ?? array();
if(empty($lang_ids)) {
return;
}
$baselang_class = new RepairPluginPro\Download_Languages($rpQuery);
$alreadyDownloaded = rp_get_uq_id_of_all_rs_languages();
foreach($lang_ids as $key => $lang_id) {
if(in_array($lang_id, $alreadyDownloaded)) {
unset($lang_ids[$key]);
}
}
$lang_ids = array_values($lang_ids);
if( empty( $lang_ids ) ) {
return;
}
$_POST['lang_uq_ids'] = $lang_ids;
$response = $baselang_class->fetch_repair_base(TRUE, FALSE);
$baselang_class->save_handler_first_time($response);
}
}
// It was only for computerglobe.nl website compatibility.
// leaving it so that we can go back to this code and copy if needed in the future in similar scenario
// where indexes are corrupted
// rp_add_action('init', 're_add_rs_repair_attr_indexes_after_deleting_old_ones', 999);
function rp_add_first_time_languages_and_translations(){
if( isset( $GLOBALS['rp_skip_ajax_check'] ) && $GLOBALS['rp_skip_ajax_check'] == true ) {
// Skip the check!!
} else {
if( !wp_doing_ajax() && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' ) !== 'xmlhttprequest' ) {
return;
}
}
global $rpQuery;
$rs_translations = $rpQuery->prefix . 'rs_translations';
$rs_languages = $rpQuery->prefix . 'rs_languages';
if( !defined('WP_REPAIR_REQUIRE_LICENSE') ) {
if( rp_get_option('rp_download_lang_translations_first_time', FALSE) === FALSE ) {
rp_add_option('rp_download_lang_translations_first_time', '1');
// ----------- MAKING SURE IT'S FIRST TIME DOWNLOAD
// in rs_planning_and_discount table, make pickup_service and repair_on_location = 1
$rs_planning_and_discount = $rpQuery->prefix . 'rs_planning_and_discount';
$rpQuery->query("UPDATE `$rs_planning_and_discount` SET `pickup_service` = 1, `repair_on_location` = 1");
// ------------ MAKING SURE IT'S FIRST TIME DOWNLOAD
if( !isset($_POST) ) {
$_POST = array();
}
$_POST['lang_ids'] = array('lang_5cb71ecQxMIZ', 'lang_dfb21ebmKgeS');
// empty rs_languages table
$rpQuery->query("TRUNCATE TABLE `$rs_languages`;");
// empty rs_translations table
$rpQuery->query("TRUNCATE TABLE `$rs_translations`;");
rp_assume_existing_text_as_translated();
rp_assume_existing_text_desc_as_translated();
download_languages_from_server_first_time();
// Latest translations already fetched so mark all groups as fetched
$new_translation_groups = apply_filters('rp_force_fetch_new_translation_groups', array());
if( !empty( $new_translation_groups ) ) {
foreach( $new_translation_groups as $group => $groupItems ) {
if( rp_get_option( $group, FALSE ) === FALSE ) {
rp_add_option( $group, '1' );
}
}
}
}
}
}
rp_add_action('init', 'rp_add_first_time_languages_and_translations', 999);
function rp_assume_existing_text_as_translated() {
$key_value = json_decode('{"repair_105679":"Koptelefoonpoort","repair_112816":"GPS-antenne","repair_121308":"NFC-antenne","repair_139755":"Touchscreen (glas)","repair_163266":"Gyroscoop (draaisensor)","repair_197069":"Softwarereset","repair_198982":"Luidspreker","repair_223897":"Display (LCD)","repair_241218":"Geheugenkaartlezer","repair_265315":"GSM-antenne","repair_266233":"Bluetooth-antenne","repair_272218":"Waterschade","repair_279312":"Simkaartlezer","repair_325712":"Volumeknop(pen)","repair_351195":"Cameraglas","repair_388209":"Nabijheidssensor","repair_401401":"Schermmodule","repair_426379":"Gezichtsherkenningsmodule","repair_433241":"Oplaadpoort","repair_445208":"Oorspeaker","repair_520851":"Vingerafdrukscanner","repair_537674":"Aan-uitknop","repair_540484":"WiFi-antenne","repair_545344":"Batterij","repair_551559":"Stille Modusknop","repair_566600":"Onderzoeken","repair_587656":"Camera voorzijde","repair_680281":"Overzetten oude gegevens","repair_732129":"Draadloze oplaadmodule","repair_768329":"Achterpaneel","repair_806428":"Vergrendelingsreset","repair_839922":"Flitser","repair_860132":"Home-knop","repair_870919":"Microfoon (video)","repair_927037":"Moederbord","repair_929441":"Trilmotor","repair_945141":"Microfoon (telefoon)","repair_947962":"Behuizing","repair_993586":"Camera achterzijde"}', TRUE);
global $rpQuery;
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_dr_translations = $rpQuery->prefix . 'rs_dr_translations';
$languages = array('English (United States)', 'Dutch (Netherlands)');
// get all default repair
$default_repairs = $rpQuery->get_results("SELECT * FROM `$rs_default_repair`");
$keys = array('repair_name');
foreach($default_repairs as $drepair) {
$dr_name = $drepair->dr_name;
$uq_id = $drepair->dr_uq_id;
if( isset($key_value[$uq_id]) ) {
// Is Downloaded Default Repair
if( trim($dr_name) !== trim($key_value[$uq_id]) ) {
// Has Changed Default Repair Name
foreach($keys as $key) {
foreach($languages as $language) {
$rpQuery->insert($rs_dr_translations, array(
'language' => $language,
'key' => $key,
'uq_id' => $uq_id,
'value' => $drepair->dr_name
));
}
}
}
}
}
}
function rp_assume_existing_text_desc_as_translated() {
$key_value = json_decode('{"repair_105679":"Verstopping van de ingang en\/of geen verbinding met bekabelde headset mogelijk.","repair_112816":"Problemen met navigatie en\/of het verkrijgen locatiegegevens.","repair_121308":"Problemen met contactloos betalen, digitale toegangsbewijzen of legitimatie met DigiD-app.","repair_139755":"Scherm reageert niet\/slecht op aanrakingen en\/of is gebarsten.","repair_163266":"Bij kwartslag apparaat draait scherm niet mee.","repair_197069":"Problemen met updates besturingssysteem of wissen van gegevens (gebruikersinformatie, beeldmateriaal en apps).","repair_198982":"Weinig, slecht of geen geluid uit interne speakers.","repair_223897":"Het scherm toont ongewenste strepen, vegen en\/of kleuren.","repair_241218":"SD-kaart wordt niet herkend en\/of de pinnetjes zijn gebroken.","repair_265315":"Niet mogelijk om verbinding te maken met 3G- of 4G-netwerk.","repair_266233":"Verbindingsproblemen met draadloze speakers, headsets of andere randapparatuur.","repair_272218":"Defecten na contact met water of andere vloeistoffen.","repair_279312":"Problemen met herkennen van simkaart en\/of gebroken pinnetjes in de sleuf.","repair_325712":"Knop reageert niet en\/of kan niet ingedrukt worden.","repair_351195":"Vuil onder en\/of beschadigingen in het glas van de lens.","repair_388209":"Schermslot schakelt zichzelf niet in tijdens telefoongesprekken aan het oor. ","repair_401401":"Fysieke barsten en\/of ongewenste strepen\/vegen\/kleuren in het display.","repair_426379":"Ontgrendelen via iris- of gezicht is niet mogelijk.","repair_433241":"Opladen en\/of verbinding maken met computer niet mogelijk.","repair_445208":"Tijdens telefoongesprekken kun je de andere persoon niet of slecht horen.","repair_520851":"Problemen met ontgrendelen of legitimatie via vingerafdruk.","repair_537674":"De aan-uitknop reageert niet en\/of kan niet ingedrukt worden.","repair_540484":"Last van trage verbinding via WiFi, oorzaak ligt niet bij internetprovider.","repair_545344":"Apparaat valt onverwacht uit, is snel leeg en\/of moet vaak aan de lader.","repair_551559":"Schuifknop aan de zijkant werkt niet en\/of kan niet verschoven worden.","repair_566600":"Niet zeker wat er mis is? Geen probleem! Wij voeren een onderzoek uit.","repair_587656":"Selfie-camera werkt niet en\/of maakt slechte, onduidelijke of onscherpe beelden.","repair_680281":"Overdracht bestanden van oud naar nieuw toestel zonder verlies persoonlijke gegevens.","repair_732129":"Bekabeld opladen werkt normaal terwijl draadloos niet mogelijk is.","repair_768329":"Barsten in glasplaat aan de achterkant.","repair_806428":"Geen ontgrendeling mogelijk omdat toegangscode niet werkt, ontbreekt en\/of vergeten is.","repair_839922":"De camera flits kan niet meer ingeschakeld worden en\/of uw zaklamp werkt niet. ","repair_860132":"De knop (onder) reageert niet en\/of kan niet ingedrukt worden.","repair_870919":"Geen\/slechte audio van video-opnames en\/of geen gehoor bij videobellen of telefoongesprekken via de luidspreker.","repair_927037":"Vervangbare onderdelen lijken allemaal in orde, toestel toch defect. (Nader onderzoek vereist)","repair_929441":"Trilfunctie werkt niet bij notificaties.","repair_945141":"Anderen horen jou niet of slecht tijdens telefoongesprekken.","repair_947962":"Deuken of krassen aan de randen en\/of achterkant.","repair_993586":"Camera(\u2019s) aan de achterkant van het toestel werkt niet en\/of maakt slechte, onduidelijke of onscherpe beelden."}', TRUE);
global $rpQuery;
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_dr_translations = $rpQuery->prefix . 'rs_dr_translations';
$languages = array('English (United States)', 'Dutch (Netherlands)');
// get all default repair
$default_repairs = $rpQuery->get_results("SELECT * FROM `$rs_default_repair`");
$keys = array('repair_desc');
foreach($default_repairs as $drepair) {
$dr_discription = $drepair->dr_discription;
$uq_id = $drepair->dr_uq_id;
if( isset($key_value[$uq_id]) ) {
// Is Downloaded Default Repair
if( trim($dr_discription) !== trim($key_value[$uq_id]) ) {
// Has Changed Default Repair Name
foreach($keys as $key) {
foreach($languages as $language) {
$rpQuery->insert($rs_dr_translations, array(
'language' => $language,
'key' => $key,
'uq_id' => $uq_id,
'value' => $drepair->dr_discription
));
}
}
}
}
}
}
function rp_get_search_box_redirect_link() {
/* Added in V1.5.0 */
$permalink = rp_get_option('rp_search_box_redirect_option', 'Find It Automatically');
if( $permalink === 'Use My Custom Link' ) {
$link = rp_get_option('rp_search_box_custom_redirect_link', '');
if( !empty( $link ) && filter_var($link, FILTER_VALIDATE_URL) ) {
return $link;
}
}
return '';
}
// add 'Approved (Send device)' in noti_type column of rs_notification_types table
function add_approved_send_device_in_rs_notification_types() {
/* Added in V1.4.5 */
global $rpQuery;
$noti_type = 'Booking Approved (Send device)';
$rs_notification_types = $rpQuery->prefix . 'rs_notification_types';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notification_types` WHERE `noti_type` = '".rp_escape_sql($noti_type)."' LIMIT 1;");
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notification_types` (`noti_type`, `is_active`) VALUES ('".rp_escape_sql($noti_type)."', '1');");
}
}
rp_add_action('init', 'add_approved_send_device_in_rs_notification_types', 999);
// insert into all columns from rs_notifications_and_offers table if noti_type_id_fk 5 doesn't exist
function insert_approved_send_device_markup_in_notification_table() {
/* Added in V1.4.5 */
global $rpQuery;
$rs_notifications_and_offers = $rpQuery->prefix . 'rs_notifications_and_offers';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notifications_and_offers` WHERE `noti_type_id_fk` = '6' LIMIT 1;");
$subject = 'Uw afspraak is goedgekeurd';
$message = '<p>Beste $CustomerName$,</p> <p>Bedankt voor het maken van een afspraak bij $LocationName$ om jouw $Model$ te laten repareren.</p> <h3 style="font-family: sans-serif; font-size: 24px; border-radius: 8px; padding: 6px 12px; margin-bottom: 10px; background-color: #d5e4f4; color: #000000; border: 1px solid #b5c6b6;">De afspraak is op $AppointmentDate$, om $AppointmentTime$ uur.</h3> <p> </p> <p>$OrderSummary$</p> <p> </p> <p><strong>Uw gegevens<br></strong>Naam: $CustomerName$<br>Email: $CustomerEmail$<br>Tel: $CustomerPhone$</p> <p> </p> <p>Tijdens de reparatie kun je wachten bij ons in de winkel. We hebben supersnelle Wi-fi en heerlijke koffie. Komt het toch niet uit en wil je de afspraak annuleren?<br /><br />Klik dan op de volgende link: $cancel$.</p> <p> </p> <p>Met vriendelijke groet,</p> <p><strong>$LocationName$<br /></strong>$LocationAddress$<br />$LocationZipcodeCity$</p> <p> </p> <p> </p> <footer style="margin-top: 20px; font-size: 80%; color: #888; clear: both;"> <p>Je krijgt deze e-mail omdat er een afspraak is gemaakt met dit emailadres op de website van $LocationName$. Deze e-mail is een bevestiging van de gemaakte afspraak. Heb je deze afspraak niet zelf gemaakt, neem dan contact met ons op.</p> </footer>';
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notifications_and_offers` (`noti_subject`, `noti_message`, `noti_type_id_fk`, `is_active`, `date_time`) VALUES ('$subject', '$message', '6', '1', '".date('Y-m-d H:i:s')."');");
}
}
rp_add_action('init', 'insert_approved_send_device_markup_in_notification_table', 999);
function rp_get_last_models_downloaded_date() {
/* Added in V1.5.0 */
global $rpQuery;
$model_table = $rpQuery->prefix . 'rs_model';
$latest_package = $rpQuery->get_row("SELECT * FROM $model_table ORDER BY updated_on DESC");
if(!empty($latest_package)){
$date = strtotime($latest_package->updated_on);
$date = date('Y-m-d H:i:s', $date);
return $date;
}
return FALSE;
}
function rp_update_option_for_existing_customers() {
/* Added in V1.5.0 */
if( rp_get_option('rp_download_models_last_update', FALSE) === FALSE ) {
$date = rp_get_last_models_downloaded_date();
if( !empty( $date ) ) {
rp_add_option('rp_download_models_last_update', $date);
}
}
}
rp_add_action('init', 'rp_update_option_for_existing_customers', 999);
// add 'Reminder' in noti_type column of rs_notification_types table
function add_reminder_in_rs_notification_types() {
/* Added in V1.5.0 */
global $rpQuery;
$noti_type = 'Reminder';
$rs_notification_types = $rpQuery->prefix . 'rs_notification_types';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notification_types` WHERE `noti_type` = '".rp_escape_sql($noti_type)."' LIMIT 1;");
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notification_types` (`noti_type`, `is_active`) VALUES ('".rp_escape_sql($noti_type)."', '1');");
}
}
rp_add_action('init', 'add_reminder_in_rs_notification_types', 999);
// insert into all columns from rs_notifications_and_offers table if noti_type_id_fk 5 doesn't exist
function insert_reminder_markup_in_notification_table() {
/* Added in V1.5.0 */
global $rpQuery;
$rs_notifications_and_offers = $rpQuery->prefix . 'rs_notifications_and_offers';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notifications_and_offers` WHERE `noti_type_id_fk` = '7' LIMIT 1;");
$subject = 'Subject for Reminder Email';
$message = 'This is message for reminder email';
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notifications_and_offers` (`noti_subject`, `noti_message`, `noti_type_id_fk`, `is_active`, `date_time`) VALUES ('$subject', '$message', '7', '1', '".date('Y-m-d H:i:s')."');");
}
}
rp_add_action('init', 'insert_reminder_markup_in_notification_table', 999);
// add 'Aftersales' in noti_type column of rs_notification_types table
function add_aftersales_in_rs_notification_types() {
/* Added in V1.5.0 */
global $rpQuery;
$noti_type = 'Aftersales';
$rs_notification_types = $rpQuery->prefix . 'rs_notification_types';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notification_types` WHERE `noti_type` = '".rp_escape_sql($noti_type)."' LIMIT 1;");
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notification_types` (`noti_type`, `is_active`) VALUES ('".rp_escape_sql($noti_type)."', '1');");
}
}
rp_add_action('init', 'add_aftersales_in_rs_notification_types', 999);
// insert into all columns from rs_notifications_and_offers table if noti_type_id_fk 5 doesn't exist
function insert_aftersales_markup_in_notification_table() {
/* Added in V1.5.0 */
global $rpQuery;
$rs_notifications_and_offers = $rpQuery->prefix . 'rs_notifications_and_offers';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notifications_and_offers` WHERE `noti_type_id_fk` = '8' LIMIT 1;");
$subject = 'Subject for Aftersales Email';
$message = 'This is message for aftersales email';
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notifications_and_offers` (`noti_subject`, `noti_message`, `noti_type_id_fk`, `is_active`, `date_time`) VALUES ('$subject', '$message', '8', '1', '".date('Y-m-d H:i:s')."');");
}
}
rp_add_action('init', 'insert_aftersales_markup_in_notification_table', 999);
function rp_get_come_our_store_available_days( $loc_id = 0, $selectedDate = '' ) {
if( empty( $selectedDate ) ) {
$selectedDate = date('Y-m-d');
}
// Using -1 just to avoid bug. For example the page was visited at 23:59 2024-02-11
// but ajax request is created on 00:00 2024-02-12. So 2024-02-11 will not be there
// in below list and cause the bug if we use 0.
// Using -1 always will make sure we never get this bug
$count = -1;
$key_pair = array();
while ($count < 14) {
$countDays = '+'.$count;
if( $countDays < 0 ) {
$countDays = '-'.$count;
}
$calc = date('D d', strtotime(date('Y-m-d').' '.$countDays.' days'));
$day = date('l', strtotime(date('Y-m-d').' '.$countDays.' days'));
$date = date('d-m-Y', strtotime(date('d-m-Y').' '.$countDays.' days'));
$calc = explode(' ', $calc);
$selected = '';
$is_day_off = '';
if(strtotime(date('Y-m-d').' '.$countDays.' days') === strtotime($selectedDate)) {
$selected = ' selected';
}
$date_ymd = date('Y-m-d', strtotime(date('Y-m-d').' '.$countDays.' days'));
$is_day_off = rp_is_day_off( $loc_id, $day, $date_ymd ) ? ' is_day_off' : '';
$key_pair[$date] = array();
if( !empty( $selected ) ) {
$key_pair[$date][] = $selected;
}
if( !empty( $is_day_off ) ) {
$key_pair[$date][] = $is_day_off;
}
$count++;
}
return $key_pair;
}
function rp_get_all_reminder_emails() {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$all_orders = $rpQuery->get_results("SELECT * FROM `$rs_orders` WHERE `reminder` = '0' AND (`created_time` IS NOT NULL AND `created_time` != '');");
$filtered_orders = array();
$rp_x_hours_before_appointment = (int) rp_get_option('rp_x_hours_before_appointment', '2');
foreach ($all_orders as $order) {
$_delivery_method = str_replace(' ', '_', strtolower(trim($order->delivery_method)));
if(empty( ($order->created_time ?? '') ) || $_delivery_method == 'ship_device' || $_delivery_method == 'pdf_offer' ) {
continue;
}
if( empty( trim( $order->delivery_date ) ) || empty( trim( $order->delivery_time ) ) ) {
continue;
}
$delivery_date = $order->delivery_date;
if( strpos($delivery_date, '-') !== 4 ) {
// convert d-m-Y to Y-m-d
$delivery_date_arr = explode('-', $delivery_date);
$delivery_date = $delivery_date_arr[2] . '-' . $delivery_date_arr[1] . '-' . $delivery_date_arr[0];
}
if( strpos( $order->delivery_time, ' — ' ) !== FALSE ) {
$delivery_time = explode(' — ', $order->delivery_time)[0];
$delivery_time = date('H:i:s', strtotime($delivery_time));
} else {
$delivery_time = date('H:i:s', strtotime($order->delivery_time));
}
$appointment_date_time = strtotime($delivery_date . ' ' . $delivery_time); // 10:30
$appointment_date_time_less_x_hours = $appointment_date_time - ($rp_x_hours_before_appointment * 3600); // 10:30 - 2 hours = 8:30
$created_time = strtotime($order->created_time);
$diff = $appointment_date_time - $created_time;
$diff_in_hours = $diff / 3600;
if( $diff_in_hours > $rp_x_hours_before_appointment ) {
// We will have opportunity to send reminder email
$current_time = strtotime(date('Y-m-d H:i:s'));
if( $current_time >= $appointment_date_time_less_x_hours && $current_time < $appointment_date_time && ((int) $order->status_id_fk == 3) ) {
$payment_method = ($order->payment_method ?? '');
$payment_status = ($order->payment_status ?? '');
$online_payment_methods = array('stripe', 'paypal', 'mollie', 'ideal_in3');
if( !empty( $payment_method ) && in_array( $payment_method, $online_payment_methods ) !== FALSE ) {
// Is online payment method
if( strtolower( $payment_status ) == 'paid' ) {
$filtered_orders[] = $order->o_id;
}
} else {
// Not an online payment method...
$filtered_orders[] = $order->o_id;
}
}
}
}
return $filtered_orders;
}
function rp_get_all_aftersales_emails() {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$all_orders = $rpQuery->get_results("SELECT * FROM `$rs_orders` WHERE `aftersales` = '0' AND (`created_time` IS NOT NULL AND `created_time` != '');");
$filtered_orders = array();
$rp_x_hours_after_appointment = (int) rp_get_option('rp_x_hours_after_appointment', '2');
foreach ($all_orders as $order) {
$_delivery_method = str_replace(' ', '_', strtolower(trim($order->delivery_method)));
if(empty( ($order->created_time ?? '') ) || $_delivery_method == 'ship_device' || $_delivery_method == 'pdf_offer' ) {
continue;
}
if( empty( trim( $order->delivery_date ) ) || empty( trim( $order->delivery_time ) ) ) {
continue;
}
$delivery_date = $order->delivery_date;
if( strpos($delivery_date, '-') !== 4 ) {
// convert d-m-Y to Y-m-d
$delivery_date_arr = explode('-', $delivery_date);
$delivery_date = $delivery_date_arr[2] . '-' . $delivery_date_arr[1] . '-' . $delivery_date_arr[0];
}
if( strpos( $order->delivery_time, ' — ' ) !== FALSE ) {
$delivery_time = explode(' — ', $order->delivery_time)[1];
$delivery_time = date('H:i:s', strtotime($delivery_time));
} else {
$delivery_time = date('H:i:s', strtotime($order->delivery_time));
}
$appointment_date_time = strtotime($delivery_date . ' ' . $delivery_time); // 10:30
$appointment_date_time_plus_x_hours = $appointment_date_time + ($rp_x_hours_after_appointment * 3600); // 10:30 + 2 hours = 12:30
$current_time = strtotime(date('Y-m-d H:i:s'));
$max_time_for_aftersale = $appointment_date_time_plus_x_hours + ( 7 * 24 * 60 * 60 ); // If 7 days have passed after the time we had to send aftersale email, skip it. We no longer need to send the aftersale email now. This is for the scenario when user had aftersales disabled for a month or so and then they re-enabled it.
if( $current_time >= $appointment_date_time_plus_x_hours && $current_time <= $max_time_for_aftersale && (((int) $order->status_id_fk == 3) || ((int) $order->status_id_fk == 11)) ) {
$payment_method = ($order->payment_method ?? '');
$payment_status = ($order->payment_status ?? '');
$online_payment_methods = array('stripe', 'paypal', 'mollie', 'ideal_in3');
if( !empty( $payment_method ) && in_array( $payment_method, $online_payment_methods ) !== FALSE ) {
// Is online payment method
if( strtolower( $payment_status ) == 'paid' ) {
$filtered_orders[] = $order->o_id;
}
} else {
// Not an online payment method...
$filtered_orders[] = $order->o_id;
}
}
}
return $filtered_orders;
}
function rp_send_all_reminder_emails() {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$filtered_orders = rp_get_all_reminder_emails();
foreach ($filtered_orders as $order_id) {
rp_send_appointment_status_update_email($order_id, FALSE);
// update reminder status to 1
$rpQuery->query("UPDATE `$rs_orders` SET `reminder` = '1' WHERE `o_id` = '$order_id';");
}
}
function rp_send_all_aftersales_emails() {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$filtered_orders = rp_get_all_aftersales_emails();
foreach ($filtered_orders as $order_id) {
rp_send_appointment_status_update_email($order_id, FALSE);
// update aftersales status to 1
$rpQuery->query("UPDATE `$rs_orders` SET `aftersales` = '1' WHERE `o_id` = '$order_id';");
}
}
function _rp_return_7($status = '', $order = NULL) {
return 7;
}
function _rp_return_8($status = '', $order = NULL) {
return 8;
}
function rp_send_scheduled_emails() {
global $rp_cron_job;
if( isset($rp_cron_job) && $rp_cron_job === 'rp' ) {
rp_update_option( 'rp_last_scheduled_emails_cron_run', time() );
_rp_set_default_tiemzone();
// Reminder
add_filter('rp_override_status_while_sending_email', '_rp_return_7', 2);
rp_send_all_reminder_emails();
remove_filter('rp_override_status_while_sending_email', '_rp_return_7');
// Aftersales
add_filter('rp_override_status_while_sending_email', '_rp_return_8', 2);
rp_send_all_aftersales_emails();
remove_filter('rp_override_status_while_sending_email', '_rp_return_8');
$start_time = microtime( true );
rp_generate_needed_analytics_reports();
include_once WP_REPAIR_PLUGIN_PATH.'html/order_emails.php';
while( ( microtime( true ) - $start_time ) < 30 && !empty( $queued_email = rp_get_a_single_queued_email() ) ) {
if( filter_var( $queued_email->email ?? '', FILTER_VALIDATE_EMAIL ) !== FALSE ) {
wp_repair_send_mail( $queued_email->email, $queued_email->subject, $queued_email->message, $queued_email->bcc_email );
}
}
}
exit;
}
function _run_rp_send_scheduled_emails_through_cron() {
if( isset( $_REQUEST['action'] ) && ( $_REQUEST['action'] ?? '' ) == 'rp_send_scheduled_emails' ) {
global $rp_cron_job;
if( isset($rp_cron_job) && $rp_cron_job === 'rp' ) {
rp_send_scheduled_emails();
}
}
}
rp_add_action('init', '_run_rp_send_scheduled_emails_through_cron', 9999);
function rp_update_general_location_timings() {
rp_verify_csrf_token_for_ajax('opening_hours');
global $rpQuery;
$company_location = $rpQuery->prefix . "rs_company_location";
$company_schedules = $rpQuery->prefix . "rs_company_schedules";
if( rp_is_active_enhanced_locations_addon() === true ) {
echo json_encode(Array('status'=> true, 'message' => 'Successfully Updated'));
exit;
}
// Update Locations Information
// loc_ids: loc_ids,
$loc_ids = $_POST['loc_ids'] ?? array();
foreach($loc_ids as $index => $loc_id) {
// cs_ids: cs_ids,
// cs_days: cs_days,
// cs_open_timings: cs_open_timings,
// cs_close_timings: cs_close_timings,
// cs_break_from_times: cs_break_from_times,
// cs_break_to_times: cs_break_to_times,
// cs_closed: cs_closed,
$cs_id = $_POST['cs_ids'][$index] ?? array();
$cs_day = $_POST['cs_days'][$index] ?? array();
$cs_open_timing = $_POST['cs_open_timings'][$index] ?? array();
$cs_close_timing = $_POST['cs_close_timings'][$index] ?? array();
$cs_breaktime_from = $_POST['cs_break_from_times'][$index] ?? array();
$cs_breaktime_to = $_POST['cs_break_to_times'][$index] ?? array();
$is_closed = $_POST['cs_closed'][$index] ?? array();
$somethingHasChanged = FALSE;
foreach($cs_id as $i => $id){
if($is_closed[$i] == 'true'){
$closed = '1';
}else{
$closed = '0';
}
// check if same entry exists
$check = $rpQuery->query("SELECT * FROM `$company_schedules` WHERE cs_day='".rp_escape_sql($cs_day[$i])."' AND cs_open_timing='".rp_escape_sql($cs_open_timing[$i])."' AND cs_close_timing='".rp_escape_sql($cs_close_timing[$i])."' AND cs_breaktime_from='".rp_escape_sql($cs_breaktime_from[$i])."' AND cs_breaktime_to='".rp_escape_sql($cs_breaktime_to[$i])."' AND is_closed='".rp_escape_sql($closed)."' AND location_id_fk='".rp_escape_sql($loc_id)."' AND cs_id = '".rp_escape_sql($id)."'");
if( empty( $check ) ) {
$somethingHasChanged = TRUE;
}
$rpQuery->query("UPDATE `$company_schedules` SET cs_day='".rp_escape_sql($cs_day[$i])."',cs_open_timing='".rp_escape_sql($cs_open_timing[$i])."',cs_close_timing='".rp_escape_sql($cs_close_timing[$i])."',cs_breaktime_from='".rp_escape_sql($cs_breaktime_from[$i])."',cs_breaktime_to='".rp_escape_sql($cs_breaktime_to[$i])."',is_closed='".rp_escape_sql($closed)."',location_id_fk='".rp_escape_sql($loc_id)."' WHERE cs_id='".rp_escape_sql($id)."'");
}
if( $somethingHasChanged === TRUE ) {
$schedule_group_id = 0;
$rpQuery->query("UPDATE $company_location SET schedule_group_id='".rp_escape_sql($schedule_group_id)."', business_profile_synced = 0 WHERE location_id='".rp_escape_sql($loc_id)."'");
}
}
$actual_total_count = rp_get_total_company_locations();
$location_ids = $_POST['loc_ids'] ?? array();
if( !is_array( $location_ids ) ) {
$location_ids = array();
}
$main_location_id = rp_get_main_location_id_of_company();
$all_actual_locations = rp_get_all_company_locations();
$valid_location_ids = array();
foreach( $all_actual_locations as $theLocation ) {
$valid_location_ids[] = (int) $theLocation->location_id;
}
$all_locations_included = count( $location_ids ) == $actual_total_count;
$main_location_on_top = $location_ids[0] == $main_location_id;
$all_locations_valid = true;
// make sure all location_ids are within valid locations
foreach( $location_ids as $loc_id ) {
$loc_id = (int) $loc_id;
if( !in_array( $loc_id, $valid_location_ids ) ) {
$all_locations_valid = false;
}
}
if( $all_locations_included && $main_location_on_top && $all_locations_valid ) {
$order = 0;
foreach( $location_ids as $loc_id ) {
$loc_id = (int) $loc_id;
$rpQuery->query("UPDATE `$company_location` SET `location_order` = '".rp_escape_sql($order)."' WHERE `location_id` = '".rp_escape_sql($loc_id)."'");
$order++;
}
}
rp_register_business_profile_for_sync();
echo json_encode(Array('status'=> true, 'message' => 'Successfully Updated'));
exit;
}
rp_ajax_for_admin('rp_update_general_location_timings', 'rp_update_general_location_timings');
function rp_update_general_info() {
rp_verify_csrf_token_for_ajax('general_info');
global $rpQuery;
$company_information = $rpQuery->prefix . "rs_company_information";
$company_location = $rpQuery->prefix . "rs_company_location";
$company_schedules = $rpQuery->prefix . "rs_company_schedules";
$c_results = $rpQuery->get_results("SELECT * FROM `$company_information`");
$company_id = $c_results[0]->company_id;
// Update General Information
$c_name = $_POST['c_name'];
$c_email = $_POST['c_email'];
$c_phone = $_POST['c_phone'];
$c_reg_no = $_POST['c_reg_no'];
$tax_reg_no = $_POST['tax_reg_no'];
$rpQuery->query("UPDATE $company_information SET company_name = '".rp_escape_sql($c_name)."',company_email = '".rp_escape_sql($c_email)."',company_phone = '".rp_escape_sql($c_phone)."',company_reg_no = '".rp_escape_sql($c_reg_no)."',tax_reg_no = '".rp_escape_sql($tax_reg_no)."' WHERE company_id='".rp_escape_sql($company_id)."'");
if( isset( $_POST['terms_and_conditions_page'] ) && !empty( $_POST['terms_and_conditions_page'] ) && filter_var( $_POST['terms_and_conditions_page'], FILTER_VALIDATE_URL ) !== FALSE ) {
// check if have get_option rp_terms_and_conditions_page_link
if( rp_get_option( 'rp_terms_and_conditions_page_link', FALSE ) !== FALSE ) {
rp_update_option( 'rp_terms_and_conditions_page_link', $_POST['terms_and_conditions_page'] );
} else {
rp_add_option( 'rp_terms_and_conditions_page_link', $_POST['terms_and_conditions_page'] );
}
} else {
// check if have get_option rp_terms_and_conditions_page_link
if( rp_get_option( 'rp_terms_and_conditions_page_link', FALSE ) !== FALSE ) {
rp_update_option( 'rp_terms_and_conditions_page_link', '' );
}
}
if( rp_is_active_enhanced_locations_addon() === true ) {
echo json_encode(Array('status'=> true, 'message' => 'Successfully Updated'));
exit;
}
// Update Locations Information
// loc_ids: loc_ids,
// location_names: location_names,
// location_addresses: location_addresses,
// location_cities: location_cities,
// google_maps_links: google_maps_links,
// location_emails: location_emails,
$loc_ids = $_POST['loc_ids'] ?? array();
foreach($loc_ids as $index => $loc_id) {
$location_name = $_POST['location_names'][$index] ?? '';
$location_address = $_POST['location_addresses'][$index] ?? '';
$location_city = $_POST['location_cities'][$index] ?? '';
$google_maps_link = $_POST['google_maps_links'][$index] ?? '';
$loc_email = $_POST['location_emails'][$index] ?? '';
if(!empty($loc_email) && filter_var($loc_email, FILTER_VALIDATE_EMAIL) !== FALSE) {
if( trim($loc_email) !== rp_get_settings_placeholder_email() && trim($loc_email) !== rp_get_settings_company_email() ) {
// Skip... So It will save the email.
} else {
$loc_email = '';
}
} else {
$loc_email = '';
}
$rpQuery->query("UPDATE $company_location SET location_name='".rp_escape_sql($location_name)."',location_address='".rp_escape_sql($location_address)."',location_city_district='".rp_escape_sql($location_city)."',google_map_link='".rp_escape_sql($google_maps_link)."',location_email='".rp_escape_sql($loc_email)."' WHERE location_id='".rp_escape_sql($loc_id)."'");
}
$actual_total_count = rp_get_total_company_locations();
$location_ids = $_POST['loc_ids'] ?? array();
if( !is_array( $location_ids ) ) {
$location_ids = array();
}
$main_location_id = rp_get_main_location_id_of_company();
$all_actual_locations = rp_get_all_company_locations();
$valid_location_ids = array();
foreach( $all_actual_locations as $theLocation ) {
$valid_location_ids[] = (int) $theLocation->location_id;
}
$all_locations_included = count( $location_ids ) == $actual_total_count;
$main_location_on_top = $location_ids[0] == $main_location_id;
$all_locations_valid = true;
// make sure all location_ids are within valid locations
foreach( $location_ids as $loc_id ) {
$loc_id = (int) $loc_id;
if( !in_array( $loc_id, $valid_location_ids ) ) {
$all_locations_valid = false;
}
}
if( $all_locations_included && $main_location_on_top && $all_locations_valid ) {
$order = 0;
foreach( $location_ids as $loc_id ) {
$loc_id = (int) $loc_id;
$rpQuery->query("UPDATE `$company_location` SET `location_order` = '".rp_escape_sql($order)."' WHERE `location_id` = '".rp_escape_sql($loc_id)."'");
$order++;
}
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully Updated'));
exit;
}
rp_ajax_for_admin('rp_update_general_info', 'rp_update_general_info');
function rp_get_sorted_noti_types() {
global $rpQuery;
$notification_types = $rpQuery->prefix . "rs_notification_types";
$n_types = $rpQuery->get_results("SELECT * FROM $notification_types");
if( !empty($n_types) ) {
$sort_by_id_like_this = array(1,3,6,9,10,4,5,2,7,8);
// sot $n_types as $n_type->noti_type_id like $sort_by_id_like_this
$sorted_n_types = array();
foreach($sort_by_id_like_this as $sort_id) {
foreach($n_types as $n_type) {
if($n_type->noti_type_id == $sort_id) {
$sorted_n_types[] = $n_type;
}
}
}
$n_types = $sorted_n_types;
}
return $n_types;
}
function rp_get_all_noti_type_names() {
$n_types = rp_get_sorted_noti_types();
$pair = array();
foreach($n_types as $n_type) {
if($n_type->noti_type_id == 3) {
$name = 'Booking Approved (Come by our store)';
} else {
$name = $n_type->noti_type;
}
// get all alphabets and spaces
$key = preg_replace('/[^a-zA-Z\s]/', '', $name);
// replace space with underscore
$key = str_replace(' ', '_', $key);
// make it lowercase
$key = trim( strtolower($key) );
$pair[$key.'_email_subject'] = '<span class="notification-badge">Email</span>' . $name;
$pair[$key.'_email_template'] = '<span class="notification-badge">Email</span>' . $name;
}
return $pair;
}
function get_translation_key_by_noti_type_id($noti_type_id = 0) {
$noti_type_id = (int) $noti_type_id;
$n_types = rp_get_sorted_noti_types();
foreach($n_types as $n_type) {
if($n_type->noti_type_id == $noti_type_id) {
if($n_type->noti_type_id == 3) {
$name = 'Booking Approved (Come by our store)';
} else {
$name = $n_type->noti_type;
}
// get all alphabets and spaces
$key = preg_replace('/[^a-zA-Z\s]/', '', $name);
// replace space with underscore
$key = str_replace(' ', '_', $key);
// make it lowercase
$key = trim( strtolower($key) );
return $key;
}
}
return false;
}
function rp_get_notification_and_offer_row( $_noti_type_id = 0 ) {
static $rp_get_notification_and_offer_row = NULL;
if( $rp_get_notification_and_offer_row !== NULL && array_key_exists( $_noti_type_id, $rp_get_notification_and_offer_row ) ) {
return $rp_get_notification_and_offer_row[$_noti_type_id];
}
if( $rp_get_notification_and_offer_row === NULL ) {
$rp_get_notification_and_offer_row = array();
}
global $rpQuery;
$notification_offers = $rpQuery->prefix . "rs_notifications_and_offers";
$n_offer = $rpQuery->get_results("SELECT * FROM $notification_offers");
if( !empty( $n_offer ) ) {
foreach( $n_offer as $nOfferRow ) {
$rp_get_notification_and_offer_row[ $nOfferRow->noti_type_id_fk ] = $nOfferRow;
}
}
if( array_key_exists( $_noti_type_id, $rp_get_notification_and_offer_row ) ) {
return $rp_get_notification_and_offer_row[$_noti_type_id];
}
return array();
}
function rp_get_all_noti_key_value_translation() {
global $rpQuery;
$notification_offers = $rpQuery->prefix . "rs_notifications_and_offers";
$n_types = rp_get_sorted_noti_types();
$pair = array();
foreach($n_types as $n_type) {
// $n_offer = $rpQuery->get_row("SELECT * FROM $notification_offers WHERE noti_type_id_fk = '".rp_escape_sql($n_type->noti_type_id)."'");
$n_offer = rp_get_notification_and_offer_row( $n_type->noti_type_id );
if($n_type->noti_type_id == 3) {
$name = 'Booking Approved (Come by our store)';
} else {
$name = $n_type->noti_type;
}
// get all alphabets and spaces
$key = preg_replace('/[^a-zA-Z\s]/', '', $name);
// replace space with underscore
$key = str_replace(' ', '_', $key);
// make it lowercase
$key = trim( strtolower($key) );
$pair[$key.'_email_subject'] = $n_offer->noti_subject;
$pair[$key.'_email_template'] = $n_offer->noti_message;
}
return $pair;
}
add_filter('rp_get_where_translation_is_used', function($pair = array()) {
$pair = array_merge($pair, rp_get_all_noti_type_names());
return $pair;
}, 10, 1);
add_filter('rp_returning_static_translations_pair', function($pair = array(), $language = '') {
$pair = array_merge($pair, rp_get_all_noti_key_value_translation());
return $pair;
}, 10, 2);
function rp_get_all_device_categories() {
global $rpQuery;
$rs_category = $rpQuery->prefix . "rs_category";
return $rpQuery->get_results("SELECT * FROM $rs_category");
}
function rp_get_all_models_for_upsales_page() {
global $rpQuery;
$rs_category = $rpQuery->prefix . "rs_category";
$rs_brand = $rpQuery->prefix . "rs_brand";
$rs_model = $rpQuery->prefix . "rs_model";
$allCategories = $rpQuery->get_results("SELECT * FROM $rs_category ORDER BY `c_position` ASC");
$result = array();
if( !empty( $allCategories ) ) {
foreach($allCategories as $category) {
if( !isset( $category->_brands ) ) {
$category->_brands = array();
}
$allBrands = $rpQuery->get_results("SELECT * FROM `$rs_brand` WHERE c_id_fk = '".rp_escape_sql($category->c_id)."' ORDER BY `b_position` ASC");
if( !empty( $allBrands ) ) {
foreach($allBrands as $brand) {
if( !isset( $brand->_models ) ) {
$brand->_models = array();
}
$allModels = $rpQuery->get_results("SELECT * FROM `$rs_model` WHERE brand_id_fk = '".rp_escape_sql($brand->b_id)."' ORDER BY `m_position` ASC");
if( !empty( $allModels ) ) {
foreach($allModels as $model) {
$brand->_models[] = $model;
}
$category->_brands[] = $brand;
}
}
}
$result[] = $category;
}
}
return $result;
}
function rp_remove_repair_related_attributes( $r_id_fk = '' ) {
global $rpQuery;
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$rpQuery->query("DELETE FROM `$rs_repair_attr` WHERE `r_id_fk` = '".rp_escape_sql($r_id_fk)."'");
}
function rp_remove_model_related_repairs( $m_id_fk = '' ) {
if( !isset( $_REQUEST['rp_process_background_job'] ) || empty( $_REQUEST['rp_process_background_job'] ) ) {
rp_insert_rs_background_jobs_table(__FUNCTION__, func_get_args());
return;
}
$m_id_fk = (int) $m_id_fk;
_rp_delete_model_related_repairs( $m_id_fk );
global $rpQuery;
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_repairs_category = $rpQuery->prefix . 'rs_repairs_category';
$repairs = $rpQuery->get_results("SELECT * FROM `$rs_repair` WHERE `m_id_fk` = '".rp_escape_sql($m_id_fk)."'");
if( !empty( $repairs ) ) {
foreach( $repairs as $repair ) {
rp_remove_repair_related_attributes( $repair->r_id );
}
$rpQuery->query("DELETE FROM `$rs_repair` WHERE `m_id_fk` = '".rp_escape_sql($m_id_fk)."'");
}
$rpQuery->query("DELETE FROM `$rs_repairs_category` WHERE `m_id_fk` = '".rp_escape_sql($m_id_fk)."'");
}
function rp_delete_brand_related_data( $brand_id_fk = '' ) {
global $rpQuery;
$rs_model = $rpQuery->prefix . 'rs_model';
$models = $rpQuery->get_results("SELECT * FROM `$rs_model` WHERE `brand_id_fk` = '".rp_escape_sql($brand_id_fk)."'");
if( !empty( $models ) ) {
foreach( $models as $model ) {
rp_remove_model_related_repairs( $model->m_id );
}
$rpQuery->query("DELETE FROM `$rs_model` WHERE `brand_id_fk` = '".rp_escape_sql($brand_id_fk)."'");
}
}
function rp_remove_category_related_data( $c_id_fk = '' ) {
global $rpQuery;
$rs_brand = $rpQuery->prefix . 'rs_brand';
$rs_default_repairs_category = $rpQuery->prefix . 'rs_default_repairs_category';
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$rs_location_prices = $rpQuery->prefix . 'rs_location_prices';
$brands = $rpQuery->get_results("SELECT * FROM `$rs_brand` WHERE `c_id_fk` = '".rp_escape_sql($c_id_fk)."'");
if( !empty( $brands ) ) {
foreach( $brands as $brand ) {
rp_delete_brand_related_data($brand->b_id);
}
$rpQuery->query("DELETE FROM `$rs_brand` WHERE `c_id_fk` = '".rp_escape_sql($c_id_fk)."'");
}
$rpQuery->query("DELETE FROM `$rs_default_repair` WHERE `dr_category` = '".rp_escape_sql($c_id_fk)."'");
$rpQuery->query("DELETE FROM `$rs_default_repair_attr` WHERE `dr_category` = '".rp_escape_sql($c_id_fk)."'");
$rpQuery->query("DELETE FROM `$rs_default_repairs_category` WHERE `dc_category` = '".rp_escape_sql($c_id_fk)."'");
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `dr_category` = '".rp_escape_sql($c_id_fk)."'");
}
function rp_get_all_outgoing_triggers() {
global $rpQuery;
$rs_outgoing_triggers = $rpQuery->prefix . "rs_outgoing_triggers";
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$sql = "SELECT * FROM `$rs_outgoing_triggers` LEFT JOIN `$rs_company_location` ON `$rs_outgoing_triggers`.`location_id` = `$rs_company_location`.`location_id`";
$results = $rpQuery->get_results($sql);
if( !empty($results) ) {
return $results;
}
return array();
}
function rp_get_all_locations() {
global $rpQuery;
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$locations = $rpQuery->get_results("SELECT * FROM `$rs_company_location`");
return $locations;
}
function rp_available_trigger_options() {
return array(
'scheduled_appointment_created', // done
'scheduled_appointment_updated', // done
'scheduled_appointment_cancelled', // done
'scheduled_appointment_deleted', // done
'ship_device_appointment_created', // done
'ship_device_appointment_updated', // done
'ship_device_appointment_cancelled', // done
'ship_device_appointment_deleted', // done
'pdf_offer_created', // done
'pdf_offer_updated', // done
'pdf_offer_cancelled', // done
'pdf_offer_deleted' // done
);
}
function rp_get_outgoing_triggers_data_for_edit() {
rp_verify_csrf_token_for_ajax('webhooks');
$available_options = rp_available_trigger_options();
$locations = rp_get_all_locations();
global $rpQuery;
$rs_outgoing_triggers = $rpQuery->prefix . "rs_outgoing_triggers";
$id = (int) ($_POST['id'] ?? 0);
if( empty( $id ) ) {
// it is a create form
echo json_encode(Array('status'=> true, 'data' => array(
'id' => 0,
'trigger' => '',
'url' => '',
'available_options' => $available_options,
'locations' => $locations,
'location_id' => ''
)));
exit;
} else {
// verify if the location exists
$sql = "SELECT * FROM $rs_outgoing_triggers WHERE `id` = $id";
$results = $rpQuery->get_row($sql);
if( empty($results) ) {
echo json_encode(Array('status'=> false, 'rp_validation_error' => 'Invalid Trigger ID'));
exit;
}
$results = rp_sanitize_output($results);
echo json_encode(Array('status'=> true, 'data' => array(
'id' => $results->id,
'trigger' => $results->trigger,
'url' => $results->url,
'available_options' => $available_options,
'locations' => $locations,
'location_id' => $results->location_id
)));
exit;
}
exit;
}
rp_ajax_for_admin('rp_get_outgoing_triggers_data_for_edit', 'rp_get_outgoing_triggers_data_for_edit');
function rp_create_or_edit_outgoing_trigger() {
rp_verify_csrf_token_for_ajax('webhooks');
global $rpQuery;
$rs_outgoing_triggers = $rpQuery->prefix . "rs_outgoing_triggers";
$required_fields = array( 'trigger', 'url' );
// make sure all required fields are present
foreach( $required_fields as $field ) {
if( empty( $_POST[$field] ) ) {
echo json_encode(Array('status'=> false, 'rp_validation_error' => 'Please fill all required fields'));
exit;
}
}
$trigger = sanitize_text_field( trim( $_POST['trigger'] ?? '' ) );
$url = sanitize_text_field( trim( $_POST['url'] ?? '' ) );
$location_id = sanitize_text_field( trim( $_POST['locations'] ?? '' ) );
// make sure selected schedule is valid
$triggerOptions = rp_available_trigger_options();
if( !in_array( $trigger, $triggerOptions ) ) {
echo json_encode(Array('status'=> false, 'rp_validation_error' => 'Invalid trigger'));
exit;
}
// make sure url is valid url
if( !filter_var($url, FILTER_VALIDATE_URL) ) {
echo json_encode(Array('status'=> false, 'rp_validation_error' => 'Invalid URL'));
exit;
}
$trigger_id = (int) ($_POST['id'] ?? 0);
if( $trigger_id == 0 ) {
// create new location
$sql = "INSERT INTO `$rs_outgoing_triggers` (`trigger`, `url`, `location_id`) VALUES (':trigger', ':url', ':location_id')";
$rpQuery->query($sql, array(
'trigger' => $trigger,
'url' => $url,
'location_id' => $location_id
));
$insert_id = $rpQuery->insert_id;
$payload = rp_get_example_trigger_payload( $trigger );
RepairPluginPro\RP_Trigger_Request::create_request_safe( $url, $payload );
} else {
// verify location id
$verify = $rpQuery->get_row("SELECT * FROM $rs_outgoing_triggers WHERE `id` = $trigger_id");
if( empty( $verify ) ) {
echo json_encode(Array('status'=> false, 'rp_validation_error' => 'Invalid Trigger ID'));
exit;
}
$old_url = $verify->url;
$sql = "UPDATE `$rs_outgoing_triggers` SET `trigger` = ':trigger', `url` = ':url', `location_id` = ':location_id' WHERE `id` = $trigger_id";
$rpQuery->query($sql, array(
'trigger' => $trigger,
'url' => $url,
'location_id' => $location_id
));
if( trim( $old_url ) !== trim( $url ) ) {
$payload = rp_get_example_trigger_payload( $trigger );
RepairPluginPro\RP_Trigger_Request::create_request_safe( $url, $payload );
}
}
echo json_encode(Array('status'=> true, 'message' => 'Successfully created / updated'));
exit;
}
rp_ajax_for_admin('rp_create_or_edit_outgoing_trigger', 'rp_create_or_edit_outgoing_trigger');
function rp_delete_outgoing_trigger() {
rp_verify_csrf_token_for_ajax('webhooks');
global $rpQuery;
$rs_outgoing_triggers = $rpQuery->prefix . "rs_outgoing_triggers";
$trigger_id = (int) ($_POST['id'] ?? 0);
if( $trigger_id == 0 ) {
echo json_encode(Array('status'=> false, 'rp_validation_error' => 'Invalid Trigger ID'));
exit;
}
// verify location id
$verify = $rpQuery->get_row("SELECT * FROM $rs_outgoing_triggers WHERE `id` = $trigger_id");
if( empty( $verify ) ) {
echo json_encode(Array('status'=> false, 'rp_validation_error' => 'Invalid Trigger ID'));
exit;
}
$rpQuery->query("DELETE FROM `$rs_outgoing_triggers` WHERE `id` = $trigger_id");
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted'));
exit;
}
rp_ajax_for_admin('rp_delete_outgoing_trigger', 'rp_delete_outgoing_trigger');
function rp_get_payload_of_outgoing_trigger() {
global $rpQuery;
$rs_outgoing_triggers = $rpQuery->prefix . 'rs_outgoing_triggers';
$id = (int) $_POST['id'] ?? '';
if( empty( $id ) ) {
echo json_encode(Array('status'=> false, 'rp_validation_error' => 'Invalid Trigger ID'));
exit;
}
$sql = "SELECT * FROM `$rs_outgoing_triggers` WHERE `id` = {$id}";
$result = $rpQuery->get_row( $sql );
if( empty( $result ) ) {
echo json_encode(Array('status'=> false, 'rp_validation_error' => 'Invalid Trigger ID'));
exit;
}
$payload = rp_get_example_trigger_payload( $result->trigger );
echo json_encode(Array('status'=> true, 'payload' => $payload));
exit;
}
function rp_get_example_trigger_payload( $name_of_trigger = '' ) {
$payload = array();
$org_trigger = $name_of_trigger;
// explode by _ and get last element
$name_of_trigger = explode( '_', $name_of_trigger );
$name_of_trigger = end( $name_of_trigger );
$payload = RepairPluginPro\RP_Trigger_Examples::prepare( $name_of_trigger );
$payload = apply_filters('rp_filter_outgoing_trigger_payload', $payload, $org_trigger, 0);
return $payload;
}
function rp_get_customer_business_name( $customer_id_fk = 0 ) {
global $rpQuery;
$rs_customer_business = $rpQuery->prefix . "rs_customer_business";
$rp_customer_business_details = $rpQuery->get_results("SELECT * FROM `$rs_customer_business` WHERE customer_id_fk = '".rp_escape_sql($customer_id_fk)."' LIMIT 1;");
$_customer_business_name = '';
if( !empty( $rp_customer_business_details ) ) {
$_customer_business_name = $rp_customer_business_details[0]->cb_name ?? '';
}
return $_customer_business_name;
}
function rp_filter_outgoing_trigger_payload( $payload = array(), $name_of_trigger = '', $o_id = 0 ) {
if( empty( $payload ) ) {
return $payload;
}
if( strpos( $name_of_trigger, 'pdf_offer_' ) !== FALSE ) {
$unset_these = array(
'payment_method',
'payment_status',
'payment_datetime',
'payment_transaction_id'
);
foreach( $unset_these as $value ) {
$payload[ $value ] = '';
}
}
if( strpos( $name_of_trigger, 'ship_device_' ) !== FALSE || strpos( $name_of_trigger, 'pdf_offer_' ) !== FALSE ) {
$unset_these = array(
'reschedule_link',
'event_start_datetime',
'event_end_datetime',
'appointment_date',
'appointment_time'
);
foreach( $unset_these as $value ) {
$payload[ $value ] = '';
}
}
if( strpos( $name_of_trigger, 'pdf_offer_' ) !== FALSE ) {
if( !empty( $o_id ) ) {
global $rpQuery;
$rs_user_pdfs = $rpQuery->prefix . 'rs_user_pdfs';
$o_id = (int) $o_id;
$sql = "SELECT * FROM `$rs_user_pdfs` WHERE `o_id_fk` = {$o_id}";
$pdf_row = $rpQuery->get_row( $sql );
if( !empty( $pdf_row ) ) {
$pdf_row->finalize_link = rp_override_reschedule_or_finalize_link( $pdf_row->finalize_link );
$payload['finalize_link'] = $pdf_row->finalize_link;
$payload['customer_house_no'] = $pdf_row->house_no;
$payload['customer_street_address'] = $pdf_row->streetname_phone;
$payload['customer_city'] = $pdf_row->zipcode_city;
$payload['customer_zipcode'] = $pdf_row->zipcode_only;
$payload['customer_country'] = rp_get_single_translated_country_name($pdf_row->user_country);
$payload['customer_imei'] = $pdf_row->notes;
} else {
$payload['finalize_link'] = '';
$payload['customer_house_no'] = '';
$payload['customer_street_address'] = '';
$payload['customer_city'] = '';
$payload['customer_zipcode'] = '';
$payload['customer_country'] = '';
$payload['customer_imei'] = '';
}
} else {
$payload['finalize_link'] = '';
$payload['customer_house_no'] = 'House No';
$payload['customer_street_address'] = 'Streetname';
$payload['customer_city'] = 'Amsterdam';
$payload['customer_zipcode'] = '1102 MX';
$payload['customer_country'] = 'Netherlands';
$payload['customer_imei'] = '9999999999999999';
}
$unset_these = array(
// 'customer_house_no',
'customer_notes'
);
foreach( $unset_these as $valuep ) {
$payload[ $valuep ] = '';
}
// loop through payload and make position of customer_imei after customer_zipcode
$payload_copy = $payload;
$payload = array();
foreach( $payload_copy as $keyp => $valuep ) {
if( $keyp == 'customer_imei' ) {
continue;
}
$payload[ $keyp ] = $valuep;
if( $keyp == 'customer_zipcode' ) {
$payload['customer_imei'] = $payload_copy['customer_imei'];
}
}
}
// set if not set:
$items = array(
'finalize_link',
'customer_house_no',
'customer_street_address',
'customer_city',
'customer_zipcode',
'customer_country',
'customer_imei'
);
foreach( $items as $item ) {
if( !isset( $payload[ $item ] ) ) {
$payload[ $item ] = '';
}
}
if( empty( $o_id ) ) {
if( strpos( $name_of_trigger, 'pdf_offer_' ) !== FALSE ) {
$payload['service_method'] = 'PDF Quote';
if( $payload['appointment_status'] !== 'Deleted' ) {
$payload['appointment_status'] = 'Offered';
}
}
if( strpos( $name_of_trigger, 'ship_device_' ) !== FALSE ) {
$payload['service_method'] = 'Ship device';
}
}
return $payload;
}
add_filter('rp_filter_outgoing_trigger_payload', 'rp_filter_outgoing_trigger_payload', 10, 3);
function rp_get_order_location_id( $o_id = 0 ) {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$row = $rpQuery->get_row("SELECT `location_id_fk` FROM `$rs_orders` WHERE `o_id` = '".rp_escape_sql($o_id)."'");
if( !empty( $row ) ) {
return $row->location_id_fk ?? 0;
}
return 0;
}
function rp_trigger_outgoing_webhook( $name_of_trigger = '', $o_id = 0 ) {
rp_handle_google_calendar_integration( $name_of_trigger, $o_id );
global $rpQuery;
$rs_outgoing_triggers = $rpQuery->prefix . 'rs_outgoing_triggers';
$where_sql = "";
if( rp_is_active_enhanced_locations_addon() === true ) {
$order_location_id = rp_get_order_location_id( $o_id );
if( !empty( $order_location_id ) ) {
$where_sql .= " OR `location_id` = '".rp_escape_sql( $order_location_id )."' ";
}
}
$sql = "SELECT * FROM `$rs_outgoing_triggers` WHERE `trigger` = '".rp_escape_sql( $name_of_trigger )."' AND (
`location_id` = '' OR
`location_id` = NULL OR
`location_id` = 'all'
{$where_sql}
)";
$triggers = $rpQuery->get_results( $sql );
if( !empty( $triggers ) ) {
$payload = rp_get_order_trigger_payload( $name_of_trigger, $o_id );
$payload_copy = $payload;
$payload_copy['trigger_name'] = $name_of_trigger;
if( !empty( $payload ) ) {
foreach( $triggers as $theTrigger ) {
$url = $theTrigger->url;
RepairPluginPro\RP_Trigger_Request::create_request_safe( $url, $payload );
}
}
}
}
function rp_get_order_trigger_payload( $name_of_trigger = '', $o_id = 0 ) {
$payload = array();
$org_trigger = $name_of_trigger;
// explode by _ and get last element
$name_of_trigger = explode( '_', $name_of_trigger );
$name_of_trigger = end( $name_of_trigger );
$payload = RepairPluginPro\RP_Trigger_Payload::prepare( $o_id, $name_of_trigger );
$payload = apply_filters('rp_filter_outgoing_trigger_payload', $payload, $org_trigger, $o_id);
return $payload;
}
rp_ajax_for_admin('rp_get_payload_of_outgoing_trigger', 'rp_get_payload_of_outgoing_trigger');
function rp_save_session_data($session_id = '', $session_data = array()) {
global $rpQuery;
$table_rs_sessions = $rpQuery->prefix . 'rs_sessions';
$session_data = json_encode($session_data, JSON_UNESCAPED_UNICODE);
$session_expires = time() + (86400 * 30); // 30 days
// if have session id related row then update it
$session = $rpQuery->get_row("SELECT * FROM `$table_rs_sessions` WHERE `session_id` = '".rp_escape_sql($session_id)."'");
if( !empty( $session ) ) {
$rpQuery->query("UPDATE `$table_rs_sessions` SET `session_data` = '".rp_escape_sql($session_data)."', `session_expires` = '".rp_escape_sql($session_expires)."' WHERE `session_id` = '".rp_escape_sql($session_id)."'");
} else {
$rpQuery->query("INSERT INTO `$table_rs_sessions` (`session_id`, `session_data`, `session_expires`) VALUES ('".rp_escape_sql($session_id)."', '".rp_escape_sql($session_data)."', '".rp_escape_sql($session_expires)."')");
}
}
function rp_delete_expired_sessions() {
global $rpQuery;
$table_rs_sessions = $rpQuery->prefix . 'rs_sessions';
$rpQuery->query("DELETE FROM `$table_rs_sessions` WHERE `session_expires` < '".time()."'");
}
function rp_get_session_data($session_id = '') {
rp_delete_expired_sessions();
global $rpQuery;
$table_rs_sessions = $rpQuery->prefix . 'rs_sessions';
$session_data = $rpQuery->get_row("SELECT * FROM `$table_rs_sessions` WHERE `session_id` = '".rp_escape_sql($session_id)."'");
if(!empty($session_data)) {
$session_data = json_decode($session_data->session_data, true);
}
return $session_data;
}
function rp_increment_appointment_number($created_date = '') {
global $rpQuery;
$rs_appointment_number = $rpQuery->prefix . 'rs_appointment_number';
$parsed = date('Y-m-d', strtotime($created_date));
$row = $rpQuery->get_row("SELECT * FROM `$rs_appointment_number` WHERE `date` = '$parsed'");
if( !empty( $row ) ) {
$new_count = ($row->count) + 1;
$rpQuery->query("UPDATE `$rs_appointment_number` SET `count` = '{$new_count}' WHERE `id` = {$row->id}");
} else {
$rpQuery->query("INSERT INTO `$rs_appointment_number` (`date`, `count`) VALUES ('$parsed', 1)");
}
}
function rp_get_new_appointment_number($created_date = '') {
global $rpQuery;
$rs_appointment_number = $rpQuery->prefix . 'rs_appointment_number';
$parsed = date('Y-m-d', strtotime($created_date));
$row = $rpQuery->get_row("SELECT * FROM `$rs_appointment_number` WHERE `date` = '$parsed'");
if( !empty( $row ) ) {
$old = $row->count;
return date('ymdh', strtotime($created_date)) . ($old + 1);
}
return date('ymdh', strtotime($created_date)) . '1';
}
function rp_get_appointment_number_of_order( $oid = '' ) {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$row = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '".rp_escape_sql($oid)."'");
if( !empty( $row ) ) {
return ($row->appointment_number ?? '');
}
return '';
}
function rp_set_new_appointment_number($oid = '', $created_time = '') {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$new_appointment_number = rp_get_new_appointment_number( $created_time );
$rpQuery->query("UPDATE `$rs_orders` SET `appointment_number` = '$new_appointment_number' WHERE `o_id` = '{$oid}' LIMIT 1;");
rp_increment_appointment_number( $created_time );
}
function rp_get_all_dr_uq_ids() {
$cache_key = 'rp_get_all_dr_uq_ids';
$cached = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if(!empty($cached)) {
return $cached;
}
$uq_ids = rp_get_all_dr_uq_id_from_rs_default_repair_table();
RepairPluginPro\RP_Memory_Cache::save($cache_key, $uq_ids);
return $uq_ids;
}
function rp_get_all_dr_uq_ids_and_da_uq_ids() {
$cache_key = 'rp_get_all_dr_uq_ids_and_da_uq_ids';
$cached = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if(!empty($cached)) {
return $cached;
}
$all_dr_uq_ids = rp_get_all_dr_uq_id_from_rs_default_repair_table();
$all_da_uq_ids = rp_get_all_da_uq_id_from_rs_default_repair_attr_table();
$uq_ids = array_merge( $all_dr_uq_ids, $all_da_uq_ids );
RepairPluginPro\RP_Memory_Cache::save($cache_key, $uq_ids);
return $uq_ids;
}
function rp_is_default_repair_or_attr( $uq_id = '' ) {
return in_array($uq_id, rp_get_all_dr_uq_ids_and_da_uq_ids()) !== false;
}
function rp_is_default_repair( $r_uq_id = '' ) {
return in_array($r_uq_id, rp_get_all_dr_uq_ids()) !== false;
}
function rp_get_default_repair_attr_row_by_uq_id( $a_uq_id = '', $dr_category = '', $da_row_old = null ) {
if( !empty( $da_row_old ) ) {
return $da_row_old;
}
global $rpQuery;
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
return $rpQuery->get_row("SELECT * FROM `$rs_default_repair_attr` WHERE `da_uq_id` = '".rp_escape_sql($a_uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."' LIMIT 1;");
}
function rp_get_default_repair_row_by_uq_id( $r_uq_id = '', $dr_category = '', $dr_row_old = null ) {
if( !empty( $dr_row_old ) ) {
return $dr_row_old;
}
global $rpQuery;
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
return $rpQuery->get_row("SELECT * FROM `$rs_default_repair` WHERE `dr_uq_id` = '".rp_escape_sql($r_uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."' LIMIT 1;");
}
function rp_get_attributes_of_default_repair( $dr_id = '', $create_attr_later = array() ) {
global $rpQuery;
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$results = $rpQuery->get_results("SELECT * FROM `$rs_default_repair_attr` WHERE `dr_id_fk` = '".rp_escape_sql($dr_id)."';");
if( !empty( $results ) ) {
$new_results = array();
foreach( $results as $attr_row ) {
if( !in_array($attr_row->da_id, $create_attr_later) ) {
$new_results[] = $attr_row;
}
}
return $new_results;
}
return $results;
}
function rp_exclude_just_adding_repairs( $attr_rows = array(), $create_attr_later = array() ) {
global $rpQuery;
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
if( !empty( $attr_rows ) && !empty( $create_attr_later ) ) {
$create_attr_later_str = join(', ', $create_attr_later);
$just_adding_rows = $rpQuery->get_results("SELECT * FROM `$rs_default_repair_attr` WHERE `da_id` IN ({$create_attr_later_str});");
if( !empty( $just_adding_rows ) ) {
$excludeUqIds = array();
foreach( $just_adding_rows as $justAddingRow ) {
$excludeUqIds[] = $justAddingRow->da_uq_id;
}
$new_results = array();
foreach( $attr_rows as $attr_row ) {
if( !in_array( $attr_row->a_uq_id, $excludeUqIds ) ) {
$new_results[] = $attr_row;
}
}
return $new_results;
}
}
return $attr_rows;
}
function rp_default_repair_structure_matches( $r_id = '', $dr_category = '', $dr_row_old = null, $create_attr_later = array() ) {
global $rpQuery;
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$row = $rpQuery->get_row("SELECT * FROM `$rs_repair` WHERE `r_id` = '".rp_escape_sql($r_id)."' LIMIT 1;");
if( !empty( $row ) ) {
if( rp_is_default_repair( $row->r_uq_id ) !== false ) {
$dr_row = rp_get_default_repair_row_by_uq_id( $row->r_uq_id, $dr_category, $dr_row_old );
$dr_attr_rows = rp_get_attributes_of_default_repair( $dr_row->dr_id, $create_attr_later );
$attr_rows = $rpQuery->get_results("SELECT * FROM `$rs_repair_attr` WHERE `r_id_fk` = '".rp_escape_sql($r_id)."';");
$attr_rows = rp_exclude_just_adding_repairs( $attr_rows, $create_attr_later );
if( empty( $dr_attr_rows ) && empty( $attr_rows ) ) {
return TRUE;
} else if( rp_attributes_exactly_matches_default( $attr_rows, $dr_attr_rows ) ) {
// Attributes exactly matches but might have price changed
return TRUE;
} else {
return FALSE;
}
}
}
return FALSE;
}
function rp_is_unchanged_default_repair_individually( $r_id = '', $dr_category = '', $dr_row_old = null, $create_attr_later = array() ) {
global $rpQuery;
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$row = $rpQuery->get_row("SELECT * FROM `$rs_repair` WHERE `r_id` = '".rp_escape_sql($r_id)."' LIMIT 1;");
if( !empty( $row ) ) {
if( rp_is_default_repair( $row->r_uq_id ) !== false ) {
$dr_row = rp_get_default_repair_row_by_uq_id( $row->r_uq_id, $dr_category, $dr_row_old );
$dr_attr_rows = rp_get_attributes_of_default_repair( $dr_row->dr_id, $create_attr_later );
$attr_rows = $rpQuery->get_results("SELECT * FROM `$rs_repair_attr` WHERE `r_id_fk` = '".rp_escape_sql($r_id)."';");
$attr_rows = rp_exclude_just_adding_repairs( $attr_rows, $create_attr_later );
if( empty( $dr_attr_rows ) && empty( $attr_rows ) ) {
if( rp_is_enabled_dynamic_pricing() == TRUE ) {
// Do not have attributes.. Means row matches... Just check the price & is_free
return ($row->is_free === $dr_row->is_free) && ($row->r_price === $dr_row->dr_price) && ($row->r_margin === $dr_row->dr_margin);
} else {
// Do not have attributes.. Means row matches... Just check the price & is_free
return ($row->is_free === $dr_row->is_free) && ($row->r_price === $dr_row->dr_price);
}
} else if( rp_attributes_exactly_matches_default( $attr_rows, $dr_attr_rows ) ) {
// Attributes exactly matches but might have price changed
return TRUE;
} else {
return FALSE;
}
}
}
return FALSE;
}
function rp_attributes_exactly_matches_default( $attr_rows = array(), $dr_attr_rows = array() ) {
if( empty( $attr_rows ) || empty( $dr_attr_rows ) || (count($attr_rows) !== count($dr_attr_rows)) ) {
return FALSE;
}
$uq_ids = array();
foreach( $dr_attr_rows as $dr_attr_row ) {
$uq_ids[] = $dr_attr_row->da_uq_id;
}
foreach( $attr_rows as $attr_row ) {
if( !in_array( $attr_row->a_uq_id, $uq_ids ) ) {
return FALSE;
}
}
return TRUE;
}
function rp_verify_selected_location_frontend( $selected_location_id = 0 ) {
global $rpQuery;
$rs_company_location = $rpQuery->prefix . "rs_company_location";
$all_locations = $rpQuery->get_results("SELECT * FROM $rs_company_location;");
if( !empty( $selected_location_id ) && !empty( $all_locations ) ) {
foreach( $all_locations as $theLocation ) {
if( (int) $theLocation->location_id == (int) $selected_location_id ) {
return TRUE;
}
}
}
return FALSE;
}
function rp_loc_based_pricing_selected_id() {
global $rpQuery;
$selected_location_id = 0;
if( isset($_COOKIE) && !empty($_COOKIE) && isset($_COOKIE['wordpress_rp_loc_based_pricing']) ) {
$selected_location_id = $_COOKIE['wordpress_rp_loc_based_pricing'] ?? 0;
}
// verify selected location
$verified = rp_verify_selected_location_frontend( $selected_location_id );
if( $verified == FALSE ) {
$selected_location_id = 0;
}
if( empty( $selected_location_id ) ) {
// If empty, the location id should be main location id
$selected_location_id = rp_get_main_location_id_of_company();
}
$selectable_locations = rp_get_allowed_locations_of_current_user();
$inSelectable = false;
foreach( $selectable_locations as $selectableLocationId ) {
if( (int) $selectableLocationId == (int) $selected_location_id ) {
$inSelectable = true;
break;
}
}
if( $inSelectable == false ) {
if( !empty( $selectable_locations ) ) {
$selected_location_id = $selectable_locations[0];
} else {
$selected_location_id = 0;
}
}
if( rp_is_enabled_pricing_based_on_location() == TRUE ) {
global $rp_location_based_price_id;
$rp_location_based_price_id = $selected_location_id;
} else {
$selected_location_id = 0;
}
return $selected_location_id;
}
function _rp_remove_individual_repair_translations_because_reset_default( $key = '', $uqid = '', $connection_id = '' ) {
global $rpQuery;
$rs_r_translations = $rpQuery->prefix . 'rs_r_translations';
// key, uq_id, m_id_fk
$results = $rpQuery->query("DELETE FROM $rs_r_translations WHERE `key` = '".rp_escape_sql($key)."' AND `uq_id` = '".rp_escape_sql($uqid)."' AND `m_id_fk` IN (".rp_escape_sql($connection_id).");");
}
function _rp_remove_individual_repair_translations( $key = '', $uqid = '', $connection_id = '' ) {
global $rpQuery;
$rs_r_translations = $rpQuery->prefix . 'rs_r_translations';
// key, uq_id, m_id_fk
$results = $rpQuery->query("DELETE FROM $rs_r_translations WHERE `key` = '".rp_escape_sql($key)."' AND `uq_id` = '".rp_escape_sql($uqid)."' AND `m_id_fk` = '".rp_escape_sql($connection_id)."';");
}
function _rp_remove_individual_attributes_translations_because_reset_default( $key = '', $connection_id = '' ) {
global $rpQuery;
$rs_rattr_translations = $rpQuery->prefix . 'rs_rattr_translations';
// key, r_id_fk
$results = $rpQuery->query("DELETE FROM $rs_rattr_translations WHERE `key` = '".rp_escape_sql($key)."' AND `r_id_fk` IN (".rp_escape_sql($connection_id).");");
}
function _rp_remove_individual_attributes_translations( $key = '', $connection_id = '' ) {
global $rpQuery;
$rs_rattr_translations = $rpQuery->prefix . 'rs_rattr_translations';
// key, r_id_fk
$results = $rpQuery->query("DELETE FROM $rs_rattr_translations WHERE `key` = '".rp_escape_sql($key)."' AND `r_id_fk` = '".rp_escape_sql($connection_id)."';");
}
function _rp_individual_repair_translation_exists( $key = '', $uqid = '', $connection_id = '' ) {
global $rpQuery;
$rs_r_translations = $rpQuery->prefix . 'rs_r_translations';
// key, uq_id, m_id_fk
$results = $rpQuery->get_results("SELECT * FROM $rs_r_translations WHERE `key` = '".rp_escape_sql($key)."' AND `uq_id` = '".rp_escape_sql($uqid)."' AND `m_id_fk` = '".rp_escape_sql($connection_id)."';");
return !empty( $results );
}
function _rp_individual_attributes_translation_exists( $key = '', $connection_id = '' ) {
global $rpQuery;
$rs_rattr_translations = $rpQuery->prefix . 'rs_rattr_translations';
// key, r_id_fk
$results = $rpQuery->get_results("SELECT * FROM $rs_rattr_translations WHERE `key` = '".rp_escape_sql($key)."' AND `r_id_fk` = '".rp_escape_sql($connection_id)."';");
return !empty( $results );
}
function _rp_handle_individually_changed_translations( $final_result , $row = null, $dr_row = null) {
if( rp_current_user_has_full_access_cached() == FALSE ) {
return $final_result;
}
if( $final_result === FALSE ) {
return FALSE;
}
// Do your processing here!
$fieldsToCheckRepair = array();
$fieldsToCheckAttr = array();
if( rp_get_option('rp_enable_read_more_link_for_repairs', '0') == '1' ) {
$fieldsToCheckRepair[] = 'repair_read_more';
$fieldsToCheckRepair[] = 'repair_readmore_text';
}
if( rp_get_option('rp_enable_read_more_link_for_attributes', '0') == '1' ) {
$fieldsToCheckAttr[] = 'attr_read_more';
$fieldsToCheckAttr[] = 'attr_readmore_text';
}
if( empty( $fieldsToCheckRepair ) && empty( $fieldsToCheckAttr ) ) {
return $final_result; // Whatever final result it
}
$isChangedAny = FALSE;
$all_languages = \rp_get_all_languages();
if( !empty( $fieldsToCheckRepair ) ) {
foreach( $fieldsToCheckRepair as $key ) {
$hasIndividualTranslations = _rp_individual_repair_translation_exists( $key, $row->r_uq_id.'_'.rp_get_model_cached_category_by_mid( $row->m_id_fk ), $row->m_id_fk );
if( $hasIndividualTranslations == TRUE ) {
$isChangedAny = TRUE;
}
}
}
if( !empty( $fieldsToCheckAttr ) ) {
foreach( $fieldsToCheckAttr as $key ) {
$hasIndividualTranslations = _rp_individual_attributes_translation_exists( $key, $row->r_id );
if( $hasIndividualTranslations == TRUE ) {
$isChangedAny = TRUE;
}
}
}
return $isChangedAny === FALSE;
}
add_filter('rp_is_fully_unchanged_default_repair_individually', '_rp_handle_individually_changed_translations', 10, 3);
function rp_is_fully_unchanged_default_repair_individually( $r_id = '', $mid = '' ) {
$dr_category = rp_get_model_cached_category_by_mid($mid);
global $rpQuery;
global $rp_location_based_price_id;
$selected_location_id = $rp_location_based_price_id ?? 0;
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$row = $rpQuery->get_row("SELECT * FROM `$rs_repair` WHERE `r_id` = '".rp_escape_sql($r_id)."' LIMIT 1;");
if( !empty( $row ) ) {
if( rp_is_default_repair( $row->r_uq_id ) !== false ) {
$dr_row = rp_get_default_repair_row_by_uq_id( $row->r_uq_id, $dr_category );
$dr_attr_rows = rp_get_attributes_of_default_repair( $dr_row->dr_id );
$attr_rows = $rpQuery->get_results("SELECT * FROM `$rs_repair_attr` WHERE `r_id_fk` = '".rp_escape_sql($r_id)."';");
if( !empty( $selected_location_id ) ) {
$dr_row = apply_filters('rp_overwrite_default_repair_row', $dr_row, $selected_location_id);
$row = apply_filters('rp_overwrite_individual_repair_row', $row, $selected_location_id);
if( !empty( $dr_attr_rows ) ) {
foreach( $dr_attr_rows as $ow_key => $thRow ) {
$dr_attr_rows[ $ow_key ] = apply_filters('rp_overwrite_default_repair_attr_row', $thRow, $selected_location_id);
}
}
if( !empty( $attr_rows ) ) {
foreach( $attr_rows as $ow_key => $thRow ) {
$attr_rows[ $ow_key ] = apply_filters('rp_overwrite_individual_repair_attr_row', $thRow, $selected_location_id);
}
}
}
if( empty( $dr_attr_rows ) && empty( $attr_rows ) ) {
if( rp_current_user_has_full_access_cached() == TRUE ) {
// Do not have attributes.. Means row matches... Just check the price & is_free
return apply_filters('rp_is_fully_unchanged_default_repair_individually',(($row->is_free == $dr_row->is_free) &&
($row->r_price == $dr_row->dr_price) &&
($row->r_duration == $dr_row->dr_duration) &&
($row->r_duration_measure == $dr_row->dr_duration_measure)), $row, $dr_row);
} else {
// Do not have attributes.. Means row matches... Just check the price & is_free
return apply_filters('rp_is_fully_unchanged_default_repair_individually',(($row->is_free == $dr_row->is_free) &&
($row->r_price == $dr_row->dr_price)), $row, $dr_row);
}
} else if( rp_attributes_exactly_matches_default_with_price( $attr_rows, $dr_attr_rows ) ) {
if( rp_current_user_has_full_access_cached() == TRUE ) {
// Attributes exactly matches but might have price changed
return apply_filters('rp_is_fully_unchanged_default_repair_individually',(($row->is_free == $dr_row->is_free) &&
($row->r_price == $dr_row->dr_price) &&
($row->r_duration == $dr_row->dr_duration) &&
($row->r_duration_measure == $dr_row->dr_duration_measure)), $row, $dr_row);
} else {
// Attributes exactly matches but might have price changed
return apply_filters('rp_is_fully_unchanged_default_repair_individually',(($row->is_free == $dr_row->is_free) &&
($row->r_price == $dr_row->dr_price)), $row, $dr_row);
}
} else {
return FALSE;
}
}
}
return FALSE;
}
function rp_attributes_exactly_matches_default_with_price( $attr_rows = array(), $dr_attr_rows = array() ) {
if( empty( $attr_rows ) || empty( $dr_attr_rows ) ) {
return FALSE;
}
if( rp_current_user_has_full_access_cached() == true ) {
if( (count($attr_rows) !== count($dr_attr_rows)) ) {
return FALSE;
}
}
$uq_ids = array();
$price = array();
$duration = array();
$duration_measure = array();
foreach( $dr_attr_rows as $dr_attr_row ) {
$uq_ids[] = $dr_attr_row->da_uq_id;
$price[] = $dr_attr_row->da_price;
$duration[] = $dr_attr_row->da_duration;
$duration_measure[] = $dr_attr_row->da_duration_measure;
}
$results = array();
foreach( $attr_rows as $attr_row ) {
if( !in_array( $attr_row->a_uq_id, $uq_ids ) ) {
if( rp_current_user_has_full_access_cached() == true ) {
return FALSE;
} else {
$results[] = TRUE;
}
} else {
if( rp_current_user_has_full_access_cached() == true ) {
$results[] = $price[array_search($attr_row->a_uq_id, $uq_ids)] == $attr_row->a_price && $duration[array_search($attr_row->a_uq_id, $uq_ids)] == $attr_row->a_duration && $duration_measure[array_search($attr_row->a_uq_id, $uq_ids)] == $attr_row->a_duration_measure;
} else {
$results[] = $price[array_search($attr_row->a_uq_id, $uq_ids)] == $attr_row->a_price;
}
}
}
$final_result = array_search(FALSE, $results) === FALSE;
return apply_filters('rp_attributes_exactly_matches_default_with_price', $final_result, $attr_rows, $dr_attr_rows);
}
function rp_get_model_cached_category_by_mid( $mid = '' ) {
$cache_key = 'rp_get_model_cached_category_by_mid_'.$mid;
$cached = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if( !empty( $cached ) ) {
return $cached;
}
global $rpQuery;
$rs_model = $rpQuery->prefix . 'rs_model';
$model_row = $rpQuery->get_row("SELECT `device_type` FROM `$rs_model` WHERE `m_id` = '$mid' LIMIT 1;");
$result = 0;
if( !empty( $model_row ) ) {
$result = $model_row->device_type;
}
RepairPluginPro\RP_Memory_Cache::save($cache_key, $result);
return $result;
}
function rp_reset_default_repair_individually() {
rp_verify_csrf_token_for_ajax('manage_models');
rp_verify_selected_location_id_by_location_head();
$rp_current_user_has_full_access = rp_current_user_has_full_access();
global $rpQuery;
list( $selected_location_id, $rp_location_based_price_id ) = rp_must_verify_selected_location_if_needed_ajax();
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$rs_location_prices = $rpQuery->prefix . 'rs_location_prices';
$rid = $_POST['drid'] ?? '';
$category_based = array();
$categoriesCount = 0;
$m_id_fk = 0;
$repair_row = $rpQuery->get_row("SELECT * FROM `$rs_repair` WHERE `r_id` = '".rp_escape_sql($rid)."' LIMIT 1;");
if( !empty( $repair_row ) ) {
$dr_category = rp_get_model_cached_category_by_mid( $repair_row->m_id_fk );
$uq_id = $repair_row->r_uq_id;
$dr_row = $rpQuery->get_row("SELECT * FROM `$rs_default_repair` WHERE `dr_uq_id` = '".rp_escape_sql($uq_id)."' AND `dr_category` = '".rp_escape_sql($dr_category)."' LIMIT 1");
if( !empty( $dr_row ) ) {
$also_reset_margin = apply_filters('rp_reset_default_repair_individually_margin', FALSE);
$reset_margin = '';
if( $also_reset_margin === TRUE ) {
$reset_margin = "`r_margin` = '".rp_escape_sql($dr_row->dr_margin)."',";
}
// Update individual repair row to match default repair
if( $rp_current_user_has_full_access == true ) {
$rpQuery->query("UPDATE `$rs_repair` SET
`r_name` = '".rp_escape_sql($dr_row->dr_name)."',
`r_discription` = '".rp_escape_sql($dr_row->dr_discription)."',
`r_badge` = '".rp_escape_sql($dr_row->dr_badge)."',
`r_readmore` = '".rp_escape_sql($dr_row->dr_readmore)."',
`r_readmoretext` = '".rp_escape_sql($dr_row->dr_readmoretext)."',
`is_free` = '".rp_escape_sql($dr_row->is_free)."',
`r_price` = '".rp_escape_sql($dr_row->dr_price)."',
`r_duration` = '".rp_escape_sql($dr_row->dr_duration)."',
`r_duration_measure` = '".rp_escape_sql($dr_row->dr_duration_measure)."',
{$reset_margin}
`r_img` = '".rp_escape_sql($dr_row->dr_img)."'
WHERE `r_id` = '".rp_escape_sql($repair_row->r_id)."';
");
_rp_remove_individual_repair_translations( 'repair_read_more', $repair_row->r_uq_id.'_'.$dr_category, $repair_row->m_id_fk );
_rp_remove_individual_repair_translations( 'repair_readmore_text', $repair_row->r_uq_id.'_'.$dr_category, $repair_row->m_id_fk );
_rp_remove_individual_attributes_translations( 'attr_read_more', $repair_row->r_id );
_rp_remove_individual_attributes_translations( 'attr_readmore_text', $repair_row->r_id );
}
if( !empty( $selected_location_id ) ) {
// delete from $rs_location_prices where type = 'r' and connection_id = $repair_row->r_id and dr_category = dr_category
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'r' AND `connection_id` = '".rp_escape_sql($repair_row->r_id)."' AND `location_id_fk` = '".rp_escape_sql($selected_location_id)."'");
}
$default_attrs = $rpQuery->get_results("SELECT * FROM `$rs_default_repair_attr` WHERE `dr_id_fk` = '".rp_escape_sql($dr_row->dr_id)."'");
$default_attrs_uq_ids = array();
if( !empty( $default_attrs ) ) {
foreach( $default_attrs as $dAttr ) {
$default_attrs_uq_ids[] = $dAttr->da_uq_id;
}
}
$andStr = '';
if( !empty( $default_attrs_uq_ids ) ) {
$attr_uq_ids = "'".implode("','", $default_attrs_uq_ids)."'";
$andStr = " AND `a_uq_id` NOT IN ( $attr_uq_ids )";
}
if( $rp_current_user_has_full_access == true ) {
// Remove custom created repair attributes
$rpQuery->query("DELETE FROM `$rs_repair_attr` WHERE `r_id_fk` = '".rp_escape_sql($rid)."'{$andStr};");
}
if( !empty( $default_attrs ) ) {
foreach( $default_attrs as $dAttr ) {
$r_id_fk = $repair_row->r_id;
$a_name = $dAttr->da_name;
$a_desc = $dAttr->da_desc;
$a_badge = $dAttr->da_badge;
$a_readmore = $dAttr->da_readmore;
$a_readmoretext = $dAttr->da_readmoretext;
$a_duration = $dAttr->da_duration;
$a_duration_measure = $dAttr->da_duration_measure;
$a_price = $dAttr->da_price;
$a_uq_id = $dAttr->da_uq_id;
$is_active = $dAttr->is_active;
$ra_position = $dAttr->da_position;
if( $also_reset_margin === TRUE ) {
$a_margin_reset = ', `a_margin`';
$a_margin_reset_value = ", '".rp_escape_sql($dAttr->da_margin)."'";
$update_margin_sql = ", `a_margin` = '".rp_escape_sql($dAttr->da_margin)."'";
} else {
$a_margin_reset = '';
$a_margin_reset_value = '';
$update_margin_sql = '';
}
// check if already exists
$attrAlreadyExists = $rpQuery->get_row("SELECT * FROM `$rs_repair_attr` WHERE `r_id_fk` = '".rp_escape_sql($r_id_fk)."' AND `a_uq_id` = '".rp_escape_sql($a_uq_id)."' LIMIT 1;");
if( !empty( $attrAlreadyExists ) ) {
if( $rp_current_user_has_full_access == true ) {
// Attribute already exists, so need to update it.
$rpQuery->query("UPDATE `$rs_repair_attr` SET
`a_name` = '".rp_escape_sql($a_name)."',
`a_desc` = '".rp_escape_sql($a_desc)."',
`a_badge` = '".rp_escape_sql($a_badge)."',
`a_readmore` = '".rp_escape_sql($a_readmore)."',
`a_readmoretext` = '".rp_escape_sql($a_readmoretext)."',
`a_duration` = '".rp_escape_sql($a_duration)."',
`a_duration_measure` = '".rp_escape_sql($a_duration_measure)."',
`a_price` = '".rp_escape_sql($a_price)."',
`is_active` = '".rp_escape_sql($is_active)."',
`ra_position` = '".rp_escape_sql($ra_position)."' {$update_margin_sql}
WHERE `r_id_fk` = '".rp_escape_sql($r_id_fk)."' AND `a_uq_id` = '".rp_escape_sql($a_uq_id)."'
");
}
if( !empty( $selected_location_id ) ) {
// delete from $rs_location_prices where type = 'a' and connection_id = $attrAlreadyExists->a_id
$rpQuery->query("DELETE FROM `$rs_location_prices` WHERE `type` = 'a' AND `connection_id` = '".rp_escape_sql($attrAlreadyExists->a_id)."' AND `location_id_fk` = '".rp_escape_sql($selected_location_id)."'");
}
} else {
if( $rp_current_user_has_full_access == true ) {
// Doesn't exists, so create a new one
$rpQuery->query("INSERT INTO `$rs_repair_attr` (`r_id_fk`, `a_name`, `a_desc`, `a_badge`, `a_readmore`, `a_readmoretext`, `a_duration`, `a_duration_measure`,`a_price`, `a_uq_id`, `is_active`, `ra_position` $a_margin_reset)
VALUES ('".rp_escape_sql($r_id_fk)."', '".rp_escape_sql($a_name)."', '".rp_escape_sql($a_desc)."', '".rp_escape_sql($a_badge)."', '".rp_escape_sql($a_readmore)."', '".rp_escape_sql($a_readmoretext)."', '".rp_escape_sql($a_duration)."', '".rp_escape_sql($a_duration_measure)."', '".rp_escape_sql($a_price)."', '".rp_escape_sql($a_uq_id)."', '".rp_escape_sql($is_active)."', '".rp_escape_sql($ra_position)."' $a_margin_reset_value);
");
}
}
}
}
}
list( $category_based, $categoriesCount ) = rp_get_model_related_repairs_for_admin_page( $repair_row->m_id_fk );
$m_id_fk = $repair_row->m_id_fk;
}
echo json_encode(array(
'status' => true,
'category_based' => $category_based,
'categories_count' => $categoriesCount,
'm_id_fk' => $m_id_fk
));
exit;
}
rp_ajax_for_admin('rp_reset_default_repair_individually', 'rp_reset_default_repair_individually');
// create 32 character unique id for csrf token
function rp_create_csrf_token($action = '') {
RepairPluginPro\RP_Session_Handler::start();
if( !isset($_SESSION['rp_csrf_tokens']) ) {
$_SESSION['rp_csrf_tokens'] = array();
}
// loop through all $_SESSION['rp_csrf_tokens'] and remove expired tokens (older than 1 hour)
foreach( $_SESSION['rp_csrf_tokens'] as $key => $value ) {
if( time() - $value['time'] > 3600 ) {
unset( $_SESSION['rp_csrf_tokens'][$key] );
}
}
if( !isset( $_SESSION['rp_csrf_tokens'][$action] ) ) {
$token = bin2hex(random_bytes(32));
$_SESSION['rp_csrf_tokens'][$action] = array(
'token' => $token,
'time' => time()
);
} else {
$token = $_SESSION['rp_csrf_tokens'][$action]['token'];
$_SESSION['rp_csrf_tokens'][$action]['time'] = time();
}
RepairPluginPro\RP_Session_Handler::close();
return $token;
}
function rp_redirect_refresh_form_with_success( $action = '', $success_msg = '' ) {
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['rp_refresh_form_success'] = $success_msg;
RepairPluginPro\RP_Session_Handler::close();
$referrer = $_SERVER['HTTP_REFERER'] ?? '';
rp_refresh_form_debug_info_save();
if( !empty( $referrer ) && strpos( $referrer, get_site_url() ) !== FALSE ) {
echo '<script>window.location.href = "'.$referrer.'";</script>';
} else {
echo '<script>window.location.href = "'.get_site_url().'";</script>';
}
exit;
}
function rp_redirect_refresh_form_with_error( $action = '', $error_msg = '', $redirect_url = '' ) {
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['rp_validation_error'] = $error_msg;
RepairPluginPro\RP_Session_Handler::close();
$referrer = $_SERVER['HTTP_REFERER'] ?? '';
rp_refresh_form_debug_info_save();
if( empty( $redirect_url ) ) {
if( !empty( $referrer ) && strpos( $referrer, get_site_url() ) !== FALSE ) {
echo '<script>window.location.href = "'.$referrer.'";</script>';
} else {
echo '<script>window.location.href = "'.get_site_url().'";</script>';
}
} else {
echo '<script>window.location.href = "'.$redirect_url.'";</script>';
}
exit;
}
function rp_verify_csrf_token_for_simple_form($action = '') {
if( !rp_verify_csrf_token($action) ) {
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['rp_validation_error'] = 'Form submission failed due to security reasons, please try again and it should work fine.';
RepairPluginPro\RP_Session_Handler::close();
$referrer = $_SERVER['HTTP_REFERER'] ?? '';
if( !empty( $referrer ) && strpos( $referrer, get_site_url() ) !== FALSE ) {
echo '<script>window.location.href = "'.$referrer.'";</script>';
} else {
echo '<script>window.location.href = "'.get_site_url().'";</script>';
}
exit;
}
}
function rp_verify_csrf_token_for_apple_calendar() {
if( !rp_verify_csrf_token('appointments') && !rp_verify_csrf_token('frontend') ) {
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['rp_validation_error'] = 'Form submission failed due to security reasons, please try again and it should work fine.';
RepairPluginPro\RP_Session_Handler::close();
$referrer = $_SERVER['HTTP_REFERER'] ?? '';
if( !empty( $referrer ) && strpos( $referrer, get_site_url() ) !== FALSE ) {
echo '<script>window.location.href = "'.$referrer.'";</script>';
} else {
echo '<script>window.location.href = "'.get_site_url().'";</script>';
}
exit;
}
}
function rp_verify_csrf_token_for_ajax($action = '') {
if( !is_array($action) ) {
$action = array($action);
}
foreach( $action as $_action ) {
if( rp_verify_csrf_token($_action) ) {
return true;
}
}
echo json_encode(
array(
'status'=> false,
'rp_validation_error' => 'Form submission failed, please refresh the page and try again.'
)
);
exit();
}
function rp_verify_csrf_token($action = '') {
if( $action == 'frontend' ) {
$csrf_protection_enabled = rp_get_option('rp_enable_csrf_protection_frontend', '1') == '1';
if( $csrf_protection_enabled == false ) {
// If csrf protection is not enabled, pretend like it passes csrf protection test
return true;
}
}
$token = $_POST['rp_csrf_token'] ?? '';
if( empty($token) ) {
return false;
}
RepairPluginPro\RP_Session_Handler::start();
if( !isset($_SESSION['rp_csrf_tokens']) ) {
// Try to re-read session from scratch
// as some other plugins might have overwrite
// $_SESSION variable till the time this function is called
RepairPluginPro\RP_Session_Handler::$readed_cookie = false;
RepairPluginPro\RP_Session_Handler::start();
if( !isset($_SESSION['rp_csrf_tokens']) ) {
$_SESSION['rp_csrf_tokens'] = array();
}
}
// loop through all $_SESSION['rp_csrf_tokens'] and remove expired tokens (older than 1 hour)
foreach( $_SESSION['rp_csrf_tokens'] as $key => $value ) {
if( time() - $value['time'] > 3600 ) {
unset( $_SESSION['rp_csrf_tokens'][$key] );
}
}
if( !isset( $_SESSION['rp_csrf_tokens'][$action] ) ) {
return false;
} else {
$_token = $_SESSION['rp_csrf_tokens'][$action]['token'];
if( $_token === $token ) {
$_SESSION['rp_csrf_tokens'][$action]['time'] = time();
RepairPluginPro\RP_Session_Handler::close();
return true;
} else {
return false;
}
}
}
function rp_is_recaptcha_correctly_configured() {
$is_enabled = rp_is_enabled_recaptcha();
$site_key = trim( rp_get_google_recaptcha_site_key() );
$secret_key = trim( rp_get_google_recaptcha_secret_key() );
if( $is_enabled == 1 && !empty( $site_key ) && !empty( $secret_key ) ) {
return TRUE;
}
return FALSE;
}
function rp_google_recaptcha_token_form_for_ajax() {
$is_enabled = rp_is_enabled_recaptcha();
$need_to_hide_badge = rp_is_need_to_hide_recaptcha_badge();
$site_key = trim( rp_get_google_recaptcha_site_key() );
$secret_key = trim( rp_get_google_recaptcha_secret_key() );
if( $is_enabled == 1 && !empty( $site_key ) && !empty( $secret_key ) ) {
echo '<form method="POST" style="display:none;">';
echo '<input type="hidden" name="rp-recaptcha-response" id="rp-recaptcha-response" value="">';
echo '</form>';
if( $need_to_hide_badge == 1 ) {
?>
<style type="text/css">
.grecaptcha-badge { display: none !important; }
</style>
<?php
}
?>
<script src="https://www.google.com/recaptcha/api.js?render=<?php echo $site_key; ?>"></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<?php echo $site_key; ?>', {action: 'submit'}).then(function(token) {
document.getElementById('rp-recaptcha-response').value = token;
console.log(token);
});
});
</script>
<?php
}
}
function rp_csrf_token_form_for_ajax($action = '') {
$token = rp_create_csrf_token($action);
echo '<form method="POST" style="display:none;">';
echo '<input type="hidden" name="rp_csrf_token" value="'.$token.'">';
echo '</form>';
}
function rp_regenerate_front_end_csrf_token() {
if( !isset( $_POST['regenerate'] ) ) {
echo json_encode(array(
'status' => false,
'message' => 'Invalid request'
));
exit();
}
$token = rp_create_csrf_token( 'frontend' );
echo json_encode(array(
'status' => true,
'token' => $token
));
exit();
}
rp_ajax_for_public('rp_regenerate_front_end_csrf_token', 'rp_regenerate_front_end_csrf_token');
function rp_csrf_token_input_field($action = '') {
static $cached_created_tokens = NULL;
if( $cached_created_tokens !== NULL && array_key_exists( $action, $cached_created_tokens ) ) {
$token = $cached_created_tokens[$action];
} else {
$token = rp_create_csrf_token($action);
$cached_created_tokens[$action] = $token;
}
echo '<input type="hidden" name="rp_csrf_token" value="'.$token.'">';
return $token;
}
function rp_load_session_data() {
$page = $_REQUEST['page'] ?? '';
$repairPluginPages = array(
'wp_repair_analytics',
'wp_repair_appointments',
'wp_repair_customers',
'wp_repair_manage_categories',
'wp_repair_manage_models',
'wp_repair_manage_upsales',
'wp_repair_download_libraries',
'wp_repair_default_repairs',
'wp_repair_settings'
);
if( in_array($page, $repairPluginPages) ) {
// check if is ajax request (xmlhttprequest)
if( strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' ) !== 'xmlhttprequest' ) {
rp_fix_addon_switch_settings_on_backend();
}
RepairPluginPro\RP_Session_Handler::start();
}
}
rp_add_action('init', 'rp_load_session_data');
function rp_is_enabled_recaptcha() {
return rp_get_option('rp_enable_recaptcha', 0);
}
function rp_is_need_to_hide_recaptcha_badge() {
return rp_get_option('rp_hide_recaptcha_badge', 0);
}
function rp_get_google_recaptcha_site_key() {
return rp_get_option('rp_recaptcha_site_key', '');
}
function rp_get_google_recaptcha_secret_key() {
return rp_get_option('rp_recaptcha_secret_key', '');
}
function rp_verify_google_recaptcha() {
if( !rp_is_recaptcha_correctly_configured() ) {
return TRUE;
}
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = rp_get_google_recaptcha_secret_key();
$recaptcha_response = trim($_POST['recaptcha_response'] ?? '');
if( empty($recaptcha_response) ) {
return FALSE;
}
$recaptcha = rp_fetch_image_from_base($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
if( empty($recaptcha) ) {
return FALSE;
}
$recaptcha = json_decode($recaptcha);
if (!empty($recaptcha) && isset($recaptcha->success) && $recaptcha->success == true && isset($recaptcha->score) && $recaptcha->score >= 0.5) {
return TRUE;
} else {
return FALSE;
}
}
function rp_get_recaptcha_info() {
echo json_encode(array(
'success' => true,
'site_key' => rp_get_google_recaptcha_site_key(),
'secret_key' => rp_get_google_recaptcha_secret_key(),
'enable_protection' => rp_is_enabled_recaptcha(),
'hide_recaptcha_badge' => rp_is_need_to_hide_recaptcha_badge()
));
exit;
}
rp_ajax_for_admin('rp_get_recaptcha_info', 'rp_get_recaptcha_info');
function rp_save_recaptcha_info() {
// data: {
// action:'rp_save_recaptcha_info',
// rp_enable_recaptcha: rp_enable_recaptcha,
// hide_recaptcha_badge: hide_recaptcha_badge,
// recaptcha_site_key: recaptcha_site_key,
// recaptcha_secret_key: recaptcha_secret_key
// },
rp_verify_csrf_token_for_ajax('styling');
$rp_enabled_recaptcha = $_POST['rp_enable_recaptcha'] ?? 0;
$rp_hide_recaptcha_badge = $_POST['hide_recaptcha_badge'] ?? 0;
$rp_recaptcha_site_key = trim( $_POST['recaptcha_site_key'] ?? '' );
$rp_recaptcha_secret_key = trim( $_POST['recaptcha_secret_key'] ?? '' );
// make sure rp_enabled_recaptcha is either 1 or 0
$rp_enabled_recaptcha = $rp_enabled_recaptcha == 1 ? 1 : 0;
// make sure rp_hide_recaptcha_badge is either 1 or 0
$rp_hide_recaptcha_badge = $rp_hide_recaptcha_badge == 1 ? 1 : 0;
if( rp_get_option('rp_enable_recaptcha', FALSE) === FALSE ) {
rp_add_option('rp_enable_recaptcha', $rp_enabled_recaptcha);
} else {
rp_update_option('rp_enable_recaptcha', $rp_enabled_recaptcha);
}
if( rp_get_option('rp_hide_recaptcha_badge', FALSE) === FALSE ) {
rp_add_option('rp_hide_recaptcha_badge', $rp_hide_recaptcha_badge);
} else {
rp_update_option('rp_hide_recaptcha_badge', $rp_hide_recaptcha_badge);
}
if( rp_get_option('rp_recaptcha_site_key', FALSE) === FALSE ) {
rp_add_option('rp_recaptcha_site_key', $rp_recaptcha_site_key);
} else {
rp_update_option('rp_recaptcha_site_key', $rp_recaptcha_site_key);
}
if( rp_get_option('rp_recaptcha_secret_key', FALSE) === FALSE ) {
rp_add_option('rp_recaptcha_secret_key', $rp_recaptcha_secret_key);
} else {
rp_update_option('rp_recaptcha_secret_key', $rp_recaptcha_secret_key);
}
echo json_encode(array(
'success' => true,
'correctly_configured' => rp_is_recaptcha_correctly_configured()
));
exit;
}
rp_ajax_for_admin('rp_save_recaptcha_info', 'rp_save_recaptcha_info');
// add default rows in delivery timeslots table
function rp_add_default_delivery_timeslots_rows() {
global $rpQuery;
$rs_delivery_timeslots = $rpQuery->prefix . 'rs_delivery_timeslots';
$is_empty_table = empty($rpQuery->get_row("SELECT * FROM `$rs_delivery_timeslots` LIMIT 1"));
if( $is_empty_table === TRUE && rp_get_option('rp_added_default_delivery_timeslots_rows', FALSE) === FALSE ) {
$delivery_methods = array('pickup_service', 'repair_on_location');
$slots = array(
array(
'start' => '09:00',
'end' => '12:00'
),
array(
'start' => '12:00',
'end' => '15:00'
),
array(
'start' => '15:00',
'end' => '18:00'
)
);
foreach( $delivery_methods as $method ) {
foreach( $slots as $slot ) {
$rpQuery->insert($rs_delivery_timeslots, array(
'slot_start' => $slot['start'],
'slot_end' => $slot['end'],
'delivery_method' => $method
));
}
}
// also setup default available on days if not already
if( rp_get_option('rp_pickup_service_available_days', FALSE) === FALSE ) {
rp_add_option('rp_pickup_service_available_days', json_encode(array(
'monday' => 1,
'tuesday' => 1,
'wednesday' => 1,
'thursday' => 1,
'friday' => 1,
'saturday' => 1,
'sunday' => 0
)));
}
if( rp_get_option('rp_repair_on_location_available_days', FALSE) === FALSE ) {
rp_add_option('rp_repair_on_location_available_days', json_encode(array(
'monday' => 1,
'tuesday' => 1,
'wednesday' => 1,
'thursday' => 1,
'friday' => 1,
'saturday' => 1,
'sunday' => 0
)));
}
rp_add_option('rp_added_default_delivery_timeslots_rows', '1');
}
}
rp_add_action('init', 'rp_add_default_delivery_timeslots_rows', 999);
function rp_get_special_timing($cs_day = '', $loc_id = '') {
global $rpQuery;
$rs_special_timing = $rpQuery->prefix . 'rs_special_timing';
// check if cs_day and location_id_fk already exists
$all_rows = $rpQuery->get_results("SELECT * FROM `$rs_special_timing` WHERE cs_day = '".rp_escape_sql($cs_day)."';");
if( empty( $all_rows ) ) {
return array();
}
foreach($all_rows as $row) {
$location_id_fk = $row->location_id_fk;
$location_id_fk_array = explode(',', $location_id_fk);
if( array_search($loc_id, $location_id_fk_array) !== FALSE ) {
return $row;
}
}
return array();
}
function rp_check_if_special_timing_exists($cs_day = '', $loc_id = '') {
return !empty( rp_get_special_timing( $cs_day, $loc_id ) );
}
function rp_get_delivery_timeslots( $method = '', $day = '' ) {
global $rpQuery;
$rs_delivery_timeslots = $rpQuery->prefix . 'rs_delivery_timeslots';
$key = 'rp_'.$method.'_available_days';
$available_days = rp_get_option($key, json_encode(array()));
$available_days = json_decode($available_days, TRUE);
$day = strtolower($day);
if( isset( $available_days[ $day ] ) && (int) $available_days[ $day ] === 1 ) {
$all_rows = $rpQuery->get_results("SELECT * FROM `$rs_delivery_timeslots` WHERE `delivery_method` = '".rp_escape_sql($method)."' ORDER BY `slot_start` ASC;");
return $all_rows;
}
return array();
}
// add 'Pickup Service' in noti_type column of rs_notification_types table
function add_pickup_service_in_rs_notification_types() {
/* Added in V1.5.1 */
global $rpQuery;
$noti_type = 'Booking Approved (Pickup Service)';
$rs_notification_types = $rpQuery->prefix . 'rs_notification_types';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notification_types` WHERE `noti_type` = '".rp_escape_sql($noti_type)."' LIMIT 1;");
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notification_types` (`noti_type`, `is_active`) VALUES ('".rp_escape_sql($noti_type)."', '1');");
}
}
rp_add_action('init', 'add_pickup_service_in_rs_notification_types', 999);
// insert into all columns from rs_notifications_and_offers table if noti_type_id_fk 5 doesn't exist
function insert_pickup_service_markup_in_notification_table() {
/* Added in V1.5.1 */
global $rpQuery;
$rs_notifications_and_offers = $rpQuery->prefix . 'rs_notifications_and_offers';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notifications_and_offers` WHERE `noti_type_id_fk` = '9' LIMIT 1;");
$subject = 'Subject for Pickup Service Email';
$message = 'This is message for pickup service email';
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notifications_and_offers` (`noti_subject`, `noti_message`, `noti_type_id_fk`, `is_active`, `date_time`) VALUES ('$subject', '$message', '9', '1', '".date('Y-m-d H:i:s')."');");
}
}
rp_add_action('init', 'insert_pickup_service_markup_in_notification_table', 999);
// add 'Repair on Location' in noti_type column of rs_notification_types table
function add_repair_on_location_in_rs_notification_types() {
/* Added in V1.5.1 */
global $rpQuery;
$noti_type = 'Booking Approved (Repair on Location)';
$rs_notification_types = $rpQuery->prefix . 'rs_notification_types';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notification_types` WHERE `noti_type` = '".rp_escape_sql($noti_type)."' LIMIT 1;");
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notification_types` (`noti_type`, `is_active`) VALUES ('".rp_escape_sql($noti_type)."', '1');");
}
}
rp_add_action('init', 'add_repair_on_location_in_rs_notification_types', 999);
// insert into all columns from rs_notifications_and_offers table if noti_type_id_fk 5 doesn't exist
function insert_on_location_markup_in_notification_table() {
/* Added in V1.5.1 */
global $rpQuery;
$rs_notifications_and_offers = $rpQuery->prefix . 'rs_notifications_and_offers';
$exists = $rpQuery->get_row("SELECT * FROM `$rs_notifications_and_offers` WHERE `noti_type_id_fk` = '10' LIMIT 1;");
$subject = 'Subject for Repair on Location Email';
$message = 'This is message for repair on location email';
if(empty($exists)) {
$rpQuery->query("INSERT INTO `$rs_notifications_and_offers` (`noti_subject`, `noti_message`, `noti_type_id_fk`, `is_active`, `date_time`) VALUES ('$subject', '$message', '10', '1', '".date('Y-m-d H:i:s')."');");
}
}
rp_add_action('init', 'insert_on_location_markup_in_notification_table', 999);
// if not exists, wp_repair_admin_duplicate_email_status_5,6,7,8,9,10 add to options table using get_option, rp_add_option
function add_duplicate_email_status_arr_in_options_table() {
/* Added in V1.5.1 */
$notification_ids = array(
'5',
'6',
'7',
'8',
'9',
'10'
);
foreach( $notification_ids as $the_id ) {
$exists = rp_get_option('wp_repair_admin_duplicate_email_status_'.$the_id, FALSE);
if( $exists === FALSE ) {
rp_add_option('wp_repair_admin_duplicate_email_status_'.$the_id, '1');
}
}
}
rp_add_action('init', 'add_duplicate_email_status_arr_in_options_table', 999);
function rp_add_new_translation_by_release( $new_translation_groups = array() ) {
$new_translation_groups['rp_plugin_translations_v1_5_1'] = array(
'user_location_zipcode',
'user_location_house_number',
'user_location_street_address',
'user_location_city',
'let_us_pickup_your_device',
'pickup_service_description',
'repair_on_your_location',
'repair_on_your_location_description',
'booking_approved_pickup_service_email_subject',
'booking_approved_pickup_service_email_template',
'booking_approved_repair_on_location_email_subject',
'booking_approved_repair_on_location_email_template',
'do_you_need_help',
'invalid_license_code',
'enter_your_license_key_here',
'if_you_dont_have_license',
'license_code',
'license_email',
'we_will_send_updated_news_of_this_product'
);
$new_translation_groups['rp_plugin_translations_v1_5_2'] = array(
'device_mobile'
);
$new_translation_groups['rp_plugin_translations_v1_5_7'] = array(
'combo_discount_percent_off'
);
$new_translation_groups['rp_plugin_translations_v1_6_0'] = array(
'type_in_your_brand_model_or_modelcode',
'model_searchbar_placeholder_text',
'which_model_do_you_have',
'what_model_do_i_have',
'filter_by_series',
'reset_filter',
'all_models',
'total_models',
'how_to_find_your_model_code',
'what_model_step_1',
'what_model_step_2',
'what_model_step_3',
'button_ios',
'what_model_ios_step_1_desc',
'what_model_ios_step_2_desc',
'what_model_ios_step_3_desc',
'button_android',
'what_model_android_step_1_desc',
'what_model_android_step_2_desc',
'what_model_android_step_3_desc',
'or_select_your_type',
'or_select_your_brand',
'select_location',
'your_location',
'select_date',
'select_time',
'select_color_new',
'select_repair_new'
);
$new_translation_groups['rp_plugin_translations_v1_6_0_d15'] = array(
'select_location',
'your_location',
'select_date',
'select_time'
);
$new_translation_groups['rp_plugin_translations_v161_preselect'] = array(
'pre_select_location_heading',
'all_locations',
'total_locations',
'no_locations_found'
);
$new_translation_groups['rp_plugin_translations_v170_step_wizard'] = array(
'select'
);
$new_translation_groups['rp_plugin_translations_v170_payments_n'] = array(
'rp_paypal_label',
'rp_pay_repair_label',
'rp_mollie_label',
'rp_stripe_label',
'please_select_any_payment_method',
'payment_method_error',
'select_payment_method',
'payment_status_pending',
'payment_status_paid',
'payment_method',
'payment_status',
'processing_your_request',
'please_wait_it_may_take_a_while'
);
$new_translation_groups['rp_plugin_translations_v171'] = array(
'prepare_for_your_upcoming_appointment'
);
$new_translation_groups['rp_plugin_translations_v180'] = array(
'pickup_service',
'distance_verification_please_wait_msg',
'distance_verification_not_available_msg',
'distance_verification_is_available_msg'
);
$new_translation_groups['rp_plugin_translations_v182'] = array(
'distance_verification_not_available_msg',
'please_select_any_delivery_method',
'select_delivery_method'
);
$new_translation_groups['rp_plugin_translations_v192_dev4'] = array(
'dropdown_select'
);
$new_translation_groups['rp_plugin_translations_v192_approve_link'] = array(
'appointment_approved',
'your_appointment_has_been_approved'
);
$new_translation_groups['rp_plugin_translations_v192_confirm_cancel'] = array(
'cancel_appointment',
'are_you_sure_you_want_to_cancel',
'yes_cancel',
'approve_appointment',
'are_you_sure_you_want_to_approve',
'yes_approve'
);
$new_translation_groups['rp_plugin_translations_vat_switch'] = array(
'excl'
);
$new_translation_groups['rp_plugin_translations_v200'] = array(
'combo_discount_info'
);
$new_translation_groups['rp_plugin_translations_v200_d13'] = array(
'indicator_now_open_message',
'indicator_now_closed_message',
'indicator_opening_soon_message',
'indicator_closing_soon_message',
'indicator_special_date_open_message',
'indicator_special_date_close_message',
'indicator_closed',
'short_month_name_jan',
'short_month_name_feb',
'short_month_name_mar',
'short_month_name_apr',
'short_month_name_may',
'short_month_name_jun',
'short_month_name_jul',
'short_month_name_aug',
'short_month_name_sep',
'short_month_name_oct',
'short_month_name_nov',
'short_month_name_dec',
'full_month_name_january',
'full_month_name_february',
'full_month_name_march',
'full_month_name_april',
'full_month_name_may',
'full_month_name_june',
'full_month_name_july',
'full_month_name_august',
'full_month_name_september',
'full_month_name_october',
'full_month_name_november',
'full_month_name_december'
);
$new_translation_groups['rp_plugin_translations_v200_d14'] = array(
'indicator_open_before_breaktime_message',
'indicator_open_but_breaktime_message'
);
$new_translation_groups['rp_plugin_translations_v200_d23'] = array(
'please_select_priority',
'select_priority'
);
$new_translation_groups['rp_plugin_translations_v200_d26'] = array(
'item_name',
'price',
'uncategorised',
'upsales'
);
$new_translation_groups['rp_plugin_translations_v200_d28'] = array(
'rp_ideal_in3_label',
'rp_ideal_in3_description',
'today',
'user_location_country',
'first_name',
'last_name'
);
$new_translation_groups['rp_plugin_translations_v200_d31'] = array(
'ideal_in3_popup_heading',
'ideal_in3_popup_description',
'ideal_in3_popup_subtext'
);
$new_translation_groups['rp_plugin_translations_v200_d32'] = array(
'ideal_in3_or'
);
$new_translation_groups['rp_plugin_translations_v200_d33_1'] = array(
'ideal_in3_popup_footer_text'
);
$new_translation_groups['rp_plugin_translations_v200_d34'] = array(
'all_country_names'
);
$new_translation_groups['rp_plugin_translations_v201_d2'] = array(
'loading_data'
);
return $new_translation_groups;
}
add_filter('rp_force_fetch_new_translation_groups', 'rp_add_new_translation_by_release', 10, 1);
function rp_download_new_translations_from_server( $new_translation_keys = array() ) {
global $rpQuery;
$baselang_class = new RepairPluginPro\Download_Languages($rpQuery);
$lang_ids = rp_get_uq_id_of_all_rs_languages();
if( empty( $lang_ids ) ) {
// No languages available!
return TRUE;
}
$_POST['lang_uq_ids'] = $lang_ids;
$response = $baselang_class->fetch_repair_base(TRUE, FALSE);
if( empty( $response ) ) {
return FALSE;
}
return $baselang_class->save_handler_new_translations($response, $new_translation_keys) !== FALSE;
}
function rp_force_fetch_new_translations(){
if( empty( $_REQUEST['action'] ?? '' ) && !wp_doing_ajax() ) {
return;
}
if( !defined('WP_REPAIR_REQUIRE_LICENSE') ) {
$new_translation_groups = apply_filters('rp_force_fetch_new_translation_groups', array());
if( empty( $new_translation_groups ) ) {
return;
}
$uniqueGroups = array();
$new_translation_keys = array();
foreach( $new_translation_groups as $group => $groupItems ) {
if( array_search( $group, $uniqueGroups ) === FALSE ) {
$uniqueGroups[] = $group;
}
if( rp_get_option( $group, FALSE ) === FALSE ) {
foreach( $groupItems as $item ) {
if( array_search( trim($item), $new_translation_keys ) === FALSE ) {
$new_translation_keys[] = trim($item);
}
}
}
}
if( !empty( $new_translation_keys ) ) {
if( rp_download_new_translations_from_server( $new_translation_keys ) !== FALSE ) {
// Downloaded correctly!
foreach($uniqueGroups as $group) {
if( rp_get_option( $group, FALSE ) === FALSE ) {
rp_add_option( $group, '1' );
}
}
}
}
}
}
rp_add_action('init', 'rp_force_fetch_new_translations', 999);
// Fix for those sites that already got messed by v1.5.2
function rp_remove_empty_sorting_values_from_options() {
// delete from $wpdb->prefix . options where option_name like 'rp_default_listing_index_' and (option_value = '' or option_value = '0' or option_value IS NULL);
if( rp_get_option('rp_remove_empty_sorting_values_from_options', FALSE) === FALSE ) {
rp_add_option('rp_remove_empty_sorting_values_from_options', '1');
global $rpQuery;
$options_table = $rpQuery->prefix . 'options';
$rpQuery->query("DELETE FROM `$options_table` WHERE `option_name` LIKE 'rp_default_listing_index_%' AND (`option_value` = '' OR `option_value` = '0' OR `option_value` IS NULL);");
}
}
rp_add_action('init', 'rp_remove_empty_sorting_values_from_options', 999);
function rp_round_to_even_number( $number = 0 ) {
if( $number == 0 ) {
return 0;
}
if( $number % 2 == 0 ) {
return $number;
}
return $number + 1;
}
function returning_por_repairs( $por_repairs = array(), $order_id = 0 ) {
/* Added in V1.4.4 */
global $rpQuery;
$rs_order_repairs = $rpQuery->prefix . 'rs_order_repairs';
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
$rs_repair = $rpQuery->prefix . 'rs_repair';
$order_repairs = $rpQuery->get_results("SELECT * FROM `$rs_order_repairs` WHERE `o_id_fk` = '{$order_id}';");
if( !empty( $order_repairs ) ) {
$r_id_fk = array();
foreach( $order_repairs as $row ) {
$repair_attrs = $rpQuery->get_results("SELECT * FROM `$rs_order_repair_attr` WHERE `o_id_fk` = '{$order_id}' AND `r_id_fk` = '".rp_escape_sql($row->r_id_fk)."';");
if( empty( $repair_attrs ) && ((float) $row->repair_price) <= 0 && property_exists( $row, 'pricing_method' ) && $row->pricing_method === 'price_on_request') {
$r_id_fk[] = $row->r_id_fk;
}
}
if( !empty( $r_id_fk ) ) {
$r_id_fk = join(',', $r_id_fk);
$price_on_request = $rpQuery->get_results("SELECT * FROM `$rs_repair` WHERE `r_id` IN ({$r_id_fk}) AND `is_free` != '1';");
$unique_tracking = array();
$filtered_items = array();
foreach( $por_repairs as $theRepairRow ) {
if( array_search( $theRepairRow->r_id, $unique_tracking ) === FALSE ) {
$unique_tracking[] = $theRepairRow->r_id;
$filtered_items[] = $theRepairRow;
}
}
if( !empty( $price_on_request ) ) {
// loop through the price on request items and add them to the list
foreach( $price_on_request as $por_row ) {
if( array_search( $por_row->r_id, $unique_tracking ) === FALSE ) {
$unique_tracking[] = $por_row->r_id;
$filtered_items[] = $por_row;
}
}
}
$por_repairs = $filtered_items;
}
}
return $por_repairs;
}
add_filter('returning_por_repairs', 'returning_por_repairs', 10, 2);
function returning_por_repair_attrs( $por_repairs = array(), $order_id = 0 ) {
/* Added in V1.4.4 */
global $rpQuery;
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$order_repairs = $rpQuery->get_results("SELECT * FROM `$rs_order_repair_attr` WHERE `o_id_fk` = '{$order_id}';");
if( !empty( $order_repairs ) ) {
$ra_id_fk = array();
foreach( $order_repairs as $row ) {
if( ((float) $row->repair_attr_price) <= 0 && property_exists( $row, 'pricing_method' ) && $row->pricing_method === 'price_on_request' ) {
$ra_id_fk[] = $row->ra_id_fk;
}
}
if( !empty( $ra_id_fk ) ) {
$ra_id_fk = join(',', $ra_id_fk);
$price_on_request = $rpQuery->get_results("SELECT * FROM `$rs_repair_attr` WHERE `a_id` IN ({$ra_id_fk});");
$unique_tracking = array();
$filtered_items = array();
foreach( $por_repairs as $theRepairRow ) {
if( array_search( $theRepairRow->a_id, $unique_tracking ) === FALSE ) {
$unique_tracking[] = $theRepairRow->a_id;
$filtered_items[] = $theRepairRow;
}
}
if( !empty( $price_on_request ) ) {
// loop through the price on request items and add them to the list
foreach( $price_on_request as $por_row ) {
if( array_search( $por_row->a_id, $unique_tracking ) === FALSE ) {
$unique_tracking[] = $por_row->a_id;
$filtered_items[] = $por_row;
}
}
}
$por_repairs = $filtered_items;
}
}
return $por_repairs;
}
add_filter('returning_por_repair_attrs', 'returning_por_repair_attrs', 10, 2);
function rp_appointment_is_dynamic_price( $row = null ) {
if( property_exists( $row, 'pricing_method' ) && $row->pricing_method === 'dynamic' && property_exists( $row, 'pricing_info' ) && !empty( $row->pricing_info ) ) {
return TRUE;
}
return FALSE;
}
function rp_find_model_by_id( $m_id = 0 ) {
global $rpQuery;
$rs_model = $rpQuery->prefix . 'rs_model';
$rs_brand = $rpQuery->prefix . 'rs_brand';
$rs_category = $rpQuery->prefix . 'rs_category';
$m_id = intval( $m_id );
$sql = "SELECT $rs_model.*, $rs_brand.b_name, $rs_category.c_name FROM `$rs_model`
LEFT JOIN `$rs_brand` ON `$rs_brand`.`b_id` = `$rs_model`.`brand_id_fk`
LEFT JOIN `$rs_category` ON `$rs_category`.`c_id` = `$rs_model`.`device_type`
WHERE m_id = {$m_id}";
$model = $rpQuery->get_row( $sql );
if( !empty( $model ) ) {
return $model;
}
return array();
}
function rp_get_more_details_of_sku() {
global $rpQuery;
$rs_order_repairs = $rpQuery->prefix . 'rs_order_repairs';
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_order_repair_attr = $rpQuery->prefix . 'rs_order_repair_attr';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
$row_id = intval($_POST['row_id'] ?? 0);
$row_type = $_POST['row_type'] ?? '';
if( !empty( $row_id ) && !empty( $row_type ) ) {
if( $row_type === 'attr' ) {
$id_col = 'ora_id';
$table = $rs_order_repair_attr;
$id_fk = 'ra_id_fk';
$uqid = 'a_uq_id';
} else {
$id_col = 'or_id';
$table = $rs_order_repairs;
$id_fk = 'r_id_fk';
$uqid = 'r_uq_id';
}
$row = $rpQuery->get_row("SELECT * FROM `$table` WHERE `$id_col` = '{$row_id}' AND `pricing_method` = 'dynamic';");
if( !empty( $row ) ) {
$o_id_fk = $row->o_id_fk;
$_POST['selected_location_id'] = rp_get_location_id_of_order( $o_id_fk );
rp_verify_selected_location_id_by_location_head();
if( $uqid === 'r_uq_id' ) {
$repair_uqid = ( ( rp_find_repair_row_by_id( $row->{$id_fk} )->{$uqid} ) ?? 0 );
} else {
$repair_uqid = ( ( rp_find_repair_attr_row_by_id( $row->{$id_fk} )->{$uqid} ) ?? 0 );
}
$pricing_info = $row->pricing_info;
// select * from rs_orders where o_id = $o_id_fk
$rs_orders = $rpQuery->prefix . 'rs_orders';
$order = $rpQuery->get_row("SELECT * FROM `$rs_orders` WHERE `o_id` = '{$o_id_fk}';");
if( !empty( $order ) ) {
$theModel = rp_find_model_by_id( $order->m_id_fk );
$m_uq_id = $theModel->m_uq_id;
$modelName = $theModel->c_name . '<span class="model-name-separator">></span>' . $theModel->b_name . '<span class="model-name-separator">></span>' . $theModel->m_name;
if( !empty( $m_uq_id ) ) {
$live_skus = rp_dp_get_live_skus( $m_uq_id, $repair_uqid );
if( empty( $live_skus ) ) {
$live_skus = array();
}
$rp_dp_finished_cron_processing_time = '';
if( rp_get_option('rp_dp_finished_cron_processing', FALSE) !== FALSE ) {
$rp_dp_finished_cron_processing = rp_get_option('rp_dp_finished_cron_processing', FALSE);
if( !empty( $rp_dp_finished_cron_processing ) ) {
$rp_dp_finished_cron_processing_time = '<span class="rp-dp-rounded-time-box">' .file_get_contents(WP_REPAIR_PLUGIN_PATH.'assets/images/history.svg') . trim( _rp_dp_human_readable_difference( date('Y-m-d H:i:s', $rp_dp_finished_cron_processing), date('Y-m-d H:i:s', time()) ) ) . ' ago</span>';
}
}
$pricing_info = unserialize( $pricing_info );
if( isset( $pricing_info['calculated_at_time'] ) && !empty( $pricing_info['calculated_at_time'] ) ) {
$pricing_info['calculated_at_time'] = '<span class="rp-dp-rounded-time-box">' . file_get_contents(WP_REPAIR_PLUGIN_PATH.'assets/images/history.svg') . trim( _rp_dp_human_readable_difference( date('Y-m-d H:i:s', $pricing_info['calculated_at_time']), date('Y-m-d H:i:s', time()) ) ) . ' ago</span>';
} else {
$pricing_info['calculated_at_time'] = '';
}
echo json_encode( array(
'status' => true,
'pricing_info' => $pricing_info,
'live_skus' => $live_skus,
'model_name' => $modelName,
'last_processing' => $rp_dp_finished_cron_processing_time
) );
exit;
}
}
}
echo json_encode( array(
'status'=> false,
'rp_validation_error' => 'Something went wrong, please refresh the page and try agian.'
) );
} else {
echo json_encode( array(
'status'=> false,
'rp_validation_error' => 'Invalid request'
) );
}
exit;
}
rp_ajax_for_admin('rp_get_more_details_of_sku', 'rp_get_more_details_of_sku');
function _get_human_readable_difference_from_now( $time = '' ) {
if( empty( $time ) || $time == 'N/A' ) {
return 'N/A';
}
$provided_time = date( 'Y-m-d H:i:s', $time );
$current_time = date( 'Y-m-d H:i:s', time() );
$diff = _rp_dp_human_readable_difference( $current_time, $provided_time );
if( empty( $diff ) ) {
return 'Just Now';
}
return $diff . ' ago';
}
function _rp_dp_human_readable_difference( $date1 = '', $date2 = '' ) {
$diff = new \DateTime( $date1 );
$now = new \DateTime( $date2 );
$interval = $now->diff( $diff );
// year, month, day, hour, minute, second
$y = $interval->y;
$m = $interval->m;
$d = $interval->d;
$h = $interval->h;
$i = $interval->i;
$s = $interval->s;
$response = '';
if( $y > 0 ) {
$response .= $y . ' year';
if( $y > 1 ) {
$response .= 's';
}
$response .= ' ';
return $response;
}
if( $m > 0 ) {
$response .= $m . ' month';
if( $m > 1 ) {
$response .= 's';
}
$response .= ' ';
return $response;
}
if( $d > 0 ) {
$response .= $d . ' day';
if( $d > 1 ) {
$response .= 's';
}
$response .= ' ';
return $response;
}
if( $h > 0 ) {
$response .= $h . ' hour';
if( $h > 1 ) {
$response .= 's';
}
$response .= ' ';
return $response;
}
if( $i > 0 ) {
$response .= $i . ' minute';
if( $i > 1 ) {
$response .= 's';
}
$response .= ' ';
return $response;
}
if( $s > 0 ) {
$response .= $s . ' second';
if( $s > 1 ) {
$response .= 's';
}
$response .= ' ';
return $response;
}
return $response ?? 'Just now';
}
function _rp_manage_upsales_more_details( $upsales_id = 0 ) {
global $rpQuery;
ob_start();
require WP_REPAIR_PLUGIN_PATH.'html/manage_upsales_more_details.php';
$content = ob_get_contents();
ob_end_clean();
return $content;
}
function rp_manage_upsales_more_details() {
global $rpQuery;
$upsales_id = (int) $_POST['upsales_id'] ?? 0;
$rs_upsales = $rpQuery->prefix . "rs_upsales";
$up_sales = $rpQuery->get_row("SELECT * FROM $rs_upsales WHERE `upsales_id` = '".rp_escape_sql($upsales_id)."' ORDER BY upsales_position ASC");
if( !empty( $up_sales ) ) {
$more_details = _rp_manage_upsales_more_details( $upsales_id );
echo json_encode(array(
'status' => true,
'more_details' => $more_details
));
exit;
}
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid Upsale ID'
));
exit;
}
rp_ajax_for_admin('rp_manage_upsales_more_details', 'rp_manage_upsales_more_details');
function rp_get_individual_repairs_markup() {
$start_time = microtime(true);
list( $selected_location_id, $rp_location_based_price_id ) = rp_must_verify_selected_location_if_needed_ajax();
global $rpQuery;
$rs_model = $rpQuery->prefix . 'rs_model';
$rs_brand = $rpQuery->prefix . 'rs_brand';
$rs_category = $rpQuery->prefix . 'rs_category';
$rs_repair = $rpQuery->prefix . 'rs_repair';
$localization = $rpQuery->prefix . "rs_localization";
$localization_data = $rpQuery->get_results("SELECT * FROM $localization");
$decimal = $localization_data[0]->set_decimals;
$m_id = $_POST['m_id'] ?? 0;
// check if m_id exists in rs_model table
$model = $rpQuery->get_row("SELECT * FROM `$rs_model` AS `m`
Left Join $rs_category AS c ON c.c_id = m.device_type
Left Join $rs_brand AS b ON b.b_id = m.brand_id_fk
WHERE `m_id` = '".rp_escape_sql($m_id)."' LIMIT 1;");
if( !empty( $model ) ) {
$category_based = rp_get_individual_repairs_based_on_repair_category( $m_id );
$model = rp_sanitize_output($model);
ob_start();
require_once WP_REPAIR_PLUGIN_PATH . 'html/manage_repairs_standalone.php';
global $added_margin_column;
$added_margin_column = FALSE;
$price_markup = '<th style="width: 75px"><p>Price</p></th>';
$filtered_price_th = apply_filters('rp_individual_repair_price_th', $price_markup);
if( $price_markup !== $filtered_price_th ) {
$added_margin_column = TRUE;
}
rp_manage_repairs_standalone_markup( $m_id, $category_based, $model, $decimal, $model->device_type );
$more_details = ob_get_contents();
ob_end_clean();
$all_dr_uq_ids = rp_get_all_dr_uq_id_from_rs_default_repair_table();
$all_da_uq_ids = rp_get_all_da_uq_id_from_rs_default_repair_attr_table();
$all_dc_uq_ids = rp_get_all_dc_uq_id_from_rs_default_repairs_category();
echo json_encode(array(
'status' => true,
'more_details' => $more_details,
'update_all_dr_uq_ids' => $all_dr_uq_ids,
'update_all_da_uq_ids' => $all_da_uq_ids,
'update_all_dc_uq_ids' => $all_dc_uq_ids,
'execution_time' => ( microtime(true) - $start_time )
));
exit;
}
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid Model ID'
));
exit;
}
rp_ajax_for_admin('rp_get_individual_repairs_markup', 'rp_get_individual_repairs_markup');
function rp_svg_icon_only( $icon = '' ) {
$icon_file = WP_REPAIR_PLUGIN_PATH.'assets/images/'. $icon . '.svg';
if( file_exists( $icon_file ) ) {
return rp_fetch_image_from_base( $icon_file );
}
return '';
}
function rp_svg_icons_loader( $icon = '', $sizes = '' ) {
$fa_spinning = '';
if( strpos( $icon, 'fa-spinner' ) !== false ) {
$fa_spinning = ' fa-spinning';
}
$icon_file = WP_REPAIR_PLUGIN_PATH.'assets/images/'. $icon . '.svg';
if( file_exists( $icon_file ) ) {
return '<span class="rp-svg-icon '.$sizes.' '.$icon.$fa_spinning.'">'.rp_fetch_image_from_base( $icon_file ).'</span>';
}
return '';
}
function rp_fix_attribute_duration_field_first_time() {
if( rp_get_option('rp_fix_attribute_duration_field_first_time', FALSE) !== FALSE ) {
return;
}
rp_add_option('rp_fix_attribute_duration_field_first_time', '1');
// It will work only once
global $rpQuery;
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_default_repair_attr = $rpQuery->prefix . 'rs_default_repair_attr';
$rs_repair_attr = $rpQuery->prefix . 'rs_repair_attr';
// SELECT * FROM $rs_default_repair
$default_repairs = $rpQuery->get_results("SELECT * FROM `$rs_default_repair`;");
if( !empty( $default_repairs ) ) {
foreach( $default_repairs as $row ) {
$duration = $row->dr_duration;
$duration_measure = $row->dr_duration_measure;
$rpQuery->query("UPDATE `$rs_default_repair_attr` SET `da_duration` = '{$duration}', `da_duration_measure` = '{$duration_measure}' WHERE `da_duration` = '0' AND (`da_duration_measure` = '' OR `da_duration_measure` IS NULL) AND `dr_id_fk` = '{$row->dr_id}';");
}
}
// SELECT * FROM $rs_repair
$repairs = $rpQuery->get_results("SELECT * FROM `$rs_repair`;");
if( !empty( $repairs ) ) {
foreach( $repairs as $row ) {
$duration = $row->r_duration;
$duration_measure = $row->r_duration_measure;
$rpQuery->query("UPDATE `$rs_repair_attr` SET `a_duration` = '{$duration}', `a_duration_measure` = '{$duration_measure}' WHERE `a_duration` = '0' AND (`a_duration_measure` = '' OR `a_duration_measure` IS NULL) AND `r_id_fk` = '{$row->r_id}';");
}
}
}
rp_add_action('init', 'rp_fix_attribute_duration_field_first_time', 9999);
function rp_fix_order_discount_fields_first_time() {
if( rp_get_option('rp_fix_order_discount_fields_first_time', FALSE) !== FALSE ) {
return;
}
rp_add_option('rp_fix_order_discount_fields_first_time', '1');
// It will work only once
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$all_orders = $rpQuery->get_results("SELECT * FROM `$rs_orders`;");
if( !empty( $all_orders ) ) {
foreach( $all_orders as $row ) {
if( $row->combo_dstatus == '1' ) {
continue;
}
$discount = $row->combo_discount;
if( $discount != '' ) {
$discount = (float) $discount;
if( $discount == 0 || $discount == 0.00 ) {
$discount = 0;
}
} else {
$discount = 0;
}
if( $discount != 0 ) {
list( $rpCart, $calculations ) = rp_get_latest_order_calculations( $row->o_id );
$total_items = $rpCart->calculate_combo_discount_items();
$discount = round( ($discount / $total_items), 2 );
$rpQuery->query("UPDATE `$rs_orders` SET `combo_damount` = '{$discount}', `combo_dtype` = 'Fixed', `combo_dstatus` = '1' WHERE `o_id` = '{$row->o_id}';");
}
}
}
}
// Print search bar data if not already
function rp_print_searchbar_data_if_not_already() {
// no longer needed!
return;
static $already_printed = FALSE;
// if( $already_printed ) {
// return;
// }
$already_printed = TRUE;
$wp_repair_search_bar = new RepairPluginPro\Search_Bar();
$wp_repair_search_bar_data = $wp_repair_search_bar->get_json();
?>
<script type="text/javascript">
window.wp_repair_search_bar_data = <?php echo $wp_repair_search_bar_data; ?>;
</script>
<?php
}
rp_add_action('init', 'rp_fix_order_discount_fields_first_time', 9999);
// Repairs Category Work Started..
// Below this, make sure to create relevant indexes
// to make queries faster
function rp_get_uncategorised_category_row_by_model_category( $device_type = 0 ) {
$cache_key = 'uncategorised_cached_results|'.$device_type;
$cached = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if(!empty($cached)) {
return $cached;
}
global $rpQuery;
$rs_default_repairs_category = $rpQuery->prefix . "rs_default_repairs_category";
$sql = "SELECT * FROM `$rs_default_repairs_category` WHERE `is_uncategorised` = '1' AND `dc_category` = '".rp_escape_sql($device_type)."'";
$result = $rpQuery->get_row( $sql );
RepairPluginPro\RP_Memory_Cache::save($cache_key, $result);
return $result;
}
function rp_force_needed_repairs_category_creation() {
rp_update_option( 'rp_created_needed_repair_categories', '0' );
rp_create_needed_repair_categories_if_not_already_created();
}
function rp_create_needed_repair_categories_if_not_already_created() {
if( rp_get_option( 'rp_needed_repair_categories_in_processing', '0' ) != '0' ) {
// already created
return;
}
if( rp_get_option( 'rp_created_needed_repair_categories', '0' ) != '0' ) {
// already created
return;
}
rp_update_option( 'rp_needed_repair_categories_in_processing', '1' );
// get all categories from rs_category table (model related category)
global $rpQuery;
$rs_category = $rpQuery->prefix . "rs_category";
$rs_default_repairs_category = $rpQuery->prefix . "rs_default_repairs_category";
$rs_repairs_category = $rpQuery->prefix . "rs_repairs_category";
$rs_model = $rpQuery->prefix . "rs_model";
$sql = "SELECT * FROM `$rs_category` WHERE `c_id` NOT IN (SELECT `dc_category` FROM `$rs_default_repairs_category` WHERE `is_uncategorised` = '1' GROUP BY `dc_category`) LIMIT 100";
$result = $rpQuery->get_results( $sql );
if( !empty( $result ) ) {
foreach( $result as $modelCategory ) {
$uqid = uniqid('rcat_');
$sql = "INSERT INTO `$rs_default_repairs_category` (`dc_name`, `dc_img`, `is_active`, `dc_uq_id`, `dc_date_time`, `dc_position`, `dc_category`, `is_uncategorised`) VALUES ('Uncategorised', '', '1', '".$uqid."', '".date('Y-m-d H:i:s')."', '0', '".rp_escape_sql($modelCategory->c_id)."', '1')";
$rpQuery->query( $sql );
}
}
// select * from rs_model where m_id not in rs_repairs_category table (m_id_fk column)
$sql = "SELECT * FROM `$rs_model` WHERE `m_id` NOT IN (SELECT `m_id_fk` FROM `$rs_repairs_category` GROUP BY `m_id_fk`) LIMIT 100";
$result = $rpQuery->get_results( $sql );
if( !empty( $result ) ) {
// start transaction
$rpQuery->query("START TRANSACTION");
foreach( $result as $modelRow ) {
$repairCategories = rp_get_default_repairs_categories( $modelRow->device_type );
if( !empty( $repairCategories ) ) {
foreach( $repairCategories as $repair_category_row ) {
$c_name = $repair_category_row->dc_name;
$c_img = $repair_category_row->dc_img;
$is_active = $repair_category_row->is_active;
$updated_on = $repair_category_row->updated_on;
$c_uq_id = $repair_category_row->dc_uq_id;
$m_id_fk = $modelRow->m_id;
$c_date_time = date('Y-m-d H:i:s');
$c_position = $repair_category_row->dc_position;
$is_uncategorised = $repair_category_row->is_uncategorised;
$sql = "INSERT INTO `$rs_repairs_category` (`c_name`, `c_img`, `is_active`, `updated_on`, `c_uq_id`, `m_id_fk`, `c_date_time`, `c_position`, `is_uncategorised`) VALUES ('".rp_escape_sql($c_name)."', '".rp_escape_sql($c_img)."', '".rp_escape_sql($is_active)."', '".rp_escape_sql($updated_on)."', '".rp_escape_sql($c_uq_id)."', '".rp_escape_sql($m_id_fk)."', '".rp_escape_sql($c_date_time)."', '".rp_escape_sql($c_position)."', '".rp_escape_sql($is_uncategorised)."')";
$rpQuery->query( $sql );
}
}
}
// commit transaction
$rpQuery->query("COMMIT");
} else {
rp_update_option( 'rp_created_needed_repair_categories', '1' );
}
rp_update_option( 'rp_needed_repair_categories_in_processing', '0' );
}
rp_add_action('init', 'rp_create_needed_repair_categories_if_not_already_created', 9999);
function rp_get_default_repairs_categories( $c_id = 0 ) {
$cache_key = 'rp_get_default_repairs_categories|'.$c_id;
$cached = RepairPluginPro\RP_Memory_Cache::get($cache_key);
if(!empty($cached)) {
return $cached;
}
global $rpQuery;
$rs_default_repairs_category = $rpQuery->prefix . "rs_default_repairs_category";
// select * from $rs_default_repairs_category where dc_category = $c_id
$sql = "SELECT * FROM `$rs_default_repairs_category` WHERE `dc_category` = '".rp_escape_sql($c_id)."' ORDER BY `dc_position` ASC";
$result = $rpQuery->get_results( $sql );
if( !empty( $result ) ) {
RepairPluginPro\RP_Memory_Cache::save($cache_key, $result);
return $result;
}
return array();
}
function rp_get_individual_repairs_categories( $m_id = 0 ) {
global $rpQuery;
$rs_repairs_category = $rpQuery->prefix . "rs_repairs_category";
// select * from $rs_repairs_category where m_id_fk = $m_id
$sql = "SELECT * FROM `$rs_repairs_category` WHERE `m_id_fk` = '".rp_escape_sql($m_id)."' ORDER BY `c_position` ASC, `c_id` ASC";
$result = $rpQuery->get_results( $sql );
if( !empty( $result ) ) {
return $result;
}
return array();
}
function rp_get_all_repair_cat_linking_related_to_model_cat( $c_id = 0 ) {
global $rpQuery;
$rs_repair_cat_linking = $rpQuery->prefix . 'rs_repair_cat_linking';
$sql = "SELECT * FROM `$rs_repair_cat_linking` WHERE `c_id_fk` = '".rp_escape_sql($c_id)."'";
$result = $rpQuery->get_results( $sql );
if( !empty( $result ) ) {
$key_pair = array(); // repair_uqid => rc_uq_id
foreach( $result as $row ) {
$key_pair[$row->repair_uqid] = $row->rc_uq_id;
}
return $key_pair;
}
return array();
}
function rp_get_all_repair_cat_linking_related_to_ind_model( $m_id = 0 ) {
global $rpQuery;
$rs_repair_cat_linking = $rpQuery->prefix . 'rs_repair_cat_linking';
$sql = "SELECT * FROM `$rs_repair_cat_linking` WHERE `m_id_fk` = '".rp_escape_sql($m_id)."'";
$result = $rpQuery->get_results( $sql );
if( !empty( $result ) ) {
$key_pair = array(); // repair_uqid => rc_uq_id
foreach( $result as $row ) {
$key_pair[$row->repair_uqid] = $row->rc_uq_id;
}
return $key_pair;
}
return array();
}
function rp_fix_default_repair_category_sorting($current_rows = array(), $m_id = '') {
global $rpQuery;
$rs_model = $rpQuery->prefix . 'rs_model';
$rs_default_repairs_category = $rpQuery->prefix . 'rs_default_repairs_category';
$m_id = (int) $m_id;
$model_info = rp_get_model_row_device_type_by_m_id_cached( $m_id );
if(!empty($model_info)) {
$result = $rpQuery->get_results("SELECT * FROM `$rs_default_repairs_category` WHERE dc_category = '".rp_escape_sql($model_info[0]->device_type)."'");
} else {
$result = $rpQuery->get_results("SELECT * FROM `$rs_default_repairs_category`");
}
if(!empty($result)) {
$key_value_pair = array();
$default_repairs = array();
foreach ($result as $key => $value) {
$key_value_pair[$value->dc_uq_id] = $value->dc_position;
$default_repairs[] = $value->dc_uq_id;
}
$not_default = 1;
foreach ($current_rows as $key => $value) {
if(!in_array($value->c_uq_id, $default_repairs)) {
$value->c_position = $not_default;
$current_rows[$key] = $value;
$not_default++;
} else {
if(($value->c_position == '0' || $value->c_position == '') && isset($key_value_pair[$value->c_uq_id])) {
// Skip...
} else {
$value->c_position = $not_default;
$current_rows[$key] = $value;
$not_default++;
}
}
}
foreach ($current_rows as $key => $value) {
if(!in_array($value->c_uq_id, $default_repairs)) {
// Skip..
} else {
if(($value->c_position == '0' || $value->c_position == '') && isset($key_value_pair[$value->c_uq_id])) {
$value->c_position = $not_default+$key_value_pair[$value->c_uq_id];
$current_rows[$key] = $value;
}
}
}
}
$sort_position = array();
foreach ($current_rows as $key => $value) {
$sort_position[] = array('key'=>$key, 'position'=>$value->c_position);
}
usort($sort_position, function ($item1, $item2) {
return $item1['position'] <=> $item2['position'];
});
$new_arr = array();
foreach ($sort_position as $row) {
$new_arr[] = $current_rows[$row['key']];
}
return $new_arr;
}
function rp_get_individual_repairs_based_on_repair_category( $m_id = 0, $onlyActive = FALSE, $forFrontEnd = FALSE ) {
global $rpQuery;
$rs_model = $rpQuery->prefix . 'rs_model';
$rs_repair = $rpQuery->prefix . 'rs_repair';
// select * from rs_model WHERE m_id = $m_id
$model = $rpQuery->get_row("SELECT * FROM `$rs_model` WHERE `m_id` = '".rp_escape_sql($m_id)."' LIMIT 1;");
if( empty( $model ) ) {
return array();
}
$individual_repairs_category = rp_get_individual_repairs_categories( $m_id );
$individual_repairs_category = rp_fix_default_repair_category_sorting( $individual_repairs_category, $m_id );
$drc_key_pair = array();
foreach( $individual_repairs_category as $drc ) {
$drc->repairs = array();
$drc_key_pair[$drc->c_uq_id] = $drc;
}
$default_linking = rp_get_all_repair_cat_linking_related_to_model_cat( $model->device_type );
$individual_linking = rp_get_all_repair_cat_linking_related_to_ind_model( $m_id );
foreach( $default_linking as $repair_uqid => $rc_uq_id ) {
if( !isset( $individual_linking[$repair_uqid] ) ) {
$individual_linking[$repair_uqid] = $rc_uq_id;
}
}
$linking = $individual_linking;
$is_active = '';
if( $onlyActive == TRUE ) {
$is_active = " AND is_active = '1' ";
}
// $repairs = $rpQuery->get_results("SELECT * FROM $rs_repair WHERE m_id_fk = '".rp_escape_sql($m_id)."' {$is_active} ORDER BY r_position ASC, r_id ASC");
if( $onlyActive == TRUE ) {
$repairs = rp_get_model_related_repairs_front_end( $m_id, 'r_position ASC, r_id ASC', array( 'is_active' => '1' ) );
if( $forFrontEnd === TRUE ) {
$need_to_handle_hiding_repair = !empty( rp_hide_repair_if() );
if( $need_to_handle_hiding_repair == TRUE ) {
$repairs = apply_filters( 'rp_handle_hiding_main_repair_if_needed', $repairs );
}
}
} else {
$repairs = rp_get_model_related_repairs_front_end( $m_id, 'r_position ASC, r_id ASC' );
}
$repairs = rp_fix_default_repair_sorting($repairs, $m_id);
if( !empty( $repairs ) ) {
$uncategorised = array();
foreach( $repairs as $theRepair ) {
$repair_uqid = $theRepair->r_uq_id;
if( !empty( $linking ) && isset( $linking[ $repair_uqid ] ) && isset( $drc_key_pair[ $linking[ $repair_uqid ] ] ) ) {
if( !property_exists( $drc_key_pair[ $linking[ $repair_uqid ] ], 'repairs' ) ) {
$drc_key_pair[ $linking[ $repair_uqid ] ]->repairs = array();
}
$drc_key_pair[ $linking[ $repair_uqid ] ]->repairs[] = $theRepair;
} else {
$uncategorised[] = $theRepair;
}
}
// loop through all $drc_key_pair, find uncatorised and add uncategorised to it
foreach( $drc_key_pair as $key => $drc ) {
if( $drc->is_uncategorised == '1' ) {
if( !property_exists( $drc, 'repairs' ) ) {
$drc->repairs = array();
}
foreach( $uncategorised as $theRepair ) {
$drc->repairs[] = $theRepair;
}
// sort drc->repairs by r_position
$sort_position = array();
foreach ($drc->repairs as $key => $value) {
$sort_position[] = array('key'=>$key, 'position'=>$value->r_position);
}
usort($sort_position, function ($item1, $item2) {
return $item1['position'] <=> $item2['position'];
});
$new_arr = array();
foreach ($sort_position as $row) {
$new_arr[] = $drc->repairs[$row['key']];
}
$drc->repairs = $new_arr;
}
}
return $drc_key_pair;
}
return $drc_key_pair;
}
function rp_get_default_repairs_based_on_repair_category( $c_id = 0 ) {
global $rpQuery;
$default_repairs_category = rp_get_default_repairs_categories( $c_id );
$drc_key_pair = array();
foreach( $default_repairs_category as $drc ) {
$drc->repairs = array();
$drc_key_pair[$drc->dc_uq_id] = $drc;
}
$linking = rp_get_all_repair_cat_linking_related_to_model_cat( $c_id );
$default_repair_table = $rpQuery->prefix . 'rs_default_repair';
$repairs = $rpQuery->get_results("SELECT * FROM `$default_repair_table` WHERE dr_category = '".rp_escape_sql($c_id)."' ORDER BY dr_position ASC, dr_id ASC");
if( !empty( $repairs ) ) {
$uncategorised = array();
foreach( $repairs as $theRepair ) {
$repair_uqid = $theRepair->dr_uq_id;
if( !empty( $linking ) && isset( $linking[ $repair_uqid ] ) && isset( $drc_key_pair[ $linking[ $repair_uqid ] ] ) ) {
if( !property_exists( $drc_key_pair[ $linking[ $repair_uqid ] ], 'repairs' ) ) {
$drc_key_pair[ $linking[ $repair_uqid ] ]->repairs = array();
}
$drc_key_pair[ $linking[ $repair_uqid ] ]->repairs[] = $theRepair;
} else {
$uncategorised[] = $theRepair;
}
}
// loop through all $drc_key_pair, find uncatorised and add uncategorised to it
foreach( $drc_key_pair as $key => $drc ) {
if( $drc->is_uncategorised == '1' ) {
if( !property_exists( $drc, 'repairs' ) ) {
$drc->repairs = array();
}
foreach( $uncategorised as $theRepair ) {
$drc->repairs[] = $theRepair;
}
// sort drc->repairs by r_position
$sort_position = array();
foreach ($drc->repairs as $key => $value) {
$sort_position[] = array('key'=>$key, 'position'=>$value->dr_position);
}
usort($sort_position, function ($item1, $item2) {
return $item1['position'] <=> $item2['position'];
});
$new_arr = array();
foreach ($sort_position as $row) {
$new_arr[] = $drc->repairs[$row['key']];
}
$drc->repairs = $new_arr;
}
}
return $drc_key_pair;
}
return $drc_key_pair;
}
function rp_convert_to_array_if_not_already( $row ) {
if( is_object( $row ) ) {
$row = (array) $row;
}
return $row;
}
function rp_convert_array_items_to_array_if_not_already( $rows ) {
foreach( $rows as $key => $row ) {
$rows[$key] = rp_convert_to_array_if_not_already( $row );
}
return $rows;
}
function rp_update_repairs_by_category( $dr_category = 0, $repairsByCategory = array() ) {
if( empty( $dr_category ) || empty( $repairsByCategory ) ) {
return;
}
global $rpQuery;
$rs_repair_cat_linking = $rpQuery->prefix . 'rs_repair_cat_linking';
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_default_repairs_category = $rpQuery->prefix . 'rs_default_repairs_category';
foreach( $repairsByCategory as $category_id => $repair_ids ) {
if( empty( $repair_ids ) ) {
continue;
}
// select dc_uq_id from rs_default_repairs_category where dc_category = $dr_category and dc_id
$sql = "SELECT `dc_uq_id`, `is_uncategorised` FROM `$rs_default_repairs_category` WHERE `dc_category` = '".rp_escape_sql($dr_category)."' AND `dc_id` = '".rp_escape_sql($category_id)."'";
$dc_uq_id_row = $rpQuery->get_row( $sql );
if( !empty( $dc_uq_id_row ) ) {
$dc_uq_id = $dc_uq_id_row->dc_uq_id;
$is_uncategorised = $dc_uq_id_row->is_uncategorised;
// get dr_uq_id from rs_default_repair where dr_id in $repair_ids
$sql = "SELECT `dr_uq_id` FROM `$rs_default_repair` WHERE `dr_id` IN (".rp_escape_sql(implode(',', $repair_ids)).") AND dr_category = '".rp_escape_sql($dr_category)."'";
$result = $rpQuery->get_results( $sql );
if( $is_uncategorised == '1' ) {
if( !empty( $result ) ) {
foreach( $result as $dr_row ) {
$dr_uq_id = $dr_row->dr_uq_id;
// check if linking already exists (c_id_fk and repair_uqid)
$sql = "DELETE FROM `$rs_repair_cat_linking` WHERE `c_id_fk` = '".rp_escape_sql($dr_category)."' AND `repair_uqid` = '".rp_escape_sql($dr_uq_id)."'";
$rpQuery->query( $sql );
}
}
} else {
if( !empty( $result ) ) {
foreach( $result as $dr_row ) {
$dr_uq_id = $dr_row->dr_uq_id;
// check if linking already exists (c_id_fk and repair_uqid)
$sql = "SELECT `id` FROM `$rs_repair_cat_linking` WHERE `c_id_fk` = '".rp_escape_sql($dr_category)."' AND `repair_uqid` = '".rp_escape_sql($dr_uq_id)."'";
$exists = $rpQuery->get_var( $sql );
if( empty( $exists ) ) {
// insert into rs_repair_cat_linking
$sql = "INSERT INTO `$rs_repair_cat_linking` (`rc_uq_id`, `repair_uqid`, `c_id_fk`, `m_id_fk`) VALUES ('".rp_escape_sql($dc_uq_id)."', '".rp_escape_sql($dr_uq_id)."', '".rp_escape_sql($dr_category)."', '0')";
$rpQuery->query( $sql );
} else {
// update rs_repair_cat_linking
$sql = "UPDATE `$rs_repair_cat_linking` SET `rc_uq_id` = '".rp_escape_sql($dc_uq_id)."' WHERE `c_id_fk` = '".rp_escape_sql($dr_category)."' AND `repair_uqid` = '".rp_escape_sql($dr_uq_id)."'";
$rpQuery->query( $sql );
}
}
}
}
}
}
}
function rp_update_repairs_by_model( $m_id_fk = 0, $repairsByCategory = array() ) {
if( empty( $m_id_fk ) || empty( $repairsByCategory ) ) {
return;
}
global $rpQuery;
$rs_repair_cat_linking = $rpQuery->prefix . 'rs_repair_cat_linking';
$rs_repair = $rpQuery->prefix . 'rs_repair';
$rs_repairs_category = $rpQuery->prefix . 'rs_repairs_category';
$model_category = rp_get_model_cached_category_by_mid( $m_id_fk );
foreach( $repairsByCategory as $category_id => $repair_ids ) {
if( empty( $repair_ids ) ) {
continue;
}
// select c_uq_id from rs_repairs_category where m_id_fk = $m_id_fk and dc_id
$sql = "SELECT `c_uq_id`, `is_uncategorised` FROM `$rs_repairs_category` WHERE `m_id_fk` = '".rp_escape_sql($m_id_fk)."' AND `c_id` = '".rp_escape_sql($category_id)."'";
$c_uq_id_row = $rpQuery->get_row( $sql );
if( !empty( $c_uq_id_row ) ) {
$c_uq_id = $c_uq_id_row->c_uq_id;
$is_uncategorised = $c_uq_id_row->is_uncategorised;
// get r_uq_id from rs_repair where dr_id in $repair_ids
$sql = "SELECT `r_uq_id` FROM `$rs_repair` WHERE `r_id` IN (".rp_escape_sql(implode(',', $repair_ids)).") AND m_id_fk = '".rp_escape_sql($m_id_fk)."'";
$result = $rpQuery->get_results( $sql );
if( !empty( $result ) ) {
foreach( $result as $r_row ) {
$r_uq_id = $r_row->r_uq_id;
$sameExists = FALSE;
if( $is_uncategorised == '1' ) {
// if it's uncategorised, expected is that, it won't be present in rs_repair_cat_linking table
$sql = "SELECT `id` FROM `$rs_repair_cat_linking` WHERE `c_id_fk` = '".rp_escape_sql($model_category)."' AND `repair_uqid` = '".rp_escape_sql($r_uq_id)."'";
$sameExists = empty( $rpQuery->get_row( $sql ) );
} else {
// if it's uncategorised, expected is that, it won't be present in rs_repair_cat_linking table
$sql = "SELECT `id` FROM `$rs_repair_cat_linking` WHERE `c_id_fk` = '".rp_escape_sql($model_category)."' AND `repair_uqid` = '".rp_escape_sql($r_uq_id)."' AND `rc_uq_id` = '".rp_escape_sql($c_uq_id)."'";
$sameExists = !empty($rpQuery->get_row( $sql ));
}
if( $sameExists !== FALSE ) {
// Same linking exists on category level, so we do not need it on model level
$sql = "DELETE FROM `$rs_repair_cat_linking` WHERE `m_id_fk` = '".rp_escape_sql($m_id_fk)."' AND `repair_uqid` = '".rp_escape_sql($r_uq_id)."'";
$rpQuery->query( $sql );
} else {
// We need to create linking on model level
// check if linking already exists (m_id_fk and repair_uqid)
$sql = "SELECT `id` FROM `$rs_repair_cat_linking` WHERE `m_id_fk` = '".rp_escape_sql($m_id_fk)."' AND `repair_uqid` = '".rp_escape_sql($r_uq_id)."'";
$exists = $rpQuery->get_var( $sql );
if( empty( $exists ) ) {
// insert into rs_repair_cat_linking
$sql = "INSERT INTO `$rs_repair_cat_linking` (`rc_uq_id`, `repair_uqid`, `m_id_fk`, `c_id_fk`) VALUES ('".rp_escape_sql($c_uq_id)."', '".rp_escape_sql($r_uq_id)."', '".rp_escape_sql($m_id_fk)."', '0')";
$rpQuery->query( $sql );
} else {
// update rs_repair_cat_linking
$sql = "UPDATE `$rs_repair_cat_linking` SET `rc_uq_id` = '".rp_escape_sql($c_uq_id)."' WHERE `m_id_fk` = '".rp_escape_sql($m_id_fk)."' AND `repair_uqid` = '".rp_escape_sql($r_uq_id)."'";
$rpQuery->query( $sql );
}
}
}
}
}
}
}
function rp_get_all_series_filters_related_to_brand( $b_id = 0 ) {
global $rpQuery;
if( empty( $b_id ) ) {
return array();
}
$rs_series_filters = $rpQuery->prefix . "rs_series_filters";
$sql = "SELECT * FROM `$rs_series_filters` WHERE `b_id_fk` = '".rp_escape_sql($b_id)."' ORDER BY `position` ASC";
$result = $rpQuery->get_results( $sql );
if( !empty( $result ) ) {
return $result;
}
return array();
}
function rp_get_active_series_filters_related_to_brand( $b_id = 0 ) {
global $rpQuery;
if( empty( $b_id ) ) {
return array();
}
$rs_series_filters = $rpQuery->prefix . "rs_series_filters";
$sql = "SELECT * FROM `$rs_series_filters` WHERE `b_id_fk` = '".rp_escape_sql($b_id)."' AND `is_active` = '1' ORDER BY `position` ASC";
$result = $rpQuery->get_results( $sql );
if( !empty( $result ) ) {
return $result;
}
return array();
}
function rp_verify_brand_id_exists( $b_id = 0 ) {
global $rpQuery;
$rs_brand = $rpQuery->prefix . 'rs_brand';
return !empty( $rpQuery->get_results("SELECT b_id FROM `$rs_brand` WHERE `b_id` = ".rp_escape_sql( $b_id )." LIMIT 1") );
}
function rp_get_series_filters_for_popup() {
global $rpQuery;
$rs_series_filters = $rpQuery->prefix . 'rs_series_filters';
$b_id = $_POST['b_id'] ?? 0;
if( empty( $b_id ) || rp_verify_brand_id_exists( $b_id ) == FALSE ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid Brand ID'
));
exit;
}
$series_filters = rp_get_all_series_filters_related_to_brand( $b_id );
echo json_encode(array(
'status' => true,
'series_filters' => $series_filters
));
exit;
}
rp_ajax_for_admin('rp_get_series_filters_for_popup', 'rp_get_series_filters_for_popup');
function rp_update_series_filters(){
rp_verify_csrf_token_for_ajax('manage_categories');
global $rpQuery; $s= array();
$rs_brand = $rpQuery->prefix . "rs_brand";
$rs_series_filters = $rpQuery->prefix . "rs_series_filters";
// b_id: b_id,
// filter_id: filter_id,
// title: title,
// search_string: search_string,
// is_active: is_active
$b_id = $_POST['b_id'] ?? 0;
$filter_id = $_POST['filter_id'] ?? array();
$title = $_POST['title'] ?? array();
$search_string = $_POST['search_string'] ?? array();
$is_active = $_POST['is_active'] ?? array();
$skipped_index = array();
if( empty( $b_id ) || rp_verify_brand_id_exists( $b_id ) == FALSE ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid Brand ID'
));
exit;
}
// Update/Create Repairs of Model
foreach($filter_id as $i => $fid){
if(trim(strtoupper($fid)) === 'NEW') {
// Create
if(!empty(trim($title[$i]))) {
$rpQuery->query("INSERT INTO $rs_series_filters (title, search_string, b_id_fk) VALUES ('".rp_escape_sql($title[$i])."', '".rp_escape_sql($search_string[$i])."', '".rp_escape_sql($b_id)."')");
$rid[$i] = $rpQuery->insert_id;
} else {
$skipped_index[] = $i;
}
$filter_id[$i] = $rpQuery->insert_id;
} else {
$rpQuery->query("UPDATE $rs_series_filters SET title='".rp_escape_sql($title[$i])."', search_string='".rp_escape_sql($search_string[$i])."' WHERE id='".rp_escape_sql($fid)."' AND b_id_fk ='".rp_escape_sql($b_id)."'");
}
}
// Update Position
$f_i = 1;
foreach($filter_id as $i => $filterId){
if(!in_array($i, $skipped_index)) {
$rpQuery->query("UPDATE $rs_series_filters SET position='".rp_escape_sql($f_i)."' WHERE id='".rp_escape_sql($filterId)."'");
$f_i++;
}
}
// Update Statuses
$rpQuery->query("UPDATE $rs_series_filters SET is_active= '0' WHERE b_id_fk ='".rp_escape_sql($b_id)."'");
foreach($is_active as $i => $s){
if(!in_array($i, $skipped_index)) {
if(!empty($s)) {
$rpQuery->query("UPDATE $rs_series_filters SET is_active='1' WHERE id='".rp_escape_sql($filter_id[$i])."' AND b_id_fk ='".rp_escape_sql($b_id)."'");
}
}
}
$series_filters = rp_get_all_series_filters_related_to_brand( $b_id );
echo json_encode(Array('status' => true, 'message' => 'Successfully Updated', 'series_filters' => $series_filters));
exit();
}
rp_ajax_for_admin('rp_update_series_filters', 'rp_update_series_filters');
//-------------------------------------------------------------------delete series filter
function rp_delete_series_filter(){
rp_verify_csrf_token_for_ajax('manage_categories');
global $rpQuery;
$b_id = $_POST['b_id'] ?? 0;
$filter_id = $_POST['filter_id'] ?? 0;
if( empty( $b_id ) || rp_verify_brand_id_exists( $b_id ) == FALSE ) {
echo json_encode(array(
'status' => false,
'rp_validation_error' => 'Invalid Brand ID'
));
exit;
}
$rs_brand = $rpQuery->prefix . "rs_brand";
$rs_series_filters = $rpQuery->prefix . "rs_series_filters";
$result = $rpQuery->get_row("SELECT * FROM $rs_series_filters WHERE id = '".rp_escape_sql($filter_id)."'");
if( !empty( $result ) ) {
$rpQuery->query("DELETE FROM $rs_series_filters WHERE id='".rp_escape_sql($filter_id)."'");
}
$series_filters = rp_get_all_series_filters_related_to_brand( $b_id );
echo json_encode(Array('status'=> true, 'message' => 'Successfully deleted', 'series_filters' => $series_filters));
exit();
}
rp_ajax_for_admin('rp_delete_series_filter','rp_delete_series_filter');
function rp_get_only_active_model_series_with_atleast_one_model( $b_id = 0 ) {
global $rpQuery;
if( empty( $b_id ) ) {
return array();
}
$rs_series_filters = $rpQuery->prefix . "rs_series_filters";
$rs_model = $rpQuery->prefix . "rs_model";
$sql = "SELECT * FROM `$rs_series_filters` WHERE `b_id_fk` = '".rp_escape_sql($b_id)."' AND `is_active` = '1' ORDER BY `position` ASC";
$result = $rpQuery->get_results( $sql );
$model_series = array();
if( !empty( $result ) ) {
foreach( $result as $row ) {
// lowercase and trim before compare
$sql = "SELECT * FROM `$rs_model` WHERE LOWER(`m_name`) LIKE '%".rp_escape_sql( strtolower( trim( $row->search_string ) ) )."%' AND `brand_id_fk` = '".rp_escape_sql($b_id)."' AND `is_active` = '1' ORDER BY `m_position` ASC, `release_date` DESC";
$model_result = $rpQuery->get_results( $sql );
if( !empty( $model_result ) ) {
$row->m_img = $model_result[0]->m_img;
$row->count = count( $model_result );
$model_series[] = $row;
}
}
}
return $model_series;
}
// Compatibility Fix for Divi Theme
function rp_move_jquery_to_head() {
if (!is_admin()) {
// Deregister the default jQuery version that comes with WordPress
wp_dequeue_script('jquery-core');
wp_deregister_script('jquery-core');
// Register and enqueue a new version of jQuery to be loaded in the head
wp_register_script('jquery-core', includes_url('/js/jquery/jquery.min.js'), array(), null, false);
wp_enqueue_script('jquery-core');
}
}
// Hook the function to be executed during the wp_enqueue_scripts action
// Removed temporary as some sites are experiencing issue because of this change in V1.7.0
// rp_add_action('wp_enqueue_scripts', 'rp_move_jquery_to_head', 1);
function rp_get_sorted_customer_address_fields() {
$sorted_fields = rp_get_option('rp_get_sorted_customer_address_fields', json_encode(array(
'house_no',
'street_address',
'user_city',
'user_zipcode',
'user_country'
)));
$sorted_fields = json_decode($sorted_fields);
$required_fields = array(
'house_no',
'street_address',
'user_city',
'user_zipcode',
'user_country'
);
// make sure only required fields are there
foreach($sorted_fields as $sf_key => $sf_value) {
if( !in_array($sf_value, $required_fields) ) {
unset($sorted_fields[$sf_key]);
}
}
foreach($required_fields as $rf_key => $rf_value) {
if( !in_array($rf_value, $sorted_fields) ) {
$sorted_fields[] = $rf_value;
}
}
return $sorted_fields;
}
function rp_google_calendar_redirect_callback() {
if( !empty( $_REQUEST['rp_google_calendar_redirect'] ?? '' ) ) {
if( isset( $_REQUEST['error'] ) && !empty( $_REQUEST['error'] ) ) {
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['rp_google_calendar_success'] = '';
$_SESSION['rp_google_calendar_error'] = $_REQUEST['error'];
RepairPluginPro\RP_Session_Handler::close();
$redirectUri = rtrim( get_site_url() ) . '/wp-admin/admin.php?page=wp_repair_settings§ion=webhooks&tab=google_calendar';
header('Location: '.$redirectUri);
exit;
}
if( empty( $_REQUEST['code'] ?? '' ) ) {
return;
}
if(!current_user_can('manage_repairplugin_pro')) {
return;
}
$gClientId = rp_get_option('rp_google_auth_client_id', '');
$gClientSecret = rp_get_option('rp_google_auth_client_secret', '');
$googleCalendar = new RepairPluginPro\GoogleCalendar( $gClientId, $gClientSecret );
$accessToken = $googleCalendar->fetchAccessToken( $_REQUEST['code'] ?? '' );
RepairPluginPro\RP_Session_Handler::start();
if( empty( $googleCalendar->getErrorResponse() ) ) {
$missing_scopes = $googleCalendar->get_missing_scopes();
if( empty( $missing_scopes ) ) {
$_SESSION['rp_google_calendar_success'] = 'Google Calendar has been successfully authorized.';
$_SESSION['rp_google_calendar_error'] = '';
} else {
$googleCalendar->clear_last_google_auth_response();
$_SESSION['rp_google_calendar_success'] = '';
if( strpos( $missing_scopes, '&' ) !== FALSE ) {
$_SESSION['rp_google_calendar_error'] = $missing_scopes . ' scopes are missing.';
} else {
$_SESSION['rp_google_calendar_error'] = $missing_scopes . ' scope is missing.';
}
}
} else {
$_SESSION['rp_google_calendar_success'] = '';
$_SESSION['rp_google_calendar_error'] = $googleCalendar->getErrorResponse();
}
RepairPluginPro\RP_Session_Handler::close();
$redirectUri = rtrim( get_site_url() ) . '/wp-admin/admin.php?page=wp_repair_settings§ion=webhooks&tab=google_calendar';
header('Location: '.$redirectUri);
exit;
}
}
rp_add_action('init', 'rp_google_calendar_redirect_callback');
function rp_google_business_profile_redirect_callback() {
if( !empty( $_REQUEST['rp_google_business_profile_redirect'] ?? '' ) ) {
if( isset( $_REQUEST['error'] ) && !empty( $_REQUEST['error'] ) ) {
RepairPluginPro\RP_Session_Handler::start();
$_SESSION['rp_google_business_profile_success'] = '';
$_SESSION['rp_google_business_profile_error'] = $_REQUEST['error'];
RepairPluginPro\RP_Session_Handler::close();
$redirectUri = rtrim( get_site_url() ) . '/wp-admin/admin.php?page=wp_repair_settings§ion=webhooks&tab=google_business_profile';
header('Location: '.$redirectUri);
exit;
}
if( empty( $_REQUEST['code'] ?? '' ) ) {
return;
}
if(!current_user_can('manage_repairplugin_pro')) {
return;
}
$gClientId = rp_get_option('rp_google_bp_auth_client_id', '');
$gClientSecret = rp_get_option('rp_google_bp_auth_client_secret', '');
$googleBusinessProfile = new RepairPluginPro\GoogleBusinessProfile( $gClientId, $gClientSecret );
$accessToken = $googleBusinessProfile->fetchAccessToken( $_REQUEST['code'] ?? '' );
RepairPluginPro\RP_Session_Handler::start();
if( empty( $googleBusinessProfile->getErrorResponse() ) ) {
$missing_scopes = $googleBusinessProfile->get_missing_scopes();
if( empty( $missing_scopes ) ) {
$_SESSION['rp_google_business_profile_success'] = 'Google Business Profile has been successfully authorized.';
$_SESSION['rp_google_business_profile_error'] = '';
} else {
$googleBusinessProfile->clear_last_google_auth_response();
$_SESSION['rp_google_business_profile_success'] = '';
if( strpos( $missing_scopes, '&' ) !== FALSE ) {
$_SESSION['rp_google_business_profile_error'] = $missing_scopes . ' scopes are missing.';
} else {
$_SESSION['rp_google_business_profile_error'] = $missing_scopes . ' scope is missing.';
}
}
} else {
$_SESSION['rp_google_business_profile_success'] = '';
$_SESSION['rp_google_business_profile_error'] = $googleBusinessProfile->getErrorResponse();
}
RepairPluginPro\RP_Session_Handler::close();
$redirectUri = rtrim( get_site_url() ) . '/wp-admin/admin.php?page=wp_repair_settings§ion=webhooks&tab=google_business_profile';
header('Location: '.$redirectUri);
exit;
}
}
rp_add_action('init', 'rp_google_business_profile_redirect_callback');
function rp_refresh_google_auth_access_token_if_needed() {
$maxTokenRefreshWaitTime = 60 * 60 * 6; // 6 hours
// get last token refresh time
$lastTokenRefreshTime = rp_get_option('rp_last_google_auth_refresh_time', '0');
if( empty( $lastTokenRefreshTime ) ) {
// make it 2x more than maxTokenRefreshWaitTime
$lastTokenRefreshTime = time() - ( $maxTokenRefreshWaitTime * 2 );
}
// if last token refresh time is more than maxTokenRefreshWaitTime
if( ( time() - $lastTokenRefreshTime ) > $maxTokenRefreshWaitTime ) {
try {
$gClientId = rp_get_option('rp_google_auth_client_id', '');
$gClientSecret = rp_get_option('rp_google_auth_client_secret', '');
$googleCalendar = new RepairPluginPro\GoogleCalendar( $gClientId, $gClientSecret );
$isAuthorized = $googleCalendar->isAuthorized();
if( $isAuthorized == TRUE ) {
$userEmail = $googleCalendar->getUserEmail();
}
} catch ( Exception|Error $e ) {
// Do nothing
}
// update last token refresh time
rp_update_option('rp_last_google_auth_refresh_time', time());
}
}
rp_add_action('init', 'rp_refresh_google_auth_access_token_if_needed', 9999);
function rp_refresh_google_bp_auth_access_token_if_needed() {
$maxTokenRefreshWaitTime = 60 * 60 * 6; // 6 hours
// get last token refresh time
$lastTokenRefreshTime = rp_get_option('rp_last_google_bp_auth_refresh_time', '0');
if( empty( $lastTokenRefreshTime ) ) {
// make it 2x more than maxTokenRefreshWaitTime
$lastTokenRefreshTime = time() - ( $maxTokenRefreshWaitTime * 2 );
}
// if last token refresh time is more than maxTokenRefreshWaitTime
if( ( time() - $lastTokenRefreshTime ) > $maxTokenRefreshWaitTime ) {
try {
$gClientId = rp_get_option('rp_google_bp_auth_client_id', '');
$gClientSecret = rp_get_option('rp_google_bp_auth_client_secret', '');
$googleBusinessProfile = new RepairPluginPro\GoogleBusinessProfile( $gClientId, $gClientSecret );
$isAuthorized = $googleBusinessProfile->isAuthorized();
if( $isAuthorized == TRUE ) {
$userEmail = $googleBusinessProfile->getUserEmail();
}
} catch ( Exception|Error $e ) {
// Do nothing
}
// update last token refresh time
rp_update_option('rp_last_google_bp_auth_refresh_time', time());
}
}
rp_add_action('init', 'rp_refresh_google_bp_auth_access_token_if_needed', 9999);
function rp_google_calendar_authorize_redirect() {
if( !empty( $_REQUEST['rp_google_calendar_authorize'] ?? '' ) ) {
if(!current_user_can('manage_repairplugin_pro')) {
return;
}
$_POST['rp_csrf_token'] = $_REQUEST['rp_csrf_token'] ?? '';
if( !rp_verify_csrf_token('google_calendar') ) {
$redirectUri = rtrim( get_site_url() ) . '/wp-admin/admin.php?page=wp_repair_settings§ion=webhooks&tab=google_calendar';
header('Location: '.$redirectUri);
exit;
}
$gClientId = rp_get_option('rp_google_auth_client_id', '');
$gClientSecret = rp_get_option('rp_google_auth_client_secret', '');
$googleCalendar = new RepairPluginPro\GoogleCalendar( $gClientId, $gClientSecret );
$authUri = $googleCalendar->getAuthUrl();
header('Location: '.$authUri);
exit;
}
}
rp_add_action('init', 'rp_google_calendar_authorize_redirect');
function rp_google_business_profile_authorize_redirect() {
if( !empty( $_REQUEST['rp_google_business_profile_authorize'] ?? '' ) ) {
if(!current_user_can('manage_repairplugin_pro')) {
return;
}
$_POST['rp_csrf_token'] = $_REQUEST['rp_csrf_token'] ?? '';
if( !rp_verify_csrf_token('google_business_profile') ) {
$redirectUri = rtrim( get_site_url() ) . '/wp-admin/admin.php?page=wp_repair_settings§ion=webhooks&tab=google_business_profile';
header('Location: '.$redirectUri);
exit;
}
$gClientId = rp_get_option('rp_google_bp_auth_client_id', '');
$gClientSecret = rp_get_option('rp_google_bp_auth_client_secret', '');
$googleBusinessProfile = new RepairPluginPro\GoogleBusinessProfile( $gClientId, $gClientSecret );
$authUri = $googleBusinessProfile->getAuthUrl();
header('Location: '.$authUri);
exit;
}
}
rp_add_action('init', 'rp_google_business_profile_authorize_redirect');
function rp_get_locked_coupon_info( $order_id = 0 ) {
global $rpQuery;
$rs_orders = $rpQuery->prefix . 'rs_orders';
$order_id = (int) $order_id;
$sql = "SELECT * FROM `$rs_orders` WHERE o_id = '".$order_id."' LIMIT 1";
$order = $rpQuery->get_row( $sql );
if( !empty( $order ) ) {
if( !empty( $order->locked_coupon_info ?? '' ) ) {
$locked_coupon_info = json_decode($order->locked_coupon_info);
if( !empty( $locked_coupon_info ) ) {
return $locked_coupon_info;
}
}
}
return FALSE;
}
// deregister and dequeue tinyMCE script if loaded by another plugin
function rp_dequeue_tinymce_for_rp_pages() {
$toUnset = array(
'wp-tinymce-root',
'tinymce',
'wp-tinymce',
'wp-tinymce-core',
);
foreach($toUnset as $unsetItem) {
// remove scripts
wp_deregister_script($unsetItem);
wp_dequeue_script($unsetItem);
// remove styles also
wp_deregister_style($unsetItem);
wp_dequeue_style($unsetItem);
}
}
function rp_get_all_unique_brand_names() {
global $rpQuery;
$rs_brand = $rpQuery->prefix . 'rs_brand';
$rows = $rpQuery->get_results("SELECT * FROM `$rs_brand`");
$unique_names = array();
foreach( $rows as $row ) {
$brand_name = trim( $row->b_name );
if( !in_array( $brand_name, $unique_names ) ) {
$unique_names[] = $brand_name;
}
}
return $unique_names;
}
function rp_is_allowed_appointment_booking_with_price_on_request() {
return rp_get_option('rp_allow_appointment_with_price_on_request', '0') == '1';
}
function rp_which_action_when_por() {
if( !rp_is_allowed_appointment_booking_with_price_on_request() ) {
// When not allowed, default is always set_price
return 'set_price';
}
$rp_action_when_por = rp_get_option('rp_action_when_por', 'set_price');
if( $rp_action_when_por != 'accept' ) {
$rp_action_when_por = 'set_price';
}
return $rp_action_when_por;
}
function rp_need_to_show_payment_methods_on_price_on_request() {
return rp_is_allowed_appointment_booking_with_price_on_request() == TRUE && rp_get_option('rp_show_payment_methods_on_price_on_request', '0') == '1';
}
function rp_is_downloaded_repair( $uq_id = '' ) {
$downloaded_repair_ids = rp_get_cached_download_repair_ids();
return in_array( $uq_id, $downloaded_repair_ids );
}
function rp_get_cached_download_repair_ids() {
static $cached_download_repair_ids = NULL;
if( $cached_download_repair_ids !== NULL ) {
return $cached_download_repair_ids;
}
$data = rp_get_cached_download_repairs_data();
$ids = array();
if( !empty( $data ) && property_exists($data, 'categories') && isset( $data->categories ) && !empty( $data->categories ) ) {
foreach( $data->categories as $category ) {
$repairs = $category->repairs ?? array();
foreach( $repairs as $repair ) {
$ids[] = $repair->dr_uq_id;
$attrs = $repair->attrs ?? array();
foreach( $attrs as $theAttr ) {
$ids[] = $theAttr->da_uq_id;
}
}
}
}
$cached_download_repair_ids = $ids;
return $ids;
}
function rp_get_cached_download_repairs_data() {
global $rpQuery;
$baserepair_class = new RepairPluginPro\Download_Repairs($rpQuery);
$previous_data = rp_get_option('rp_last_repairs_fetched_from_base_cached', FALSE);
$data = array();
$got_cached_data = FALSE;
if( !empty( $previous_data ) && is_array( $previous_data ) && isset( $previous_data['data'] ) && !empty( $previous_data['data'] ) ) {
$data = $previous_data['data'];
$got_cached_data = TRUE;
}
if( empty( $data ) || $got_cached_data == FALSE ) {
$data = $baserepair_class->fetch_repair_base(TRUE, TRUE);
if( !empty( $data ) ) {
$last_updated = time();
// Update last models fetched from base
rp_update_option('rp_last_repairs_fetched_from_base_cached', array(
'data' => $data,
'last_updated' => $last_updated
));
} else {
$data = array();
}
}
return $data;
}
function rp_fix_db_structure_manually() {
if( !is_admin() || !current_user_can( 'activate_plugins' ) ) {
return;
}
if( isset( $_REQUEST['rp_fix_db_structure_nonce'] ) && !empty( $_REQUEST['rp_fix_db_structure_nonce'] ) ) {
$verifyNonce = wp_verify_nonce( $_REQUEST['rp_fix_db_structure_nonce'], 'rp-fix-database-structure' );
if( !$verifyNonce ) {
wp_safe_redirect( admin_url( 'admin.php?page=repair-plugin' ) );
exit;
}
rp_update_option('rp_fix_database_structure_manual_triggered', TRUE);
// We are doing this extra redirect only so that memory cahce of auto_fix_database_structure
// doesn't create conflict when we try to get status on status page..
wp_safe_redirect( admin_url( 'admin.php?page=repair-plugin&rp_db_structure_fix_refresh=true' ) );
exit;
}
}
add_action('init', 'rp_fix_db_structure_manually');
function rp_clear_smart_cache_form_handler() {
if( !is_admin() || !current_user_can( 'activate_plugins' ) ) {
return;
}
if( isset( $_REQUEST['rp_clear_smart_cache_nonce'] ) && !empty( $_REQUEST['rp_clear_smart_cache_nonce'] ) ) {
$verifyNonce = wp_verify_nonce( $_REQUEST['rp_clear_smart_cache_nonce'], 'rp-clear-smart-cache' );
if( !$verifyNonce ) {
wp_safe_redirect( admin_url( 'admin.php?page=wp_repair_settings§ion=caching_performance' ) );
exit;
}
rp_clear_all_smart_cache();
// We are doing this extra redirect only so that memory cahce of auto_fix_database_structure
// doesn't create conflict when we try to get status on status page..
wp_safe_redirect( admin_url( 'admin.php?page=wp_repair_settings§ion=caching_performance' ) );
exit;
}
}
add_action('init', 'rp_clear_smart_cache_form_handler');
function rp_clear_error_log_files() {
if( !is_admin() || !current_user_can( 'activate_plugins' ) ) {
return;
}
if( isset( $_REQUEST['rp_clear_error_logs_nonce'] ) && !empty( $_REQUEST['rp_clear_error_logs_nonce'] ) ) {
$verifyNonce = wp_verify_nonce( $_REQUEST['rp_clear_error_logs_nonce'], 'rp-clear-error-logs' );
if( !$verifyNonce ) {
wp_safe_redirect( admin_url( 'admin.php?page=repair-plugin' ) );
exit;
}
rp_clear_all_error_files();
rp_update_option( 'rp_last_errors_cleared', time() );
// We are doing this extra redirect only so that memory cahce of auto_fix_database_structure
// doesn't create conflict when we try to get status on status page..
wp_safe_redirect( admin_url( 'admin.php?page=repair-plugin' ) );
exit;
}
}
add_action('init', 'rp_clear_error_log_files');
function rp_download_error_log_files() {
if( !is_admin() || !current_user_can( 'activate_plugins' ) ) {
return;
}
if( isset( $_REQUEST['rp_download_error_logs_nonce'] ) && !empty( $_REQUEST['rp_download_error_logs_nonce'] ) ) {
$verifyNonce = wp_verify_nonce( $_REQUEST['rp_download_error_logs_nonce'], 'rp-download-error-logs' );
if( !$verifyNonce ) {
wp_safe_redirect( admin_url( 'admin.php?page=repair-plugin' ) );
exit;
}
rp_download_all_error_files_handler();
exit;
}
}
add_action('init', 'rp_download_error_log_files');
function rp_create_error_responsive_table_markup( $error_file = '' ) {
ob_start();
$gotError = false;
try {
$error_file_content = file_get_contents( $error_file );
$error_file_content = json_decode( $error_file_content, TRUE );
} catch( Exception|Error $e ) {
$error_file_content = 'Failed to get error file content '. $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine();
$gotError = TRUE;
}
$error_count = 1;
if( $gotError === FALSE ) {
?>
<table>
<tbody>
<?php
foreach( $error_file_content as $error ) {
if( !empty( $error['backtrace'] ) && !is_string( $error['backtrace'] ) ) {
$error['backtrace'] = json_encode( $error['backtrace'] );
}
?>
<tr>
<td class="highlighted-issue" colspan="4">
<div class="error-box">
<b>#<?php echo $error_count; ?> - <?php echo htmlspecialchars( $error['message'] ); ?></b><br><pre><?php print_r( htmlspecialchars( $error['backtrace'] ) ); ?></pre>
<table>
<tbody>
<tr>
<td width="20%" class="highlighted-issue">
<small>Total Count</small>
<br>
<b><?php echo ($error['count'] ?? 1); ?></b>
</td>
<td width="40%" class="highlighted-issue">
<small>First Occurred</small>
<br>
<b><?php echo $error['first_occurred']; ?></b> - <?php
if( !empty( $error['first_occurred_timestamp'] ) ) {
$readableDifference = _rp_dp_human_readable_difference( date('Y-m-d H:i:s'), date('Y-m-d H:i:s', $error['first_occurred_timestamp'] ) );
echo $readableDifference . ' ago';
}
?>
</td>
<td width="40%" class="highlighted-issue">
<small>Last Occurred</small>
<br>
<b><?php echo $error['last_occurred']; ?></b> - <?php
if( !empty( $error['last_occurred_timestamp'] ) ) {
$readableDifference = _rp_dp_human_readable_difference( date('Y-m-d H:i:s'), date('Y-m-d H:i:s', $error['last_occurred_timestamp'] ) );
echo $readableDifference . ' ago';
}
?>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
<?php
$error_count++;
}
?>
</tbody>
</table>
<?php
} else {
?>
<table>
<tbody>
<tr>
<td class="highlighted-issue" colspan="4">
<b>Couldn't get error file content</b>
<br>
<?php echo htmlspecialchars($error_file_content); ?>
</td>
</tr>
</tbody>
</table>
<?php
}
?>
<div class="rp-loading-spinner-container">
<i class="fas fa-spinner fa-spin" style="font-size: 24px;"></i>
</div>
<?php
return ob_get_clean();
}
function rp_get_error_file_content() {
if( !current_user_can( 'activate_plugins' ) ) {
echo json_encode( array( 'status' => 'error', 'message' => 'Invalid permissions' ) );
exit;
}
$error_file = $_REQUEST['error_file'] ?? '';
if( empty( trim( $error_file ) ) || strpos( $error_file, '/' ) !== FALSE || strpos( $error_file, '\\' ) !== FALSE || strpos( $error_file, '..' ) !== FALSE ) {
echo json_encode( array( 'status' => 'error', 'message' => 'Invalid error file' ) );
exit;
}
$fileContent = '';
try {
$fileContent = rp_create_error_responsive_table_markup( rp_get_targeted_error_log_file( $error_file ) );
} catch ( Exception|Error $e ) {
echo json_encode( array( 'status' => 'error', 'message' => 'Failed to get error file content '. $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() ) );
exit;
}
echo json_encode( array( 'status' => 'success', 'content' => $fileContent ) );
exit;
}
rp_ajax_for_admin('rp_get_error_file_content', 'rp_get_error_file_content');
function rp_repairplugin_inspect_toggle() {
if( !current_user_can( 'activate_plugins' ) ) {
echo json_encode( array( 'status' => 'error', 'message' => 'Invalid permissions' ) );
exit;
}
$verifyNonce = wp_verify_nonce( $_REQUEST['nonce'] ?? '', 'rp-repairplugin-inspect' );
if( !$verifyNonce ) {
echo json_encode( array( 'status' => 'error', 'message' => 'Invalid nonce' ) );
exit;
}
$checked = $_REQUEST['checked'] ?? '0';
if( $checked != '1' ) {
$checked = '0';
} else {
$checked = '1';
}
$refreshed_nonce = wp_create_nonce( 'rp-repairplugin-inspect' );
rp_update_option('rp_repairplugin_inspect', $checked );
echo json_encode( array( 'status' => 'success', 'message' => 'Successfully updated', 'switch_status' => $checked, 'refreshed_nonce' => $refreshed_nonce ) );
exit;
}
rp_ajax_for_admin('rp_repairplugin_inspect_toggle', 'rp_repairplugin_inspect_toggle');
function rp_safe_debug_mode_toggle() {
if( !current_user_can( 'activate_plugins' ) ) {
echo json_encode( array( 'status' => 'error', 'message' => 'Invalid permissions' ) );
exit;
}
$verifyNonce = wp_verify_nonce( $_REQUEST['nonce'] ?? '', 'rp-safe-debug-mode' );
if( !$verifyNonce ) {
echo json_encode( array( 'status' => 'error', 'message' => 'Invalid nonce' ) );
exit;
}
$checked = $_REQUEST['checked'] ?? '0';
if( $checked != '1' ) {
$checked = '0';
} else {
$checked = '1';
}
$refreshed_nonce = wp_create_nonce( 'rp-safe-debug-mode' );
rp_update_option('rp_safe_debug_mode', $checked );
echo json_encode( array( 'status' => 'success', 'message' => 'Successfully updated', 'switch_status' => $checked, 'refreshed_nonce' => $refreshed_nonce ) );
exit;
}
rp_ajax_for_admin('rp_safe_debug_mode_toggle', 'rp_safe_debug_mode_toggle');
function rp_db_structure_fix_refresh() {
if( isset( $_REQUEST['rp_db_structure_fix_refresh'] ) && $_REQUEST['rp_db_structure_fix_refresh'] === 'true' ) {
// We are doing this extra redirect only so that memory cahce of auto_fix_database_structure
// doesn't create conflict when we try to get status on status page..
wp_safe_redirect( admin_url( 'admin.php?page=repair-plugin' ) );
exit;
}
}
add_action('init', 'rp_db_structure_fix_refresh');
function rp_setup_enhanced_ajax_if_needed() {
try {
if( rp_get_option( 'rp_optimized_ajax_status', '0' ) == '1' ) {
$wp_content = defined( 'WP_CONTENT_DIR' ) ? WP_CONTENT_DIR : ABSPATH . 'wp-content';
$mu_plugins = $wp_content . '/mu-plugins';
// check if directory exists
if( !is_dir( $mu_plugins ) ) {
// create directory
mkdir( $mu_plugins, 0777, true );
}
$mu_file = $mu_plugins . '/rp-enhanced-ajax.php';
$copying_file = WP_REPAIR_PLUGIN_PATH . 'includes' . DIRECTORY_SEPARATOR . 'enhanced-ajax.php';
if( file_exists( $mu_file ) && rp_read_version_of_file( $mu_file ) == rp_read_version_of_file( $copying_file ) ) {
return;
}
$content = file_get_contents( $copying_file );
file_put_contents( $mu_file, $content );
}
} catch ( Exception|Error|Throwable|ErrorException|ArgumentCountError|DivisionByZeroError|ParseError|TypeError|mysqli_sql_exception $e ) {
// Do nothing
}
}
add_action('init', 'rp_setup_enhanced_ajax_if_needed');
function rp_separate_dr_translations_first_time() {
global $rpQuery;
if( rp_get_option('rp_separate_dr_translations_first_time', '0') == '1' ) {
return;
}
rp_update_option('rp_separate_dr_translations_first_time', '1');
$rpQuery->query("START TRANSACTION");
_rp_separate_default_repair_translations_based_on_model_category();
$rpQuery->query("COMMIT");
}
add_action('init', 'rp_separate_dr_translations_first_time', 9999);
function rp_separate_default_repair_translations_background_job( $ignore = '' ) {
if( !isset( $_REQUEST['rp_process_background_job'] ) || empty( $_REQUEST['rp_process_background_job'] ) ) {
rp_insert_rs_background_jobs_table(__FUNCTION__, func_get_args());
return;
}
_rp_separate_default_repair_translations_based_on_model_category();
}
function _rp_separate_default_repair_translations_based_on_model_category(){
global $rpQuery;
$rs_category = $rpQuery->prefix . 'rs_category';
$rs_default_repair = $rpQuery->prefix . 'rs_default_repair';
$rs_dr_translations = $rpQuery->prefix . 'rs_dr_translations';
// select all categories
$categories = $rpQuery->get_results("SELECT * FROM $rs_category");
$duplicated_row_ids = array();
if( !empty( $categories ) ) {
foreach( $categories as $category ) {
$dr_category = $category->c_id;
// select all default repairs for this category
$default_repairs = $rpQuery->get_results("SELECT * FROM $rs_default_repair WHERE dr_category = $dr_category");
if( !empty( $default_repairs ) ) {
foreach( $default_repairs as $default_repair_row ) {
$dr_uq_id = $default_repair_row->dr_uq_id;
// select all translations for this default repair
$translations = $rpQuery->get_results("SELECT * FROM $rs_dr_translations WHERE uq_id = '".rp_escape_sql($dr_uq_id)."'");
if( !empty( $translations ) ) {
foreach( $translations as $translation_row ) {
$language = $translation_row->language;
$key = $translation_row->key;
$value = $translation_row->value;
$uq_id = $translation_row->uq_id;
$new_uq_id = $uq_id . '_' . $dr_category;
// check if language, key, new_uq_id already exists
$check_query = "SELECT * FROM $rs_dr_translations WHERE `language` = '".rp_escape_sql($language)."' AND `key` = '".rp_escape_sql($key)."' AND `uq_id` = '".rp_escape_sql($new_uq_id)."'";
$check_result = $rpQuery->get_row($check_query);
if( empty( $check_result ) ) {
// insert new row
$insert_query = "INSERT INTO $rs_dr_translations (`language`, `key`, `value`, `uq_id`) VALUES ('".rp_escape_sql($language)."', '".rp_escape_sql($key)."', '".rp_escape_sql($value)."', '".rp_escape_sql($new_uq_id)."')";
$rpQuery->query($insert_query);
}
if( !in_array( $uq_id, $duplicated_row_ids ) ) {
$duplicated_row_ids[] = $uq_id;
}
}
}
}
}
}
}
// remove all duplicated rows
if( !empty( $duplicated_row_ids ) ) {
// get all dr_translations
$all_translations = $rpQuery->get_results("SELECT * FROM $rs_dr_translations");
$rows_to_delete = array();
// loop through all translations, where uq_id only has one underscore, remove it
if( !empty( $all_translations ) ) {
foreach( $all_translations as $translation_row ) {
$uq_id = $translation_row->uq_id;
// If it's really a repair
if( strpos( $uq_id, 'repair_' ) === 0 && count( explode('_', $uq_id) ) == 2 ) {
$rows_to_delete[] = $translation_row->id;
}
}
}
if( !empty( $rows_to_delete ) ) {
$comma_separated_rows_to_delete = implode(',', array_map('intval', $rows_to_delete));
$delete_query = "DELETE FROM $rs_dr_translations WHERE id IN ($comma_separated_rows_to_delete)";
$rpQuery->query($delete_query);
}
}
}
function wpRepairLoadScriptOfUIJSForFrontEnd() {
static $loaded = false;
if( $loaded == true ) {
return;
}
if( !defined('WP_REPAIR_PLUGIN_URL') || !defined('WP_REPAIR_ASSETS_CACHE_V') ) {
return;
}
$loaded = true;
$fileName = WP_REPAIR_PLUGIN_URL.'assets/js/ui-by-repairplugin.js?id='.WP_REPAIR_ASSETS_CACHE_V;
$fileName = str_replace(array('/', '\\'), '/', $fileName);
return '<script type="text/javascript" src="'.$fileName.'"></script>';
}
function rp_get_sorted_customer_address_field_markup( $delivery_method = '', $_customer_house_no = '', $_customer_street_address = '', $_customer_city = '', $_customer_zipcode = '', $_customer_country = '' ) {
global $wp_repair_lang;
$delivery_methods = array(
'ship_device' => 'sd_',
'pickup_service' => 'ps_',
'repair_on_location' => 'rol_'
);
$dm_short = $delivery_methods[ $delivery_method ?? '' ] ?? '';
if( empty( $dm_short ) ) {
return '';
}
$sorted_fields = rp_get_sorted_customer_address_fields();
$sortedFieldCount = 0;
$totalColspan = 0;
ob_start();
foreach( $sorted_fields as $theSortedField ) {
if( $totalColspan == 0 ) {
echo '<!-- starttr --><tr>';
}
if( $theSortedField == 'house_no' ) {
$totalColspan++;
?>
<td class="rp-ptb-0">
<div class="wp-repair-input-group both">
<label><?php echo $wp_repair_lang['user_location_house_number']; ?> <span class="required-asterisk">*</span></label>
<div class="rp-input-box-shadow-container">
<input type="text" class="user-info" name="<?php echo $dm_short; ?>house_no" value="<?php echo $_customer_house_no; ?>">
</div>
</div>
</td>
<?php
}
if( $theSortedField == 'street_address' ) {
$totalColspan++;
?>
<td class="rp-ptb-0">
<div class="wp-repair-input-group both">
<label><?php echo $wp_repair_lang['user_location_street_address']; ?> <span class="required-asterisk">*</span></label>
<div class="rp-input-box-shadow-container">
<input type="text" class="user-info" name="<?php echo $dm_short; ?>street_address" value="<?php echo $_customer_street_address; ?>">
</div>
</div>
</td>
<?php
}
if( $theSortedField == 'user_city' ) {
$totalColspan++;
?>
<td class="rp-ptb-0">
<div class="wp-repair-input-group both">
<label><?php echo $wp_repair_lang['user_location_city']; ?> <span class="required-asterisk">*</span></label>
<div class="rp-input-box-shadow-container">
<input type="text" class="user-info" name="<?php echo $dm_short; ?>user_city" value="<?php echo $_customer_city; ?>">
</div>
</div>
</td>
<?php
}
if( $theSortedField == 'user_zipcode' ) {
$totalColspan++;
?>
<td class="rp-ptb-0">
<div class="wp-repair-input-group both">
<label><?php echo $wp_repair_lang['user_location_zipcode']; ?> <span class="required-asterisk">*</span></label>
<div class="rp-input-box-shadow-container">
<input type="text" class="user-info" name="<?php echo $dm_short; ?>user_zipcode" value="<?php echo $_customer_zipcode; ?>">
</div>
</div>
</td>
<?php
}
if( $theSortedField == 'user_country' ) {
if( $totalColspan == 1 ) {
echo '</tr><!-- endtr -->';
echo '<!-- starttr --><tr>';
$totalColspan = 0;
}
$totalColspan += 2;
$rp_reschedule = !empty($_GET['reschedule'] ?? '') ? 1 : 0;
if( $rp_reschedule === 0 ) {
$countryOptionsMarkup = '<option value="">-- Select --</option>';
$rp_countries_list = rp_get_countries_list_data_translated();
foreach( $rp_countries_list as $countryName => $translatedCountryName ) {
$isSelected = '';
if( !empty( $_customer_country ?? '' ) && $_customer_country == $countryName ) {
$isSelected = 'selected="selected"';
}
$countryOptionsMarkup .= '<option value="'.esc_attr( $countryName ).'" '.$isSelected.'>'.esc_html( $translatedCountryName ).'</option>';
}
?>
<td colspan="2" class="rp-ptb-country">
<div class="wp-repair-input-group both country">
<label><?php echo $wp_repair_lang['user_location_country']; ?> <span class="required-asterisk">*</span></label>
<div class="rp-input-box-shadow-container">
<select name="<?php echo $dm_short; ?>user_country" class="user-info user_country">
<?php echo $countryOptionsMarkup; ?>
</select>
</div>
</div>
</td>
<?php
} else {
if( !empty( $_customer_country ) ) {
?>
<td colspan="2" class="rp-ptb-country">
<div class="wp-repair-input-group both country">
<label><?php echo $wp_repair_lang['user_location_country']; ?> <span class="required-asterisk">*</span></label>
<div class="rp-input-box-shadow-container">
<input type="text" class="user-info user_country" name="<?php echo $dm_short; ?>user_country" value="<?php echo $_customer_country; ?>">
</div>
</div>
</td>
<?php
}
}
}
$sortedFieldCount++;
if( $totalColspan == 2 || $sortedFieldCount == count($sorted_fields) ) {
echo '</tr><!-- endtr -->';
$totalColspan = 0;
}
}
$content = ob_get_clean();
return $content;
}
function rp_get_localization_country() {
return rp_get_option( 'rp_get_localization_country', '' );
}
function rp_get_country_translation_key( $countryName = '' ) {
$replacements = array(
'Å' => 'a',
'ç' => 'c',
'ã' => 'a',
'é' => 'e',
'í' => 'i',
' ' => '_'
);
$countryName = str_replace( array_keys( $replacements ), array_values( $replacements ), $countryName);
// get only A-Z and _
$countryName = preg_replace('/[^A-Za-z_]/', '', $countryName);
return strtolower( $countryName );
}
function rp_get_countries_list_key_pair_for_translation_category() {
$key_pair = array();
$key_pair['all_country_names'] = 'Countries List';
return $key_pair;
}
function rp_get_countries_list_key_pair_for_translation() {
$countries = rp_get_countries_list_data();
$key_pair = array();
foreach( $countries as $countryName => $countryCode ) {
$key_pair[ rp_get_country_translation_key( $countryName ) ] = $countryName;
}
return array(
'all_country_names' => json_encode( $key_pair, JSON_UNESCAPED_UNICODE ), // This is for the new badge
);
}
function rp_get_translated_country_names_from_wp_repair_lang() {
global $wp_repair_lang;
$all_country_names = array();
if( isset( $wp_repair_lang[ 'all_country_names' ] ) && !empty( $wp_repair_lang['all_country_names'] ) ) {
try {
$all_country_names = json_decode( $wp_repair_lang['all_country_names'], true );
if( JSON_ERROR_NONE !== json_last_error() ) {
$all_country_names = array();
}
} catch( Exception|Error $e ) {
$all_country_names = array();
}
}
if( !empty( $all_country_names ) ) {
return $all_country_names;
}
// Create new / static key pairs
$countries = rp_get_countries_list_data();
$key_pair = array();
foreach( $countries as $countryName => $countryCode ) {
$key_pair[ rp_get_country_translation_key( $countryName ) ] = $countryName;
}
return $key_pair;
}
function rp_get_countries_list_data_translated() {
$translated_arr = rp_get_translated_country_names_from_wp_repair_lang();
$countries = rp_get_countries_list_data();
$key_pair = array();
foreach( $countries as $countryName => $countryCode ) {
$key_pair[ $countryName ] = $translated_arr[ rp_get_country_translation_key( $countryName ) ];
}
return $key_pair;
}
function rp_get_single_translated_country_name( $countryName = '' ) {
if( empty( trim( $countryName ?? '' ) ) ) {
return $countryName;
}
$translated_arr = rp_get_translated_country_names_from_wp_repair_lang();
$key = rp_get_country_translation_key( $countryName );
if( isset( $translated_arr[ $key ] ) ) {
return $translated_arr[ $key ];
}
return $countryName;
}
function rp_get_countries_list_data() {
$list = array(
"Afghanistan" => "AF",
"Åland Islands" => "AX",
"Albania" => "AL",
"Algeria" => "DZ",
"American Samoa" => "AS",
"Andorra" => "AD",
"Angola" => "AO",
"Anguilla" => "AI",
"Antarctica" => "AQ",
"Antigua and Barbuda" => "AG",
"Argentina" => "AR",
"Armenia" => "AM",
"Aruba" => "AW",
"Australia" => "AU",
"Austria" => "AT",
"Azerbaijan" => "AZ",
"Bahamas" => "BS",
"Bahrain" => "BH",
"Bangladesh" => "BD",
"Barbados" => "BB",
"Belarus" => "BY",
"Belau" => "PW",
"Belgium" => "BE",
"Belize" => "BZ",
"Benin" => "BJ",
"Bermuda" => "BM",
"Bhutan" => "BT",
"Bolivia" => "BO",
"Bonaire, Saint Eustatius and Saba" => "BQ",
"Bosnia and Herzegovina" => "BA",
"Botswana" => "BW",
"Bouvet Island" => "BV",
"Brazil" => "BR",
"British Indian Ocean Territory" => "IO",
"Brunei" => "BN",
"Bulgaria" => "BG",
"Burkina Faso" => "BF",
"Burundi" => "BI",
"Cambodia" => "KH",
"Cameroon" => "CM",
"Canada" => "CA",
"Cape Verde" => "CV",
"Cayman Islands" => "KY",
"Central African Republic" => "CF",
"Chad" => "TD",
"Chile" => "CL",
"China" => "CN",
"Christmas Island" => "CX",
"Cocos (Keeling) Islands" => "CC",
"Colombia" => "CO",
"Comoros" => "KM",
"Congo (Brazzaville)" => "CG",
"Congo (Kinshasa)" => "CD",
"Cook Islands" => "CK",
"Costa Rica" => "CR",
"Croatia" => "HR",
"Cuba" => "CU",
"Curaçao" => "CW",
"Cyprus" => "CY",
"Czech Republic" => "CZ",
"Denmark" => "DK",
"Djibouti" => "DJ",
"Dominica" => "DM",
"Dominican Republic" => "DO",
"Ecuador" => "EC",
"Egypt" => "EG",
"El Salvador" => "SV",
"Equatorial Guinea" => "GQ",
"Eritrea" => "ER",
"Estonia" => "EE",
"Eswatini" => "SZ",
"Ethiopia" => "ET",
"Falkland Islands" => "FK",
"Faroe Islands" => "FO",
"Fiji" => "FJ",
"Finland" => "FI",
"France" => "FR",
"French Guiana" => "GF",
"French Polynesia" => "PF",
"French Southern Territories" => "TF",
"Gabon" => "GA",
"Gambia" => "GM",
"Georgia" => "GE",
"Germany" => "DE",
"Ghana" => "GH",
"Gibraltar" => "GI",
"Greece" => "GR",
"Greenland" => "GL",
"Grenada" => "GD",
"Guadeloupe" => "GP",
"Guam" => "GU",
"Guatemala" => "GT",
"Guernsey" => "GG",
"Guinea" => "GN",
"Guinea-Bissau" => "GW",
"Guyana" => "GY",
"Haiti" => "HT",
"Heard Island and McDonald Islands" => "HM",
"Honduras" => "HN",
"Hong Kong" => "HK",
"Hungary" => "HU",
"Iceland" => "IS",
"India" => "IN",
"Indonesia" => "ID",
"Iran" => "IR",
"Iraq" => "IQ",
"Ireland" => "IE",
"Isle of Man" => "IM",
"Israel" => "IL",
"Italy" => "IT",
"Ivory Coast" => "CI",
"Jamaica" => "JM",
"Japan" => "JP",
"Jersey" => "JE",
"Jordan" => "JO",
"Kazakhstan" => "KZ",
"Kenya" => "KE",
"Kiribati" => "KI",
"Kuwait" => "KW",
"Kyrgyzstan" => "KG",
"Laos" => "LA",
"Latvia" => "LV",
"Lebanon" => "LB",
"Lesotho" => "LS",
"Liberia" => "LR",
"Libya" => "LY",
"Liechtenstein" => "LI",
"Lithuania" => "LT",
"Luxembourg" => "LU",
"Macao" => "MO",
"Madagascar" => "MG",
"Malawi" => "MW",
"Malaysia" => "MY",
"Maldives" => "MV",
"Mali" => "ML",
"Malta" => "MT",
"Marshall Islands" => "MH",
"Martinique" => "MQ",
"Mauritania" => "MR",
"Mauritius" => "MU",
"Mayotte" => "YT",
"Mexico" => "MX",
"Micronesia" => "FM",
"Moldova" => "MD",
"Monaco" => "MC",
"Mongolia" => "MN",
"Montenegro" => "ME",
"Montserrat" => "MS",
"Morocco" => "MA",
"Mozambique" => "MZ",
"Myanmar" => "MM",
"Namibia" => "NA",
"Nauru" => "NR",
"Nepal" => "NP",
"Netherlands" => "NL",
"New Caledonia" => "NC",
"New Zealand" => "NZ",
"Nicaragua" => "NI",
"Niger" => "NE",
"Nigeria" => "NG",
"Niue" => "NU",
"Norfolk Island" => "NF",
"North Korea" => "KP",
"North Macedonia" => "MK",
"Northern Mariana Islands" => "MP",
"Norway" => "NO",
"Oman" => "OM",
"Pakistan" => "PK",
"Palestinian Territory" => "PS",
"Panama" => "PA",
"Papua New Guinea" => "PG",
"Paraguay" => "PY",
"Peru" => "PE",
"Philippines" => "PH",
"Pitcairn" => "PN",
"Poland" => "PL",
"Portugal" => "PT",
"Puerto Rico" => "PR",
"Qatar" => "QA",
"Reunion" => "RE",
"Romania" => "RO",
"Russia" => "RU",
"Rwanda" => "RW",
"São Tomé and Príncipe" => "ST",
"Saint Barthélemy" => "BL",
"Saint Helena" => "SH",
"Saint Kitts and Nevis" => "KN",
"Saint Lucia" => "LC",
"Saint Martin (Dutch part)" => "SX",
"Saint Martin (French part)" => "MF",
"Saint Pierre and Miquelon" => "PM",
"Saint Vincent and the Grenadines" => "VC",
"Samoa" => "WS",
"San Marino" => "SM",
"Saudi Arabia" => "SA",
"Senegal" => "SN",
"Serbia" => "RS",
"Seychelles" => "SC",
"Sierra Leone" => "SL",
"Singapore" => "SG",
"Slovakia" => "SK",
"Slovenia" => "SI",
"Solomon Islands" => "SB",
"Somalia" => "SO",
"South Africa" => "ZA",
"South Georgia/Sandwich Islands" => "GS",
"South Korea" => "KR",
"South Sudan" => "SS",
"Spain" => "ES",
"Sri Lanka" => "LK",
"Sudan" => "SD",
"Suriname" => "SR",
"Svalbard and Jan Mayen" => "SJ",
"Sweden" => "SE",
"Switzerland" => "CH",
"Syria" => "SY",
"Taiwan" => "TW",
"Tajikistan" => "TJ",
"Tanzania" => "TZ",
"Thailand" => "TH",
"Timor-Leste" => "TL",
"Togo" => "TG",
"Tokelau" => "TK",
"Tonga" => "TO",
"Trinidad and Tobago" => "TT",
"Tunisia" => "TN",
"Turkey" => "TR",
"Turkmenistan" => "TM",
"Turks and Caicos Islands" => "TC",
"Tuvalu" => "TV",
"Uganda" => "UG",
"Ukraine" => "UA",
"United Arab Emirates" => "AE",
"United Kingdom (UK)" => "GB",
"United States (US)" => "US",
"United States (US) Minor Outlying Islands" => "UM",
"Uruguay" => "UY",
"Uzbekistan" => "UZ",
"Vanuatu" => "VU",
"Vatican" => "VA",
"Venezuela" => "VE",
"Vietnam" => "VN",
"Virgin Islands (British)" => "VG",
"Virgin Islands (US)" => "VI",
"Wallis and Futuna" => "WF",
"Western Sahara" => "EH",
"Yemen" => "YE",
"Zambia" => "ZM",
"Zimbabwe" => "ZW",
);
return $list;
}
function rp_disable_reset_buttons_if_needed() {
global $rpQuery;
$rs_model = $rpQuery->prefix . 'rs_model';
if( rp_get_option('rp_already_checked_initial_status', '0') != '1' ) {
rp_update_option('rp_already_checked_initial_status', '1');
$any_model = $rpQuery->get_row("SELECT * FROM $rs_model LIMIT 1");
if( !empty( $any_model ) ) {
// Has entries
rp_update_option('rp_disable_reset_buttons_for_safety', '1');
}
}
}
add_action('init', 'rp_disable_reset_buttons_if_needed', 9999);
// load background jobs file
require_once WP_REPAIR_PLUGIN_PATH . 'background_jobs.php';
// load coupons work file
require_once WP_REPAIR_PLUGIN_PATH . 'includes' . DIRECTORY_SEPARATOR . 'coupons.php';
// load bulk edit work file
require_once WP_REPAIR_PLUGIN_PATH . 'includes' . DIRECTORY_SEPARATOR . 'bulk_edit.php';
// load advanced searchbar work file
require_once WP_REPAIR_PLUGIN_PATH . 'includes' . DIRECTORY_SEPARATOR . 'advanced_searchbar.php';
// load reset functions work file
require_once WP_REPAIR_PLUGIN_PATH . 'includes' . DIRECTORY_SEPARATOR . 'reset_functions.php';
// load coupons work file
require_once WP_REPAIR_PLUGIN_PATH . 'includes' . DIRECTORY_SEPARATOR . 'custom_fields.php';
// load coupons work file
require_once WP_REPAIR_PLUGIN_PATH . 'includes' . DIRECTORY_SEPARATOR . 'priority_repair.php';
// load analytics work file
require_once WP_REPAIR_PLUGIN_PATH . 'includes' . DIRECTORY_SEPARATOR . 'analytics.php';
// load opening hours addon work file
require_once WP_REPAIR_PLUGIN_PATH . 'includes' . DIRECTORY_SEPARATOR . 'opening_hours_addon.php';
// load dynamic pricing addon
require_once WP_REPAIR_PLUGIN_PATH . 'dynamic_pricing.php';
// load enhanced_locations addon
require_once WP_REPAIR_PLUGIN_PATH . 'enhanced_locations.php';
// load google_calendar_integration addon
require_once WP_REPAIR_PLUGIN_PATH . 'google_calendar_integration.php';
// load google_business_profile_integration addon
require_once WP_REPAIR_PLUGIN_PATH . 'google_business_profile_integration.php';
// load google_autocomplete_integration addon
require_once WP_REPAIR_PLUGIN_PATH . 'google_autocomplete_integration.php';
// load payment_integrations addon
require_once WP_REPAIR_PLUGIN_PATH . 'payment_integrations.php';
// load appointment_checklist addon
require_once WP_REPAIR_PLUGIN_PATH . 'appointment_checklist.php';
// load backups addon
require_once WP_REPAIR_PLUGIN_PATH . 'backups.php';
// load permissions addon
require_once WP_REPAIR_PLUGIN_PATH . 'enhanced_permissions.php';
// --------------START ---------------------------
// Default Repairs & Individual Repairs Markup ColSpan Issue Fix
// It was always taking too much time and code to fix html markup everytime
// we have to add / remove field. So below functions are very useful
function _rp_has_added_margin_column() {
static $added_margin_column = NULL;
if( $added_margin_column !== NULL ) {
return $added_margin_column;
}
$added_margin_column = FALSE;
$price_markup = '<th style="width: 75px"><p>Price</p></th>';
$filtered_price_th = apply_filters('rp_default_repair_price_th', $price_markup);
if( $price_markup !== $filtered_price_th ) {
$added_margin_column = TRUE;
}
return $added_margin_column;
}
function rp_get_original_colspans( $key = '' ) {
$colspans = array(
'order_repairs_row_colspan' => 8,
'sub_repair_details_colspan' => 9,
'order_repair_attrs_row_colspan' => 5
);
if( empty( $key ) || !array_key_exists( $key, $colspans ) ) {
return 0;
}
return $colspans[$key];
}
function rp_get_correct_colspan_based_on_conditions( $key = '' ) {
$original = rp_get_original_colspans( $key );
if( $original === 0 ) {
return 0;
}
$added_margin_column = _rp_has_added_margin_column();
if( $added_margin_column === TRUE ) {
if( $key == 'order_repair_attrs_row_colspan' ) {
$original = $original - 1;
} else {
$original = $original + 1;
}
}
if( rp_get_option('rp_enable_read_more_link_for_repairs', '0') == '1' ) {
if( $key == 'order_repair_attrs_row_colspan' ) {
// Nothing to do here!
} else {
$original = $original + 2;
}
}
return $original;
}
// **************************
// START - SMTP Credentials and Logging Emails
// **************************
function rp_get_default_email_address_for_test_email() {
$saved = rp_get_option('rp_get_default_email_address_for_test_email', '');
$company_email = rp_get_settings_company_email();
$placeholder_email = rp_get_settings_placeholder_email();
if( !empty( $saved ) && filter_var( $saved, FILTER_VALIDATE_EMAIL ) !== FALSE ) {
return $saved;
} else if( !empty( $company_email ) && filter_var( $company_email, FILTER_VALIDATE_EMAIL ) !== FALSE && $company_email != $placeholder_email ) {
return $company_email;
} else {
return '';
}
}
function _rp_get_email_smtp_details() {
static $cached = NULL;
if( $cached === NULL ) {
$cached = rp_get_option('rp_email_smtp_details', FALSE);
if( empty( $cached ) ) {
$cached = array();
}
}
return $cached;
}
function rp_get_email_smtp_details( $key = '', $default = '' ) {
$details = _rp_get_email_smtp_details();
if( empty( $details ) ) {
return $default;
}
return array_key_exists( $key, $details ) ? $details[$key] : $default;
}
function rp_mail_smtp_phpmailer_from_email($wp_from_email = '') {
$from_email = rp_get_email_smtp_details('from_email', '');
if( !empty( $from_email ) && filter_var( $from_email, FILTER_VALIDATE_EMAIL ) ) {
return $from_email;
}
return $wp_from_email;
}
function rp_mail_smtp_phpmailer_from_name($wp_from_name = '') {
$from_name = rp_get_email_smtp_details('from_name', '');
if( !empty( $from_name ) ) {
return $from_name;
}
return $wp_from_name;
}
function rp_mail_smtp_phpmailer_from_name_and_email( $phpmailer ) {
global $rp_before_change_from_email;
global $rp_before_change_from_name;
$rp_before_change_from_email = $phpmailer->From;
$rp_before_change_from_name = $phpmailer->FromName;
$from_email = rp_get_email_smtp_details('from_email', '');
if( !empty( $from_email ) && filter_var( $from_email, FILTER_VALIDATE_EMAIL ) ) {
$phpmailer->From = $from_email;
}
$from_name = rp_get_email_smtp_details('from_name', '');
if( !empty( $from_name ) ) {
$phpmailer->FromName = $from_name;
}
$phpmailer->setFrom( $phpmailer->From, $phpmailer->FromName, false );
}
function _rp_mail_wrapper_started_handler(){
add_filter('wp_mail_from', 'rp_mail_smtp_phpmailer_from_email', PHP_INT_MAX, 1);
add_filter('wp_mail_from_name', 'rp_mail_smtp_phpmailer_from_name', PHP_INT_MAX, 1);
add_action('phpmailer_init', 'rp_mail_smtp_phpmailer_from_name_and_email', PHP_INT_MAX, 1);
}
function _rp_mail_wrapper_ended_handler(){
global $phpmailer;
global $rp_before_change_from_email;
global $rp_before_change_from_name;
if( !empty( $phpmailer ) ) {
$phpmailer->From = $rp_before_change_from_email;
$phpmailer->FromName = $rp_before_change_from_name;
}
remove_filter('wp_mail_from', 'rp_mail_smtp_phpmailer_from_email', PHP_INT_MAX);
remove_filter('wp_mail_from_name', 'rp_mail_smtp_phpmailer_from_name', PHP_INT_MAX);
remove_action('phpmailer_init', 'rp_mail_smtp_phpmailer_from_name_and_email', PHP_INT_MAX);
}
if( rp_get_email_smtp_details('rp_use_these_sender_details_globally', '0') == '1' ) {
add_filter('wp_mail_from', 'rp_mail_smtp_phpmailer_from_email', PHP_INT_MAX);
add_filter('wp_mail_from_name', 'rp_mail_smtp_phpmailer_from_name', PHP_INT_MAX);
add_action('phpmailer_init', 'rp_mail_smtp_phpmailer_from_name_and_email', PHP_INT_MAX, 1);
} else {
add_action('rp_mail_wrapper_started', '_rp_mail_wrapper_started_handler', 10);
add_action('rp_mail_wrapper_ended', '_rp_mail_wrapper_ended_handler', 10);
}
function _rp_mail_wrapper_started_handler_2(){
add_action('phpmailer_init', 'rp_mail_smtp_phpmailer', PHP_INT_MAX, 1);
}
function _rp_mail_wrapper_ended_handler_2(){
remove_action('phpmailer_init', 'rp_mail_smtp_phpmailer', PHP_INT_MAX);
}
if( rp_get_email_smtp_details('rp_use_these_smtp_details_globally', '0') == '1' ) {
add_action('phpmailer_init', 'rp_mail_smtp_phpmailer', PHP_INT_MAX, 1);
} else {
add_action('rp_mail_wrapper_started', '_rp_mail_wrapper_started_handler_2', 10);
add_action('rp_mail_wrapper_ended', '_rp_mail_wrapper_ended_handler_2', 10);
}
function rp_mail_wrapper( $to, $subject, $message, $headers = '', $attachments = array() ) {
try {
$timezone_string = wp_timezone_string();
// if timezone is UTC or timezone is not set or timezone doesn't have / then show error
if( $timezone_string == 'UTC' || empty( $timezone_string ) || strpos( $timezone_string, '/' ) === false ) {
// Do nothing...
} else {
_rp_set_default_tiemzone();
}
// catch exception, errors, warning and everything
} catch ( Exception|Error|Throwable|ErrorException|ArgumentCountError|DivisionByZeroError|ParseError|TypeError|mysqli_sql_exception $e ) {
// Do nothing
}
do_action('rp_mail_wrapper_started');
add_filter('wp_mail_succeeded', 'rp_log_successful_outgoing_emails', PHP_INT_MAX, 1);
add_filter('wp_mail_failed', 'rp_log_failed_outgoing_emails', PHP_INT_MAX, 2);
add_filter('wp_mail', 'rp_save_original_headers_in_global', PHP_INT_MAX, 1);
$GLOBALS['rp_wp_mail_original_headers'] = null;
$sent = wp_mail( $to, $subject, $message, $headers, $attachments );
remove_filter('wp_mail_succeeded', 'rp_log_successful_outgoing_emails', PHP_INT_MAX);
remove_filter('wp_mail_failed', 'rp_log_failed_outgoing_emails', PHP_INT_MAX);
remove_filter('wp_mail', 'rp_save_original_headers_in_global', PHP_INT_MAX);
do_action('rp_mail_wrapper_ended');
return $sent;
}
function rp_mail_smtp_phpmailer($phpmailer) {
$rp_use_custom_smtp_settings = rp_get_email_smtp_details('rp_use_custom_smtp_settings', '0');
$host = trim( rp_get_email_smtp_details('host', '') ?? '' );
$encryption = trim( rp_get_email_smtp_details('encryption', '') ?? '' );
$port = trim( rp_get_email_smtp_details('port', '0') ?? '' );
$rp_use_smtp_auto_tls = rp_get_email_smtp_details('rp_use_smtp_auto_tls', '0');
$rp_use_smtp_authentication = rp_get_email_smtp_details('rp_use_smtp_authentication', '0');
$username = trim( rp_get_email_smtp_details('username', '') ?? '' );
$password = ( rp_get_email_smtp_details('password', '') ?? '' );
if( $rp_use_custom_smtp_settings != '1' || empty( $host ) ) {
return $phpmailer;
}
$phpmailer->isSMTP();
$phpmailer->Host = $host;
$phpmailer->SMTPSecure = $encryption;
if( empty( $port ) ) {
$port = 0;
}
$port = (int) $port;
$phpmailer->Port = $port;
if( $rp_use_smtp_auto_tls == '1' ) {
$phpmailer->SMTPAutoTLS = true;
} else {
$phpmailer->SMTPAutoTLS = false;
}
if( $rp_use_smtp_authentication == '1' && !empty( $username ) ) {
$phpmailer->SMTPAuth = true;
$phpmailer->Username = $username;
$phpmailer->Password = $password;
} else {
$phpmailer->SMTPAuth = false;
$phpmailer->Username = '';
$phpmailer->Password = '';
}
}
function rp_save_email_logs( $status = '', $atts = array() ) {
global $rpQuery;
$rs_email_logs = $rpQuery->prefix . 'rs_email_logs';
$to = is_array($atts['to']) ? implode(', ', $atts['to']) : $atts['to'];
$subject = $atts['subject'] ?? '';
$message = $atts['message'] ?? '';
$atts['headers'] = $GLOBALS['rp_wp_mail_original_headers'] ?? array();
$headers = is_array($atts['headers']) ? implode("\n", $atts['headers']) : $atts['headers'];
if( is_array( $atts['attachments'] ) ) {
$atts['attachments'] = array_map( 'basename', $atts['attachments'] );
} else {
$atts['attachments'] = basename( $atts['attachments'] );
}
$attachments = is_array($atts['attachments']) ? implode("\n", $atts['attachments']) : $atts['attachments'];
$error_message = array_key_exists( 'error_message', $atts ) ? $atts['error_message'] : '';
$sent_at = date('Y-m-d H:i:s');
if( strpos( $message, '<span class="rp-secret-code">' ) !== FALSE ) {
// get everything between <span class="rp-secret-code"></span> and replace each character with *
// using preg replace
$message = preg_replace_callback('/<span class="rp-secret-code">(.*?)<\/span>/', function($matches) {
return '<span class="rp-secret-code">' . str_repeat('*', strlen($matches[1])) . ' (Verification codes are not stored in email logs.)</span>';
}, $message);
}
$data = array(
'recipient' => $to,
'subject' => $subject,
'message' => $message,
'headers' => $headers,
'attachments' => $attachments,
'status' => $status,
'error_message' => $error_message,
'sent_at' => $sent_at
);
$rpQuery->insert($rs_email_logs, $data);
}
function rp_log_successful_outgoing_emails( $atts = array() ) {
rp_save_email_logs( 'success', $atts );
}
function rp_log_failed_outgoing_emails( $errorObject = null, $other_data = null ) {
$error_message = $errorObject->get_error_message() ?? '';
$atts = $errorObject->get_error_data() ?? array();
$atts['error_message'] = $error_message;
rp_save_email_logs( 'failed', $atts );
}
function rp_save_original_headers_in_global( $atts ) {
$GLOBALS['rp_wp_mail_original_headers'] = $atts['headers'] ?? array();
return $atts;
}
function rp_get_model_table_actions_column_width() {
return 260;
$baseWidth = 260;
$added_margin_column = _rp_has_added_margin_column();
if( $added_margin_column === TRUE ) {
$baseWidth += 100;
}
if( rp_get_option('rp_enable_read_more_link_for_repairs', '0') == '1' || rp_get_option('rp_enable_read_more_link_for_attributes', '0') == '1' ) {
$baseWidth += 375;
}
return $baseWidth;
}
function rp_get_default_repairs_table_conditional_table_widths() {
$width1Original = 1200;
$width2Original = 1160;
$added_margin_column = _rp_has_added_margin_column();
if( $added_margin_column === TRUE ) {
$width1Original += 100;
$width2Original += 100;
}
if( rp_get_option('rp_enable_read_more_link_for_repairs', '0') == '1' || rp_get_option('rp_enable_read_more_link_for_attributes', '0') == '1' ) {
$width1Original += 375;
$width2Original += 375;
}
return array( $width1Original, $width2Original );
}
function rp_get_booking_slot_length() {
global $rpQuery;
$rs_planning_and_discount = $rpQuery->prefix . "rs_planning_and_discount";
$d_result = $rpQuery->get_row("SELECT * FROM $rs_planning_and_discount");
if( empty( $d_result ) ) {
return 30;
}
$time_slots = $d_result->booking_slots_length;
$time_slots = str_replace(' Minutes (Default)', '', $time_slots);
$time_slots = (int) $time_slots;
return $time_slots;
}
function rp_get_email_content_ajax() {
rp_verify_csrf_token_for_ajax('email_smtp');
try {
$timezone_string = wp_timezone_string();
// if timezone is UTC or timezone is not set or timezone doesn't have / then show error
if( $timezone_string == 'UTC' || empty( $timezone_string ) || strpos( $timezone_string, '/' ) === false ) {
// Do nothing...
} else {
_rp_set_default_tiemzone();
}
// catch exception, errors, warning and everything
} catch ( Exception|Error|Throwable|ErrorException|ArgumentCountError|DivisionByZeroError|ParseError|TypeError|mysqli_sql_exception $e ) {
// Do nothing
}
$log_id = intval( ($_POST['log_id'] ?? 0) );
global $wpdb;
$table_name = $wpdb->prefix . 'rs_email_logs';
$record = $wpdb->get_row($wpdb->prepare("select * from {$table_name} where id = %s", $log_id));
if($record) {
$data['status'] = true;
$data['message'] = 'Success';
$record->human_readable_time = _get_human_readable_difference_from_now( strtotime($record->sent_at ?? 0) );
$data['result'] = $record;
echo json_encode($data);
exit;
}
$data['status'] = false;
$data['message'] = 'Failed';
echo json_encode($data);
exit;
}
rp_ajax_for_admin('rp_get_email_content', 'rp_get_email_content_ajax');
function rp_clear_all_email_logs_ajax() {
global $rpQuery;
rp_verify_csrf_token_for_ajax('email_smtp');
$rs_email_logs = $rpQuery->prefix . 'rs_email_logs';
$rpQuery->query("DELETE FROM $rs_email_logs");
echo json_encode(array('status' => true, 'message' => 'Successfully deleted'));
exit;
}
rp_ajax_for_admin('rp_clear_all_email_logs_ajax', 'rp_clear_all_email_logs_ajax');
function rp_delete_email_log_ajax() {
global $rpQuery;
rp_verify_csrf_token_for_ajax('email_smtp');
$id = intval( ($_POST['id'] ?? 0) );
$rs_email_logs = $rpQuery->prefix . 'rs_email_logs';
$rpQuery->query("DELETE FROM $rs_email_logs WHERE id = $id");
echo json_encode(array('status' => true, 'message' => 'Successfully deleted'));
exit;
}
rp_ajax_for_admin('rp_delete_email_log_ajax', 'rp_delete_email_log_ajax');
function rp_wp_timezone_choice( $selected_zone, $locale = null ) {
static $mo_loaded = false, $locale_loaded = null;
$continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific' );
// Load translations for continents and cities.
if ( ! $mo_loaded || $locale !== $locale_loaded ) {
$locale_loaded = $locale ? $locale : get_locale();
$mofile = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
unload_textdomain( 'continents-cities', true );
load_textdomain( 'continents-cities', $mofile, $locale_loaded );
$mo_loaded = true;
}
$tz_identifiers = timezone_identifiers_list();
$zonen = array();
foreach ( $tz_identifiers as $zone ) {
$zone = explode( '/', $zone );
if ( ! in_array( $zone[0], $continents, true ) ) {
continue;
}
// This determines what gets set and translated - we don't translate Etc/* strings here, they are done later.
$exists = array(
0 => ( isset( $zone[0] ) && $zone[0] ),
1 => ( isset( $zone[1] ) && $zone[1] ),
2 => ( isset( $zone[2] ) && $zone[2] ),
);
$exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
$exists[4] = ( $exists[1] && $exists[3] );
$exists[5] = ( $exists[2] && $exists[3] );
// phpcs:disable WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText
$zonen[] = array(
'continent' => ( $exists[0] ? $zone[0] : '' ),
'city' => ( $exists[1] ? $zone[1] : '' ),
'subcity' => ( $exists[2] ? $zone[2] : '' ),
't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' ),
);
// phpcs:enable
}
usort( $zonen, '_wp_timezone_choice_usort_callback' );
$structure = array();
// If this is a deprecated, but valid, timezone string, display it at the top of the list as-is.
if ( in_array( $selected_zone, $tz_identifiers, true ) === false
&& in_array( $selected_zone, timezone_identifiers_list( DateTimeZone::ALL_WITH_BC ), true )
) {
$structure[$selected_zone] = $selected_zone;
}
foreach ( $zonen as $key => $zone ) {
// Build value in an array to join later.
$value = array( $zone['continent'] );
$display = $zone['t_continent'];
if ( empty( $zone['city'] ) ) {
// It's at the continent level (generally won't happen).
$display = $zone['t_continent'];
} else {
// It's inside a continent group.
$label = $zone['t_continent'];
// Add the city to the value.
$value[] = $zone['city'];
$display .= '/' . $zone['t_city'];
if ( ! empty( $zone['subcity'] ) ) {
// Add the subcity to the value.
$value[] = $zone['subcity'];
$display .= '/' . $zone['t_subcity'];
}
}
// Build the value.
$value = implode( '/', $value );
$structure[ $value ] = $display;
}
if( $selected_zone == 'UTC' ) {
$structure['UTC'] = 'UTC';
}
// Do manual UTC offsets.
$offset_range = array(
-12,
-11.5,
-11,
-10.5,
-10,
-9.5,
-9,
-8.5,
-8,
-7.5,
-7,
-6.5,
-6,
-5.5,
-5,
-4.5,
-4,
-3.5,
-3,
-2.5,
-2,
-1.5,
-1,
-0.5,
0,
0.5,
1,
1.5,
2,
2.5,
3,
3.5,
4,
4.5,
5,
5.5,
5.75,
6,
6.5,
7,
7.5,
8,
8.5,
8.75,
9,
9.5,
10,
10.5,
11,
11.5,
12,
12.75,
13,
13.75,
14,
);
foreach ( $offset_range as $offset ) {
if ( 0 <= $offset ) {
$offset_name = '+' . $offset;
} else {
$offset_name = (string) $offset;
}
$offset_value = $offset_name;
$offset_name = str_replace( array( '.25', '.5', '.75' ), array( ':15', ':30', ':45' ), $offset_name );
$offset_name = 'UTC' . $offset_name;
$offset_value = 'UTC' . $offset_value;
if( $selected_zone == $offset_value ) {
$structure[ $offset_value ] = $offset_name;
}
}
return $structure;
}
function rp_wp_selected_timezone() {
$current_offset = get_option( 'gmt_offset' );
$tzstring = get_option( 'timezone_string' );
// Remove old Etc mappings. Fallback to gmt_offset.
if ( str_contains( $tzstring, 'Etc/GMT' ) ) {
$tzstring = '';
}
if ( empty( $tzstring ) ) { // Create a UTC+- zone if no timezone string exists.
if ( 0 === (int) $current_offset ) {
$tzstring = 'UTC+0';
} elseif ( $current_offset < 0 ) {
$tzstring = 'UTC' . $current_offset;
} else {
$tzstring = 'UTC+' . $current_offset;
}
}
return $tzstring;
}
function _rp_add_my_custom_font_option( $fonts = array() ) {
$fonts['arial'] = array(
'name' => 'Arial',
'font_link' => '',
'font_family' => '"Arial", sans-serif',
);
return $fonts;
}
add_filter( 'rp_get_font_options', '_rp_add_my_custom_font_option', 10, 1 );
function rp_print_selected_font_styling_var() {
$rp_selectedFontInfo = rp_get_selected_font_info();
if(!empty($rp_selectedFontInfo['font_link'] ?? '')) {
echo $rp_selectedFontInfo['font_link'];
}
if( !empty( $rp_selectedFontInfo['font_family'] ?? '' ) ) {
?>
<style type="text/css">
:root {
--rp-font-family: <?php echo $rp_selectedFontInfo['font_family']; ?>;
}
</style>
<?php
}
}
function rp_get_selected_font_info() {
$selected = rp_get_selected_font();
return rp_get_font_options()[ $selected ] ?? array(
'name' => 'Montserrat',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Montserrat", sans-serif',
);
}
function rp_get_selected_font() {
$selected_font = rp_get_option('rp_selected_font', FALSE);
$font_options = rp_get_font_options();
if( empty( $selected_font ) || !isset( $font_options[ $selected_font ] ) ) {
return 'montserrat';
}
return $selected_font;
}
function _rp_get_all_fonts_load_link() {
$fonts = rp_get_font_options();
$font_family = array();
foreach( $fonts as $font_option => $font_info ) {
if( !empty( $font_info['name'] ) && !empty( $font_info['font_link'] ) && strpos( $font_info['font_link'], 'google' ) !== FALSE ) {
$font_family[] = 'family='. urlencode($font_info['name']);
}
}
$font_family = implode('&', $font_family);
if( empty( $font_family ) ) {
return;
}
return '<link href="https://fonts.googleapis.com/css2?'.$font_family.':wght@400&display=swap" rel="stylesheet">';
}
function _rp_get_font_options() {
$fonts = array(
'montserrat' => array(
'name' => 'Montserrat',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Montserrat", sans-serif',
),
'open_sans' => array(
'name' => 'Open Sans',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Open Sans", sans-serif',
),
'roboto' => array(
'name' => 'Roboto',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">',
'font_family' => '"Roboto", sans-serif',
),
'lato' => array(
'name' => 'Lato',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700&display=swap" rel="stylesheet">',
'font_family' => '"Lato", sans-serif',
),
'poppins' => array(
'name' => 'Poppins',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Poppins", sans-serif',
),
'raleway' => array(
'name' => 'Raleway',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Raleway", sans-serif',
),
'nunito' => array(
'name' => 'Nunito',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Nunito", sans-serif',
),
'merriweather' => array(
'name' => 'Merriweather',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Merriweather:wght@300;400;700&display=swap" rel="stylesheet">',
'font_family' => '"Merriweather", serif',
),
'playfair_display' => array(
'name' => 'Playfair Display',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;500;700&display=swap" rel="stylesheet">',
'font_family' => '"Playfair Display", serif',
),
'inter' => array(
'name' => 'Inter',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Inter", sans-serif',
),
'work_sans' => array(
'name' => 'Work Sans',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Work+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Work Sans", sans-serif',
),
'roboto_slab' => array(
'name' => 'Roboto Slab',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@300;400;700&display=swap" rel="stylesheet">',
'font_family' => '"Roboto Slab", serif',
),
'source_sans_pro' => array(
'name' => 'Source Sans Pro',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Source Sans Pro", sans-serif',
),
'oswald' => array(
'name' => 'Oswald',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@300;400;700&display=swap" rel="stylesheet">',
'font_family' => '"Oswald", sans-serif',
),
'ubuntu' => array(
'name' => 'Ubuntu',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap" rel="stylesheet">',
'font_family' => '"Ubuntu", sans-serif',
),
'muli' => array(
'name' => 'Muli',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Muli:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Muli", sans-serif',
),
'quicksand' => array(
'name' => 'Quicksand',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Quicksand", sans-serif',
),
'cabin' => array(
'name' => 'Cabin',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Cabin:wght@400;500;700&display=swap" rel="stylesheet">',
'font_family' => '"Cabin", sans-serif',
),
'hind' => array(
'name' => 'Hind',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Hind:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Hind", sans-serif',
),
'archivo' => array(
'name' => 'Archivo',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Archivo:wght@400;500;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Archivo", sans-serif',
),
'josefin_sans' => array(
'name' => 'Josefin Sans',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Josefin Sans", sans-serif',
),
'dm_sans' => array(
'name' => 'DM Sans',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;700&display=swap" rel="stylesheet">',
'font_family' => '"DM Sans", sans-serif',
),
'manrope' => array(
'name' => 'Manrope',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Manrope", sans-serif',
),
'noto_sans' => array(
'name' => 'Noto Sans',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@300;400;500;700&display=swap" rel="stylesheet">',
'font_family' => '"Noto Sans", sans-serif',
),
'karla' => array(
'name' => 'Karla',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Karla:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Karla", sans-serif',
),
'barlow' => array(
'name' => 'Barlow',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Barlow", sans-serif',
),
'fira_sans' => array(
'name' => 'Fira Sans',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@300;400;500;700&display=swap" rel="stylesheet">',
'font_family' => '"Fira Sans", sans-serif',
),
'assistant' => array(
'name' => 'Assistant',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Assistant:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Assistant", sans-serif',
),
'signika' => array(
'name' => 'Signika',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Signika:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Signika", sans-serif',
),
'titillium_web' => array(
'name' => 'Titillium Web',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Titillium+Web:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Titillium Web", sans-serif',
),
'kanit' => array(
'name' => 'Kanit',
'font_link' => '<link href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;600;700&display=swap" rel="stylesheet">',
'font_family' => '"Kanit", sans-serif',
),
);
// sort by keys
ksort( $fonts );
return $fonts;
}
function rp_get_font_options() {
$fonts = _rp_get_font_options();
$fonts = apply_filters('rp_get_font_options', $fonts);
// sort by keys
ksort( $fonts );
return $fonts;
}
// ------------ END ------------------------------
new Repairplugin();
new RP_DynamicPricingAddon();
new RP_EnhancedLocationsAddon();
$rp_start_time_after_rp_loading_hook = microtime(true);