AlkantarClanX12
| Current Path : /www/capitalgmcbuickregina_830/public/wp-content/plugins/leadbox/lib/ |
| Current File : /www/capitalgmcbuickregina_830/public/wp-content/plugins/leadbox/lib/actions.php |
<?php
add_action('init', function () {
add_action('enqueue_block_editor_assets', function () {
wp_enqueue_script(
'leadbox-gutenberg-blocks',
dirname(plugin_dir_url(__FILE__)) . '/dist/blocks.build.js',
array(
'wp-blocks',
'wp-editor',
'wp-element',
'wp-components'
),
false,
false
);
wp_enqueue_style(
'leadbox-gutenberg-blocks',
dirname(plugin_dir_url(__FILE__)) . '/dist/blocks.editor.build.css',
array(),
false,
false
);
wp_enqueue_style(
'leadbox-gutenberg-blocks',
dirname(plugin_dir_url(__FILE__)) . '/dist/blocks.style.build.css',
array(),
false,
false
);
});
add_filter('block_categories', function ($categories, $post) {
return array_merge(
$categories,
array(
array(
'slug' => 'leadbox',
'title' => __('Leadbox', 'leadbox-plugin'),
),
)
);
}, 10, 2);
// Check cache first
$cached_data = get_transient('leadbox_block_data');
$file = wp_get_upload_dir()['basedir'] . '/data/inventory.json';
// Only proceed if file exists
if (!file_exists($file)) {
leadbox_logger()->error('Inventory file not found for block registration', array(
'file' => $file,
));
// Initialize empty data structure
$cached_data = array(
'years' => array(),
'makes' => array(),
'models' => array(),
'trims' => array(),
'locations' => array(),
'types' => array(),
'statuses' => array(),
'stock_numbers' => array(),
'tags' => array(),
'year_min' => 0,
'year_max' => 0,
'price_min' => 0,
'price_max' => 0,
'mileage_min' => 0,
'mileage_max' => 0,
);
} else {
$file_mtime = filemtime($file);
$cached_mtime = get_transient('leadbox_block_data_mtime');
// Only read if cache is empty OR file was modified
if ($cached_data === false || $cached_mtime != $file_mtime) {
// Read and process inventory
$data = json_decode(file_get_contents($file), true);
if ($data === null || !isset($data['vehicles'])) {
leadbox_logger()->error('Failed to parse inventory for block registration', array(
'file' => $file,
'json_error' => json_last_error_msg(),
));
// Initialize empty data structure
$cached_data = array(
'years' => array(),
'makes' => array(),
'models' => array(),
'trims' => array(),
'locations' => array(),
'types' => array(),
'statuses' => array(),
'stock_numbers' => array(),
'tags' => array(),
'year_min' => 0,
'year_max' => 0,
'price_min' => 0,
'price_max' => 0,
'mileage_min' => 0,
'mileage_max' => 0,
);
} else {
// Extract unique values
$years = array();
$makes = array();
$models = array();
$trims = array();
$locations = array();
$prices = array();
$mileages = array();
$types = array();
$statuses = array();
$stock_numbers = array();
$tags = array();
foreach ($data['vehicles'] as $vehicle) {
$years[] = $vehicle['year'];
$makes[] = $vehicle['make'];
$models[] = $vehicle['model'];
$trims[] = (isset($vehicle) && isset($vehicle['trim'])) ? $vehicle['trim'] : "";
$locations[] = (isset($vehicle) && isset($vehicle['location'])) ? $vehicle['location'] : "";
$prices[] = $vehicle['price'];
$mileages[] = (isset($vehicle['mileage'])) ? $vehicle['mileage'] : 0;
$types[] = $vehicle['type'];
$statuses[] = $vehicle['condition'];
$stock_numbers[] = $vehicle['stocknumber'];
$tags[] = $vehicle['tags'];
}
// Deduplicate and sort
$years = unique($years);
$makes = unique($makes);
$models = unique($models);
$trims = unique($trims);
$locations = unique($locations);
$prices = unique($prices);
$mileages = unique($mileages);
$types = unique($types);
$statuses = unique($statuses);
//$stock_numbers = unique($stock_numbers);
if(!isset($mileages) || sizeof($mileages) == 0 ){
$mileages[]=0;
}
//var_dump($tags);
$tags = array_reduce(unique($tags), function ($_tags, $item) {
$_tags = is_array($_tags) ? $_tags : (array) $_tags;
// Verificar si $item es null o no es string
if ($item === null || !is_string($item)) {
// Si es null o no es string, usar array vacío para evitar warnings
$exploded = [];
} else {
// Si es string válido, hacer el explode normalmente
$exploded = explode(',', $item);
}
$merged = array_merge($_tags, $exploded);
return array_unique($merged);
}, []);
$tags = array_values($tags);
sort($makes);
sort($models);
sort($trims);
sort($locations);
sort($types);
sort($statuses);
// Min/max values
$year_min = !empty($years) ? min($years) : 0;
$year_max = !empty($years) ? max($years) : 0;
$price_min = !empty($prices) ? min($prices) : 0;
$price_max = !empty($prices) ? max($prices) : 0;
$mileage_min = !empty($mileages) ? min($mileages) : 0;
$mileage_max = !empty($mileages) ? max($mileages) : 0;
// Cache for 1 hour
$cached_data = array(
'years' => $years,
'makes' => $makes,
'models' => $models,
'trims' => $trims,
'locations' => $locations,
'types' => $types,
'statuses' => $statuses,
'stock_numbers' => $stock_numbers,
'tags' => $tags,
'year_min' => $year_min,
'year_max' => $year_max,
'price_min' => $price_min,
'price_max' => $price_max,
'mileage_min' => $mileage_min,
'mileage_max' => $mileage_max,
);
set_transient('leadbox_block_data', $cached_data, HOUR_IN_SECONDS);
set_transient('leadbox_block_data_mtime', $file_mtime, HOUR_IN_SECONDS);
}
}
}
$flags = [
'special' => 'Special',
'salepending' => 'Sale Pending',
'onhome' => 'On Home',
'certified' => 'Certified',
'demo' => 'Demo',
'asis' => 'Asis',
'incoming' => 'Incoming',
'excludeincoming' => 'Exclude Incoming',
'excludesalepending' => 'Exclude Sale Pending',
'excludedemo' => 'Exclude Demo',
'noprice' => 'No Price',
'reserved' => 'Reserved'
];
// LBT-1462: reusable listing-image groups the dealer can pick from in this block.
// Passed as an attribute default (same pattern as make_items/flags_items) so the
// editor can build the select without an extra localize/REST round-trip.
$listing_image_groups = class_exists('LBX_Listing_Image_Groups')
? LBX_Listing_Image_Groups::get_groups_for_select()
: array();
// Register our block, and explicitly define the attributes we accept.
register_block_type('leadbox/inventory-block', array(
'attributes' => array(
'filter' => array(
'type' => 'boolean',
'default' => false,
),
// LBT-1462: id of the selected listing-image group ('' = use global/legacy
// config). `_items` feeds the editor's select and is not persisted meaningfully.
'listing_image_group' => array(
'type' => 'string',
'default' => '',
),
'listing_image_group_items' => array(
'type' => 'array',
'default' => $listing_image_groups,
),
'slick' => array(
'type' => 'boolean',
'default' => false,
),
'layout' => array(
'type' => 'string',
'default' => 'normal'
),
'layout_items' => array(
'type' => 'array',
'default' => array('normal', 'compact')
),
'limit' => array(
'type' => 'string',
'default' => '0',
),
'sort_by' => array(
'type' => 'string',
'default' => 'year'
),
'sort_by_model' => array(
'type' => 'string',
'default' => 'model'
),
'sort_by_items' => array(
'type' => 'array',
'default' => array('Year', 'Price', 'Age','Totaldiscounts', 'Make','Make (Custom)', 'Model','Model (Custom)','NumberOfPics', 'Location', 'Location (Custom)', 'Stocknumbers','Stocknumber (Custom)','CashPrice')
),
'sort_by_condition' => array(
'type' => 'string',
'default' => 'desc'
),
'sort_makes' => array(
'type' => 'array',
'default' => array(),
),
'sort_models' => array(
'type' => 'array',
'default' => array(),
),
'sort_locations' => array(
'type' => 'array',
'default' => array(),
),
'sort_stocks' => array(
'type' => 'array',
'default' => array(),
),
'sort_by_condition_items' => array(
'type' => 'array',
'default' => array('Asc', 'Desc')
),
'sort_by_secondary' => array(
'type' => 'string',
'default' => 'none'
),
'sort_by_condition_secondary' => array(
'type' => 'string',
'default' => 'desc'
),
'year' => array(
'type' => 'string',
'default' => 'all',
),
'year_from' => array(
'type' => 'integer',
'default' => $cached_data['year_min'] ?? 0,
),
'year_to' => array(
'type' => 'integer',
'default' => $cached_data['year_max'] ?? 0,
),
'year_min' => array(
'type' => 'integer',
'default' => $cached_data['year_min'] ?? 0,
),
'year_max' => array(
'type' => 'integer',
'default' => $cached_data['year_max'] ?? 0,
),
'make' => array(
'type' => 'string',
'default' => 'all',
),
'make_items' => array(
'type' => 'array',
'default' => $cached_data['makes'] ?? array(),
'items' => array('type' => 'string')
),
'make_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
),
'model' => array(
'type' => 'string',
'default' => 'all',
),
'model_items' => array(
'type' => 'array',
'default' => $cached_data['models'] ?? array(),
'items' => array('type' => 'string')
),
'model_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
),
'trim' => array(
'type' => 'string',
'default' => 'all',
),
'trim_items' => array(
'type' => 'array',
'default' => $cached_data['trims'] ?? array(),
'items' => array('type' => 'string')
),
'trim_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
),
'location' => array(
'type' => 'string',
'default' => 'all',
),
'location_items' => array(
'type' => 'array',
'default' => $cached_data['locations'] ?? array(),
'items' => array('type' => 'string')
),
'location_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
),
'price' => array(
'type' => 'string',
'default' => 'all',
),
'price_from' => array(
'type' => 'integer',
'default' => $cached_data['price_min'] ?? 0,
),
'price_to' => array(
'type' => 'integer',
'default' => $cached_data['price_max'] ?? 0,
),
'price_min' => array(
'type' => 'integer',
'default' => $cached_data['price_min'] ?? 0,
),
'price_max' => array(
'type' => 'integer',
'default' => $cached_data['price_max'] ?? 0,
),
'mileage' => array(
'type' => 'string',
'default' => 'all',
),
'mileage_from' => array(
'type' => 'integer',
'default' => $cached_data['mileage_min'] ?? 0,
),
'mileage_to' => array(
'type' => 'integer',
'default' => $cached_data['mileage_max'] ?? 0,
),
'mileage_min' => array(
'type' => 'integer',
'default' => $cached_data['mileage_min'] ?? 0,
),
'mileage_max' => array(
'type' => 'integer',
'default' => $cached_data['mileage_max'] ?? 0,
),
'type' => array(
'type' => 'string',
'default' => 'all',
),
'type_items' => array(
'type' => 'array',
'default' => $cached_data['types'] ?? array(),
'items' => array('type' => 'string')
),
'type_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
),
'status' => array(
'type' => 'string',
'default' => 'all',
),
'status_items' => array(
'type' => 'array',
'default' => $cached_data['statuses'] ?? array(),
'items' => array('type' => 'string')
),
'status_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
),
'tags' => array(
'type' => 'string',
'default' => 'all',
),
'tags_items' => array(
'type' => 'array',
'default' => $cached_data['tags'] ?? array(),
'items' => array('type' => 'string')
),
'tags_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
),
'stock' => array(
'type' => 'string',
'default' => 'all',
),
'stock_items' => array(
'type' => 'array',
'default' => $cached_data['stock_numbers'] ?? array(),
'items' => array('type' => 'string')
),
'stock_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
),
'flags' => array(
'type' => 'string',
'default' => 'none',
),
'flags_items' => array(
'type' => 'array',
'default' => $flags,
'items' => array('type' => 'string')
),
'flags_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
),
'vehicle_card' => array(
'type' => 'string',
'default' => '',
),
'exclude_tags' => array(
'type' => 'string',
'default' => '',
),
'exclude_tags_items' => array(
'type' => 'array',
'default' => $cached_data['tags'] ?? array(),
'items' => array('type' => 'string')
),
'exclude_tags_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
)
),
'editor_script' => 'leadbox-gutenberg-blocks',
'render_callback' => 'leadbox_render_inventory',
));
// Register our block, and explicitly define the attributes we accept.
register_block_type('leadbox/line-up-block', array(
'attributes' => array(),
'editor_script' => 'leadbox-gutenberg-blocks',
'render_callback' => 'leadbox_render_line_up',
));
// Register our block, and explicitly define the attributes we accept.
register_block_type('leadbox/omnisearch-block', array(
'attributes' => array(),
'editor_script' => 'leadbox-gutenberg-blocks',
'render_callback' => 'leadbox_render_omnisearch',
));
// Register our block, and explicitly define the attributes we accept.
register_block_type('leadbox/quick-search-block', array(
'attributes' => array(),
'editor_script' => 'leadbox-gutenberg-blocks',
'render_callback' => 'leadbox_render_quick_search',
));
register_block_type('leadbox/previously-viewed-block', array(
'attributes' => array(),
'editor_script' => 'leadbox-gutenberg-blocks',
'render_callback' => 'leadbox_render_previously_viewed',
));
register_block_type('leadbox/hours-of-operations-block', array(
'attributes' => array(
'sales' => array(
'type' => 'boolean',
'default' => true,
),
'service' => array(
'type' => 'boolean',
'default' => true,
),
'parts' => array(
'type' => 'boolean',
'default' => true,
),
'additional1' => array(
'type' => 'boolean',
'default' => false,
),
'additional2' => array(
'type' => 'boolean',
'default' => false,
),
'additional3' => array(
'type' => 'boolean',
'default' => false,
)
),
'editor_script' => 'leadbox-gutenberg-blocks',
'render_callback' => 'leadbox_render_hours_of_operations',
));
// VDP
register_block_type('leadbox/vdp-block', array(
'attributes' => array(
'stock_vdp' => array(
'type' => 'string',
'default' => '',
),
'stock_items' => array(
'type' => 'array',
'default' => $cached_data['stock_numbers'] ?? array(),
'items' => array('type' => 'string')
),
'stock_vdp_selected' => array(
'type' => 'array',
'default' => array(),
'items' => array('type' => 'string')
),
),
'editor_script' => 'leadbox-gutenberg-blocks',
'render_callback' => 'leadbox_render_vdp',
));
add_shortcode('inventory', 'leadbox_render_inventory');
}, 100);
add_action('admin_init', function () {
if (is_admin()) {
remove_submenu_page('edit.php?post_type=team_manager', 'team_manager');
remove_submenu_page('edit.php?post_type=team_manager', 'team-manager-shortcode-generator');
}
}, 100);
add_action('do_meta_boxes', function () {
if (is_admin()) {
remove_meta_box('team_social', 'team_manager', 'normal');
}
}, 100);
function wps_remove_role() {
remove_role( 'marketer' );
remove_role( 'admin' );
remove_role( 'seo-manager' );
remove_role( 'seo-editor' );
remove_role( 'wpseo_manager' );
remove_role( 'wpseo_editor' );
remove_role( 'author' );
remove_role( 'contributor' );
remove_role( 'subscriber' );
remove_role( 'dealer-admin' );
}
add_action( 'admin_init', 'wps_remove_role' );
function wps_change_role_name() {
global $wp_roles;
if ( ! isset( $wp_roles ) )
$wp_roles = new WP_Roles();
$wp_roles->roles['administrator']['name'] = 'Leadbox Admin';
$wp_roles->role_names['administrator'] = 'Leadbox Admin';
$wp_roles->roles['editor']['name'] = 'Dealer Marketing';
$wp_roles->role_names['editor'] = 'Dealer Marketing';
}
add_action('admin_init', 'wps_change_role_name');
function leadbox_new_role()
{
// add the new user role
add_role(
'dealer-admin',
'Dealer Admin',
array(
'upload_files' => true,
'read' => true,
'edit_posts' => true,
'delete_posts' => true,
'delete_others_posts' =>true,
'delete_published_posts' => true,
'publish_posts' => true,
'read_page' => true,
'read_pages' => true,
'read_private_pages' => true,
'edit_page' => true,
'manage_categories' => true,
'edit_pages' => true,
'edit_others_pages' => true,
'edit_published_pages' => true,
'edit_published_posts' => true,
'delete_pages' => true,
'delete_others_pages' =>true,
'delete_published_pages' => true,
'publish_pages' => true,
'smartslider' => true,
'smartslider_config' => true,
'smartslider_edit' => true,
'smartslider_delete' => true,
'pixelyoursite' => true,
'manage_pys' => true,
'manage_options' => true,
'switch_themes' => true,
'edit_theme_options' => true,
'create_users' => true,
'delete_users' => true,
'list_users' => true,
'promote_users' => true,
'edit_others_posts' => true,
'moderate_comments' => false,
'import' => false,
'menus' => true,
'widgets' => true,
'wpseo_manage_options' => true,
'wpseo_dashboard' => true,
'unfiltered_html' => true,
)
);
}
add_action('admin_init', 'leadbox_new_role');
/**
* Helper function get getting roles that the user is allowed to create/edit/delete.
*
* @param WP_User $user
* @return array
*/
function wpse_188863_get_allowed_roles( $user ) {
$allowed = array();
if ( in_array( 'administrator', $user->roles ) ) { // Admin can edit all roles
$allowed = array_keys( $GLOBALS['wp_roles']->roles );
} elseif ( in_array( 'dealer-admin', $user->roles ) ) {
$allowed[] = 'dealer-admin';
$allowed[] = 'editor';
}
return $allowed;
}
/**
* Remove roles that are not allowed for the current user role.
*/
function wpse_188863_editable_roles( $roles ) {
if ( $user = wp_get_current_user() ) {
$allowed = wpse_188863_get_allowed_roles( $user );
foreach ( $roles as $role => $caps ) {
if ( ! in_array( $role, $allowed ) )
unset( $roles[ $role ] );
}
}
return $roles;
}
add_filter( 'editable_roles', 'wpse_188863_editable_roles' );
/**
* Prevent users deleting/editing users with a role outside their allowance.
*/
function wpse_188863_map_meta_cap( $caps, $cap, $user_ID, $args ) {
if ( ( $cap === 'edit_user' || $cap === 'delete_user' ) && $args ) {
$the_user = get_userdata( $user_ID ); // The user performing the task
$user = get_userdata( $args[0] ); // The user being edited/deleted
if ( $the_user && $user && $the_user->ID != $user->ID /* User can always edit self */ ) {
$allowed = wpse_188863_get_allowed_roles( $the_user );
if ( array_diff( $user->roles, $allowed ) ) {
// Target user has roles outside of our limits
$caps[] = 'not_allowed';
}
}
}
return $caps;
}
add_filter( 'map_meta_cap', 'wpse_188863_map_meta_cap', 10, 4 );
function add_admin_caps() {
$role = get_role( 'administrator');
$role->add_cap('leadbox_settings');
$role->add_cap('smartslider');
$role->add_cap('smartslider_config');
$role->add_cap('smartslider_edit');
$role->add_cap('smartslider_delete');
$role->add_cap('menus');
}
add_action( 'admin_init', 'add_admin_caps');
function add_dealer_marketing_caps() {
$role = get_role( 'editor');
$role->add_cap('menus');
$role->add_cap('manage_options');
$role->add_cap('wpseo_manage_options');
$role->add_cap('wpseo_dashboard');
$role->add_cap('smartslider');
$role->add_cap('smartslider_config');
$role->add_cap('smartslider_edit');
$role->add_cap('smartslider_delete');
}
add_action( 'admin_init', 'add_dealer_marketing_caps');
function remove_user_role_menus()
{
$roles = wp_get_current_user()->roles;
if (in_array('editor', $roles)) {
remove_menu_page('admin.php?page=stackable');
remove_menu_page('admin.php?page=ninja-forms');
remove_menu_page('edit-comments.php');
remove_menu_page('tools.php');
}
}
add_action('admin_menu', 'remove_user_role_menus', 9999);
function rewrites()
{
// vdp rewrite
//add_rewrite_rule('test-model/([^/]+)/?$', 'index.php?pagename=test-model&model_string=$matches[1]', 'top');
add_rewrite_rule('forme/([A-Za-z-]+)/?$', 'index.php?pagename=forme&form_id=$matches[1]', 'top');
add_rewrite_rule(
'forme/([A-Za-z-]+)/([0-9]+)/?$',
'index.php?pagename=forme&form_id=$matches[1]&vehicle_id=$matches[2]&from=vls',
'top'
);
add_rewrite_rule('form/([A-Za-z-]+)/?$', 'index.php?pagename=form&form_id=$matches[1]', 'top');
add_rewrite_rule(
'form/([A-Za-z-]+)/([0-9]+)/?$',
'index.php?pagename=form&form_id=$matches[1]&vehicle_id=$matches[2]&from=vls',
'top'
);
add_rewrite_rule('view/([^/]+)/?$', 'index.php?pagename=view&vdp_string=$matches[1]', 'top');
add_rewrite_rule('model/([^/]+)/?$', 'index.php?pagename=model&model_string=$matches[1]', 'top');
add_rewrite_rule('model-vue/([^/]+)/?$', 'index.php?pagename=model-vue&model_string=$matches[1]', 'top');
add_rewrite_rule('modele/([^/]+)/?$', 'index.php?pagename=modele&model_string=$matches[1]', 'top');
add_rewrite_rule('showroom/([^/]+)/?$', 'index.php?pagename=showroom&model_string=$matches[1]', 'top');
add_rewrite_rule('salle-de-montre/([^/]+)/?$', 'index.php?pagename=salle-de-montre&model_string=$matches[1]', 'top');
add_rewrite_rule('new/([A-Za-zÀ-ÿ0-9/.,-_]+)/?$', 'index.php?pagename=new&search_string=$matches[1]', 'top');
add_rewrite_rule('neufs/([A-Za-zÀ-ÿ0-9/.,-_]+)/?$', 'index.php?pagename=neufs&model_string=$matches[1]', 'top');
add_rewrite_rule('view-print/([^/]+)/?$', 'index.php?pagename=view-print&vdp_string=$matches[1]', 'top');
add_rewrite_rule('vue/([^/]+)/?$', 'index.php?pagename=vue&vdp_string=$matches[1]', 'top');
add_rewrite_rule('vue-imprimer/([^/]+)/?$', 'index.php?pagename=vue-imprimer&vdp_string=$matches[1]', 'top');
add_rewrite_rule('search/([A-Za-zÀ-ÿ0-9/.,-_]+)/?$', 'index.php?pagename=search&search_string=$matches[1]', 'top');
add_rewrite_rule('recherche/([A-Za-zÀ-ÿ0-9/.,-_]+)/?$', 'index.php?pagename=recherche&search_string=$matches[1]', 'top');
add_rewrite_rule('build-and-price/([A-Za-zÀ-ÿ0-9/.,-_]+)/?$', 'index.php?pagename=build-and-price&search_string=$matches[1]', 'top');
$pages = get_pages();
// Sort by depth: parents first, children last.
// Since 'top' prepends rules, children added last end up with higher priority.
usort($pages, function($a, $b) {
return count(get_post_ancestors($a->ID)) - count(get_post_ancestors($b->ID));
});
foreach ( $pages as $page ) {
if ( has_block( 'leadbox/inventory-block',$page ) ) {
$page_name = get_page_uri($page->ID);
// Filter rule requires at least two URL segments (key/value pair like status/demo/).
// Single segments like "corvette" won't match, so child page URLs fall through
// to WordPress native page routing instead of being captured as filters.
add_rewrite_rule($page_name.'/([A-Za-zÀ-ÿ0-9._-]+/[A-Za-zÀ-ÿ0-9/.,-_]+)/?$', 'index.php?pagename='.$page_name.'&search_string=$matches[1]', 'top');
}
}
// Auto-heal: if stored rewrite rules are missing the dynamic inventory rules, flush.
// This fixes rules lost when other plugins update or WP flushes independently.
$stored_rules = get_option('rewrite_rules', []);
if (is_array($stored_rules) && !empty($stored_rules)) {
$needs_flush = false;
foreach ($pages as $page) {
if (has_block('leadbox/inventory-block', $page)) {
$page_name = get_page_uri($page->ID);
$rule_key = $page_name . '/([A-Za-zÀ-ÿ0-9._-]+/[A-Za-zÀ-ÿ0-9/.,-_]+)/?$';
if (!isset($stored_rules[$rule_key])) {
$needs_flush = true;
break;
}
}
}
if ($needs_flush) {
flush_rewrite_rules();
}
}
}
add_action('init', 'rewrites');
add_action('template_redirect', function () {
// Soporta tanto 'form' (inglés) como 'forme' (francés)
$is_form_page = is_page('form');
$is_forme_page = is_page('forme');
if (!$is_form_page && !$is_forme_page) return;
$form = get_query_var('form_id') ?: (isset($_GET['form_id']) ? sanitize_title($_GET['form_id']) : '');
$veh_id = get_query_var('vehicle_id') ?: (isset($_GET['vehicle_id']) ? intval($_GET['vehicle_id']) : 0);
// Determinar la ruta base según el idioma de la página actual
$base_path = $is_forme_page ? 'forme' : 'form';
// Si viene con ?vehicle_id=… y aún no está en formato /{form|forme}/{form_id}/{vehicle_id}/, redirige
if ($form && $veh_id) {
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?: '';
$pretty = "/{$base_path}/{$form}/{$veh_id}/";
if ($path !== $pretty) {
$target = home_url($pretty);
if (trailingslashit($path) !== trailingslashit(parse_url($target, PHP_URL_PATH))) {
wp_safe_redirect($target, 301);
exit;
}
}
}
}, 0);
function query_vars($query_vars)
{
$query_vars[] = 'form_id';
$query_vars[] = 'vehicle_id';
$query_vars[] = 'vdp_string';
$query_vars[] = 'vehicles';
$query_vars[] = 'search_string';
return $query_vars;
}
add_filter('query_vars', 'query_vars');
add_filter('ninja_forms_render_default_value', function ($default_value, $field_type, $field_settings) {
if (isset($field_settings['key']) && ($field_settings['key'] === 'vehicleid' || $field_settings['key'] === 'vehicle_id')) {
$veh = get_query_var('vehicle_id');
if (!empty($veh)) {
$veh = preg_replace('/\D+/', '', $veh);
if ($veh !== '') {
return $veh;
}
}
}
return $default_value;
}, 99, 3);
function leadbox_flush_rewrites_on_update($upgrader_object, $options) {
if ($options['action'] == 'update' && $options['type'] == 'plugin') {
if (!empty($options['plugins'])) {
foreach ($options['plugins'] as $plugin) {
// Verificar si es el plugin Leadbox (funciona con cualquier nombre de carpeta)
if (strpos($plugin, 'Leadbox.php') !== false) {
rewrites();
flush_rewrite_rules();
}
}
}
}
}
add_action('upgrader_process_complete', 'leadbox_flush_rewrites_on_update', 10, 2);
function web_report_options_panel()
{
add_menu_page('Theme page title', 'Web reports', 'manage_options', 'web-report-options', 'wps_theme_func');
}
add_action('admin_menu', 'web_report_options_panel');
function wps_theme_func()
{
$web_report_options = get_option('leadbox-settings');
echo '<div class="wrap"><div id="icon-options-general" class="icon32"><br></div>
<h2>Web reports</h2></div>
<iframe src="' . $web_report_options["report_url"] . '" style="width: 90%; height: 600px;"></iframe>';
}
function wordpress_custom_login_logo()
{
echo '<style type="text/css">' .
'h1 a {
background-image:url(' . dirname(plugin_dir_url(__FILE__)) . '/assets/logo.png) !important;
height: 100px !important;
width: 100% !important;
background-size:100% !important;
line-height:inherit !important;
}' .
'</style>';
}
add_action('login_head', 'wordpress_custom_login_logo');
function custom_admin_logo()
{
echo '
<style type="text/css">
#wp-admin-bar-wp-logo .ab-icon:before {
content:"" !important;
}
#wpadminbar > #wp-toolbar > #wp-admin-bar-root-default > #wp-admin-bar-wp-logo .ab-icon {
background-image: url(' . dirname(plugin_dir_url(__FILE__)) . '/assets/logo.png) !important;
background-size: contain;
background-repeat: no-repeat;
width: 150px;
height: 15px;
padding: 4px 0;
margin: 4px 0;
}
</style>
';
}
add_action('admin_head', 'custom_admin_logo');
function remove_simple_staff_member_widget(){
echo '
<style>
.sslp-widget {
display: none !important;
}
</style>
';
}
add_action('admin_head', 'remove_simple_staff_member_widget');
function unique($array) {
if (!is_array($array)) {
return [];
}
return array_values(array_unique($array));
}
function get_fileInGenius($route) {
$childRoute = get_stylesheet_directory();
$childRoute = str_replace("/resources","",$childRoute );
//var_dump($childRoute);
$parentRoute = get_template_directory();
//var_dump($parentRoute);
if(file_exists($childRoute . $route)) {
return $childRoute;
}
return $parentRoute;
}
function set_genius()
{
/**
* This code is responsible for retrieving the 'genius' option from the 'leadbox-settings' and setting it as a constant.
* TODO: I'll be back here later
* Author: Leo
*/
/* $geniusFromOptions = get_option('leadbox-settings')['genius'];
if ($geniusFromOptions) {
$valid_genius = stripslashes($geniusFromOptions);
$final_genius = json_decode($valid_genius, true);
define('GENIUS', $final_genius);
return;
} */
$jsonPath = get_fileInGenius('/resources/config/genius.json');
$genius = file_exists("{$jsonPath}/resources/config/genius.json")
? json_decode(file_get_contents( $jsonPath . '/resources/config/genius.json'), true)
: [];
define('GENIUS', $genius);
}
add_action('init', 'set_genius');
function get_used_finance_file() {
$route = '/resources/config/used-finance.json';
$jsonPath = get_fileInGenius($route);
//var_dump( $jsonPath . $route);
return json_decode(file_get_contents( $jsonPath . $route), true);
}
function get_new_finance_file() {
$lbsettings = get_option('leadbox-settings');
if (!isset($lbsettings['new_finance_lease_option']) || $lbsettings['new_finance_lease_option'] !== 'enabled')
return null;
$route = '/resources/config/new-finance.json';
$potentialRoutes = [
get_stylesheet_directory(),
get_template_directory(),
];
foreach ($potentialRoutes as $path) {
$path = str_replace("/resources","",$path);
$fullPath = $path . $route;
if (file_exists($fullPath)) {
return json_decode(file_get_contents($fullPath), true);
}
}
return null;
}