Commit inicial - WordPress Análisis de Precios Unitarios

- WordPress core y plugins
- Tema Twenty Twenty-Four configurado
- Plugin allow-unfiltered-html.php simplificado
- .gitignore configurado para excluir wp-config.php y uploads

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2025-11-03 21:04:30 -06:00
commit a22573bf0b
24068 changed files with 4993111 additions and 0 deletions

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,469 @@
<?php
/**
* Class BWFAN_AJAX_Controller
* Handles All the request came from front end or the backend
*/
abstract class BWFAN_AJAX_Controller {
public static function init() {
/**
* Run on front end backend
*/
add_action( 'wp_ajax_bwfan_update_automation', array( __CLASS__, 'update_automation' ) );
add_action( 'wp_ajax_bwfan_toggle_automation_state', array( __CLASS__, 'toggle_automation_state' ) );
add_action( 'wp_ajax_bwfan_select2ajax', array( __CLASS__, 'bwfan_select2ajax' ) );
add_action( 'wp_ajax_bwfan_show_email_preview', array( __CLASS__, 'bwfan_save_temporary_preview_data' ) );
add_action( 'wp_ajax_bwfan_test_email', array( __CLASS__, 'test_email' ) );
add_action( 'wp_ajax_bwfan_test_sms', array( __CLASS__, 'test_sms' ) );
add_action( 'wp_ajax_bwfan_automation_submit', array( __CLASS__, 'handle_automation_post_submit' ) );
}
public static function bwfan_select2ajax() {
$callback = apply_filters( 'bwfan_select2_ajax_callable', '', $_POST ); //phpcs:ignore WordPress.Security.NonceVerification
if ( ! is_callable( $callback ) ) {
wp_send_json( [] );
}
$items = call_user_func( $callback, sanitize_text_field( $_POST['search_term']['term'] ) );//phpcs:ignore WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput
wp_send_json( $items );
}
/**
* Runs when an automation is saved from single automation screen.
* @throws Exception
*/
public static function handle_automation_post_submit() {
BWFAN_Common::check_nonce();
//phpcs:disable WordPress.Security.NonceVerification
if ( ! isset( $_POST['automation_id'] ) && empty( $_POST['automation_id'] ) ) { //phpcs:ignore WordPress.Security.ValidatedSanitizedInput
return;
}
$automation_id = $_POST['automation_id']; //phpcs:ignore WordPress.Security.ValidatedSanitizedInput
$a_track_id = ( isset( $_POST['a_track_id'] ) && ! empty( $_POST['a_track_id'] ) ) ? $_POST['a_track_id'] : 0; //phpcs:ignore WordPress.Security.ValidatedSanitizedInput
$t_to_delete = ( isset( $_POST['t_to_delete'] ) && ! empty( $_POST['t_to_delete'] ) ) ? stripslashes( $_POST['t_to_delete'] ) : null; //phpcs:ignore WordPress.Security.ValidatedSanitizedInput
//make sure following is in array just like following
$data = stripslashes( $_POST['data'] ); //phpcs:ignore WordPress.Security.ValidatedSanitizedInput
$data = json_decode( $data, true );
$actions = ( isset( $data['actions'] ) && is_array( $data['actions'] ) ) ? $data['actions'] : [];
/** Make actions array if not */
if ( ! array( $actions ) ) {
$actions = [];
}
foreach ( $actions as $group_id => $action_data ) {
if ( null === $action_data ) {
continue;
}
$actions[ $group_id ] = BWFAN_Common::remove_back_slash_from_automation( $action_data );
}
$actions = BWFAN_Common::sort_actions( $actions );
/** Validate action data before save - unset temp_action_slug as of no use */
$actions = BWFAN_Common::validate_action_date_before_save( $actions );
$ui = stripslashes( $_POST['ui'] ); //phpcs:ignore WordPress.Security.ValidatedSanitizedInput
$ui = json_decode( $ui, true );
$uiData = stripslashes( $_POST['uiData'] ); //phpcs:ignore WordPress.Security.ValidatedSanitizedInput
$uiData = json_decode( $uiData, true );
$automation_data = [];
$automation_data['event'] = $data['trigger']['event'];
$automation_data['source'] = $data['trigger']['source'];
$where = [];
$where['ID'] = $automation_id;
BWFAN_Model_Automations::update( $automation_data, $where );
BWFAN_Core()->automations->set_automation_data( 'event', $data['trigger']['event'] );
BWFAN_Core()->automations->set_automation_data( 'source', $data['trigger']['source'] );
$automation_meta_data = [];
$automation_meta_data['condition'] = [];
if ( isset( $data['condition'] ) ) {
$automation_meta_data['condition'] = $data['condition'];
}
$automation_meta_data['actions'] = $actions;
$automation_meta_data['event_meta'] = ( isset( $data['trigger']['event_meta'] ) ) ? $data['trigger']['event_meta'] : [];
$automation_meta_data['ui'] = $ui;
$automation_meta_data['uiData'] = $uiData;
$automation_meta_data['a_track_id'] = $a_track_id;
$automation_meta = BWFAN_Model_Automationmeta::get_automation_meta( $automation_id );
$db_a_track_id = BWFAN_Model_Automationmeta::get_meta( $automation_id, 'a_track_id' );
/** For saving subject of send email action of automation meta for tracking purpose */
do_action( 'bwfan_automation_email_tracking_post_data', $automation_id, $automation_meta, $automation_meta_data['actions'], $db_a_track_id );
/** Update automation meta */
foreach ( $automation_meta_data as $meta_key => $meta_value ) {
$meta_value = maybe_serialize( $meta_value );
BWFAN_Core()->automations->set_automation_data( $meta_key, $meta_value );
$where = [];
$update_data = [
'bwfan_automation_id' => $automation_id,
'meta_key' => $meta_key,
'meta_value' => $meta_value,
];
if ( array_key_exists( $meta_key, $automation_meta ) ) {
// Update Meta
$where['bwfan_automation_id'] = $automation_id;
$where['meta_key'] = $meta_key;
}
if ( count( $where ) > 0 ) {
BWFAN_Model_Automationmeta::update( $update_data, $where );
} else {
BWFAN_Model_Automationmeta::insert( $update_data );
}
}
/** Update the modified date of automation */
$meta_data = array(
'meta_value' => current_time( 'mysql', 1 ),
);
$where = array(
'bwfan_automation_id' => $automation_id,
'meta_key' => 'm_date',
);
BWFAN_Model_Automationmeta::update( $meta_data, $where );
BWFAN_Core()->automations->set_automation_data( 'm_date', $meta_data['meta_value'] );
BWFAN_Core()->automations->set_automation_data( 'run_count', isset( $automation_meta['run_count'] ) ? $automation_meta['run_count'] : 0 );
// Update requires_update key to 0 on update which implies that user has verified and saved the automation
$meta_data = array(
'meta_value' => 0,
);
$where = array(
'bwfan_automation_id' => $automation_id,
'meta_key' => 'requires_update',
);
BWFAN_Model_Automationmeta::update( $meta_data, $where );
BWFAN_Core()->automations->set_automation_data( 'requires_update', 0 );
BWFAN_Core()->automations->set_automation_id( $automation_id );
do_action( 'bwfan_automation_saved', $automation_id );
// Send async call to delete all the tasks except for completed tasks (actually logs)
if ( ! is_null( $t_to_delete ) ) {
$url = rest_url( '/autonami/v1/delete-tasks' );
$body_data = array(
'automation_id' => $automation_id,
'a_track_id' => $db_a_track_id,
't_to_delete' => $t_to_delete,
'unique_key' => get_option( 'bwfan_u_key', false ),
);
$args = bwf_get_remote_rest_args( $body_data );
wp_remote_post( $url, $args );
}
$resp = array(
'id' => $automation_id,
'status' => true,
'msg' => __( 'Automation Updated', 'wp-marketing-automations' ),
);
wp_send_json( $resp );
//phpcs:enable WordPress.Security.NonceVerification
}
/**
* Runs when the title of the automation is updated from single automation screen.
*/
public static function update_automation() {
BWFAN_Common::check_nonce();
$resp = array(
'msg' => 'automation not found',
'status' => false,
);
if ( ! isset( $_POST['automation_id'] ) || empty( $_POST['automation_id'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification
wp_send_json( $resp );
}
$automation_id = sanitize_text_field( $_POST['automation_id'] ); //phpcs:ignore WordPress.Security.NonceVerification
$where = [
'bwfan_automation_id' => $automation_id,
];
$meta = array();
$where['meta_key'] = 'm_date';
$meta['meta_key'] = 'm_date';
$meta['meta_value'] = current_time( 'mysql', 1 );
BWFAN_Model_Automationmeta::update( $meta, $where );
$where['meta_key'] = 'title';
$meta['meta_key'] = 'title';
$meta['meta_value'] = sanitize_text_field( stripslashes( $_POST['title'] ) ); //phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput
BWFAN_Model_Automationmeta::update( $meta, $where );
$resp['msg'] = __( 'Automation Successfully Updated', 'wp-marketing-automations' );
$resp['status'] = true;
$resp['automation_name'] = sanitize_text_field( stripslashes( $_POST['title'] ) ); //phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput
BWFAN_Core()->automations->set_automation_id( $automation_id );
do_action( 'bwfan_automation_saved', $automation_id );
wp_send_json( $resp );
}
/**
* Runs when automation is activated/deactivated
*/
public static function toggle_automation_state() {
BWFAN_Common::check_nonce();
$resp = array(
'msg' => '',
'status' => true,
);
// phpcs:disable WordPress.Security.NonceVerification
if ( empty( $_POST['id'] ) ) {
$resp = array(
'msg' => 'Automation ID is missing',
'status' => false,
);
wp_send_json( $resp );
}
$automation_id = sanitize_text_field( $_POST['id'] );
$automation = array();
$automation['status'] = 2;
if ( isset( $_POST['state'] ) && 'true' === $_POST['state'] ) {
$automation['status'] = 1;
}
BWFAN_Core()->automations->toggle_state( $automation_id, $automation );
//phpcs:enable WordPress.Security.NonceVerification
wp_send_json( $resp );
}
public static function is_wfocu_front_ajax() {
if ( defined( 'DOING_AJAX' ) && true === DOING_AJAX && null !== filter_input( INPUT_POST, 'action' ) && false !== strpos( filter_input( INPUT_POST, 'action' ), 'wfocu_front' ) ) {
return true;
}
return false;
}
/**
* Runs when `preview` option is clicked in email action. It temporarily saved data in options table.
*/
public static function bwfan_save_temporary_preview_data() {
BWFAN_Common::check_nonce();
//phpcs:disable WordPress.Security.NonceVerification
$automation_id = sanitize_text_field( $_POST['automation_id'] );
if ( absint( $automation_id ) < 1 ) {
wp_send_json( array(
'status' => false,
) );
}
$post = $_POST;
$post['data']['to'] = stripslashes( sanitize_text_field( $post['data']['to'] ) );
$post['data']['subject'] = stripslashes( sanitize_text_field( $post['data']['subject'] ) );
$post['data']['body'] = stripslashes( $post['data']['body'] );//phpcs:ignore WordPress.Security.ValidatedSanitizedInput
$post['data']['body_raw'] = stripslashes( $post['data']['body_raw'] );//phpcs:ignore WordPress.Security.ValidatedSanitizedInput
$meta = array();
$meta['meta_key'] = 'email_preview';
$meta['meta_value'] = maybe_serialize( $post );
$current_data = BWFAN_Model_Automationmeta::get_meta( $automation_id, 'email_preview' );
if ( false === $current_data ) {
$meta['bwfan_automation_id'] = $automation_id;
BWFAN_Model_Automationmeta::insert( $meta );
} else {
$where = [
'bwfan_automation_id' => $automation_id,
'meta_key' => 'email_preview',
];
BWFAN_Model_Automationmeta::update( $meta, $where );
}
//phpcs:enable WordPress.Security.NonceVerification
wp_send_json( array(
'status' => true,
) );
}
public static function test_email() {
BWFAN_Common::check_nonce();
// phpcs:disable WordPress.Security.NonceVerification
/** Check if user has manage_options permission */
if ( ! current_user_can( BWFAN_admin::menu_cap() ) ) {
wp_send_json( array(
'status' => false,
'msg' => __( 'You are not authorized to perform this action', 'wp-marketing-automations' ),
) );
}
$result = array(
'status' => false,
'msg' => __( 'Error', 'wp-marketing-automations' ),
);
if ( ! isset( $_POST['email'] ) || ! filter_var( $_POST['email'], FILTER_VALIDATE_EMAIL ) ) {
$result['msg'] = __( 'Email not valid', 'wp-marketing-automations' );
wp_send_json( $result );
}
$post = $_POST;
$automation_id = sanitize_text_field( $post['automation_id'] );
if ( absint( $automation_id ) < 1 ) {
$result['msg'] = __( 'Automation ID missing', 'wp-marketing-automations' );
$result['status'] = false;
wp_send_json( $result );
}
$post['data']['to'] = sanitize_email( $post['email'] );
$post['data']['subject'] = isset( $post['data']['subject'] ) && ! empty( $post['data']['subject'] ) ? stripslashes( $post['data']['subject'] ) : __( 'This is a fake subject line, enter subject to fix it', 'wp-marketing-automations' );
$post['data']['preheading'] = isset( $post['data']['preheading'] ) ? stripslashes( $post['data']['preheading'] ) : '';
$post['data']['body'] = stripslashes( $post['data']['body'] );//phpcs:ignore WordPress.Security.ValidatedSanitizedInput
$post['data']['body_raw'] = stripslashes( $post['data']['body_raw'] );//phpcs:ignore WordPress.Security.ValidatedSanitizedInput
if ( isset( $post['data']['editor'] ) ) {
$post['data']['editor']['body'] = stripslashes( $post['data']['editor']['body'] );//phpcs:ignore WordPress.Security.ValidatedSanitizedInput
$post['data']['editor']['design'] = stripslashes( $post['data']['editor']['design'] );//phpcs:ignore WordPress.Security.ValidatedSanitizedInput
}
$meta = array();
$meta['meta_key'] = 'email_preview';
$meta['meta_value'] = maybe_serialize( $post );
$current_data = BWFAN_Model_Automationmeta::get_meta( $automation_id, 'email_preview' );
if ( false === $current_data ) {
$meta['bwfan_automation_id'] = $automation_id;
BWFAN_Model_Automationmeta::insert( $meta );
} else {
$where = [
'bwfan_automation_id' => $automation_id,
'meta_key' => 'email_preview',
];
BWFAN_Model_Automationmeta::update( $meta, $where );
}
BWFAN_Merge_Tag_Loader::set_data( array(
'is_preview' => true,
'test_email' => $post['email'],
) );
$post['event_data']['event_slug'] = $post['event'];
$action_object = BWFAN_Core()->integration->get_action( 'wp_sendemail' );
$action_object->is_preview = true;
$data_to_set = $action_object->make_data( '', $post );
$data_to_set['test'] = true;
$action_object->set_data( $data_to_set );
$response = $action_object->send_email();
if ( true === $response ) {
$result['msg'] = __( 'Test email sent.', 'wp-marketing-automations' );
$result['status'] = true;
} elseif ( is_array( $response ) && isset( $response['message'] ) ) {
$result['msg'] = $response['message'];
$result['status'] = false;
} else {
$result['msg'] = __( 'Server does not support email facility', 'wp-marketing-automations' );
$result['status'] = false;
}
//phpcs:enable WordPress.Security.NonceVerification
wp_send_json( $result );
}
public static function test_sms() {
BWFAN_Common::check_nonce();
/** If FKA pro is not active */
if ( ! bwfan_is_autonami_pro_active() ) {
return array(
'status' => false,
'msg' => __( 'FunnelKit Automations Pro is not active', 'wp-marketing-automations' ),
);
}
// phpcs:disable WordPress.Security.NonceVerification
$result = array(
'status' => false,
'msg' => __( 'Error', 'wp-marketing-automations' ),
);
if ( ! isset( $_POST['data']['sms_to'] ) && ! isset( $_POST['test_sms_to'] ) ) {
$result['msg'] = __( 'Phone number can\'t be blank', 'wp-marketing-automations' );
wp_send_json( $result );
}
$post = $_POST;
$mediaUrl = '';
if ( isset( $post['v'] ) && 2 === absint( $post['v'] ) ) {
$sms_to = $post['test_sms_to'];
$sms_body = isset( $post['sms_body'] ) ? stripslashes( $post['sms_body'] ) : '';
$sms_provider = isset( $post['sms_provider'] ) ? $post['sms_provider'] : '';
} else {
$sms_to = $post['data']['sms_to'];
$sms_body = isset( $post['data']['sms_body'] ) ? stripslashes( $post['data']['sms_body'] ) : '';
$sms_provider = isset( $post['data']['sms_provider'] ) ? $post['data']['sms_provider'] : '';
}
/** Append UTM parameters */
if ( class_exists( 'BWFAN_UTM_Tracking' ) ) {
$utm = BWFAN_UTM_Tracking::get_instance();
if ( version_compare( BWFAN_PRO_VERSION, '2.0.4', '>' ) ) {
$sms_body = $utm->maybe_add_utm_parameters( $sms_body, $post, 'sms' );
} else {
$sms_body = $utm->maybe_add_utm_parameters( $sms_body, $post );
}
}
/** Media handling */
if ( ! empty( $post['data']['attach_custom_img'] ) ) {
$img = stripslashes( $post['data']['attach_custom_img'] );
$img = json_decode( $img, true );
if ( is_array( $img ) && count( $img ) > 0 ) {
$mediaUrl = $img[0];
}
}
// is_preview set to true for merge tag before sending data for sms;
BWFAN_Merge_Tag_Loader::set_data( array(
'is_preview' => true,
) );
$sms_body = BWFAN_Common::decode_merge_tags( $sms_body );
$send_sms_result = BWFCRM_Common::send_sms( array(
'to' => $sms_to,
'body' => $sms_body,
'is_test' => true,
'image_url' => $mediaUrl,
'sms_provider' => $sms_provider
) );
if ( $send_sms_result instanceof WP_Error ) {
wp_send_json( array(
'status' => false,
'msg' => $send_sms_result->get_error_message(),
) );
}
$message = __( 'SMS sent successfully', 'wp-marketing-automations' );
wp_send_json( array(
'status' => true,
'msg' => $message,
) );
}
}
BWFAN_AJAX_Controller::init();

View File

@@ -0,0 +1,213 @@
<?php
#[AllowDynamicProperties]
abstract class BWFAN_API_Base {
/**
* @var string $route
*/
public $route = null;
/**
* @var string $method
*/
public $method = null;
/**
* @var stdClass $pagination
*
* It contains two keys: Limit and Offset, for pagination purposes
*/
public $pagination = null;
public $response_code = 200;
public $args = array();
public $request_args = array();
public $public_api = false;
public function __construct() {
$this->pagination = new stdClass();
$this->pagination->limit = 0;
$this->pagination->offset = 0;
}
public function api_call( WP_REST_Request $request ) {
BWFAN_Common::nocache_headers();
$params = WP_REST_Server::EDITABLE === $this->method ? $request->get_params() : false;
if ( false === $params ) {
$query_params = $request->get_query_params();
$query_params = is_array( $query_params ) ? $query_params : array();
$request_params = $request->get_params();
$request_params = is_array( $request_params ) ? $request_params : array();
$params = array_replace( $query_params, $request_params );
}
if ( isset( $params['content'] ) && ! empty( $params['content'] ) && is_string( $params['content'] ) ) {
$replace_array = BWFAN_Common::get_mail_replace_string();
if ( ! empty( $replace_array ) ) {
$params['content'] = str_replace( array_values( $replace_array ), array_keys( $replace_array ), $params['content'] );
}
}
$params['files'] = $request->get_file_params();
$this->pagination->limit = ! empty( $params['limit'] ) ? absint( $params['limit'] ) : $this->pagination->limit;
$this->pagination->offset = ! empty( $params['offset'] ) ? absint( $params['offset'] ) : 0;
$this->args = wp_parse_args( $params, $this->default_args_values() );
try {
return $this->process_api_call();
} catch ( Error $e ) {
$this->response_code = 500;
return $this->error_response( $e->getMessage() );
}
}
public function default_args_values() {
return array();
}
/** To be implemented in Child Class. Override in Child Class */
public function get_result_total_count() {
return 0;
}
/** To set count data */
public function get_result_count_data() {
return 0;
}
public function error_response( $message = '', $wp_error = null, $code = 0 ) {
if ( 0 !== absint( $code ) ) {
$this->response_code = $code;
}
$data = array();
if ( $wp_error instanceof WP_Error ) {
$message = $wp_error->get_error_message();
$data = $wp_error->get_error_data();
}
return new WP_Error( $this->response_code, $message, array( 'status' => $this->response_code, 'error_data' => $data ) );
}
public function error_response_200( $message = '', $wp_error = null, $code = 0 ) {
if ( 0 !== absint( $code ) ) {
$this->response_code = $code;
} else if ( empty( $this->response_code ) ) {
$this->response_code = 500;
}
$data = array();
if ( $wp_error instanceof WP_Error ) {
$message = $wp_error->get_error_message();
$data = $wp_error->get_error_data();
}
return new WP_Error( $this->response_code, $message, array( 'status' => 200, 'error_data' => $data ) );
}
public function success_response( $result_array, $message = '' ) {
$response = BWFAN_Common::format_success_response( $result_array, $message, $this->response_code );
/** Total Count */
$total_count = $this->get_result_total_count();
if ( ! empty( $total_count ) ) {
$response['total_count'] = $total_count;
}
/** Count Data */
$count_data = $this->get_result_count_data();
if ( ! empty( $count_data ) ) {
$response['count_data'] = $count_data;
}
/** Pagination */
if ( isset( $this->pagination->limit ) && ( 0 === $this->pagination->limit || ! empty( $this->pagination->limit ) ) ) {
$response['limit'] = absint( $this->pagination->limit );
}
if ( isset( $this->pagination->offset ) && ( 0 === $this->pagination->offset || ! empty( $this->pagination->offset ) ) ) {
$response['offset'] = absint( $this->pagination->offset );
}
return rest_ensure_response( $response );
}
/**
* @param string $key
* @param string $is_a
* @param string $collection
*
* @return bool|array|mixed
*/
public function get_sanitized_arg( $key = '', $is_a = 'key', $collection = '' ) {
$sanitize_method = ( 'bool' === $is_a ? 'rest_sanitize_boolean' : 'sanitize_' . $is_a );
if ( ! is_array( $collection ) ) {
$collection = $this->args;
}
if ( ! empty( $key ) && isset( $collection[ $key ] ) && ! empty( $collection[ $key ] ) ) {
return call_user_func( $sanitize_method, $collection[ $key ] );
}
if ( ! empty( $key ) ) {
return false;
}
return array_map( $sanitize_method, $collection );
}
/**
* rest api permission callback
*
* @return bool
*/
public function rest_permission_callback( WP_REST_Request $request ) {
$permissions = BWFAN_Common::access_capabilities();
foreach ( $permissions as $permission ) {
if ( current_user_can( $permission ) ) {
return true;
}
}
return false;
}
abstract public function process_api_call();
/**
* @param $id_key
* @param $email_key
*
* @return BWFCRM_Contact|WP_Error
*/
public function get_contact_by_id_or_email( $id_key, $email_key ) {
$email = $this->get_sanitized_arg( $email_key, 'text_field' );
$id = $this->get_sanitized_arg( $id_key, 'text_field' );
$id_or_email = ( is_numeric( $id ) && absint( $id ) > 0 ? absint( $id ) : ( is_email( $email ) ? $email : '' ) );
$contact = new BWFCRM_Contact( $id_or_email, true );
if ( ! $contact->is_contact_exists() ) {
$this->response_code = 404;
if ( is_numeric( $id_or_email ) ) {
$response = __( 'Unable to get contact with contact ID : ', 'wp-marketing-automations' ) . $id_or_email;
} else {
$response = __( 'Contact not exists with email: ', 'wp-marketing-automations' ) . $id_or_email;
}
return $this->error_response( $response );
}
return $contact;
}
}

View File

@@ -0,0 +1,76 @@
<?php
#[AllowDynamicProperties]
abstract class BWFAN_Base_Step_Controller {
public $automation_data = array();
public $step_data = array();
public $action_data = array();
public $automation_contact_id = 0;
public $automation_id = 0;
public $contact_id = 0;
public $step_id = 0;
public $attempts = 0;
public $max_attempts = 0;
public $reattempt_time = 0;
public function __construct() {
$this->max_attempts = apply_filters( 'bwfan_automation_contact_max_attempts', 3 );
$this->reattempt_time = apply_filters( 'bwfan_automation_contact_reattempt_time', 30 );
}
public function populate_automation_contact_data( $db_aContact = array() ) {
if ( ! empty( $db_aContact ) && is_array( $db_aContact ) && isset( $db_aContact['ID'] ) && isset( $db_aContact['data'] ) ) {
$aContact = $db_aContact;
$this->automation_data = json_decode( $aContact['data'], true );
$this->attempts = absint( $aContact['attempts'] );
$this->contact_id = absint( $aContact['cid'] );
$this->automation_id = absint( $aContact['aid'] );
$this->automation_contact_id = absint( $aContact['ID'] );
return true;
}
if ( empty( $this->contact_id ) || empty( $this->automation_id ) ) {
return false;
}
$aContact = BWFAN_Model_Automation_Contact::get_automation_contact( $this->automation_id, $this->contact_id );
if ( ! is_array( $aContact ) || ! isset( $aContact['data'] ) ) {
return false;
}
$this->automation_contact_id = absint( $aContact['ID'] );
$this->automation_data = json_decode( $aContact['data'], true );
$this->attempts = absint( $aContact['attempts'] );
return true;
}
public function populate_step_data( $db_step = array() ) {
$step = $db_step;
if ( is_array( $db_step ) && isset( $db_step['ID'] ) ) {
$this->step_data = isset( $db_step['data'] ) ? json_decode( $db_step['data'], true ) : [];
$this->step_id = absint( $db_step['ID'] );
}
if ( empty( $this->step_id ) ) {
return false;
}
if ( empty( $this->step_data ) ) {
$step = BWFAN_Model_Automation_Step::get_step_data_by_id( $this->step_id );
if ( ! is_array( $step ) ) {
return false;
}
$this->step_data = isset( $step['data'] ) ? json_decode( $step['data'], true ) : [];
}
if ( ! empty( $step['action'] ) ) {
$this->action_data = json_decode( $step['action'], true );
}
return true;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,152 @@
<?php
namespace BWFAN\Exporter;
/**
* Calls base class
*/
abstract class Base {
/** Handle exporter response type */
public static $EXPORTER_ONGOING = 1;
public static $EXPORTER_SUCCESS = 2;
public static $EXPORTER_FAILED = 3;
public static $export_folder = BWFAN_SINGLE_EXPORT_DIR;
/**
* Exporter Type
*
* @var string
*/
protected $type = '';
/**
* Abstract function to process export action
*
* @param int $user_id
* @param int $export_id
*
* @return void
*/
abstract public function handle_export( $user_id, $export_id );
/**
* Save processed and count data in table
*
* @param array $extra_data (optional)
*
* @return array|int
*/
public function insert_data_in_table( $extra_data = [] ) {
if ( ! class_exists( 'BWFAN_Model_Import_Export' ) || ( ! file_exists( self::$export_folder ) && ! wp_mkdir_p( self::$export_folder ) ) ) {
return 0;
}
$file_name = $this->get_file_name();
if ( empty( $file_name ) ) {
return 0;
}
$meta = [ 'file' => $file_name ];
// Add extra data to meta
if ( ! empty( $extra_data ) ) {
$meta = array_merge( $meta, $extra_data );
}
$data = [
'offset' => 0,
'processed' => 0,
'type' => 3,
'status' => self::$EXPORTER_ONGOING,
'count' => 0,
'meta' => wp_json_encode( $meta ),
'created_date' => current_time( 'mysql', 1 ),
'last_modified' => current_time( 'mysql', 1 )
];
\BWFAN_Model_Import_Export::insert( $data );
$export_id = \BWFAN_Model_Import_Export::insert_id();
if ( empty( $export_id ) ) {
return 0;
}
return [
'id' => $export_id,
'file' => self::$export_folder . '/' . $file_name
];
}
/**
* Get total count
*
* @param array $data
*
* @return mixed
*/
public function get_total_count( $data = [] ) {
return 0;
}
/**
* Get export file name
*
* @return string
*/
public function get_file_name() {
return '';
}
/**
* Update offset and processed count
*
* @return void
*/
public function update_export_offset( $export_id, $offset, $processed, $count ) {
\BWFAN_Model_Import_Export::update( [
"offset" => $offset,
"processed" => $processed,
"count" => $count
], [ 'id' => absint( $export_id ) ] );
}
/**
* End export process
*
* @param $user_id
* @param $export_id
* @param $file_name
* @param $status
* @param $status_message
*
* @return void
*/
public function end_user_export( $user_id, $export_id, $file_name, $status, $status_message ) {
if ( empty( $status_message ) && $status === self::$EXPORTER_FAILED ) {
$status_message = __( 'Export error. Export ID: ', 'wp-marketing-automations' ) . $export_id;
}
$user_data = get_user_meta( $user_id, 'bwfan_single_export_status', true ) ?: [];
$user_data[ $this->type ] = [
'status' => $status,
'url' => self::$export_folder . '/' . $file_name,
'msg' => [ $status_message ]
];
update_user_meta( $user_id, 'bwfan_single_export_status', $user_data );
BWFAN_Core()->exporter->unschedule_export_action( [
'type' => $this->type,
'user_id' => $user_id,
'export_id' => $export_id
] );
$export_meta = [
'status_msg' => $status_message
];
\BWFAN_Model_Import_Export::update( [
'status' => $status,
'meta' => wp_json_encode( $export_meta )
], [ 'id' => absint( $export_id ) ] );
}
}

View File

@@ -0,0 +1,183 @@
<?php
#[AllowDynamicProperties]
abstract class BWFAN_Integration {
/**
* Return Save setting of integration
* @var array
*/
protected $integration_settings = [];
/**
* this property use for admin builder ui
* @var array
*/
protected $localize_data = [];
/**
* Return Nice Human readable name of integration
* @var null
*/
protected $nice_name = 'WordPress';
/**
* Return integration belong native WordPress or other like activecampaign
* @var bool
*/
protected $native_integration = false;
/**
* If you add new integration and have respective action then please override this property in child class
* @var string
*/
protected $action_dir = __DIR__;
/**
* Return Unique Slug of Integration
* @var string
*/
protected $slug = '';
/**
* Return used connector slug in integration
* @var string
*/
protected $connector_slug = '';
/**
* Return integration need a separate connector
* @var bool
*/
protected $need_connector = false;
protected $group_name = '';
protected $group_slug = '';
protected $priority = 10;
/**
* Loads all actions of current integration
*/
public function load_actions() {
$resource_dir = $this->action_dir . '/actions';
if ( file_exists( $resource_dir ) ) {
foreach ( glob( $resource_dir . '/class-*.php' ) as $_field_filename ) {
$file_data = pathinfo( $_field_filename );
if ( isset( $file_data['basename'] ) && 'index.php' === $file_data['basename'] ) {
continue;
}
$action_class = require_once( $_field_filename );
if ( is_string( $action_class ) && method_exists( $action_class, 'get_instance' ) ) {
/**
* @var $action_obj BWFAN_Action
*/
$action_obj = $action_class::get_instance();
$action_obj->load_hooks();
if ( method_exists( $action_obj, 'admin_enqueue_assets' ) && is_admin() && BWFAN_Common::is_automation_v1_active() && BWFAN_Common::is_autonami_page() ) {
// Add action to avoid enqueueing assets on every admin page load
add_action( 'admin_enqueue_scripts', array( $action_obj, 'admin_enqueue_assets' ), 98 );
}
$action_obj->set_integration_type( $this->get_slug() );
BWFAN_Load_Integrations::register_actions( $action_obj );
$this->do_after_action_registration( $action_obj );
}
}
}
do_action( 'bwfan_' . $this->get_slug() . '_actions_loaded', $this );
}
/**
* Get slug of an integration
* Note: Used in change_in_automations method of BWFAN_Automations class
*
* @return mixed|string
*/
public function get_slug() {
$this->slug = str_replace( array( 'bwfan_', '_integration' ), '', sanitize_title( get_class( $this ) ) );
return $this->slug;
}
protected function do_after_action_registration( BWFAN_Action $action_object ) {
}
public function get_localize_data() {
$this->localize_data = [
'nice_name' => $this->get_name(),
'slug' => $this->get_slug(),
'connector_slug' => $this->get_connector_slug(),
'native_integration' => $this->native_integration(),
'group_slug' => $this->get_group_slug(),
'group_name' => $this->get_group_name(),
'priority' => $this->get_priority()
];
return $this->localize_data;
}
public function get_name() {
return trim( $this->nice_name );
}
public function get_connector_slug() {
return $this->connector_slug;
}
public function get_group_slug() {
return $this->group_slug;
}
public function get_group_name() {
return $this->group_name;
}
public function get_priority() {
return $this->priority;
}
public function native_integration() {
return $this->native_integration;
}
public function set_settings( $data ) {
if ( is_array( $data ) ) {
$this->integration_settings = $data;
}
}
public function get_settings( $key = '' ) {
if ( ! empty( $key ) ) {
return isset( $this->integration_settings[ $key ] ) ? $this->integration_settings[ $key ] : '';
}
return $this->integration_settings;
}
public function need_connector() {
return $this->need_connector;
}
public function handle_response( $result, $connector_slug, $action_call_class_slug, $action_data = null ) {
return $result;
}
/**
* to avoid unserialize of the current class
*/
public function __wakeup() {
throw new ErrorException( 'BWFAN_Core can`t converted to string' );
}
/**
* to avoid serialize of the current class
*/
public function __sleep() {
throw new ErrorException( 'BWFAN_Core can`t converted to string' );
}
/**
* To avoid cloning of current class
*/
protected function __clone() {
}
}

View File

@@ -0,0 +1,561 @@
<?php
#[AllowDynamicProperties]
abstract class BWFAN_Merge_Tag {
public $date_formats = array(
array(
'format' => 'j M Y',
),
array(
'format' => 'jS M Y',
),
array(
'format' => 'M j Y',
),
array(
'format' => 'M jS Y',
),
array(
'format' => 'd/m/Y',
),
array(
'format' => 'd-m-Y',
),
array(
'format' => 'Y/m/d',
),
array(
'format' => 'Y-m-d',
),
array(
'format' => 'd/m/Y H:i:s',
),
array(
'format' => 'd-m-Y H:i:s',
),
array(
'format' => 'Y/m/d H:i:s',
),
array(
'format' => 'Y-m-d H:i:s',
),
array(
'format' => 'd.m.Y',
),
);
protected $support_fallback = false;
protected $support_date = false;
protected $support_modify = true;
protected $fallback = '';
protected $tag_name = '';
protected $tag_description = '';
protected $support_v2 = true;
protected $support_v1 = true;
protected $priority = 10;
protected $is_delay_variable = false;
protected $is_crm_broadcast = false;
public function get_coupon_fields() {
$time_types = array(
'days' => __( 'Days', 'wp-marketing-automations' ),
);
?>
<div class="bwfan_mtag_wrap">
<div class="bwfan_label">
<label for="" class="bwfan-label-title"><?php esc_html_e( 'Select coupon', 'wp-marketing-automations' ); ?></label>
</div>
<div class="bwfan_label_val">
<select required id="" data-search="coupon" data-search-text="<?php esc_attr_e( 'Select Coupon', 'wp-marketing-automations' ); ?>" class="bwfan-select2ajax-single bwfan-input-wrapper bwfan_tag_select" name="parent_coupon">
<option value=""><?php esc_html_e( 'Choose Coupon', 'wp-marketing-automations' ); ?></option>
</select>
</div>
</div>
<div class="bwfan_mtag_wrap">
<div class="bwfan_label">
<label for="" class="bwfan-label-title"><?php esc_html_e( 'Coupon name', 'wp-marketing-automations' ); ?></label>
</div>
<div class="bwfan_label_val">
<input required type="text" class="bwfan-input-wrapper bwfan_tag_input" name="coupon_name"/>
</div>
</div>
<div class="bwfan_mtag_wrap">
<div class="bwfan_label">
<label for="" class="bwfan-label-title"><?php esc_html_e( 'Select Expiry Type', 'wp-marketing-automations' ); ?></label>
</div>
<div class="bwfan_label_val">
<select required id="" class="bwfan-input-wrapper bwfan_tag_select" name="expiry_type">
<?php
foreach ( $time_types as $value1 => $text ) {
?>
<option value="<?php echo esc_attr( $value1 ); ?>"><?php echo esc_attr( $text ); ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="bwfan_mtag_wrap">
<div class="bwfan_label">
<label for="" class="bwfan-label-title"><?php esc_html_e( 'Expiry', 'wp-marketing-automations' ); ?></label>
</div>
<div class="bwfan_label_val">
<input min="0" type="number" class="bwfan-input-wrapper bwfan_tag_input" name="expiry"/>
</div>
</div>
<div class="bwfan_mtag_wrap">
<label for="bwfan-restrict" class="bwfan-label-title"><input type="checkbox" name="restrict" id="bwfan-restrict" class="bwfan_tag_select" value="yes"/><?php esc_html_e( 'Restrict user email with coupon', 'wp-marketing-automations' ); ?>
</label>
</div>
<?php
}
/**
* Show the html in popup for the merge tag.
*/
public function get_view() {
$this->get_back_button();
if ( $this->support_date ) {
$this->date_format();
}
if ( $this->support_fallback ) {
$this->get_fallback();
}
$this->get_preview();
$this->get_copy_button();
}
public function get_back_button() {
?>
<div class="bwfan_inner_merge_tag_desc"></div>
<?php
}
public function date_format() {
$formats = $this->date_formats;
echo '<div class="bwfan_mtag_wrap">';
echo '<div class="bwfan_label">';
echo '<label class="bwfan-label-fallback-title">' . __( 'Select Date Format', 'wp-marketing-automations' ) . '</label>'; //phpcs:ignore WordPress.Security.EscapeOutput
echo '</div>';
echo '<div class="bwfan_label_val">';
echo '<select class="bwfan_date_format bwfan-input-wrapper bwfan_tag_select" name="format" style="width:100%;">';
foreach ( $formats as $parameters ) {
$date_time = $this->format_datetime( date( 'Y-m-d H:i:s' ), $parameters );
echo '<option value="' . $parameters['format'] . '">' . $date_time . '</option>'; //phpcs:ignore WordPress.Security.EscapeOutput
}
echo '</select>';
echo '</div></div>';
if ( true === $this->support_modify ) {
echo '<div class="bwfan_mtag_wrap">
<div class="bwfan_label">
<label for="" class="bwfan-label-fallback-title">' . esc_html__( 'Modify (Optional)', 'wp-marketing-automations' ) . '</label>
</div>
<div class="bwfan_label_val">
<input type="text" class="bwfan-input-wrapper bwfan_tag_input" name="modify" placeholder="e.g. +2 months, -1 day, +6 hours"/>
</div>
</div>';
}
}
public static function maybe_parse_nested_merge_tags( $string ) {
$position_end = strpos( $string, ']' );
if ( false === $position_end ) {
return $string;
}
$split = str_split( $string, $position_end );
$position_start = strrpos( $split[0], '[', - 1 );
if ( false === $position_start ) {
return $string;
}
$shortcode_array = explode( '[', $split[0] );
$shortcode = end( $shortcode_array );
$result = do_shortcode( '[' . $shortcode . ']' );
/** Handling in case shortcode is not available and the output again contains the shortcode that would results in infinite loop */
$result = str_replace( '[', '&#91;', $result );
$result = str_replace( ']', '&#93;', $result );
$string = str_replace( '[' . $shortcode . ']', $result, $string );
return unescape_invalid_shortcodes( self::maybe_parse_nested_merge_tags( $string ) );
}
public function format_datetime( $input, $parameters, $is_gmt = false ) {
if ( ! $input ) {
return false;
}
/** Date saved value format */
$input_format = ( isset( $parameters['input_format'] ) && ! empty( $parameters['input_format'] ) ) ? $parameters['input_format'] : 'Y-m-d H:i:s';
/** Format in which fetch date value (output format) */
$output_format = ( isset( $parameters['format'] ) && ! empty( $parameters['format'] ) ) ? $parameters['format'] : 'Y-m-d H:i:s';
/** For delay variable */
if ( isset( $parameters['from'] ) && 'delay' === $parameters['from'] ) {
$input_format = ( isset( $parameters['format'] ) && ! empty( $parameters['format'] ) ) ? $parameters['format'] : 'Y-m-d H:i:s';
$output_format = 'Y-m-d H:i:s';
}
if ( is_a( $input, 'DateTime' ) ) {
$date = $input;
} else {
if ( is_numeric( $input ) ) {
$date = new DateTime();
$date->setTimestamp( $input );
} else {
try {
$date = false !== DateTime::createFromFormat( $input_format, $input ) ? DateTime::createFromFormat( $input_format, $input ) : new DateTime( $input );
} catch ( Exception $e ) {
return '';
}
}
}
/** Convert time in store time if gmt is false */
if ( false === $is_gmt ) {
$date = BWFAN_Common::convert_to_site_time( $date );
}
if ( isset( $parameters['modify'] ) && ! empty( $parameters['modify'] ) ) {
$date->modify( $parameters['modify'] );
}
return date_i18n( $output_format, $date->getTimestamp() );
}
public function get_fallback() {
?>
<div class="bwfan_mtag_wrap">
<div class="bwfan_label">
<label for="" class="bwfan-label-fallback-title"><?php esc_html_e( 'Fallback', 'wp-marketing-automations' ); ?></label>
</div>
<div class="bwfan_label_val">
<input type="text" class="bwfan-input-wrapper bwfan_tag_input" name="fallback"/>
</div>
</div>
<?php
}
public function get_preview() {
?>
<textarea style="margin: 5px 20px 15px; width: 93%;" class="bwfan-preview-merge-tag bwfan-input-wrapper" readonly></textarea>
<?php
}
public function get_copy_button() {
?>
<span style="line-height: 70px;" class="bwfan-use-merge-tag"><?php esc_html_e( 'Copy To Clipboard', 'wp-marketing-automations' ); ?></span>
<input type="submit" class="bwfan-display-none"/>
<?php
}
public function parse_shortcode_output( $output, $atts ) {
$default = $output;
if ( empty( $output ) && isset( $atts['fallback'] ) && ! empty( $atts['fallback'] ) ) {
$this->fallback = $atts['fallback'];
$output = $this->fallback;
}
/** If value is array */
$output = is_array( $output ) && count( $output ) > 0 ? implode( ', ', $output ) : $output;
if ( ! empty( $output ) && isset( $atts['prefix'] ) && ! empty( $atts['prefix'] ) ) {
$output = $atts['prefix'] . $output;
}
if ( ! empty( $output ) && isset( $atts['suffix'] ) && ! empty( $atts['suffix'] ) ) {
$output = $output . $atts['suffix'];
}
return apply_filters( 'bwfan_parse_merge_tag_output', $output, $atts, $default );
}
public function data_key() {
?>
<div class="bwfan_mtag_wrap">
<div class="bwfan_label">
<label for="" class="bwfan-label-title"><?php esc_html_e( 'Meta Key', 'wp-marketing-automations' ); ?></label>
</div>
<div class="bwfan_label_val">
<input type="text" class="bwfan-input-wrapper bwfan_tag_input" name="key" required/>
<div class="clearfix bwfan_field_desc"><?php esc_html_e( 'Input the correct meta key in order to get the data', 'wp-marketing-automations' ); ?></div>
</div>
</div>
<?php
}
public function get_customer_city() {
$customer_city = '';
$order = BWFAN_Merge_Tag_Loader::get_data( 'wc_order' );
$user_id = BWFAN_Merge_Tag_Loader::get_data( 'user_id' );
if ( ! empty( $order ) ) {
return BWFAN_Woocommerce_Compatibility::get_order_billing_city( $order );
}
if ( ! empty( $user_id ) ) {
return get_user_meta( (int) $user_id, 'billing_city', true );
}
return $customer_city;
}
public function get_customer_country() {
$customer_country = '';
$country_slug = '';
$order = BWFAN_Merge_Tag_Loader::get_data( 'wc_order' );
$user_id = BWFAN_Merge_Tag_Loader::get_data( 'user_id' );
if ( ! empty( $order ) ) {
$country_slug = BWFAN_Woocommerce_Compatibility::get_billing_country_from_order( $order );
}
if ( ! empty( $user_id ) ) {
$country_slug = get_user_meta( (int) $user_id, 'billing_country', true );
}
if ( ! empty( $country_slug ) ) {
$countries_obj = new WC_Countries();
$countries = $countries_obj->__get( 'countries' );
$customer_country = $countries[ $country_slug ];
}
return $customer_country;
}
public function initialize_product_details() {
$product_details = BWFAN_Merge_Tag_Loader::get_data( 'product_details' );
$product_id = BWFAN_Merge_Tag_Loader::get_data( 'product_id' );
$product = BWFAN_Merge_Tag_Loader::get_data( 'product' );
if ( empty( $product_details ) ) {
BWFAN_Merge_Tag_Loader::set_data( array(
'product_details' => get_post( $product_id ),
) );
}
if ( empty( $product ) ) {
BWFAN_Merge_Tag_Loader::set_data( array(
'product' => wc_get_product( $product_id ),
) );
}
}
public function get_slug() {
return sanitize_title( get_class( $this ) );
}
public function get_name() {
return $this->tag_name;
}
public function get_description() {
return $this->tag_description;
}
public function get_localize_data() {
return [
'tag_name' => $this->tag_name,
'tag_description' => $this->tag_description,
'support_v1' => $this->support_v1,
];
}
public function get_formatted_billing_address( $empty_content = '' ) {
$order = BWFAN_Merge_Tag_Loader::get_data( 'wc_order' );
if ( $order instanceof WC_Order ) {
$address = apply_filters( 'woocommerce_order_formatted_billing_address', $order->get_address( 'billing' ), $order );
$separator = apply_filters( 'bwfan_' . $this->tag_name . '_separator', '</br>' );
$address = WC()->countries->get_formatted_address( $address, $separator );
return $address ? $address : $empty_content;
}
return '';
}
public function get_formatted_shipping_address( $empty_content = '' ) {
$order = BWFAN_Merge_Tag_Loader::get_data( 'wc_order' );
if ( $order instanceof WC_Order ) {
$address = apply_filters( 'woocommerce_order_formatted_shipping_address', $order->get_address( 'shipping' ), $order );
$separator = apply_filters( 'bwfan_' . $this->tag_name . '_separator', '</br>' );
$address = WC()->countries->get_formatted_address( $address, $separator );
return $address ? $address : $empty_content;
}
return '';
}
/**
* Get date value in WordPress set date format
*
* @param $date_value
*
* @return string
*/
public function get_formatted_date_value( $date_value ) {
if ( empty( $date_value ) ) {
return '';
}
if ( false === $this->validate_date( $date_value ) ) {
return $date_value;
}
$date_format = BWFAN_Common::bwfan_get_date_format();
$date_value = date( $date_format, strtotime( $date_value ) );
return $date_value;
}
/**
* Validate date
*
* @param $date
* @param string $format
*
* @return bool
*/
public function validate_date( $date, $format = 'Y-m-d' ) {
$d = DateTime::createFromFormat( $format, $date );
return $d && $d->format( $format ) === $date;
}
/** contact data will be used in the contact merge tag
* @return false|WooFunnels_Contact
*/
public function get_contact_data() {
/** Check if contact id is present */
$get_data = BWFAN_Merge_Tag_Loader::get_data();
if ( isset( $get_data['contact_id'] ) && 0 < intval( $get_data['contact_id'] ) ) {
$contact = new WooFunnels_Contact( '', '', '', intval( $get_data['contact_id'] ) );
if ( $contact instanceof WooFunnels_Contact && $contact->get_id() > 0 ) {
return $contact;
}
}
$user = wp_get_current_user();
if ( ! $user instanceof WP_USER ) {
return false;
}
if ( $user->ID === 0 ) {
return false;
}
/** get user email */
$user_email = $user->user_email;
$contact = new WooFunnels_Contact( $user->ID, $user_email );
if ( $contact instanceof WooFunnels_Contact && $contact->get_id() > 0 ) {
return $contact;
}
return false;
}
/**
* Get order object
*
* @param $get_data
*
* @return string|WC_Order
*/
public function get_order_object( $get_data ) {
if ( ! is_array( $get_data ) || ! bwfan_is_woocommerce_active() ) {
return '';
}
$order = isset( $get_data['wc_order'] ) ? $get_data['wc_order'] : '';
if ( $order instanceof WC_Order ) {
return $order;
}
$order = ( isset( $get_data['order_id'] ) && intval( $get_data['order_id'] ) > 0 ) ? wc_get_order( $get_data['order_id'] ) : '';
if ( $order instanceof WC_Order ) {
return $order;
}
return '';
}
public function is_support_v2() {
return $this->support_v2;
}
public function get_priority() {
return $this->priority;
}
/**
* to avoid unserialize of the current class
*/
public function __wakeup() {
throw new ErrorException( __CLASS__ . ' can`t converted to string' );
}
/**
* to avoid serialize of the current class
*/
public function __sleep() {
throw new ErrorException( __CLASS__ . ' can`t converted to string' );
}
/**
* Returns true if support for v1
*
* @return bool
*/
public function is_support_v1() {
return $this->support_v1;
}
/**
* Returns true if it is a delay variable
* @return bool|mixed
*/
public function is_delay_variable() {
return $this->is_delay_variable;
}
/**
* To avoid cloning of current class
*/
protected function __clone() {
}
public function is_crm_broadcast() {
return $this->is_crm_broadcast;
}
/**
* Get affiliate id from contact
*
* @return mixed|void
*/
public function get_affiliate_id() {
$data = BWFAN_Merge_Tag_Loader::get_data();
if ( ! isset( $data['contact_id'] ) || empty( $data['contact_id'] ) ) {
return '';
}
if ( ! class_exists( 'BWFAN_PRO_Common' ) || ! bwfan_is_affiliatewp_active() ) {
return '';
}
$contact_id = absint( $data['contact_id'] );
$contact = new BWFCRM_Contact( $contact_id );
if ( ! $contact->is_contact_exists() ) {
return '';
}
$user_id = $contact->contact->get_wpid();
if ( empty( $user_id ) ) {
return '';
}
$affiliate_id = BWFAN_PRO_Common::get_aff_id_by_user_id( $user_id );
return ! $affiliate_id ? '' : $affiliate_id;
}
}

View File

@@ -0,0 +1,54 @@
<?php
#[AllowDynamicProperties]
abstract class Cart_Merge_Tag extends BWFAN_Merge_Tag {
public $checkout_data = null;
public $cart_details = null;
/**
* Get cart value which is captured at the checkout page
*
* @param $key
* @param $cart_details
*
* @return mixed|string
*/
public function get_cart_value( $key, $cart_details ) {
if ( empty( $cart_details ) ) {
return '';
}
$this->cart_details = $cart_details;
$checkout_data = $cart_details['checkout_data'] ?? '';
if ( empty( $checkout_data ) ) {
return '';
}
$field_value = '';
$checkout_data = json_decode( $checkout_data, true );
$this->checkout_data = $checkout_data;
if ( isset( $checkout_data['fields'][ $key ] ) ) {
$field_value = $checkout_data['fields'][ $key ];
$field_value = $this->post_value_check( $field_value );
}
if ( empty( $field_value ) ) {
return $checkout_data[ $key ] ?? '';
}
return $field_value;
}
/**
* Individual merge tags can decode the value as they need
*
* @param $field_value
*
* @return mixed
*/
public function post_value_check( $field_value ) {
return $field_value;
}
}

View File

@@ -0,0 +1,227 @@
<?php
#[AllowDynamicProperties]
class BWFAN_Cart_Display extends BWFAN_Merge_Tag {
public $item_type = null;
public $cart_number = null;
public function get_currency_option() {
return array(
'symbol' => __( 'Currency Symbol', 'wp-marketing-automations' ),
'code' => __( '3 Letter Currency code', 'wp-marketing-automations' ),
);
}
/**
* Show the html in popup for the merge tag.
*/
public function get_view() {
$this->get_back_button();
$this->get_item_number_html();
if ( $this->support_fallback ) {
$this->get_fallback();
}
$this->get_preview();
$this->get_copy_button();
}
public function get_item_number_html() {
$templates = $this->get_view_data();
?>
<label for="" class="bwfan-label-title"><?php esc_html_e( 'Select Item Number', 'wp-marketing-automations' ); ?></label>
<select id="" class="bwfan-input-wrapper bwfan-mb-15 bwfan_tag_select" name="item_no" required>
<option value=""><?php esc_html_e( 'Select', 'wp-marketing-automations' ); ?></option>
<?php
foreach ( $templates as $slug => $name ) {
echo '<option value="' . esc_attr( $slug ) . '">' . esc_html( $name ) . '</option>';
}
?>
</select>
<?php
}
public function get_view_data() {
$templates = array(
'1' => __( 'First Item', 'wp-marketing-automations' ),
'2' => __( 'Second Item', 'wp-marketing-automations' ),
'3' => __( 'Third Item', 'wp-marketing-automations' ),
'4' => __( 'Fourth Item', 'wp-marketing-automations' ),
'5' => __( 'Fifth Item', 'wp-marketing-automations' ),
'6' => __( 'Sixth Item', 'wp-marketing-automations' ),
'7' => __( 'Seventh Item', 'wp-marketing-automations' ),
'8' => __( 'Eighth Item', 'wp-marketing-automations' ),
'9' => __( 'Ninth Item', 'wp-marketing-automations' ),
'10' => __( 'Tenth Item', 'wp-marketing-automations' ),
);
return $templates;
}
public function get_item_value() {
$cart_row_details = BWFAN_Merge_Tag_Loader::get_data( 'cart_details' );
$cart_items = maybe_unserialize( $cart_row_details['items'] );
$return_value = '';
$count = 1;
foreach ( $cart_items as $item_data ) {
if ( absint( $this->cart_number ) === $count ) {
$product_id = ( isset( $item_data['product_id'] ) ) ? $item_data['product_id'] : 0;
$quantity = ( isset( $item_data['quantity'] ) ) ? $item_data['quantity'] : 0;
$_pf = new WC_Product_Factory();
$product = $_pf->get_product( $product_id );
switch ( $this->item_type ) {
case 'image':
$product_image = BWFAN_Common::get_product_image( $product, 'shop_catalog', true );
$return_value = $product_image;
break;
case 'name':
$product_name = BWFAN_Common::get_name( $product );
$return_value = $product_name;
break;
case 'price':
$product_price = $product->get_price();
$return_value = $product_price;
break;
case 'quantity':
$return_value = $quantity;
break;
case 'url':
$product_url = $product->get_permalink();
$return_value = $product_url;
break;
}
break;
}
$count ++;
}
return $return_value;
}
public function get_item_details( $parameters = null ) {
$item_id = BWFAN_Merge_Tag_Loader::get_data( 'wc_single_item_id' );
/** If item id is empty */
if ( empty( $item_id ) ) {
return '';
}
try {
$item = new WC_Order_Item_Product( $item_id );
} catch ( Exception $e ) {
return '';
}
if ( ! $item instanceof WC_Order_Item_Product || empty( $item->get_id() ) ) {
return '';
}
switch ( $this->item_type ) {
case 'image':
$product_image = BWFAN_Common::get_product_image( $item->get_product(), 'shop_catalog', true );
$return_value = $product_image;
break;
case 'name':
$return_value = $item->get_name();
break;
case 'price':
$return_value = $item->get_total();
$formatting = BWFAN_Common::get_formatting_for_wc_price( $parameters, $item->get_order() );
$return_value = BWFAN_Common::get_formatted_price_wc( $return_value, $formatting['raw'], $formatting['currency'] );
break;
case 'quantity':
$return_value = $item->get_quantity();
break;
case 'stock':
$product = $item->get_product();
$return_value = $product->get_stock_quantity();
break;
case 'url':
$product = $item->get_product();
$return_value = $product->get_permalink();
break;
case 'item_data':
if ( is_array( $parameters ) && isset( $parameters['key'] ) ) {
$return_value = wc_get_order_item_meta( (int) $item_id, $parameters['key'], true );
} else {
$return_value = '';
}
break;
case 'item_attribute':
if ( is_array( $parameters ) && isset( $parameters['key'] ) ) {
$attribute = 'pa_' . $parameters['key'];
$term = $item->get_meta( $attribute );
if ( ! $term ) {
return false;
}
$term_obj = get_term_by( 'slug', $term, $attribute );
if ( ! $term_obj || is_wp_error( $term_obj ) ) {
return false;
}
return $term_obj->name;
} else {
$product = $item->get_product();
if ( ! $product instanceof WC_Product ) {
return false;
}
$attributes = $product->get_attributes();
if ( empty( $attributes ) ) {
return false;
}
$variation_names1 = array();
foreach ( $attributes as $key => $value ) {
$term = $item->get_meta( $key );
$term_obj = get_term_by( 'slug', $term, $key );
if ( ! $term_obj || is_wp_error( $term_obj ) ) {
continue;
}
$variation_names1[] = $term_obj->name;
}
$return_value = implode( ', ', $variation_names1 );
}
break;
case 'item_meta':
$product = $item->get_product();
$product_id = $product->get_id();
if ( is_array( $parameters ) && isset( $parameters['key'] ) ) {
$return_value = get_post_meta( (int) $product_id, $parameters['key'], true );
} else {
$return_value = '';
}
break;
case 'item_id':
$product = $item->get_product();
$return_value = $product->get_id();
break;
case 'item_sku':
$product = $item->get_product();
$return_value = $product->get_sku();
break;
}
return $return_value;
}
}

View File

@@ -0,0 +1,261 @@
<?php
#[AllowDynamicProperties]
abstract class Merge_Tag_Abstract_Product_Display extends BWFAN_Merge_Tag {
public $support_limit_field = false;
public $supports_order_table = false;
public $supports_cart_table = false;
public $template = null;
public $fallback = null;
public $products = [];
public $cart = null;
public $data = null;
public $order = null;
public $products_quantity = null;
public $products_sku = [];
public $products_price = null;
/**
* Show the html in popup for the merge tag.
*/
public function get_view() {
$templates = $this->get_view_data();
$this->get_back_button();
?>
<div class="bwfan_mtag_wrap">
<div class="bwfan_label">
<label for="" class="bwfan-label-title"><?php esc_html_e( 'Select Template', 'wp-marketing-automations' ); ?></label>
</div>
<div class="bwfan_label_val">
<select id="" class="bwfan-input-wrapper bwfan_tag_select" name="template">
<?php
foreach ( $templates as $slug => $name ) {
echo '<option value="' . esc_attr( $slug ) . '">' . esc_attr( $name ) . '</option>';
}
?>
</select>
</div>
</div>
<?php
if ( $this->support_fallback ) {
$this->get_fallback();
}
$this->get_preview();
$this->get_copy_button();
}
public function get_view_data() {
$templates = array(
'' => __( 'Product Grid - 2 Column', 'wp-marketing-automations' ),
'product-grid-3-col' => __( 'Product Grid - 3 Column', 'wp-marketing-automations' ),
'product-rows' => __( 'Product Rows', 'wp-marketing-automations' ),
'review-rows' => __( 'Product Rows (With Review Button)', 'wp-marketing-automations' ),
'order-table' => __( 'WooCommerce Order Summary Layout', 'wp-marketing-automations' ),
'cart-table' => __( 'Cart Table Layout', 'wp-marketing-automations' ),
'list-comma-separated' => __( 'List - Comma Separated (Product Names only)', 'wp-marketing-automations' ),
'list-comma-separated-with-quantity' => __( 'List - Comma Separated (Product Names with Quantity)', 'wp-marketing-automations' ),
);
if ( ! $this->supports_cart_table ) {
unset( $templates['cart-table'] );
}
if ( ! $this->supports_order_table ) {
unset( $templates['order-table'] );
unset( $templates['review-rows'] );
}
return $templates;
}
public function process_shortcode( $attr ) {
$cart = false;
$data = null;
$products = [];
$products_quantity = [];
$products_price = [];
if ( ! is_null( $this->cart ) && is_array( $this->cart ) && count( $this->cart ) > 0 ) {
$cart = $this->cart;
}
if ( ! is_null( $this->data ) && is_array( $this->data ) && count( $this->data ) > 0 ) {
$data = $this->data;
}
if ( is_array( $this->products ) && count( $this->products ) > 0 ) {
$products = $this->products;
}
if ( is_array( $this->products_quantity ) && count( $this->products_quantity ) > 0 ) {
$products_quantity = $this->products_quantity;
}
if ( is_array( $this->products_sku ) && count( $this->products_sku ) > 0 ) {
$products_sku = $this->products_sku;
}
if ( is_array( $this->products_price ) && count( $this->products_price ) > 0 ) {
$products_price = $this->products_price;
}
$this->template = 'product-grid-2-col';
if ( isset( $attr['template'] ) ) {
$this->template = $attr['template'];
}
/** Allowed templates for product display settings */
$allowed_templates = array( 'product-grid-2-col', 'product-grid-3-col' );
/** if display product count is set in mergetag then remove remaining products */
if ( in_array( $this->template, $allowed_templates, false ) && isset( $attr['display'] ) && absint( $attr['display'] ) >= 1 && absint( $attr['display'] ) < count( $products ) ) {
$products = array_splice( $products, 0, absint( $attr['display'] ) );
}
/** Filter products in case want to hide free products */
$hide_free_products = BWFAN_Common::hide_free_products_cart_order_items();
if ( true === $hide_free_products ) {
/** $products */
$products_mod = array_filter( $products, function ( $single_product ) {
return ( $single_product->get_price() > 0 );
} );
$products = $products_mod;
}
if ( true === BWFAN_Merge_Tag_Loader::get_data( 'is_preview' ) && empty( $products ) ) {
$products = wc_get_products( array(
'numberposts' => 3,
'post_status' => 'published', // Only published products
) );
}
if ( apply_filters( 'bwfan_current_integration_action', false ) ) {
$product_names = [];
foreach ( $products as $single_product ) {
$product_names[] = BWFAN_Common::get_name( $single_product );
}
$product_names = wp_json_encode( $product_names );
return $product_names;
}
if ( isset( $attr['fallback'] ) ) {
$this->fallback = $attr['fallback'];
}
if ( 'list' === $this->template ) {
$type = 'comma-separated';
if ( isset( $attr['type'] ) && ! empty( $attr['type'] ) ) {
$type = $attr['type'];
}
$this->template = $this->template . '-' . $type;
}
/** Handle line-separated output */
if ( 'line' === $this->template ) {
$type_line = isset( $attr['type_line'] ) && ! empty( $attr['type_line'] ) ? $attr['type_line'] : 'separated-product-name';
$items = $cart ? $cart : $products;
$is_cart = $cart ? true : false;
return self::get_formatted_items_in_line( $items, $type_line, $products_quantity, $is_cart, $attr );
}
if ( isset( $data['currency'] ) && ! empty( $data['currency'] ) ) {
remove_all_filters( 'woocommerce_currency_symbol' );
}
$file_path = BWFAN_PLUGIN_DIR . '/templates/' . $this->template . '.php';
$file_path = apply_filters( 'bwfan_cart_items_template_path', $file_path, $cart, $data, $attr );
if ( ! file_exists( $file_path ) ) {
return '';
}
ob_start();
include $file_path;
$response = ob_get_clean();
return apply_filters( 'bwfan_alter_email_body', $response, $products, $this->template, $products_quantity );
}
/**
* Format items into lines with quantity and names.
*
* @param $items
* @param $type_line
* @param $products_quantity
* @param $is_cart
* @param $attr
*
* @return array|string
*/
public static function get_formatted_items_in_line( $items, $type_line, $products_quantity, $is_cart, $attr ) {
if ( $is_cart && isset( $items['cart_items'] ) ) {
$items = $items['cart_items'];
}
if ( empty( $items ) || ! is_array( $items ) ) {
return [];
}
$result = [];
foreach ( $items as $item ) {
$product = $is_cart ? ( $item['data'] ?? null ) : $item;
if ( empty( $product ) || ! $product instanceof WC_Product ) {
continue;
}
$product_quantity = $products_quantity[ $product->get_id() ] ?? 1;
$bwfan_separator = apply_filters( 'bwfan_line_separator_symbol', '-', $product, $attr );
$formatted_product = apply_filters( 'bwfan_line_separator_formate', $product->get_name() . " X " . $product_quantity, 'X', $product->get_name(), $product_quantity, $attr );
$result[] = $type_line !== 'separated-product-name' ? "$bwfan_separator $formatted_product" : "$bwfan_separator " . $product->get_name();
}
$bwfan_line_separator = apply_filters( 'bwfan_line_separator', "\n\r", $product, $attr );
return implode( $bwfan_line_separator, $result );
}
public function prepare_products( $product_ids, $orderby = 'date', $order = 'DESC', $limit = 8 ) {
if ( empty( $product_ids ) ) {
return [];
}
$product_ids = array_filter( $product_ids );
$args = [
'post_type' => 'product',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
'posts_per_page' => $limit,
'post__in' => $product_ids,
'fields' => 'ids',
'orderby' => $orderby,
'order' => $order,
'tax_query' => $this->get_taxonomy_query(),
'meta_query' => WC()->query->get_meta_query(),
];
if ( 'popularity' === $orderby ) {
$args['meta_key'] = 'total_sales';
$args['orderby'] = 'meta_value_num';
}
$query = new WP_Query( $args );
return array_map( 'wc_get_product', $query->posts );
}
protected function get_taxonomy_query( $taxonomy_query = [] ) {
$product_visibility_not_in = [];
$product_visibility_terms = wc_get_product_visibility_term_ids();
// Hide out of stock products.
if ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) ) {
$product_visibility_not_in[] = $product_visibility_terms['outofstock'];
}
if ( ! empty( $product_visibility_not_in ) ) {
$taxonomy_query[] = [
'taxonomy' => 'product_visibility',
'field' => 'term_taxonomy_id',
'terms' => $product_visibility_not_in,
'operator' => 'NOT IN',
];
}
return $taxonomy_query;
}
}

View File

@@ -0,0 +1,264 @@
<?php
#[AllowDynamicProperties]
abstract class BWFAN_Model {
static $primary_key = 'id';
static $count = 20;
static function set_id() {
}
static function get( $value ) {
global $wpdb;
$query = self::_fetch_sql( $value );
return $wpdb->get_row( $query, ARRAY_A ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders, WordPress.DB.PreparedSQL
}
private static function _fetch_sql( $value ) {
global $wpdb;
$sql = sprintf( 'SELECT * FROM %s WHERE %s = %%s', self::_table(), static::$primary_key );
return $wpdb->prepare( $sql, $value ); // WPCS: unprepared SQL OK
}
protected static function _table() {
global $wpdb;
$tablename = strtolower( get_called_class() );
$tablename = str_replace( 'bwfan_model_', 'bwfan_', $tablename );
return $wpdb->prefix . $tablename;
}
static function insert( $data ) {
global $wpdb;
$wpdb->insert( self::_table(), $data ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders, WordPress.DB.PreparedSQL
}
static function update( $data, $where ) {
global $wpdb;
return $wpdb->update( self::_table(), $data, $where ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders, WordPress.DB.PreparedSQL
}
static function delete( $value ) {
global $wpdb;
$sql = sprintf( 'DELETE FROM %s WHERE %s = %%s', self::_table(), static::$primary_key );
return $wpdb->query( $wpdb->prepare( $sql, $value ) ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
}
static function insert_id() {
global $wpdb;
return $wpdb->insert_id;
}
static function now() {
return self::time_to_date( time() );
}
static function time_to_date( $time ) {
return gmdate( 'Y-m-d H:i:s', $time );
}
static function date_to_time( $date ) {
return strtotime( $date . ' GMT' );
}
static function num_rows() {
global $wpdb;
return $wpdb->num_rows;
}
static function count_rows( $dependency = null ) {
global $wpdb;
$sql = 'SELECT COUNT(*) FROM ' . self::_table();
if ( ! is_null( $dependency ) ) {
$sql = 'SELECT COUNT(*) FROM ' . self::_table() . ' INNER JOIN ' . $dependency['dependency_table'] . ' on ' . self::_table() . '.' . $dependency['dependent_col'] . '=' . $dependency['dependency_table'] . '.' . $dependency['dependency_col'] . ' WHERE ' . $dependency['dependency_table'] . '.' . $dependency['col_name'] . '=' . $dependency['col_value'];
if ( isset( $dependency['automation_id'] ) ) {
$sql = 'SELECT COUNT(*) FROM ' . self::_table() . ' INNER JOIN ' . $dependency['dependency_table'] . ' on ' . self::_table() . '.' . $dependency['dependent_col'] . '=' . $dependency['dependency_table'] . '.' . $dependency['dependency_col'] . ' WHERE ' . $dependency['dependency_table'] . '.' . $dependency['col_name'] . '=' . $dependency['col_value'] . ' AND ' . $dependency['automation_table'] . '.' . $dependency['automation_col'] . '=' . $dependency['automation_id'];
if ( 'any' === $dependency['col_value'] ) {
$sql = 'SELECT COUNT(*) FROM ' . self::_table() . ' INNER JOIN ' . $dependency['dependency_table'] . ' on ' . self::_table() . '.' . $dependency['dependent_col'] . '=' . $dependency['dependency_table'] . '.' . $dependency['dependency_col'] . ' WHERE ' . $dependency['automation_table'] . '.' . $dependency['automation_col'] . '=' . $dependency['automation_id'];
}
}
}
return $wpdb->get_var( $sql ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders, WordPress.DB.PreparedSQL
}
static function count( $data = array() ) {
global $wpdb;
$sql = 'SELECT COUNT(*) as `count` FROM ' . self::_table() . ' WHERE 1=1';
$sql_params = [];
if ( is_array( $data ) && count( $data ) > 0 ) {
foreach ( $data as $key => $val ) {
$sql .= " AND `{$key}` LIKE {$val['operator']}";
$sql_params[] = $val['value'];
}
if ( ! empty( $sql_params ) ) {
$sql = $wpdb->prepare( $sql, $sql_params ); // WPCS: unprepared SQL OK
}
}
return $wpdb->get_var( $sql ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders, WordPress.DB.PreparedSQL
}
static function get_specific_rows( $where_key, $where_value, $offset = 0, $limit = 0 ) {
$pagination = '';
if ( ! empty( $offset ) && ! empty( $limit ) ) {
$pagination = " LIMIT $offset, $limit";
}
global $wpdb;
$table_name = self::_table();
$query = "SELECT * FROM $table_name WHERE $where_key = '$where_value'$pagination";
return $wpdb->get_results( $query, ARRAY_A ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders, WordPress.DB.PreparedSQL
}
static function get_rows( $only_query = false, $automation_ids = array() ) {
global $wpdb;
$table_name = self::_table();
$page_number = 1;
$count_per_page = self::$count;
$next_offset = ( $page_number - 1 ) * $count_per_page;
$sql_query = $wpdb->prepare( "SELECT * FROM $table_name ORDER BY c_date DESC LIMIT %d OFFSET %d", $count_per_page, $next_offset );
if ( isset( $_GET['paged'] ) && $_GET['paged'] > 1 ) { // WordPress.CSRF.NonceVerification.NoNonceVerification
$page_number = sanitize_text_field( $_GET['paged'] ); // WordPress.CSRF.NonceVerification.NoNonceVerification
$next_offset = ( $page_number - 1 ) * $count_per_page;
$sql_query = $wpdb->prepare( "SELECT * FROM $table_name ORDER BY c_date DESC LIMIT %d OFFSET %d", $count_per_page, $next_offset );
}
if ( isset( $_GET['status'] ) && 'all' !== $_GET['status'] ) { // WordPress.CSRF.NonceVerification.NoNonceVerification
$status = sanitize_text_field( $_GET['status'] ); // WordPress.CSRF.NonceVerification.NoNonceVerification
$status = ( 'active' === $status ) ? 1 : 2;
$sql_query = $wpdb->prepare( "SELECT * FROM $table_name WHERE status = %d ORDER BY c_date DESC LIMIT %d OFFSET %d", $status, $count_per_page, $next_offset );
}
if ( ( isset( $_GET['paged'] ) && $_GET['paged'] > 0 ) && ( isset( $_GET['status'] ) && '' !== $_GET['status'] ) ) { // WordPress.CSRF.NonceVerification.NoNonceVerification
$page_number = sanitize_text_field( $_GET['paged'] ); // WordPress.CSRF.NonceVerification.NoNonceVerification
$next_offset = ( $page_number - 1 ) * $count_per_page;
$status = sanitize_text_field( $_GET['status'] ); // WordPress.CSRF.NonceVerification.NoNonceVerification
$sql_query = $wpdb->prepare( "SELECT * FROM $table_name WHERE status = %d ORDER BY c_date DESC LIMIT %d OFFSET %d", $status, $count_per_page, $next_offset );
}
$result = $wpdb->get_results( $sql_query, ARRAY_A ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
return $result;
}
static function get_results( $query ) {
global $wpdb;
$query = str_replace( '{table_name}', self::_table(), $query );
$results = $wpdb->get_results( $query, ARRAY_A ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
return $results;
}
static function get_var( $query ) {
global $wpdb;
$query = str_replace( '{table_name}', self::_table(), $query );
return $wpdb->get_var( $query ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
}
static function delete_multiple( $query ) {
self::query( $query );
}
static function query( $query ) {
global $wpdb;
$query = str_replace( '{table_name}', self::_table(), $query );
$wpdb->query( $query ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
}
static function update_multiple( $query ) {
self::query( $query );
}
static function get_current_date_time() {
return date( 'Y-m-d H:i:s' );
}
static function insert_multiple( $values, $keys, $formats = [] ) {
if ( ( ! is_array( $keys ) || empty( $keys ) ) || ( ! is_array( $values ) || empty( $values ) ) ) {
return false;
}
global $wpdb;
$values = array_map( function ( $value ) use ( $keys, $formats ) {
global $wpdb;
$return = array();
foreach ( $keys as $index => $key ) {
$format = is_array( $formats ) && isset( $formats[ $index ] ) ? $formats[ $index ] : false;
$format = ! empty( $format ) ? $format : ( is_numeric( $value[ $key ] ) ? '%d' : '%s' );
$return[] = $wpdb->prepare( $format, $value[ $key ] );
}
return '(' . implode( ',', $return ) . ')';
}, $values );
$values = implode( ', ', $values );
$keys = '(' . implode( ', ', $keys ) . ')';
$query = 'INSERT INTO ' . self::_table() . ' ' . $keys . ' VALUES ' . $values;
return $wpdb->query( $wpdb->prepare( "$query ", $values ) ); //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
}
/**
* Insert query with Ignore
*
* @param $data
* @param $format
*
* @return bool|int|mysqli_result|null
*/
static function insert_ignore( $data, $format = null ) {
if ( empty( $data ) || ! is_array( $data ) ) {
return false;
}
// Validate format if provided
if ( ! is_null( $format ) && count( $format ) !== count( $data ) ) {
$format = null; // Reset format if it doesn't match data count
}
$placeholders = is_null( $format ) ? array_fill( 0, count( $data ), '%s' ) : $format;
$columns = array_keys( $data );
$table = self::_table();
global $wpdb;
$sql = "INSERT IGNORE INTO `$table` (`" . implode( '`,`', $columns ) . "`) VALUES (" . implode( ',', $placeholders ) . ")";
//phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$result = $wpdb->query( $wpdb->prepare( $sql, array_values( $data ) ) );
if ( ! empty( $result ) ) {
return $result;
}
/** If duplicate entry DB error come */
if ( 0 === $result ) {
$warnings = $wpdb->get_results( "SHOW WARNINGS", ARRAY_A );//phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
if ( ! empty( $warnings ) ) {
foreach ( $warnings as $warning ) {
if ( empty( $warning['Message'] ) || false === strpos( $warning['Message'], 'Duplicate entry' ) ) {
continue;
}
BWFAN_Common::log_test_data( 'WP db error in ' . $table . ' : ' . $warning['Message'], 'fka-db-duplicate-error', true );
BWFAN_Common::log_test_data( $data, 'fka-db-duplicate-error', true );
}
}
}
return false;
}
}

View File

@@ -0,0 +1,420 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
#[AllowDynamicProperties]
abstract class BWFAN_Recipes {
public $data = [];
/**
* get data of the recipe
*/
public function get_data() {
return $this->data;
}
/**
* get slug of recipe
*/
public function get_slug() {
return get_class( $this );
}
/**
* get global settings
* @return mixed|void
*/
public function get_settings() {
$settings = BWFAN_Common::get_global_settings();
return $settings;
}
/**
* get plugin name
*
* @param $slug
*
* @return string
*/
public function get_plugin_name( $slug ) {
$name = '';
switch ( $slug ) {
case 'wc':
$name = __( 'WooCommerce', 'wp-marketing-automations' );
break;
case 'wc-subscription':
$name = __( 'WooCommerce Subscription', 'wp-marketing-automations' );
break;
case 'autonami-pro':
$name = __( 'FunnelKit Automations Pro', 'wp-marketing-automations' );
break;
case 'autonami-conn':
$name = __( 'FunnelKit Automations Connector', 'wp-marketing-automations' );
break;
default:
break;
}
return $name;
}
/**
* get plugin name
*
* @param $slug
*
* @return string
*/
public function get_integration_name( $slug ) {
$name = '';
switch ( $slug ) {
case 'wc':
$name = __( 'WooCommerce', 'wp-marketing-automations' );
break;
case 'wc-subscription':
$name = __( 'WooCommerce Subscription', 'wp-marketing-automations' );
break;
case 'autonami-pro':
$name = __( 'FunnelKit Automations Pro', 'wp-marketing-automations' );
break;
case 'autonami-conn':
$name = __( 'FunnelKit Automations Connector', 'wp-marketing-automations' );
break;
default:
break;
}
return $name;
}
/**
* get channel name
*
* @param $slug
*
* @return string
*/
public function get_channel_name( $slug ) {
$name = '';
switch ( $slug ) {
case 'email':
$name = __( 'Email', 'wp-marketing-automations' );
break;
default:
break;
}
return $name;
}
/**
* get goal name
*
* @param $slug
*
* @return string
*/
public function get_goal_name( $slug ) {
$name = '';
switch ( $slug ) {
case 'convert_sales':
$name = __( 'Convert Sales', 'wp-marketing-automations' );
break;
default:
break;
}
return $name;
}
/**
* get type name
*
* @param $slug
*
* @return string
*/
public function get_type_name( $slug ) {
$name = '';
switch ( $slug ) {
case 'abandoned_cart':
$name = __( 'Abandoned Cart', 'wp-marketing-automations' );
break;
case 'browse_abandonment':
$name = __( 'Browse Abandonment', 'wp-marketing-automations' );
break;
case 'customer_winback':
$name = __( 'Customer Winback', 'wp-marketing-automations' );
break;
default:
break;
}
return $name;
}
/**
* checking recipe dependency
*/
public function check_dependency() {
/** get plugin dependency */
$plugin_depend = $this->data['plugin-dependencies'];
$plugin_depend_check = BWFAN_Common::plugin_dependency_check( $plugin_depend );
/** get connector dependency */
$connnect_depend = $this->data['connector-dependencies'];
$connect_depend_check = self::connector_dependency_check( $connnect_depend );
/** check data dependency */
$data_depend = $this->data['data-dependencies'];
$data_depend_check = self::data_dependency_check( $data_depend );
/** @var $depend_error */
$depend_error = array();
// check if plugin and connector dependency match
if ( true !== $connect_depend_check || true !== $plugin_depend_check || true !== $data_depend_check ) {
if ( is_array( $plugin_depend_check ) && count( $plugin_depend_check ) > 0 ) {
$depend_error = $plugin_depend_check;
}
if ( is_array( $connect_depend_check ) && count( $connect_depend_check ) > 0 ) {
$depend_error = array_merge( $connect_depend_check, $depend_error );
}
if ( is_array( $data_depend_check ) && count( $data_depend_check ) > 0 ) {
$depend_error = array_merge( $data_depend_check, $depend_error );
}
return $depend_error;
}
return empty( $depend_error ) ? true : $depend_error;
}
/**
* checking recipe connector dependency
*
* @param $connect_depend
*
* @return array|bool
*/
public static function connector_dependency_check( $connect_depend ) {
if ( empty( $connect_depend ) ) {
return true;
}
$connect_error = [];
$connect_key = '';
// get all connectors
$all_connectors = WFCO_Load_Connectors::get_all_connectors();
if ( empty( $all_connectors ) ) {
foreach ( $connect_depend as $connect ) {
$connect_name = self::get_connector_name( $connect );
$connect_error[] = "{$connect_name} is not activate";
}
return $connect_error;
}
$saved_connectors = WFCO_Common::$connectors_saved_data;
foreach ( $connect_depend as $connect ) {
$connect_name = self::get_connector_name( $connect );
$conn_name = str_replace( ' ', '', strtolower( $connect_name ) );
$connect_key = 'bwfco_' . $conn_name;
if ( ! array_key_exists( $connect_key, $saved_connectors ) ) {
$connect_error[] = "{$connect_name} is not connected";
}
}
return empty( $connect_error ) ? true : $connect_error;
}
/**
* get connector name
*
* @param $slug
*
* @return string
*/
public static function get_connector_name( $slug ) {
$name = '';
switch ( $slug ) {
case 'ac':
$name = __( 'Active Campaign', 'wp-marketing-automations' );
break;
case 'drip':
$name = __( 'Drip', 'wp-marketing-automations' );
break;
case 'ck':
$name = __( 'Kit ( Formerly ConvertKit )', 'wp-marketing-automations' );
break;
case 'mailchimp':
$name = __( 'Mailchimp', 'wp-marketing-automations' );
break;
default:
break;
}
return $name;
}
/**
* checking data dependency
*
* @param $data_depend
*
* @return array|bool
*/
protected static function data_dependency_check( $data_depend ) {
if ( empty( $data_depend ) ) {
return true;
}
$data_error = [];
foreach ( $data_depend as $data ) {
$operator = isset( $data['operator'] ) ? $data['operator'] : '';
$current_value = isset( $data['current_value'] ) ? $data['current_value'] : '';
$check_value = isset( $data['check_value'] ) ? $data['check_value'] : '';
$data_check = self::check_data_value( $current_value, $operator, $check_value );
if ( false === $data_check ) {
$data_error[] = $data['message'];
return $data_error;
}
}
return empty( $data_error ) ? true : $data_error;
}
/**
* get operand to check the data dependency
*
* @param $operator
*
* @return string
*/
protected static function check_data_value( $current_value, $operator, $check_value ) {
switch ( $operator ) {
case '=':
return $current_value === $check_value ? true : false;
case '!=':
return $current_value !== $check_value ? true : false;
default:
return true;
}
}
/**
* creating recipe automation
*/
public function create_automation( $json_files, $title = '' ) {
if ( ! is_array( $json_files ) || empty( $json_files ) ) {
$resp = array(
'msg' => __( 'Recipe json files are missing', 'wp-marketing-automations' ),
'status' => false,
);
return $resp;
}
foreach ( $json_files as $file ) {
$json_path = plugin_dir_path( __FILE__ ) . '../recipes/json/' . $file . '.json';
/** checking is the json file exist then return */
if ( ! file_exists( $json_path ) ) {
continue;
}
$automation_data = json_decode( file_get_contents( $json_path ), true );
if ( empty( $automation_data ) && ! is_array( $automation_data ) ) {
continue;
}
foreach ( $automation_data as $import_data ) {
if ( ! isset( $import_data['meta']['title'] ) || '' === $import_data['meta']['title'] ) {
continue;
}
$post = array();
$post['status'] = 2;
$post['source'] = isset( $import_data['data']['source'] ) ? $import_data['data']['source'] : '';
$post['event'] = isset( $import_data['data']['event'] ) ? $import_data['data']['event'] : '';
$post['priority'] = 0;
if ( empty( $post ) ) {
continue;
}
BWFAN_Model_Automations::insert( $post );
$automation_id = BWFAN_Model_Automations::insert_id();
BWFAN_Core()->automations->set_automation_id( $automation_id );
BWFAN_Core()->automations->set_automation_data( 'status', $post['status'] );
if ( 0 === $automation_id && is_wp_error( $automation_id ) ) {
continue;
}
if ( ! empty( $import_data['meta'] ) ) {
foreach ( $import_data['meta'] as $key => $auto_meta ) {
if ( is_array( $auto_meta ) ) {
$auto_meta = maybe_serialize( $auto_meta );
} else {
$auto_meta = $auto_meta;
}
$meta = array();
$meta['bwfan_automation_id'] = $automation_id;
$meta['meta_key'] = $key;
if ( $key == 'title' && ! empty( $title ) ) {
$meta['meta_value'] = $title;
} else {
$meta['meta_value'] = $auto_meta;
}
BWFAN_Model_Automationmeta::insert( $meta );
BWFAN_Core()->automations->set_automation_data( $key, $meta['meta_value'] );
}
}
$meta = array();
$meta['bwfan_automation_id'] = $automation_id;
$meta['meta_key'] = 'c_date';
$meta['meta_value'] = current_time( 'mysql', 1 );
BWFAN_Model_Automationmeta::insert( $meta );
BWFAN_Core()->automations->set_automation_data( 'c_date', $meta['meta_value'] );
$meta = array();
$meta['bwfan_automation_id'] = $automation_id;
$meta['meta_key'] = 'm_date';
$meta['meta_value'] = current_time( 'mysql', 1 );
BWFAN_Model_Automationmeta::insert( $meta );
BWFAN_Core()->automations->set_automation_data( 'm_date', $meta['meta_value'] );
do_action( 'bwfan_automation_saved', $automation_id );
$resp['status'] = true;
$resp['redirect_url'] = add_query_arg( array(
'page' => 'autonami-automations',
), admin_url( 'admin.php' ) );
$resp['id'] = $automation_id;
$resp['msg'] = __( 'Recipe Successfully Imported', 'wp-marketing-automations' );
}
}
return $resp;
}
/**
* Create automation by recipe
*
* @param $recipe_slug
* @param $title
*/
public static function create_automation_by_recipe( $recipe_slug, $title ) {
$recipe_instance = $recipe_slug::get_instance();
$recipe_json = array_filter( $recipe_instance->data['json'] );
$automation = $recipe_instance->create_automation( $recipe_json, $title );
return $automation;
}
}

View File

@@ -0,0 +1,117 @@
<?php
/**
* Class BWFAN_Source
*/
#[AllowDynamicProperties]
abstract class BWFAN_Source {
protected $show_in_ui = true;
protected $localize_data = [];
protected $nice_name = '';
protected $event_dir = __DIR__;
protected $slug = '';
protected $group_slug = '';
protected $group_name = '';
protected $priority = 0;
/**
* Loads all events of current trigger
*/
public function load_events() {
$resource_dir = $this->event_dir . '/events';
if ( false === @file_exists( $resource_dir ) ) { //phpcs:ignore PHP_CodeSniffer - Generic.PHP.NoSilencedErrors, Generic.PHP.NoSilencedErrors
return;
}
foreach ( glob( $resource_dir . '/class-*.php' ) as $_field_filename ) {
$file_data = pathinfo( $_field_filename );
if ( isset( $file_data['basename'] ) && 'index.php' === $file_data['basename'] ) {
continue;
}
$event_class = require_once( $_field_filename );
if ( ! is_string( $event_class ) || ! method_exists( $event_class, 'get_instance' ) ) {
continue;
}
/**
* @var $event_obj BWFAN_Event
*/
$event_obj = $event_class::get_instance();
BWFAN_Load_Sources::$all_events[ $this->get_name() ][ $event_obj->get_slug() ] = $event_obj->get_name();
$event_obj->load_hooks();
if ( method_exists( $event_obj, 'admin_enqueue_assets' ) && is_admin() && BWFAN_Common::is_automation_v1_active() && BWFAN_Common::is_autonami_page() ) {
// Add action to avoid enqueueing assets on every admin page load
add_action( 'admin_enqueue_scripts', array( $event_obj, 'admin_enqueue_assets' ), 98 );
}
$event_obj->set_source_type( $this->get_slug() );
BWFAN_Load_Sources::register_events( $event_obj );
}
do_action( 'bwfan_' . $this->get_slug() . '_events_loaded' );
}
public function get_slug() {
$this->slug = str_replace( array( 'bwfan_', '_source' ), '', sanitize_title( get_class( $this ) ) );
return $this->slug;
}
public function get_group_slug() {
return $this->group_slug;
}
public function get_group_name() {
return $this->group_name;
}
public function get_localize_data() {
$this->localize_data = [
'show_in_ui' => $this->show_in_ui(),
'slug' => $this->get_slug(),
'group_slug' => $this->get_group_slug(),
'group_name' => $this->get_group_name(),
'nice_name' => $this->get_name(),
'priority' => $this->priority,
'available' => 'yes',
];
return $this->localize_data;
}
public function show_in_ui() {
return $this->show_in_ui;
}
public function get_name() {
return $this->nice_name;
}
public function get_priority() {
return $this->priority;
}
/**
* to avoid unserialize of the current class
*/
public function __wakeup() {
throw new ErrorException( esc_html__( 'BWFAN_Core cannot be converted to string', 'wp-marketing-automations' ) );
}
/**
* to avoid serialize of the current class
*/
public function __sleep() {
throw new ErrorException( esc_html__( 'BWFAN_Core can`t converted to string', 'wp-marketing-automations' ) );
}
/**
* To avoid cloning of current class
*/
protected function __clone() {
}
}

View File

@@ -0,0 +1,21 @@
<?php
if ( ! class_exists( 'BWFCRM_Term_Type' ) && BWFAN_Common::is_pro_3_0() ) {
abstract class BWFCRM_Term_Type {
public static $TAG = 1;
public static $LIST = 2;
}
if ( ! function_exists( 'bwfcrm_get_term_type_text' ) ) {
function bwfcrm_get_term_type_text( $type = 1 ) {
switch ( $type ) {
case BWFCRM_Term_Type::$TAG:
return 'Tag';
case BWFCRM_Term_Type::$LIST:
return 'List';
}
return 'Tag';
}
}
}

View File

@@ -0,0 +1,419 @@
<?php
if ( ! class_exists( 'BWFCRM_Term' ) && BWFAN_Common::is_pro_3_0() ) {
class BWFCRM_Term {
protected $_id = null;
protected $_name = null;
protected $_type = null;
protected $_created_at = null;
protected $_updated_at = null;
protected $_newly_created = false;
protected $_data = '';
public static $tags_by_id = array();
public function __construct( $data = false, $type = 1, $force_create = false ) {
if ( empty( $data ) ) {
$this->_type = $type;
return;
}
/** If data is BWFCRM_Term */
if ( $data instanceof BWFCRM_Term ) {
$this->init_term( $data );
}
/** Check if the term is already stored in cache */
$term = self::maybe_get_term( $data );
if ( false !== $term && $term instanceof BWFCRM_Term ) {
$this->init_term( $term );
}
/** If data is an array */
if ( is_array( $data ) ) {
$this->init_term( $data );
}
/** If data is an integer */
if ( is_numeric( $data ) && 0 < absint( $data ) ) {
$this->init_term( BWFAN_Model_Terms::get( absint( $data ) ) );
}
/** If data is a string */
if ( ! empty( $data ) && is_string( $data ) ) {
$term_row = BWFAN_Model_Terms::get_term_by_name( $data, $type );
/** in case of not found then insert */
if ( empty( $term_row ) && $force_create ) {
$term_row = self::add_term_to_db( $data, $type );
}
if ( ! empty( $term_row ) ) {
$this->init_term( $term_row );
$this->_newly_created = true;
}
}
/** Store terms for further use, within current HTTP Request */
if ( ! empty( $this->get_id() ) ) {
self::$tags_by_id[ $this->get_id() ] = $this;
}
}
public static function maybe_get_term( $data = false ) {
if ( is_array( $data ) && isset( $data['ID'] ) && isset( self::$tags_by_id[ absint( $data['ID'] ) ] ) ) {
return self::$tags_by_id[ absint( $data['ID'] ) ];
}
if ( is_numeric( $data ) && absint( $data ) > 0 ) {
if ( isset( self::$tags_by_id[ absint( $data ) ] ) ) {
return self::$tags_by_id[ absint( $data ) ];
}
}
return false;
}
public function is_exists() {
return is_numeric( $this->get_id() ) && ! empty( $this->get_id() );
}
public function is_newly_created() {
return $this->_newly_created;
}
public static function add_term_to_db( $term_name, $type = 0 ) {
BWFAN_Model_Terms::insert( array(
'name' => $term_name,
'type' => $type,
'created_at' => current_time( 'mysql', 1 ),
) );
return BWFAN_Model_Terms::get( BWFAN_Model_Terms::insert_id() );
}
private function init_term( $db_term ) {
if ( $db_term instanceof BWFCRM_Term ) {
$db_term = array(
'ID' => $db_term->get_id(),
'name' => $db_term->get_name(),
'type' => $db_term->get_type(),
'created_at' => $db_term->get_created_at(),
);
}
$this->_id = isset( $db_term['ID'] ) ? absint( $db_term['ID'] ) : 0;
if ( empty( $this->_id ) && isset( $db_term['_id'] ) ) {
$this->_id = $db_term['_id'];
}
$this->_type = isset( $db_term['type'] ) ? $db_term['type'] : - 1;
if ( empty( $this->_type ) && isset( $db_term['_type'] ) ) {
$this->_type = $db_term['_type'];
}
$this->_name = isset( $db_term['name'] ) ? $db_term['name'] : '';
if ( empty( $this->_name ) && isset( $db_term['_name'] ) ) {
$this->_name = $db_term['_name'];
}
$this->_created_at = isset( $db_term['created_at'] ) ? $db_term['created_at'] : null;
if ( empty( $this->_created_at ) && isset( $db_term['_created_at'] ) ) {
$this->_created_at = $db_term['_created_at'];
}
$this->_updated_at = isset( $db_term['updated_at'] ) ? $db_term['updated_at'] : null;
if ( empty( $this->_updated_at ) && isset( $db_term['_updated_at'] ) ) {
$this->_updated_at = $db_term['_updated_at'];
}
$this->_data = isset( $db_term['data'] ) && ! empty( $db_term['data'] ) ? json_decode( $db_term['data'], true ) : null;
if ( empty( $this->_data ) && isset( $db_term['_data'] ) && ! empty( $db_term['_data'] ) ) {
$this->_data = json_decode( $db_term['_data'], true );
}
}
public function save() {
if ( empty( $this->_name ) || empty( $this->_type ) ) {
return BWFAN_Common::crm_error( __( 'Required term data is missing.', 'wp-marketing-automations' ) );
}
$term = array(
'name' => $this->_name,
'type' => $this->_type,
'data' => empty( $this->_data ) ? '' : wp_json_encode( $this->_data ),
'updated_at' => current_time( 'mysql', 1 ),
);
if ( ! empty( $this->_id ) ) {
return BWFAN_Model_Terms::update( $term, array( 'ID' => absint( $this->_id ) ) );
} else {
$term['created_at'] = $term['updated_at'];
BWFAN_Model_Terms::insert( $term );
return BWFAN_Model_Terms::insert_id();
}
}
public function get_data() {
return $this->_data;
}
public function get_id() {
return absint( $this->_id );
}
public function get_name() {
return $this->_name;
}
public function set_name( $name ) {
$this->_name = $name;
}
public function get_type() {
return $this->_type;
}
public function get_created_at() {
return $this->_created_at;
}
public function get_updated_at() {
return $this->_updated_at;
}
public function get_array() {
return array(
'ID' => $this->get_id(),
'name' => $this->get_name(),
'type' => $this->get_type(),
'created_at' => $this->get_created_at(),
'updated_at' => $this->get_updated_at(),
'data' => $this->get_data(),
);
}
/**
* @param BWFCRM_Term[] $objects
* @param string $key
*
* @return array[]
*/
public static function get_collection_array( $objects, $key = '' ) {
if ( ! is_array( $objects ) || empty( $objects ) ) {
return array();
}
$array = array_map( function ( $object ) use ( $key ) {
if ( ! $object instanceof BWFCRM_Term ) {
return false;
}
if ( ! empty( $key ) ) {
$value = call_user_func( array( $object, 'get_' . $key ) );
return $value;
}
return $object->get_array();
}, $objects );
return array_filter( $array );
}
public static function get_objects_from_db_rows( $data = array() ) {
if ( ! is_array( $data ) || empty( $data ) ) {
return array();
}
return array_map( function ( $single_data ) {
if ( $single_data instanceof BWFCRM_Term ) {
return $single_data;
}
return ( BWFCRM_Term_Type::$TAG === absint( $single_data['type'] ) ? ( new BWFCRM_Tag( $single_data ) ) : ( new BWFCRM_Lists( $single_data ) ) );
}, $data );
}
public static function get_array_from_db_rows( $data = array() ) {
if ( ! is_array( $data ) || empty( $data ) ) {
return array();
}
return array_map( function ( $single_data ) {
/** To store the db_row in cache i.e.: BWFCRM_Term::$tags_by_id & BWFCRM_Term::$tags_by_slug */
$term = BWFCRM_Term_Type::$TAG === absint( $single_data['type'] ) ? ( new BWFCRM_Tag( $single_data ) ) : ( new BWFCRM_Lists( $single_data ) );
return $term->get_array();
}, $data );
}
public static function get_terms( $type = 1, $ids = array(), $search = '', $offset = 0, $limit = 0, $return = ARRAY_A, $search_nature = '', $use_cache = false ) {
$db_terms = BWFAN_Model_Terms::get_terms( $type, $offset, $limit, $search, $ids, $search_nature, $use_cache );
return ( ARRAY_A === $return ? self::get_array_from_db_rows( $db_terms ) : self::get_objects_from_db_rows( $db_terms ) );
}
public static function get_terms_by_type( $type = 1, $return = ARRAY_A ) {
$db_terms = BWFAN_Model_Terms::get_specific_rows( 'type', $type );
return ARRAY_A === $return ? self::get_array_from_db_rows( $db_terms ) : self::get_objects_from_db_rows( $db_terms );
}
/**
* @param $terms
* @param $type
*
* @return bool
*/
public static function add_terms_to_db( $terms, $type ) {
$terms = array_map( function ( $term ) use ( $type ) {
return array(
'name' => $term,
'type' => $type,
'created_at' => current_time( 'mysql', 1 ),
);
}, $terms );
$result = BWFAN_Model_Terms::insert_multiple( $terms, array( 'name', 'type', 'created_at' ) );
if ( false === $result ) {
return $result;
}
return true;
}
/**
* Terms in Apply Contact Tag will be in this format:
* [
* [ 'id'=> 3, 'name'=>'Product' ],
* [ 'id'=> 1, 'name'=>'Hello' ],
* [ 'id'=> 0, 'name'=>'Hi' ],
* [ 'id'=> 0, 'name'=>'Done' ],
* ]
*
* So we need to differentiate which terms are new and which are already available in DB.
* This method differentiate that
*
* @param $terms
* @param int $type
* @param bool $use_cache
*
* @return array
*/
public static function parse_terms_request( $terms, $type = 1, $use_cache = false ) {
/** Separate new terms from existing terms */
$existing_terms = array();
$new_terms_to_add = array_map( function ( $term ) use ( &$existing_terms ) {
if ( 0 !== absint( $term['id'] ) ) {
$existing_terms[] = $term;
return false;
}
return $term['value'];
}, $terms );
$new_terms_to_add = array_filter( $new_terms_to_add );
/** Get terms by IDs */
$existing_term_ids = array_map( 'absint', array_filter( array_column( $existing_terms, 'id' ) ) );
$db_existing_terms = array();
if ( ! empty( $existing_term_ids ) ) {
$db_existing_terms = BWFAN_Model_Terms::get_terms( $type, 0, count( $existing_term_ids ), '', $existing_term_ids, '', $use_cache );
}
/** Check if any term by IDs missing from DB, then add that term name to "need to be created terms" */
$db_term_ids = array_map( 'absint', array_column( $db_existing_terms, 'ID' ) );
if ( count( $db_existing_terms ) !== count( $existing_terms ) ) {
foreach ( $existing_terms as $e_term ) {
if ( false === array_search( absint( $e_term['id'] ), $db_term_ids ) ) {
$new_terms_to_add[] = $e_term['value'];
}
}
}
/** Array Unique => the (To be Created) term names, and run SQL to check if any term exists by their name */
$new_terms_to_add = array_unique( $new_terms_to_add );
$db_new_terms_to_add = array();
if ( ! empty( $new_terms_to_add ) ) {
$db_new_terms_to_add = BWFAN_Model_Terms::get_terms( $type, 0, 0, $new_terms_to_add, array(), 'exact', $use_cache );
}
/** If any exists, add the term ID to "Need to assigned terms" and remove from "to be created" terms names */
if ( ! empty( $db_new_terms_to_add ) ) {
foreach ( $db_new_terms_to_add as $e_term ) {
if ( false === array_search( $e_term['name'], $new_terms_to_add ) ) {
continue;
}
$new_terms_to_add = array_diff( $new_terms_to_add, array( $e_term['name'] ) );
if ( false === array_search( $e_term['ID'], $db_term_ids ) ) {
$db_term_ids[] = $e_term['ID'];
}
}
}
/** Array Unique => the (To be Assigned) term IDs. (In any case if duplication exists) */
$db_term_ids = array_unique( $db_term_ids );
return array(
'ids' => $db_term_ids,
'names' => $new_terms_to_add,
);
}
/**
* @param array $terms
* @param int $type
* @param bool $create_if_not_exists
* @param bool $separate_created_terms
* @param bool $use_cache
*
* @return array|array[]|BWFCRM_Lists[]|BWFCRM_Tag[]|BWFCRM_Term[]
*/
public static function get_or_create_terms( $terms = array(), $type = 1, $create_if_not_exists = false, $separate_created_terms = false, $use_cache = false ) {
$terms = self::parse_terms_request( $terms, $type, $use_cache );
if ( ! isset( $terms['ids'] ) || ! isset( $terms['names'] ) ) {
return true === $separate_created_terms ? array(
'created' => array(),
'existing' => array(),
) : array();
}
$existing_terms = array();
if ( ! empty( $terms['ids'] ) ) {
$existing_terms = self::get_terms( $type, $terms['ids'], '', 0, 0, OBJECT, '', $use_cache );
}
if ( false === $create_if_not_exists || empty( $terms['names'] ) ) {
return true === $separate_created_terms ? array(
'created' => array(),
'existing' => $existing_terms,
) : $existing_terms;
}
/** Create rest of the terms */
$terms_created = self::add_terms_to_db( $terms['names'], $type );
$new_terms = array();
if ( $terms_created ) {
$new_terms = self::get_terms( $type, array(), $terms['names'], 0, 0, OBJECT, 'exact', $use_cache );
}
/** Get added terms */
if ( false === $separate_created_terms ) {
return array_merge( $existing_terms, $new_terms );
}
return array(
'created' => $new_terms,
'existing' => $existing_terms,
);
}
}
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.