diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..328b7d3 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,5 @@ +FROM wordpress:php7.2 + +WORKDIR /var/www/html/ + +COPY . ./wp-content/plugins/paystack diff --git a/admin/class-paystack-forms-admin.php b/admin/class-paystack-forms-admin.php new file mode 100644 index 0000000..0ad6995 --- /dev/null +++ b/admin/class-paystack-forms-admin.php @@ -0,0 +1,1092 @@ +plugin_name = $plugin_name; + $this->version = $version; + add_action('admin_menu', 'kkd_pff_paystack_add_settings_page'); + add_action('admin_init', 'kkd_pff_paystack_register_setting_page'); + + function kkd_pff_paystack_add_settings_page() + { + add_submenu_page('edit.php?post_type=paystack_form', 'Settings', 'Settings', 'edit_posts', basename(__FILE__), 'kkd_pff_paystack_setting_page'); + } + function kkd_pff_paystack_register_setting_page() + { + register_setting('kkd-pff-paystack-settings-group', 'mode'); + register_setting('kkd-pff-paystack-settings-group', 'tsk'); + register_setting('kkd-pff-paystack-settings-group', 'tpk'); + register_setting('kkd-pff-paystack-settings-group', 'lsk'); + register_setting('kkd-pff-paystack-settings-group', 'lpk'); + + register_setting('kkd-pff-paystack-settings-group', 'prc'); + register_setting('kkd-pff-paystack-settings-group', 'ths'); + register_setting('kkd-pff-paystack-settings-group', 'adc'); + register_setting('kkd-pff-paystack-settings-group', 'cap'); + } + function kkd_pff_paystack_txncheck($name, $txncharge) + { + if ($name == $txncharge) { + $result = "selected"; + } else { + $result = ""; + } + return $result; + } + function kkd_pff_paystack_setting_page() + { + ?> +
+ _x('Paystack Forms', 'paystack_form'), + 'singular_name' => _x('Paystack Form', 'paystack_form'), + 'add_new' => _x('Add New', 'paystack_form'), + 'add_new_item' => _x('Add Paystack Form', 'paystack_form'), + 'edit_item' => _x('Edit Paystack Form', 'paystack_form'), + 'new_item' => _x('Paystack Form', 'paystack_form'), + 'view_item' => _x('View Paystack Form', 'paystack_form'), + 'all_items' => _x('All Forms', 'paystack_form'), + 'search_items' => _x('Search Paystack Forms', 'paystack_form'), + 'not_found' => _x('No Paystack Forms found', 'paystack_form'), + 'not_found_in_trash' => _x('No Paystack Forms found in Trash', 'paystack_form'), + 'parent_item_colon' => _x('Parent Paystack Form:', 'paystack_form'), + 'menu_name' => _x('Paystack Forms', 'paystack_form'), + ); + + $args = array( + 'labels' => $labels, + 'hierarchical' => true, + 'description' => 'Paystack Forms filterable by genre', + 'supports' => array('title', 'editor'), + 'public' => true, + 'show_ui' => true, + 'show_in_menu' => true, + 'menu_position' => 5, + 'menu_icon' => plugins_url('../images/logo.png', __FILE__), + 'show_in_nav_menus' => true, + 'publicly_queryable' => true, + 'exclude_from_search' => false, + 'has_archive' => false, + 'query_var' => true, + 'can_export' => true, + 'rewrite' => false, + 'comments' => false, + 'capability_type' => 'post' + ); + register_post_type('paystack_form', $args); + } + add_filter('user_can_richedit', 'kkd_pff_paystack_disable_wyswyg'); + + function kkd_pff_paystack_add_view_payments($actions, $post) + { + if (get_post_type() === 'paystack_form') { + unset($actions['view']); + unset($actions['quick edit']); + $url = add_query_arg( + array( + 'post_id' => $post->ID, + 'action' => 'submissions', + ) + ); + $actions['export'] = 'View Payments'; + } + return $actions; + } + add_filter('page_row_actions', 'kkd_pff_paystack_add_view_payments', 10, 2); + + + function kkd_pff_paystack_remove_fullscreen($qtInit) + { + $qtInit['buttons'] = 'fullscreen'; + return $qtInit; + } + function kkd_pff_paystack_disable_wyswyg($default) + { + global $post_type, $_wp_theme_features; + + + if ($post_type == 'paystack_form') { + echo ""; + add_action("admin_print_footer_scripts", "kkd_pff_paystack_shortcode_button_script"); + add_filter('user_can_richedit', '__return_false', 50); + add_action('wp_dashboard_setup', 'kkd_pff_paystack_remove_dashboard_widgets'); + remove_action('media_buttons', 'media_buttons'); + remove_meta_box('postimagediv', 'post', 'side'); + add_filter('quicktags_settings', 'kkd_pff_paystack_remove_fullscreen'); + } + + return $default; + } + function kkd_pff_paystack_remove_dashboard_widgets() + { + remove_meta_box('dashboard_right_now', 'dashboard', 'normal'); // Right Now + remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal'); // Recent Comments + remove_meta_box('dashboard_incoming_links', 'dashboard', 'normal'); // Incoming Links + remove_meta_box('dashboard_plugins', 'dashboard', 'normal'); // Plugins + remove_meta_box('dashboard_quick_press', 'dashboard', 'side'); // Quick Press + remove_meta_box('dashboard_recent_drafts', 'dashboard', 'side'); // Recent Drafts + remove_meta_box('dashboard_primary', 'dashboard', 'side'); // WordPress blog + remove_meta_box('dashboard_secondary', 'dashboard', 'side'); // Other WordPress News + // use 'dashboard-network' as the second parameter to remove widgets from a network dashboard. + } + add_filter('manage_edit-paystack_form_columns', 'kkd_pff_paystack_edit_dashboard_header_columns'); + + function kkd_pff_paystack_edit_dashboard_header_columns($columns) + { + $columns = array( + 'cb' => '', + 'title' => __('Name'), + 'shortcode' => __('Shortcode'), + 'payments' => __('Payments'), + 'date' => __('Date') + ); + + return $columns; + } + add_action('manage_paystack_form_posts_custom_column', 'kkd_pff_paystack_dashboard_table_data', 10, 2); + + function kkd_pff_paystack_dashboard_table_data($column, $post_id) + { + global $post, $wpdb; + $table = $wpdb->prefix . KKD_PFF_PAYSTACK_TABLE; + + switch ($column) { + case 'shortcode': + echo ' + '; + + break; + case 'payments': + + $count_query = $wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE post_id = %d AND paid = '1'", $post_id); + $num = $wpdb->get_var($count_query); + + echo '' . $num . ''; + break; + default: + break; + } + } + add_filter('default_content', 'kkd_pff_paystack_editor_content', 10, 2); + + function kkd_pff_paystack_editor_content($content, $post) + { + switch ($post->post_type) { + case 'paystack_form': + $content = '[text name="Phone Number"]'; + break; + default: + $content = ''; + break; + } + + return $content; + } + ///// + function kkd_pff_paystack_editor_help_metabox($post) + { + do_meta_boxes(null, 'custom-metabox-holder', $post); + } + add_action('edit_form_after_title', 'kkd_pff_paystack_editor_help_metabox'); + + function kkd_pff_paystack_editor_help_metabox_details($post) + { + echo ''; ?> + + + ++ + + +
+ + '; + + // Get the location data if its already been entered + $amount = get_post_meta($post->ID, '_amount', true); + $paybtn = get_post_meta($post->ID, '_paybtn', true); + $successmsg = get_post_meta($post->ID, '_successmsg', true); + $txncharge = get_post_meta($post->ID, '_txncharge', true); + $loggedin = get_post_meta($post->ID, '_loggedin', true); + $currency = get_post_meta($post->ID, '_currency', true); + $filelimit = get_post_meta($post->ID, '_filelimit', true); + $redirect = get_post_meta($post->ID, '_redirect', true); + $minimum = get_post_meta($post->ID, '_minimum', true); + $usevariableamount = get_post_meta($post->ID, '_usevariableamount', true); + $variableamount = get_post_meta($post->ID, '_variableamount', true); + $hidetitle = get_post_meta($post->ID, '_hidetitle', true); + + if ($amount == "") { + $amount = 0; + } + if ($filelimit == "") { + $filelimit = 2; + } + if ($paybtn == "") { + $paybtn = 'Pay'; + } + if ($successmsg == "") { + $successmsg = 'Thank you for paying!'; + } + if ($currency == "") { + $currency = 'NGN'; + } + if ($txncharge == "") { + $txncharge = 'merchant'; + } + if ($minimum == "") { + $minimum = 0; + } + if ($usevariableamount == "") { + $usevariableamount = 0; + } + if ($hidetitle == "") { + $hidetitle = 0; + } + if ($variableamount == "") { + $variableamount = ''; + } + // Echo out the field + + + if ($hidetitle == 1) { + echo ''; + } else { + echo ''; + } + echo "Currency:
'; + echo ''; + echo 'Ensure you are activated for the currency you are selecting. Check here for more information.'; + echo 'Amount to be paid(Set 0 for customer input):
'; + echo ''; + if ($minimum == 1) { + echo 'Variable Dropdown Amount:
Pay button Description:
'; + echo ''; + echo 'Add Extra Charge:
'; + echo ' +User logged In:
'; + echo ''; + echo 'Success Message after Payment
'; + echo ''; + echo 'File Upload Limit(MB):
'; + echo ''; + echo 'Redirect to page link after payment(keep blank to use normal success message):
'; + echo ''; + } + function kkd_pff_paystack_editor_add_email_data() + { + global $post; + + // Noncename needed to verify where the data originated + echo ''; + + // Get the location data if its already been entered + $subject = get_post_meta($post->ID, '_subject', true); + $merchant = get_post_meta($post->ID, '_merchant', true); + $heading = get_post_meta($post->ID, '_heading', true); + $message = get_post_meta($post->ID, '_message', true); + $sendreceipt = get_post_meta($post->ID, '_sendreceipt', true); + $sendinvoice = get_post_meta($post->ID, '_sendinvoice', true); + + if ($subject == "") { + $subject = 'Thank you for your payment'; + } + if ($sendreceipt == "") { + $sendreceipt = 'yes'; + } + if ($sendinvoice == "") { + $sendinvoice = 'yes'; + } + if ($heading == "") { + $heading = "We've received your payment"; + } + if ($message == "") { + $message = 'Your payment was received and we appreciate it.'; + } + // Echo out the field + echo 'Send an invoices when a payment is attempted:
'; + echo ''; + echo 'Send Email Receipt:
'; + echo ''; + echo 'Email Subject:
'; + echo ''; + echo 'Merchant Name on Receipt:
'; + echo ''; + echo 'Email Heading:
'; + echo ''; + echo 'Email Body/Message:
'; + echo ''; + } + function kkd_pff_paystack_editor_add_recur_data() + { + global $post; + + // Noncename needed to verify where the data originated + echo ''; + + // Get the location data if its already been entered + $recur = get_post_meta($post->ID, '_recur', true); + $recurplan = get_post_meta($post->ID, '_recurplan', true); + + if ($recur == "") { + $recur = 'no'; + } + if ($recurplan == "") { + $recurplan = ''; + } + // Echo out the field + echo 'Recurring Payment:
'; + echo ''; + echo 'Paystack Recur Plan code:
'; + echo ' + Plan amount must match amount on extra form description.'; + } + function kkd_pff_paystack_reset_stock() + { + } + function kkd_pff_paystack_editor_add_quantity_data() + { + global $post; + + // Noncename needed to verify where the data originated + echo ''; + + // Get the location data if its already been entered + $usequantity = get_post_meta($post->ID, '_usequantity', true); + $useinventory = get_post_meta($post->ID, '_useinventory', true); + $inventory = get_post_meta($post->ID, '_inventory', true); + $sold = get_post_meta($post->ID, '_sold', true); + $quantity = get_post_meta($post->ID, '_quantity', true); + $quantityunit = get_post_meta($post->ID, '_quantityunit', true); + $recur = get_post_meta($post->ID, '_recur', true); + + if ($usequantity == "") { + $usequantity = 'no'; + } + if ($useinventory == "") { + $useinventory = "no"; + } + if ($quantity == "") { + $quantity = '10'; + } + if ($inventory == "") { + if ($sold !== "") { + $inventory = $sold; + } else { + $inventory = '1'; + } + } + if ($sold == "") { + $sold = '0'; + } + $stock = $inventory - $sold; + if ($quantityunit == "") { + $quantityunit = 'Quantity'; + } + + // Echo out the field + echo 'Allow your users pay in multiple quantityQuantified Payment:
'; + if ($recur != "no") { + echo ''; + } else { + echo ''; + } + if ($usequantity == "yes") { + + echo 'Max payable quantity:
'; + echo ' + Your users only get to pay in quantities if the from amount is not set to zero and recur is set to none.'; + echo 'Unit of quantity:
'; + echo ' + What is the unit of this quantity? Default isQuantity
.';
+
+
+ echo 'Inventory Payment:
'; + echo ' + + Set maximum available items in stock + '; + } + if ($useinventory == "yes" && $usequantity == "yes") { + echo 'Total Inventory
'; + echo ''; + echo 'Already sold
'; + echo ' + +Use agreement checkbox:
'; + echo ''; + echo 'Agreement Page Link:
'; + echo ''; + } + function kkd_pff_paystack_editor_add_subaccount_data() + { + global $post; + + // Noncename needed to verify where the data originated + echo ''; + + // Get the location data if its already been entered + $subaccount = get_post_meta($post->ID, '_subaccount', true); + $txnbearer = get_post_meta($post->ID, '_txnbearer', true); + $merchantamount = get_post_meta($post->ID, '_merchantamount', true); + + + if ($subaccount == "") { + $subaccount = ''; + } + if ($merchantamount == "") { + $merchantamount = ''; + } + echo 'Sub Account code:
'; + echo ''; + echo 'Transaction Charge bearer:
'; + echo ''; + echo 'Merchant Amount:
'; + echo ''; + } + function kkd_pff_paystack_editor_add_startdateplan_data() + { + global $post; + + // Noncename needed to verify where the data originated + echo 'User subscribes to plan after number of days:
'; + echo ''; + + // Get the location data if its already been entered + $days = get_post_meta($post->ID, '_startdate_days', true); + $plan = get_post_meta($post->ID, '_startdate_plan_code', true); + $enabled = get_post_meta($post->ID, '_startdate_enabled', true); + + + if ($days == "") { + $days = ''; + } + if ($plan == "") { + $plan = ''; + } + if ($enabled == "") { + $enabled = 0; + } + echo 'Number of days:
'; + echo ''; + echo 'Plan:
'; + echo ''; + if ($enabled == 1) { + echo 'All payments made for this form
+ 0) { + ?> + + + + +
-
-
-
-
-
|
-
-
-
-
-
-
|
-
-
-
-
-
-
-
-
|
-
-
-
-
-
-
|
-
-
-
-
-
-
-
-
|
-
- | -
-
-
-
-
-
|
-
-
-
-
-
-
|
-
- - - | -
-
-
-
-
-
-
-
|
-
- - | -
-
-
-
-
-
-
-
-
-
|
-
-
-
-
-
-
-
-
-
|
-
-
-
-
-
-
-
-
-
|
-
-
-
-
-
-
-
-
|
-
[pff-paystack id="' . $post_id . '"]"
' );
- break;
- case 'payments':
- $num = $helpers->get_payments_count( $post_id );
- echo wp_kses_post( '' . $num . '' );
- break;
- default:
- break;
- }
- }
-}
diff --git a/includes/classes/class-forms-update.php b/includes/classes/class-forms-update.php
deleted file mode 100644
index f421220..0000000
--- a/includes/classes/class-forms-update.php
+++ /dev/null
@@ -1,612 +0,0 @@
-set_vars();
- add_action( 'admin_head', [ $this, 'setup_actions' ] );
- add_filter( 'admin_head', [ $this, 'disable_wyswyg' ], 10, 1 );
-
- // Default Content.
- add_filter('default_content', [ $this, 'default_content' ], 10, 2);
-
- // Define the meta boxes.
- add_action( 'edit_form_after_title', [ $this, 'metabox_action' ] );
- add_action( 'add_meta_boxes', [ $this, 'register_meta_boxes' ] );
-
- // Save the Meta boxes
- add_action( 'save_post', [ $this, 'save_post_meta' ], 1, 2 );
- }
-
- /**
- * Sets useable variables like the fields.
- *
- * @return void
- */
- public function set_vars() {
- $this->helpers = Helpers::get_instance();
- $this->defaults = $this->helpers->get_meta_defaults();
- $this->allowed_html = $this->helpers->get_allowed_html();
- }
-
- /**
- * Add the phone number as the default content when a form is created.
- *
- * @param string $content
- * @param WP_Post $post
- * @return string
- */
- public function default_content( $content, $post ) {
- switch ( $post->post_type ) {
- case 'paystack_form':
- $content = '[text name="' . __( 'Phone Number', 'pff-paystack' ) . '"]';
- break;
- default:
- $content = '';
- break;
- }
- return $content;
- }
-
- /**
- * Run some actions on admin_head
- *
- * @return void
- */
- public function setup_actions() {
- add_filter( 'user_can_richedit', '__return_false', 50 );
- add_filter( 'quicktags_settings', [ $this, 'remove_fullscreen' ], 10, 1 );
-
- remove_action( 'media_buttons', 'media_buttons' );
- remove_meta_box( 'postimagediv', 'post', 'side' );
-
- add_action( 'admin_print_footer_scripts', [ $this, 'shortcode_buttons_script' ] );
- }
-
- /**
- * Outputs CSS to hide the WYSIWYG
- *
- * @param string $default
- * @return string
- */
- public function disable_wyswyg( $default ) {
- if ( 'paystack_form' === get_post_type() ) {
- ?>
-
-
-
- parse_meta_values( $post );
- do_meta_boxes( 'paystack_form', 'pff', $post );
- }
-
- /**
- * Registers our custom metaboxes.
- *
- * @return void
- */
- public function register_meta_boxes() {
- // Register the information boxes.
- if ( isset( $_GET['action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
- add_meta_box( 'pff_paystack_editor_details_box', __( 'Paste shortcode on preferred page', 'paystack_form' ), [ $this, 'shortcode_details' ], 'paystack_form', 'pff' );
- }
- add_meta_box( 'pff_paystack_editor_help_box', __( 'Help Section', 'pff-paystack' ), [ $this, 'help_details' ], 'paystack_form', 'pff' );
-
- // Add in our "normal" meta boxes
- add_meta_box( 'form_data', __( 'Extra Form Description', 'pff-paystack' ), [ $this, 'form_data' ], 'paystack_form', 'normal', 'default' );
- add_meta_box( 'email_data', __( 'Email Receipt Settings', 'pff-paystack' ), [ $this, 'email_data' ], 'paystack_form', 'normal', 'default' );
-
- // Add in our "side" meta boxes
- add_meta_box( 'recuring_data', __( 'Recurring Payment', 'pff-paystack' ), [ $this, 'recur_data' ], 'paystack_form', 'side', 'default' );
- add_meta_box( 'quantity_data', __( 'Quantity Payment', 'pff-paystack' ), [ $this, 'quantity_data' ], 'paystack_form', 'side', 'default' );
- add_meta_box( 'agreement_data', __( 'Agreement checkbox', 'pff-paystack' ), [ $this, 'agreement_data' ], 'paystack_form', 'side', 'default' );
- add_meta_box( 'subaccount_data', __( 'Sub Account', 'pff-paystack' ), [ $this, 'subaccount_data' ], 'paystack_form', 'side', 'default' );
- add_meta_box( 'plan_data', __( '*Special: Subscribe to plan after time', 'pff-paystack' ), [ $this, 'plan_data' ], 'paystack_form', 'side', 'default' );
-
- }
-
- /**
- * Output the shortcode details
- *
- * @param WP_Post $post
- * @return void
- */
- public function shortcode_details( $post ) {
- ?>
- - - - - -
- - - meta = $this->helpers->parse_meta_values( $post ); - } - - /** - * Outputs the Extra Form Description Meta Box. - * - * @return void - */ - public function form_data() { - $html = []; - - // We shall output 1 Nonce Field for all of our metaboxes. - $html[] = wp_nonce_field( 'pff-paystack-save-form', 'pff_paystack_save', true, false ); - - if ($this->meta['hidetitle'] == 1) { - $html[] = ''; - } else { - $html[] = ''; - } - $html[] = 'Currency:
'; - $html[] = ''; - - $html[] = '' . __('Ensure you are activated for the currency you are selecting. Check here for more information.', 'pff-paystack') . ''; - $html[] = '' . __('Amount to be paid(Set 0 for customer input):', 'pff-paystack') . '
'; - $html[] = ''; - if ($this->meta['minimum'] == 1) { - $html[] = '' . __('Variable Dropdown Amount:', 'pff-paystack') . '
' . __('Pay button Description:', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('Add Extra Charge:', 'pff-paystack') . '
'; - $html[] = ' -' . __('User logged In:', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('Success Message after Payment', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('File Upload Limit(MB):', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('Redirect to page link after payment(keep blank to use normal success message):', 'pff-paystack') . '
'; - $html[] = ''; - - // To output the concatenated $html array content - echo wp_kses( implode( '', $html ), $this->allowed_html ); - } - - /** - * Checks to see if the curren value is selected. - * - * @param string $value - * @param string $compare - * @return string - */ - public function is_option_selected( $value, $compare, $selected = 'selected' ) { - if ( $value == $compare ) { - $result = $selected; - } else { - $result = ""; - } - return $result; - } - - /** - * Output the recurring data meta box. - * - * @return void - */ - public function recur_data(){ - $html = []; - $html[] = '' . __('Recurring Payment:', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('Paystack Recur Plan code:', 'pff-paystack') . '
'; - $html[] = ' - ' . __('Plan amount must match amount on extra form description.', 'pff-paystack') . ''; - - // Output the accumulated HTML - echo wp_kses( implode( '', $html ), $this->allowed_html ); - } - - /** - * Add the email metabox - * - * @return void - */ - public function email_data() { - $html = []; - // Echo out the field - $html[] = '' . __('Send an invoice when a payment is attempted:', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('Send Email Receipt:', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('Email Subject:', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('Merchant Name on Receipt:', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('Email Heading:', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('Email Body/Message:', 'pff-paystack') . '
'; - $html[] = ''; - - echo wp_kses( implode( '', $html ), $this->allowed_html ); - } - - /** - * Add the quantity metabox - * - * @return void - */ - public function quantity_data() { - $html = []; - - // Echo out the field - $html[] = '' . __('Allow your users pay in multiple quantity', 'pff-paystack') . ' -' . __('Quantified Payment:', 'pff-paystack') . '
'; - - if ($this->meta['recur'] != "no") { - $html[] = ''; - } else { - $html[] = ''; - } - - if ($this->meta['usequantity'] == "yes") { - - $html[] = '' . __('Max payable quantity:', 'pff-paystack') . '
'; - $html[] = '' . __('Your users only get to pay in quantities if the from amount is not set to zero and recur is set to none.', 'pff-paystack') . ''; - $html[] = '' . __('Unit of quantity:', 'pff-paystack') . '
'; - $html[] = '' . __('What is the unit of this quantity? Default isQuantity
.', 'pff-paystack') . '';
-
- $html[] = '' . __('Inventory Payment:', 'pff-paystack') . '
'; - $html[] = ' - ' . __('Set maximum available items in stock', 'pff-paystack') . ''; - } - - if ($this->meta['useinventory'] == "yes" && $this->meta['usequantity'] == "yes") { - $html[] = '' . __('Total Inventory', 'pff-paystack') . '
'; - $html[] = ''; - $html[] = '' . __('Already sold', 'pff-paystack') . '
'; - $html[] = ' - -' . __( 'Use agreement checkbox:', 'pff-paystack' ) . '
'; - $html[] = ''; - $html[] = '' . __( 'Agreement Page Link:', 'pff-paystack' ) . '
'; - $html[] = ''; - echo wp_kses( implode( '', $html ), $this->allowed_html ); - } - - /** - * Output the Subaccount metabox. - * - * @return void - */ - public function subaccount_data() { - $html = []; - // Add components to the $html array - $html[] = '' . __( 'Sub Account code:', 'pff-paystack' ) . '
'; - $html[] = ''; - $html[] = '' . __( 'Transaction Charge bearer:', 'pff-paystack' ) . '
'; - $html[] = ''; - $html[] = '' . __( 'Merchant Amount:', 'pff-paystack' ) . '
'; - $html[] = ''; - echo wp_kses( implode( '', $html ), $this->allowed_html ); - } - - /** - * Output the Plan metabox - * - * @return void - */ - public function plan_data() { - $html = []; - $html[] = '' . __( 'User subscribes to plan after number of days:', 'pff-paystack' ) . '
'; - $html[] = '' . __( 'Number of days:', 'pff-paystack' ) . '
'; - $html[] = ''; - $html[] = '' . __( 'Plan:', 'pff-paystack' ) . '
'; - $html[] = ''; - - if ($this->meta['startdate_enabled'] == 1) { - $html[] = '- -
- 0 ) { ?> - - -
+
+
+
+
+
|
+
+
+
+
+
+
|
+
+
+
+
+
+
+
+
|
+
+
+
+
+
+
|
+
+
+
+
+
+
+
+
|
+
+ + | +
+
+
+
+
+
+
+
+
+
|
+
+
+
+
+
+
+
+
+
|
+
+ + + | +
+
+
+
+
+
+
+
|
+
+ + | +
+
+
+
+
+
+
+
+
+
|
+
+
+
+
+
+
+
+
+
|
+
+ + + | +
+
+
+
+
+
+
+
|
+
'; + // print_r($_POST); + + $fixedmetadata = kkd_pff_paystack_meta_as_custom_fields($metadata); + // print_r($fixedmetadata ); + $filelimit = get_post_meta($_POST["pf-id"], '_filelimit', true); + $currency = get_post_meta($_POST["pf-id"], '_currency', true); + $formamount = get_post_meta($_POST["pf-id"], '_amount', true);/// From form + $recur = get_post_meta($_POST["pf-id"], '_recur', true); + $subaccount = get_post_meta($_POST["pf-id"], '_subaccount', true); + $txnbearer = get_post_meta($_POST["pf-id"], '_txnbearer', true); + $transaction_charge = get_post_meta($_POST["pf-id"], '_merchantamount', true); + $transaction_charge = $transaction_charge*100; + + $txncharge = get_post_meta($_POST["pf-id"], '_txncharge', true); + $minimum = get_post_meta($_POST["pf-id"], '_minimum', true); + $variableamount = get_post_meta($_POST["pf-id"], '_variableamount', true); + $usevariableamount = get_post_meta($_POST["pf-id"], '_usevariableamount', true); + $amount = (int)str_replace(' ', '', $_POST["pf-amount"]); + $variablename = $_POST["pf-vname"]; + // pf-vname + $originalamount = $amount; + $quantity = 1; + $usequantity = get_post_meta($_POST["pf-id"], '_usequantity', true); + + if (($recur == 'no') && ($formamount != 0)) { + $amount = (int)str_replace(' ', '', $formamount); + } + if ($minimum == 1 && $formamount != 0) { + if ($originalamount < $formamount) { + $amount = $formamount; + } else { + $amount = $originalamount; + } + } + if ($usevariableamount == 1) { + $paymentoptions = explode(',', $variableamount); + if (count($paymentoptions) > 0) { + foreach ($paymentoptions as $key => $paymentoption) { + list($a, $b) = explode(':', $paymentoption); + if ($variablename == $a) { + $amount = $b; + } + } + } + } + $fixedmetadata[] = array( + 'display_name' => 'Unit Price', + 'variable_name' => 'Unit_Price', + 'type' => 'text', + 'value' => $currency.number_format($amount) + ); + if ($usequantity != 'no') { + $quantity = $_POST["pf-quantity"]; + $unitamount = (int)str_replace(' ', '', $amount); + $amount = $quantity*$unitamount; + } + + + + if ($txncharge == 'customer') { + $amount = kkd_pff_paystack_add_paystack_charge($amount); + } + $maxFileSize = $filelimit * 1024 * 1024; + + if (!empty($_FILES)) { + foreach ($_FILES as $keyname => $value) { + if ($value['size'] > 0) { + if ($value['size'] > $maxFileSize) { + $response['result'] = 'failed'; + $response['message'] = 'Max upload size is '.$filelimit."MB"; + exit(json_encode($response)); + } else { + $attachment_id = media_handle_upload($keyname, $_POST["pf-id"]); + $url = wp_get_attachment_url($attachment_id); + $fixedmetadata[] = array( + 'display_name' => ucwords(str_replace("_", " ", $keyname)), + 'variable_name' => $keyname, + 'type' => 'link', + 'value' => $url + ); + } + } else { + $fixedmetadata[] = array( + 'display_name' => ucwords(str_replace("_", " ", $keyname)), + 'variable_name' => $keyname, + 'type' => 'text', + 'value' => 'No file Uploaded' + ); + } + } + } + $plancode = 'none'; + if ($recur != 'no') { + if ($recur == 'optional') { + $interval = $_POST['pf-interval']; + if ($interval != 'no') { + unset($metadata['pf-interval']); + $mode = esc_attr(get_option('mode')); + if ($mode == 'test') { + $key = esc_attr(get_option('tsk')); + } else { + $key = esc_attr(get_option('lsk')); + } + $koboamount = $amount*100; + //Create Plan + $paystack_url = 'https://api.paystack.co/plan'; + $check_url = 'https://api.paystack.co/plan?amount='.$koboamount.'&interval='.$interval; + $headers = array( + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . $key + ); + + $checkargs = array( + 'headers' => $headers, + 'timeout' => 60 + ); + // Check if plan exist + $checkrequest = wp_remote_get($check_url, $checkargs); + if (!is_wp_error($checkrequest)) { + $response = json_decode(wp_remote_retrieve_body($checkrequest)); + if ($response->meta->total >= 1) { + $plan = $response->data[0]; + $plancode = $plan->plan_code; + $fixedmetadata[] = array( + 'display_name' => 'Plan Interval', + 'variable_name' => 'Plan Interval', + 'type' => 'text', + 'value' => $plan->interval + ); + } else { + //Create Plan + $body = array( + 'name' => $currency.number_format($originalamount).' ['.$currency.number_format($amount).'] - '.$interval, + 'amount' => $koboamount, + 'interval' => $interval + ); + $args = array( + 'body' => json_encode($body), + 'headers' => $headers, + 'timeout' => 60 + ); + + $request = wp_remote_post($paystack_url, $args); + if (! is_wp_error($request)) { + $paystack_response = json_decode(wp_remote_retrieve_body($request)); + $plancode = $paystack_response->data->plan_code; + $fixedmetadata[] = array( + 'display_name' => 'Plan Interval', + 'variable_name' => 'Plan Interval', + 'type' => 'text', + 'value' => $paystack_response->data->interval + ); + } + } + } + } + } else { + //Use Plan Code + $plancode = $_POST['pf-plancode']; + unset($metadata['pf-plancode']); + } + } + + if ($plancode != 'none') { + $fixedmetadata[] = array( + 'display_name' => 'Plan', + 'variable_name' => 'Plan', + 'type' => 'text', + 'value' => $plancode + ); + } + + $insert = array( + 'post_id' => intval($_POST["pf-id"]), + 'email' => sanitize_email($_POST["pf-pemail"]), + 'user_id' => intval($_POST["pf-user_id"]), + 'amount' => sanitize_text_field($amount), + 'plan' => sanitize_text_field($plancode), + 'ip' => kkd_pff_paystack_get_the_user_ip(), // Ensure this function returns a sanitized IP address + 'txn_code' => sanitize_text_field($code), + 'metadata' => wp_json_encode($fixedmetadata) // Use wp_json_encode for WordPress environments + ); + + $exist = $wpdb->get_results( + $wpdb->prepare( + "SELECT * FROM $table WHERE post_id = %d AND email = %s AND user_id = %d AND amount = %s AND plan = %s AND ip = %s AND paid = '0' AND metadata = %s", + $insert['post_id'], $insert['email'], $insert['user_id'], $insert['amount'], $insert['plan'], $insert['ip'], $insert['metadata'] + ) + ); + if (count($exist) > 0) { + // $insert['txn_code'] = $code; + // $insert['plan'] = $exist[0]->plan; + $wpdb->query( + $wpdb->prepare( + "UPDATE {$table} SET txn_code = %s, plan = %s WHERE id = %d", + $code, + $insert['plan'], + $exist[0]->id + ) + ); + } else { + $wpdb->insert( + $table, + $insert + ); + // if("yes" == get_post_meta($insert['post_id'],'_sendinvoice',true)){ + kkd_pff_paystack_send_invoice($currency, $insert['amount'], $fullname, $insert['email'], $code); + // } + } + if ($subaccount == "" || !isset($subaccount)) { + $subaccount = null; + $txnbearer = null; + $transaction_charge = null; + } + if ($transaction_charge == "" || $transaction_charge == 0 || $transaction_charge == null) { + $transaction_charge = null; + } + + $amount = floatval($insert['amount'])*100; + $response = array( + 'result' => 'success', + 'code' => $insert['txn_code'], + 'plan' => $insert['plan'], + 'quantity' => $quantity, + 'email' => $insert['email'], + 'name' => $fullname, + 'total' => round($amount), + 'custom_fields' => $fixedmetadata, + 'currency' => $currency, + 'subaccount' => $subaccount, + 'txnbearer' => $txnbearer, + 'transaction_charge' => $transaction_charge + ); + // print_r($response); + echo json_encode($response, JSON_NUMERIC_CHECK); + + die(); +} + +function kkd_pff_paystack_meta_as_custom_fields($metadata) +{ + $custom_fields = array(); + foreach ($metadata as $key => $value) { + if (is_array($value)) { + $value = implode(', ', $value); + } + if ($key == 'pf-fname') { + $custom_fields[] = array( + 'display_name' => 'Full Name', + 'variable_name' => 'Full_Name', + 'type' => 'text', + 'value' => $value + ); + } elseif ($key == 'pf-plancode') { + $custom_fields[] = array( + 'display_name' => 'Plan', + 'variable_name' => 'Plan', + 'type' => 'text', + 'value' => $value + ); + } elseif ($key == 'pf-vname') { + $custom_fields[] = array( + 'display_name' => 'Payment Option', + 'variable_name' => 'Payment Option', + 'type' => 'text', + 'value' => $value + ); + } elseif ($key == 'pf-interval') { + $custom_fields[] = array( + 'display_name' => 'Plan Interval', + 'variable_name' => 'Plan Interval', + 'type' => 'text', + 'value' => $value + ); + } elseif ($key == 'pf-quantity') { + $custom_fields[] = array( + 'display_name' => 'Quantity', + 'variable_name' => 'Quantity', + 'type' => 'text', + 'value' => $value + ); + } else { + $custom_fields[] = array( + 'display_name' => ucwords(str_replace("_", " ", $key)), + 'variable_name' => $key, + 'type' => 'text', + 'value' => $value + ); + } + } + return $custom_fields; +} + +add_action('wp_ajax_kkd_pff_paystack_confirm_payment', 'kkd_pff_paystack_confirm_payment'); +add_action('wp_ajax_nopriv_kkd_pff_paystack_confirm_payment', 'kkd_pff_paystack_confirm_payment'); + +function kkd_pff_paystack_confirm_payment() +{ + if (trim($_POST['code']) == '') { + $response['error'] = true; + $response['error_message'] = "Did you make a payment?"; + + exit(json_encode($response)); + } + global $wpdb; + $table = $wpdb->prefix.KKD_PFF_PAYSTACK_TABLE; + $code = sanitize_text_field($_POST['code']); + $table = $wpdb->prefix . KKD_PFF_PAYSTACK_TABLE; + $record = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table} WHERE txn_code = %s", $code)); + if (array_key_exists("0", $record)) { + $payment_array = $record[0]; + $amount = get_post_meta($payment_array->post_id, '_amount', true); + $recur = get_post_meta($payment_array->post_id, '_recur', true); + $currency = get_post_meta($payment_array->post_id, '_currency', true); + $txncharge = get_post_meta($payment_array->post_id, '_txncharge', true); + $redirect = get_post_meta($payment_array->post_id, '_redirect', true); + $minimum = get_post_meta($payment_array->post_id, '_minimum', true); + $usevariableamount = get_post_meta($payment_array->post_id, '_usevariableamount', true); + $variableamount = get_post_meta($payment_array->post_id, '_variableamount', true); + + if ($minimum == 1 && $amount != 0) { + if ($payment_array->amount < $formamount) { + $amount = $formamount; + } else { + $amount = $payment_array->amount; + } + } + $oamount = $amount; + $mode = esc_attr(get_option('mode')); + if ($mode == 'test') { + $key = esc_attr(get_option('tsk')); + } else { + $key = esc_attr(get_option('lsk')); + } + $paystack_url = 'https://api.paystack.co/transaction/verify/' . $code; + $headers = array( + 'Authorization' => 'Bearer ' . $key + ); + $args = array( + 'headers' => $headers, + 'timeout' => 60 + ); + $request = wp_remote_get($paystack_url, $args); + if (! is_wp_error($request) && 200 == wp_remote_retrieve_response_code($request)) { + $paystack_response = json_decode(wp_remote_retrieve_body($request)); + if ('success' == $paystack_response->data->status) { + $customer_code = $paystack_response->data->customer->customer_code; + $amount_paid = $paystack_response->data->amount / 100; + $paystack_ref = $paystack_response->data->reference; + $paid_at = $paystack_response->data->transaction_date; + if ($recur == 'optional' || $recur == 'plan') { + $wpdb->update($table, array( 'paid' => 1,'amount' => $amount_paid, 'paid_at' => $paid_at), array('txn_code'=>$paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + } else { + if ($amount == 0 || $usevariableamount == 1) { + $wpdb->update($table, array( 'paid' => 1,'amount' => $amount_paid, 'paid_at' => $paid_at), array('txn_code'=>$paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + // kkd_pff_paystack_send_receipt($currency,$amount,$name,$payment_array->email,$code,$metadata) + } else { + if ($txncharge == 'customer') { + if ($minimum == 0 && $amount != 0) { + $oamount = kkd_pff_paystack_add_paystack_charge($oamount); + } + } + if ($oamount != $amount_paid) { + $message = "Invalid amount Paid. Amount required is ".$currency."".number_format($oamount).""; + $result = "failed"; + } else { + $wpdb->update($table, array( 'paid' => 1, 'paid_at' => $paid_at), array('txn_code'=>$paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + } + } + } + } else { + $message = "Transaction Failed/Invalid Code"; + $result = "failed"; + } + } else { + $message = "Payment Verifiction Failed"; + $result = "failed"; + } + } else { + $message = "Payment Verification Failed."; + $result = "failed"; + } + + if ($result == 'success') { + /// + //Create Plan + $enabled_custom_plan = get_post_meta($payment_array->post_id, '_startdate_enabled', true); + if ($enabled_custom_plan == 1) { + $mode = esc_attr(get_option('mode')); + if ($mode == 'test') { + $key = esc_attr(get_option('tsk')); + } else { + $key = esc_attr(get_option('lsk')); + } + //Create Plan + $paystack_url = 'https://api.paystack.co/subscription'; + $headers = array( + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . $key + ); + $custom_plan = get_post_meta($payment_array->post_id, '_startdate_plan_code', true); + $days = get_post_meta($payment_array->post_id, '_startdate_days', true); + + $start_date = date("c", strtotime("+".$days." days")); + $body = array( + 'start_date' => $start_date, + 'plan' => $custom_plan, + 'customer' => $customer_code + ); + $args = array( + 'body' => json_encode($body), + 'headers' => $headers, + 'timeout' => 60 + ); + + $request = wp_remote_post($paystack_url, $args); + if (! is_wp_error($request)) { + $paystack_response = json_decode(wp_remote_retrieve_body($request)); + $plancode = $paystack_response->data->subscription_code; + // $message.= $message.'Subscribed'; + } else { + echo "
'.$plancode.'sssss'; + } + } + + $sendreceipt = get_post_meta($payment_array->post_id, '_sendreceipt', true); + if ($sendreceipt == 'yes') { + $decoded = json_decode($payment_array->metadata); + $fullname = $decoded[0]->value; + kkd_pff_paystack_send_receipt($payment_array->post_id, $currency, $amount_paid, $fullname, $payment_array->email, $paystack_ref, $payment_array->metadata); + kkd_pff_paystack_send_receipt_owner($payment_array->post_id, $currency, $amount_paid, $fullname, $payment_array->email, $paystack_ref, $payment_array->metadata); + } + } + $response = array( + 'result' => $result, + 'message' => $message, + ); + if ($result == 'success' && $redirect != '') { + $response['result'] = 'success2'; + $response['link'] = $redirect; + } + + + echo json_encode($response); + + die(); +} + + +add_action('wp_ajax_kkd_pff_paystack_retry_action', 'kkd_pff_paystack_retry_action'); +add_action('wp_ajax_nopriv_kkd_pff_paystack_retry_action', 'kkd_pff_paystack_retry_action'); +function kkd_pff_paystack_retry_action() +{ + if (trim($_POST['code']) == '') { + $response['result'] = 'failed'; + $response['message'] = 'Cde is required'; + + // Exit here, for not processing further because of the error + exit(json_encode($response)); + } + do_action('kkd_pff_paystack_before_save'); + + global $wpdb; + $newcode = kkd_pff_paystack_generate_code(); + $newcode = $newcode.'_2'; + $insert = array(); + + $code = sanitize_text_field($_POST['code']); + $table = $wpdb->prefix . KKD_PFF_PAYSTACK_TABLE; + $record = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table} WHERE txn_code = %s", $code)); + if (array_key_exists("0", $record)) { + $dbdata = $record[0]; + $plan = $dbdata->plan; + $quantity = 1; + $wpdb->update($table, array( 'txn_code_2' => $newcode), array('txn_code' => $code)); + + $currency = get_post_meta($dbdata->post_id, '_currency', true); + $subaccount = get_post_meta($dbdata->post_id, '_subaccount', true); + $txnbearer = get_post_meta($dbdata->post_id, '_txnbearer', true); + $transaction_charge = get_post_meta($dbdata->post_id, '_merchantamount', true); + $transaction_charge = $transaction_charge*100; + $fixedmetadata = kkd_pff_paystack_meta_as_custom_fields($dbdata->metadata); + $nmeta = json_decode($dbdata->metadata); + foreach ($nmeta as $nkey => $nvalue) { + if ($nvalue->variable_name == 'Quantity') { + $quantity = $nvalue->value; + } + if ($nvalue->variable_name == 'Full_Name') { + $fullname = $nvalue->value; + } + } + } + if ($subaccount == "" || !isset($subaccount)) { + $subaccount = null; + $txnbearer = null; + $transaction_charge = null; + } + if ($transaction_charge == "" || $transaction_charge == 0 || $transaction_charge == null || !isset($transaction_charge)) { + $transaction_charge = null; + } + $response = array( + 'result' => 'success', + 'code' => $newcode, + 'plan' => $plan, + 'quantity' => $quantity, + 'email' => $dbdata->email, + 'name' => $fullname, + 'total' => $dbdata->amount*100, + 'custom_fields' => $fixedmetadata, + 'subaccount' => $subaccount, + 'txnbearer' => $txnbearer, + 'transaction_charge' => $transaction_charge + ); + echo json_encode($response); + + die(); +} +add_action('wp_ajax_kkd_pff_paystack_rconfirm_payment', 'kkd_pff_paystack_rconfirm_payment'); +add_action('wp_ajax_nopriv_kkd_pff_paystack_rconfirm_payment', 'kkd_pff_paystack_rconfirm_payment'); + +function kkd_pff_paystack_rconfirm_payment() +{ + if (trim($_POST['code']) == '') { + $response['error'] = true; + $response['error_message'] = "Did you make a payment?"; + + exit(json_encode($response)); + } + global $wpdb; + $table = $wpdb->prefix.KKD_PFF_PAYSTACK_TABLE; + $code = sanitize_text_field($_POST['code']); + $record = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table} WHERE txn_code_2 = %s", $code)); + + if (array_key_exists("0", $record)) { + $payment_array = $record[0]; + $amount = get_post_meta($payment_array->post_id, '_amount', true); + $recur = get_post_meta($payment_array->post_id, '_recur', true); + $currency = get_post_meta($payment_array->post_id, '_currency', true); + $txncharge = get_post_meta($payment_array->post_id, '_txncharge', true); + $redirect = get_post_meta($payment_array->post_id, '_redirect', true); + + + $mode = esc_attr(get_option('mode')); + if ($mode == 'test') { + $key = esc_attr(get_option('tsk')); + } else { + $key = esc_attr(get_option('lsk')); + } + $paystack_url = 'https://api.paystack.co/transaction/verify/' . $code; + $headers = array( + 'Authorization' => 'Bearer ' . $key + ); + $args = array( + 'headers' => $headers, + 'timeout' => 60 + ); + $request = wp_remote_get($paystack_url, $args); + if (! is_wp_error($request) && 200 == wp_remote_retrieve_response_code($request)) { + $paystack_response = json_decode(wp_remote_retrieve_body($request)); + if ('success' == $paystack_response->data->status) { + $amount_paid = $paystack_response->data->amount / 100; + $paystack_ref = $paystack_response->data->reference; + $paid_at = $paystack_response->data->transaction_date; + if ($recur == 'optional' || $recur == 'plan') { + $wpdb->update($table, array( 'paid' => 1,'amount' =>$amount_paid,'paid_at' => $paid_at), array('txn_code_2'=>$paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + } else { + if ($amount == 0) { + $wpdb->update($table, array( 'paid' => 1,'amount' =>$amount_paid,'paid_at' => $paid_at), array('txn_code_2'=>$paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + // kkd_pff_paystack_send_receipt($currency,$amount,$name,$payment_array->email,$code,$metadata) + } else { + $usequantity = get_post_meta($payment_array->post_id, '_usequantity', true); + if ($usequantity == 'no') { + $amount = (int)str_replace(' ', '', $amount); + } else { + $quantity = $_POST["quantity"]; + $unitamount = (int)str_replace(' ', '', $amount); + $amount = $quantity*$unitamount; + } + + + if ($txncharge == 'customer') { + $amount = kkd_pff_paystack_add_paystack_charge($amount); + } + if ($amount != $amount_paid) { + $message = "Invalid amount Paid. Amount required is ".$currency."".number_format($amount).""; + $result = "failed"; + } else { + $wpdb->update($table, array( 'paid' => 1, 'paid_at' => $paid_at), array('txn_code_2'=>$paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + } + } + } + } else { + $message = "Transaction Failed/Invalid Code"; + $result = "failed"; + } + } + } else { + $message = "Payment Verification Failed."; + $result = "failed"; + } + + if ($result == 'success') { + $sendreceipt = get_post_meta($payment_array->post_id, '_sendreceipt', true); + if ($sendreceipt == 'yes') { + $decoded = json_decode($payment_array->metadata); + $fullname = $decoded[0]->value; + kkd_pff_paystack_send_receipt($payment_array->post_id, $currency, $amount_paid, $fullname, $payment_array->email, $paystack_ref, $payment_array->metadata); + kkd_pff_paystack_send_receipt_owner($payment_array->post_id, $currency, $amount_paid, $fullname, $payment_array->email, $paystack_ref, $payment_array->metadata); + } + } + $response = array( + 'result' => $result, + 'message' => $message, + ); + if ($result == 'success' && $redirect != '') { + $response['result'] = 'success2'; + $response['link'] = $redirect; + } + + + echo json_encode($response); + + die(); +} diff --git a/public/class-paystack-forms-public.php b/public/class-paystack-forms-public.php new file mode 100644 index 0000000..0cbc42d --- /dev/null +++ b/public/class-paystack-forms-public.php @@ -0,0 +1,3141 @@ +plugin_name = $plugin_name; + $this->version = $version; + } + public function enqueue_styles() + { + wp_enqueue_style($this->plugin_name . '1', plugin_dir_url(__FILE__) . 'css/pff-paystack-style.css', array(), $this->version, 'all'); + wp_enqueue_style($this->plugin_name . '2', plugin_dir_url(__FILE__) . 'css/font-awesome.min.css', array(), $this->version, 'all'); + } + + public static function fetchPublicKey() + { + $mode = esc_attr(get_option('mode')); + if ($mode == 'test') { + $key = esc_attr(get_option('tpk')); + } else { + $key = esc_attr(get_option('lpk')); + } + return $key; + } + + public static function fetchFeeSettings() + { + $ret = []; + $ret['prc'] = intval(floatval(esc_attr(get_option('prc', 1.5))) * 100) / 10000; + $ret['ths'] = intval(floatval(esc_attr(get_option('ths', 2500))) * 100); + $ret['adc'] = intval(floatval(esc_attr(get_option('adc', 100))) * 100); + $ret['cap'] = intval(floatval(esc_attr(get_option('cap', 2000))) * 100); + return $ret; + } + + public function enqueue_scripts() + { + global $posts; + $pattern = get_shortcode_regex(); + preg_match('/'.$pattern.'/s', $posts[0]->post_content, $matches); + + wp_enqueue_script('blockUI', plugin_dir_url(__FILE__) . 'js/jquery.blockUI.min.js', array('jquery'), $this->version, true, true); + wp_enqueue_script('jquery-ui-core'); + + if(is_array($matches)) { + if(count($matches) > 0) { + if($matches[2] == 'pff-paystack') { + wp_register_script('Paystack', 'https://js.paystack.co/v1/inline.js', false, '1'); + wp_enqueue_script('Paystack'); + wp_enqueue_script('paystack_frontend', plugin_dir_url(__FILE__) . 'js/paystack-forms-public.js', array('jquery'), $this->version, true, true); + wp_localize_script('paystack_frontend', 'kkd_pff_settings', array('key' => Kkd_Pff_Paystack_Public::fetchPublicKey(), 'fee' => Kkd_Pff_Paystack_Public::fetchFeeSettings()), $this->version, true, true); + } + } + } + + + // wp_enqueue_script('blockUI', plugin_dir_url(__FILE__) . 'js/jquery.blockUI.min.js', array('jquery'), $this->version, true, true); + // wp_enqueue_script('jquery-ui-core'); + // wp_register_script('Paystack', 'https://js.paystack.co/v1/inline.js', false, '1'); + // wp_enqueue_script('Paystack'); + // wp_enqueue_script('paystack_frontend', plugin_dir_url(__FILE__) . 'js/paystack-forms-public.js', array('jquery'), $this->version, true, true); + // wp_localize_script('paystack_frontend', 'kkd_pff_settings', array('key' => Kkd_Pff_Paystack_Public::fetchPublicKey(), 'fee' => Kkd_Pff_Paystack_Public::fetchFeeSettings()), $this->version, true, true); + } +} + +define('KKD_PFF_PAYSTACK_PERCENTAGE', 0.015); +define('KKD_PFF_PAYSTACK_CROSSOVER_TOTAL', 250000); +define('KKD_PFF_PAYSTACK_ADDITIONAL_CHARGE', 10000); +define('KKD_PFF_PAYSTACK_LOCAL_CAP', 200000); + +define('KKD_PFF_PAYSTACK_CHARGE_DIVIDER', floatval(1 - KKD_PFF_PAYSTACK_PERCENTAGE)); +define('KKD_PFF_PAYSTACK_CROSSOVER_AMOUNT', intval((KKD_PFF_PAYSTACK_CROSSOVER_TOTAL * KKD_PFF_PAYSTACK_CHARGE_DIVIDER) - KKD_PFF_PAYSTACK_ADDITIONAL_CHARGE)); +define('KKD_PFF_PAYSTACK_FLATLINE_AMOUNT_PLUS_CHARGE', intval((KKD_PFF_PAYSTACK_LOCAL_CAP - KKD_PFF_PAYSTACK_ADDITIONAL_CHARGE) / KKD_PFF_PAYSTACK_PERCENTAGE)); +define('KKD_PFF_PAYSTACK_FLATLINE_AMOUNT', KKD_PFF_PAYSTACK_FLATLINE_AMOUNT_PLUS_CHARGE - KKD_PFF_PAYSTACK_LOCAL_CAP); + +class Kkd_Pff_Paystack_PaystackCharge +{ + public $percentage; + public $additional_charge; + public $crossover_total; + public $cap; + + public $charge_divider; + public $crossover; + public $flatline_plus_charge; + public $flatline; + + public function __construct($percentage = 0.015, $additional_charge = 10000, $crossover_total = 250000, $cap = 200000) + { + $this->percentage = $percentage; + $this->additional_charge = $additional_charge; + $this->crossover_total = $crossover_total; + $this->cap = $cap; + $this->__setup(); + } + + private function __setup() + { + $this->charge_divider = $this->__charge_divider(); + $this->crossover = $this->__crossover(); + $this->flatline_plus_charge = $this->__flatline_plus_charge(); + $this->flatline = $this->__flatline(); + } + + private function __charge_divider() + { + return floatval(1 - $this->percentage); + } + + private function __crossover() + { + return ceil(($this->crossover_total * $this->charge_divider) - $this->additional_charge); + } + + private function __flatline_plus_charge() + { + return floor(($this->cap - $this->additional_charge) / $this->percentage); + } + + private function __flatline() + { + return $this->flatline_plus_charge - $this->cap; + } + + public function add_for_kobo($amountinkobo) + { + if ($amountinkobo > $this->flatline) { + return $amountinkobo + $this->cap; + } elseif ($amountinkobo > $this->crossover) { + return ceil(($amountinkobo + $this->additional_charge) / $this->charge_divider); + } else { + return ceil($amountinkobo / $this->charge_divider); + } + } + + public function add_for_ngn($amountinngn) + { + return $this->add_for_kobo(ceil($amountinngn * 100)) / 100; + } +} + +function kkd_pff_paystack_add_paystack_charge($amount) +{ + $feeSettings = Kkd_Pff_Paystack_Public::fetchFeeSettings(); + $pc = new Kkd_Pff_Paystack_PaystackCharge( + $feeSettings['prc'], + $feeSettings['adc'], + $feeSettings['ths'], + $feeSettings['cap'] + ); + return $pc->add_for_ngn($amount); +} + +add_filter("wp_mail_content_type", "kkd_pff_paystack_mail_content_type"); +function kkd_pff_paystack_mail_content_type() +{ + return "text/html"; +} +add_filter("wp_mail_from_name", "kkd_pff_paystack_mail_from_name"); +function kkd_pff_paystack_mail_from_name() +{ + $name = get_option('blogname'); + return $name; +} + + +function kkd_pff_paystack_send_invoice($currency, $amount, $name, $email, $code) +{ + // echo date('F j,Y'); + $user_email = stripslashes($email); + + $email_subject = "Payment Invoice for " . $currency . ' ' . number_format($amount); + + ob_start(); ?> + + + + + + + + + + + ++ + + + + + ++ + + + " . "\r\n"); + $headers = "From: " . $website . "<$admin_email>" . "\r\n"; + wp_mail($user_email, $email_subject, $message, $headers); +} +function kkd_pff_paystack_send_receipt($id, $currency, $amount, $name, $email, $code, $metadata) +{ + // echo date('F j,Y'); + // error_log(print_r("Sending reciept", TRUE)); + $user_email = stripslashes($email); + $subject = get_post_meta($id, '_subject', true); + $merchant = get_post_meta($id, '_merchant', true); + $heading = get_post_meta($id, '_heading', true); + $sitemessage = get_post_meta($id, '_message', true); + + $email_subject = $subject; + + ob_start(); ?> + + + + + + + + + + + ++++ +
++ + ++ ++++++ +
++ + ++ ++ +
++ + ++ ++++++ +
++ + ++ + ++ +
++ + ++ ++++++ +
++ + ++ + + + ++++ +
++ + ++ + ++ +
++ + ++ ++++++ +
++ + ++ +You're getting this email because
+
you tried making a payment to .+ +
++ + +Use this link below to try again, if you encountered
+
any issue while trying to make the payment.
++ + Try Again + + ++ +
++ + ++ ++++++ +
++ + ++ +
++++ +
++ + ++ ++ + + + + + + ++ + + + + " . "\r\n"); + $headers = "From: " . $website . "<$admin_email>" . "\r\n"; + wp_mail($user_email, $email_subject, $message, $headers); +} +function kkd_pff_paystack_send_receipt_owner($id, $currency, $amount, $name, $email, $code, $metadata) +{ + // echo date('F j,Y'); + $user_email = stripslashes($email); + $subject = "You just received a payment"; + $heading = get_post_meta($id, '_heading', true); + $sitemessage = get_post_meta($id, '_message', true); + + $email_subject = $subject; + + ob_start(); ?> + + + + + + + + + + + ++++ +
++ + ++ + ++ +
++ + ++ + ++ ++ +++ ++ +
++ + ++ ++ +
Hello ,
+ ++
+ +
++ + ++ + ++ ++ ++++ +
++ + ++ ++ +
++ + ++ + ++ + +Your Details ++ Amount :
+
+ Email :
+ $item) { + if ($item->type == 'text') { + echo esc_html($item->display_name) . " :" . $item->value . "
"; + } else { + echo esc_html($item->display_name) . " : link
"; + } + } + } else { + $text = ''; + if (count($new) > 0) { + foreach ($new as $key => $item) { + echo esc_html($key) . " :" . $item . "
"; + } + } + } ?> + Transaction code:
++ +
++ + ++ + + ++ +
++ + ++ ++++++ +
++ + ++ +
++++ +
++ + ++ ++ + + + + + + ++ + + + + " . "\r\n"); + $headers = "From: " . $website . "<$admin_email>" . "\r\n"; + wp_mail($admin_email, $email_subject, $message, $headers); +} +function kkd_pff_paystack_fetch_plan($code) +{ + $mode = esc_attr(get_option('mode')); + if ($mode == 'test') { + $key = esc_attr(get_option('tsk')); + } else { + $key = esc_attr(get_option('lsk')); + } + $paystack_url = 'https://api.paystack.co/plan/' . $code; + $headers = array( + 'Authorization' => 'Bearer ' . $key + ); + $args = array( + 'headers' => $headers, + 'timeout' => 60 + ); + $request = wp_remote_get($paystack_url, $args); + if (!is_wp_error($request)) { + $paystack_response = json_decode(wp_remote_retrieve_body($request)); + } + return $paystack_response; +} +function kkd_pff_paystack_form_shortcode($atts) +{ + ob_start(); + + // Ensure the current user is populated + global $current_user; + wp_get_current_user(); + $user_id = $current_user->ID; + $email = sanitize_email($current_user->user_email); + $fname = sanitize_text_field($current_user->user_firstname); + $lname = sanitize_text_field($current_user->user_lastname); + $fullname = $fname || $lname ? trim($fname . ' ' . $lname) : ''; + + // Use array access for shortcode attributes + $atts = shortcode_atts(array('id' => 0), $atts, 'paystack_form'); + $id = intval($atts['id']); // Ensure $id is an integer + + $pk = Kkd_Pff_Paystack_Public::fetchPublicKey(); + if (!$pk) { + $settingslink = esc_url(get_admin_url(null, 'edit.php?post_type=paystack_form&page=class-paystack-forms-admin.php')); + echo "+++ +
++ + ++ + ++ +
++ + ++ + ++ ++ +++ ++ +
++ + ++ ++
You just received a payment
++ +
++ + ++ + ++ ++ ++++ +
++ + ++ ++ +
++ + ++ + ++ + +Payment Details ++ Amount :
+
+ Email :
+ $item) { + if ($item->type == 'text') { + echo esc_html($item->display_name) . " :" . $item->value . "
"; + } else { + echo esc_html($item->display_name) . " : link
"; + } + } + } else { + $text = ''; + if (count($new) > 0) { + foreach ($new as $key => $item) { + echo esc_html($key) . " :" . $item . "
"; + } + } + } ?> + Transaction code:
++ +
++ + ++ + + ++ +
++ + ++ ++++++ +
++ + ++ +
++++ +
++ + ++ +You must set your Paystack API keys first settings
"; + return ob_get_clean(); // Return early to avoid further processing + } + + if ($id > 0) { + $obj = get_post($id); + if ($obj && $obj->post_type === 'paystack_form') { + // Fetch and sanitize meta values + $meta_keys = [ + '_amount', '_successmsg', '_paybtn', '_loggedin', '_txncharge', + '_currency', '_recur', '_recurplan', '_usequantity', '_quantity', + '_useagreement', '_agreementlink', '_minimum', '_variableamount', + '_usevariableamount', '_hidetitle' + ]; + $meta = []; + foreach ($meta_keys as $key) { + $meta[$key] = sanitize_text_field(get_post_meta($id, $key, true)); + } + + // Ensure minimum defaults are set + $meta['_minimum'] = $meta['_minimum'] === "" ? 0 : $meta['_minimum']; + $meta['_usevariableamount'] = $meta['_usevariableamount'] === "" ? 0 : $meta['_usevariableamount']; + $meta['_usequantity'] = $meta['_usequantity'] === "" ? 'no' : $meta['_usequantity']; + $minimum = floatval($meta['_minimum']); + $currency = $meta['_currency'] === "" ? 'NGN' : $meta['_currency']; + $txncharge = floatval($meta['_txncharge']); + // Process variable amount options if applicable + $paymentoptions = []; + if ($meta['_usevariableamount'] == 1) { + $paymentoptions = explode(',', $meta['_variableamount']); + $paymentoptions = array_map('sanitize_text_field', $paymentoptions); + } + $showbtn = true; + $planerrorcode = 'Input Correct Recurring Plan Code'; + $recur = $meta['_recur']; + $recurplan = $meta['_recurplan']; + if ($meta['_recur']== 'plan') { + if ($meta['_recurplan'] == '' || $meta['_recurplan'] == '') { + $showbtn = false; + } else { + $plan = kkd_pff_paystack_fetch_plan($meta['_recurplan']); + if (isset($plan->data->amount)) { + $planamount = $plan->data->amount/100; + } else { + $showbtn = false; + } + } + } + // Check if the form should be displayed based on user login status + $show_form = ($user_id != 0 && $meta['_loggedin'] == 'yes') || $meta['_loggedin'] == 'no'; + + if ($show_form) { + // Form title + if ($meta['_hidetitle'] != 1) { + echo "" . esc_html($obj->post_title) . "
"; + } + + // Start form output + echo '
'; + // print_r($_POST); + + $untouchedmetadata = kkd_pff_paystack_meta_as_custom_fields($metadata); + $fixedmetadata = []; + // print_r($fixedmetadata ); + $filelimit = get_post_meta($_POST["pf-id"], '_filelimit', true); + $currency = get_post_meta($_POST["pf-id"], '_currency', true); + $formamount = get_post_meta($_POST["pf-id"], '_amount', true); /// From form + $recur = get_post_meta($_POST["pf-id"], '_recur', true); + $subaccount = get_post_meta($_POST["pf-id"], '_subaccount', true); + $txnbearer = get_post_meta($_POST["pf-id"], '_txnbearer', true); + $transaction_charge = get_post_meta($_POST["pf-id"], '_merchantamount', true); + $transaction_charge = intval(floatval($transaction_charge) * 100); + + $txncharge = get_post_meta($_POST["pf-id"], '_txncharge', true); + $minimum = get_post_meta($_POST["pf-id"], '_minimum', true); + $variableamount = get_post_meta($_POST["pf-id"], '_variableamount', true); + $usevariableamount = get_post_meta($_POST["pf-id"], '_usevariableamount', true); + $amount = (int) str_replace(' ', '', $_POST["pf-amount"]); + $variablename = $_POST["pf-vname"]; + $originalamount = $amount; + $quantity = 1; + $usequantity = get_post_meta($_POST["pf-id"], '_usequantity', true); + + if (($recur == 'no') && (floatval($formamount) != 0)) { + $amount = (int) str_replace(' ', '', floatval($formamount)); + } + if ($minimum == 1 && floatval($formamount) != 0) { + if ($originalamount < floatval($formamount)) { + $amount = floatval($formamount); + } else { + $amount = $originalamount; + } + } + if ($usevariableamount == 1) { + $paymentoptions = explode(',', $variableamount); + if (count($paymentoptions) > 0) { + foreach ($paymentoptions as $key => $paymentoption) { + list($a, $b) = explode(':', $paymentoption); + if ($variablename == $a) { + $amount = $b; + } + } + } + } + $fixedmetadata[] = array( + 'display_name' => 'Unit Price', + 'variable_name' => 'Unit_Price', + 'type' => 'text', + 'value' => $currency . number_format($amount) + ); + if ($usequantity === 'yes' && !(($recur === 'optional') || ($recur === 'plan'))) { + $quantity = $_POST["pf-quantity"]; + $unitamount = (int) str_replace(' ', '', $amount); + $amount = $quantity * $unitamount; + } + //-------------------------------------- + + //-------------------------------------- + if ($txncharge == 'customer') { + $amount = kkd_pff_paystack_add_paystack_charge($amount); + } + $maxFileSize = $filelimit * 1024 * 1024; + + if (!empty($_FILES)) { + foreach ($_FILES as $keyname => $value) { + if ($value['size'] > 0) { + if ($value['size'] > $maxFileSize) { + $response['result'] = 'failed'; + $response['message'] = 'Max upload size is ' . $filelimit . "MB"; + exit(json_encode($response)); + } else { + $attachment_id = media_handle_upload($keyname, $_POST["pf-id"]); + $url = wp_get_attachment_url($attachment_id); + $fixedmetadata[] = array( + 'display_name' => ucwords(str_replace("_", " ", $keyname)), + 'variable_name' => $keyname, + 'type' => 'link', + 'value' => $url + ); + } + } else { + $fixedmetadata[] = array( + 'display_name' => ucwords(str_replace("_", " ", $keyname)), + 'variable_name' => $keyname, + 'type' => 'text', + 'value' => 'No file Uploaded' + ); + } + } + } + $plancode = 'none'; + if ($recur != 'no') { + if ($recur == 'optional') { + $interval = $_POST['pf-interval']; + if ($interval != 'no') { + unset($metadata['pf-interval']); + $mode = esc_attr(get_option('mode')); + if ($mode == 'test') { + $key = esc_attr(get_option('tsk')); + } else { + $key = esc_attr(get_option('lsk')); + } + $koboamount = $amount * 100; + //Create Plan + $paystack_url = 'https://api.paystack.co/plan'; + $check_url = 'https://api.paystack.co/plan?amount=' . $koboamount . '&interval=' . $interval; + $headers = array( + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . $key + ); + + $checkargs = array( + 'headers' => $headers, + 'timeout' => 60 + ); + // Check if plan exist + $checkrequest = wp_remote_get($check_url, $checkargs); + if (!is_wp_error($checkrequest)) { + $response = json_decode(wp_remote_retrieve_body($checkrequest)); + if ($response->meta->total >= 1) { + $plan = $response->data[0]; + $plancode = $plan->plan_code; + $fixedmetadata[] = array( + 'display_name' => 'Plan Interval', + 'variable_name' => 'Plan Interval', + 'type' => 'text', + 'value' => $plan->interval + ); + } else { + //Create Plan + $body = array( + 'name' => $currency . number_format($originalamount) . ' [' . $currency . number_format($amount) . '] - ' . $interval, + 'amount' => $koboamount, + 'interval' => $interval + ); + $args = array( + 'body' => json_encode($body), + 'headers' => $headers, + 'timeout' => 60 + ); + + $request = wp_remote_post($paystack_url, $args); + if (!is_wp_error($request)) { + $paystack_response = json_decode(wp_remote_retrieve_body($request)); + $plancode = $paystack_response->data->plan_code; + $fixedmetadata[] = array( + 'display_name' => 'Plan Interval', + 'variable_name' => 'Plan Interval', + 'type' => 'text', + 'value' => $paystack_response->data->interval + ); + } + } + } + } + } else { + //Use Plan Code + $plancode = $_POST['pf-plancode']; + unset($metadata['pf-plancode']); + } + } + + if ($plancode != 'none') { + $fixedmetadata[] = array( + 'display_name' => 'Plan', + 'variable_name' => 'Plan', + 'type' => 'text', + 'value' => $plancode + ); + } + + $fixedmetadata = json_decode(json_encode($fixedmetadata, JSON_NUMERIC_CHECK), true); + $fixedmetadata = array_merge($untouchedmetadata, $fixedmetadata); + + $insert = array( + 'post_id' => sanitize_text_field($_POST["pf-id"]), + 'email' => sanitize_email($_POST["pf-pemail"]), + 'user_id' => sanitize_text_field($_POST["pf-user_id"]), + 'amount' => sanitize_text_field($_POST["amount"]), // Assuming $amount comes from $_POST + 'plan' => sanitize_text_field($_POST["plancode"]), // Assuming $plancode comes from $_POST + 'ip' => kkd_pff_paystack_get_the_user_ip(), // Make sure this function returns a sanitized IP + 'txn_code' => sanitize_text_field($_POST['code']), // Assuming $code comes from $_POST + 'metadata' => wp_json_encode($_POST["fixedmetadata"]) // Assuming $fixedmetadata comes from $_POST + ); + + $exist = $wpdb->get_results( + $wpdb->prepare( + "SELECT * FROM {$table} WHERE post_id = %s AND email = %s AND user_id = %s AND amount = %s AND plan = %s AND ip = %s AND paid = '0' AND metadata = %s", + $insert['post_id'], $insert['email'], $insert['user_id'], $insert['amount'], $insert['plan'], $insert['ip'], $insert['metadata'] + ) + ); + if (count($exist) > 0) { + // $insert['txn_code'] = $code; + // $insert['plan'] = $exist[0]->plan; + $wpdb->update($table, array('txn_code' => $code, 'plan' => $insert['plan']), array('id' => $exist[0]->id)); + } else { + $wpdb->insert( + $table, + $insert + ); + if("yes" == get_post_meta($insert['post_id'], '_sendinvoice', true)) { + kkd_pff_paystack_send_invoice($currency, $insert['amount'], $fullname, $insert['email'], $code); + } + } + if ($subaccount == "" || !isset($subaccount)) { + $subaccount = null; + $txnbearer = null; + $transaction_charge = null; + } + if ($transaction_charge == "" || $transaction_charge == 0 || $transaction_charge == null) { + $transaction_charge = null; + } + + $amount = floatval($insert['amount']) * 100; + $response = array( + 'result' => 'success', + 'code' => $insert['txn_code'], + 'plan' => $insert['plan'], + 'quantity' => $quantity, + 'email' => $insert['email'], + 'name' => $fullname, + 'total' => round($amount), + 'currency' => $currency, + 'custom_fields' => $fixedmetadata, + 'subaccount' => $subaccount, + 'txnbearer' => $txnbearer, + 'transaction_charge' => $transaction_charge + ); + + //------------------------------------------------------------------------------------------- + + // $pstk_logger = new paystack_plugin_tracker('pff-paystack', Kkd_Pff_Paystack_Public::fetchPublicKey()); + // $pstk_logger->log_transaction_attempt($code); + + echo json_encode($response); + die(); +} + +function kkd_pff_paystack_meta_as_custom_fields($metadata) +{ + $custom_fields = array(); + foreach ($metadata as $key => $value) { + if (is_array($value)) { + $value = implode(', ', $value); + } + if ($key == 'pf-fname') { + $custom_fields[] = array( + 'display_name' => 'Full Name', + 'variable_name' => 'Full_Name', + 'type' => 'text', + 'value' => $value + ); + } elseif ($key == 'pf-plancode') { + $custom_fields[] = array( + 'display_name' => 'Plan', + 'variable_name' => 'Plan', + 'type' => 'text', + 'value' => $value + ); + } elseif ($key == 'pf-vname') { + $custom_fields[] = array( + 'display_name' => 'Payment Option', + 'variable_name' => 'Payment Option', + 'type' => 'text', + 'value' => $value + ); + } elseif ($key == 'pf-interval') { + $custom_fields[] = array( + 'display_name' => 'Plan Interval', + 'variable_name' => 'Plan Interval', + 'type' => 'text', + 'value' => $value + ); + } elseif ($key == 'pf-quantity') { + $custom_fields[] = array( + 'display_name' => 'Quantity', + 'variable_name' => 'Quantity', + 'type' => 'text', + 'value' => $value + ); + } else { + $custom_fields[] = array( + 'display_name' => ucwords(str_replace("_", " ", $key)), + 'variable_name' => $key, + 'type' => 'text', + 'value' => (string) $value + ); + } + } + return $custom_fields; +} + +add_action('wp_ajax_kkd_pff_paystack_confirm_payment', 'kkd_pff_paystack_confirm_payment'); +add_action('wp_ajax_nopriv_kkd_pff_paystack_confirm_payment', 'kkd_pff_paystack_confirm_payment'); + +function kkd_pff_paystack_confirm_payment() +{ + if (trim($_POST['code']) == '') { + $response['error'] = true; + $response['error_message'] = "Did you make a payment?"; + + exit(json_encode($response)); + } + global $wpdb; + $table = $wpdb->prefix . KKD_PFF_PAYSTACK_TABLE; + + $code = sanitize_text_field($_POST['code']); + + $record = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table} WHERE txn_code = %s", $code)); + if (array_key_exists("0", $record)) { + $payment_array = $record[0]; + $amount = get_post_meta($payment_array->post_id, '_amount', true); + $recur = get_post_meta($payment_array->post_id, '_recur', true); + $currency = get_post_meta($payment_array->post_id, '_currency', true); + $txncharge = get_post_meta($payment_array->post_id, '_txncharge', true); + $redirect = get_post_meta($payment_array->post_id, '_redirect', true); + $minimum = get_post_meta($payment_array->post_id, '_minimum', true); + $usevariableamount = get_post_meta($payment_array->post_id, '_usevariableamount', true); + $variableamount = get_post_meta($payment_array->post_id, '_variableamount', true); + + // if ($minimum == 1 && floatval($amount) != 0) { + // if ($payment_array->amount < floatval($formamount)) { + // $amount = floatval($formamount); + // } else { + // $amount = $payment_array->amount; + // } + // } + + $amount = $payment_array->amount; + + $oamount = $amount; + $mode = esc_attr(get_option('mode')); + if ($mode == 'test') { + $key = esc_attr(get_option('tsk')); + } else { + $key = esc_attr(get_option('lsk')); + } + $paystack_url = 'https://api.paystack.co/transaction/verify/' . $code; + $headers = array( + 'Authorization' => 'Bearer ' . $key + ); + $args = array( + 'headers' => $headers, + 'timeout' => 60 + ); + $request = wp_remote_get($paystack_url, $args); + if (!is_wp_error($request) && 200 == wp_remote_retrieve_response_code($request)) { + $paystack_response = json_decode(wp_remote_retrieve_body($request)); + if ('success' == $paystack_response->data->status) { + //============================================================= + + $usequantity = get_post_meta($payment_array->post_id, '_usequantity', true); + if ($usequantity = "yes") { + $quantity = $_POST["quantity"]; + $sold = get_post_meta($payment_array->post_id, '_sold', true); + // error_log(print_r("sold", TRUE)); + // error_log(print_r($sold, TRUE)); + // error_log(print_r(" - - - -- - -- - - -- - ", TRUE)); + // error_log(print_r("Qty", TRUE)); + // error_log(print_r($quantity, TRUE)); + if ($sold == '') { + $sold = '0'; + } + $sold = $sold + $quantity; + } + + + if (get_post_meta($payment_array->post_id, '_sold', false)) { // If the custom field already has a value + + update_post_meta($payment_array->post_id, '_sold', $sold); + } else { // If the custom field doesn't have a value + add_post_meta($payment_array->post_id, '_sold', $sold); + } + //============================================================= + $customer_code = $paystack_response->data->customer->customer_code; + $amount_paid = $paystack_response->data->amount / 100; + $paystack_ref = $paystack_response->data->reference; + $paid_at = $paystack_response->data->transaction_date; + if ($recur == 'optional' || $recur == 'plan') { + $wpdb->update($table, array('paid' => 1, 'amount' => $amount_paid, 'paid_at' => $paid_at), array('txn_code' => $paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + } else { + if ($amount == 0 || $usevariableamount == 1) { + $wpdb->update($table, array('paid' => 1, 'amount' => $amount_paid, 'paid_at' => $paid_at), array('txn_code' => $paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + // kkd_pff_paystack_send_receipt($currency,$amount,$name,$payment_array->email,$code,$metadata) + } else { + if ($oamount != $amount_paid) { + $message = "Invalid amount Paid. Amount required is " . $currency . "" . number_format($oamount) . ""; + $result = "failed"; + } else { + $wpdb->update($table, array('paid' => 1, 'paid_at' => $paid_at), array('txn_code' => $paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + } + } + } + } else { + $message = "Transaction Failed/Invalid Code"; + $result = "failed"; + } + } else { + $message = "Payment Verifiction Failed"; + $result = "failed"; + } + } else { + $message = "Payment Verification Failed."; + $result = "failed"; + } + + if ($result == 'success') { + /// + //Create Plan + $pstk_logger = new kkd_pff_paystack_plugin_tracker('pff-paystack', Kkd_Pff_Paystack_Public::fetchPublicKey()); + $pstk_logger->log_transaction_success($code); + $enabled_custom_plan = get_post_meta($payment_array->post_id, '_startdate_enabled', true); + if ($enabled_custom_plan == 1) { + $mode = esc_attr(get_option('mode')); + if ($mode == 'test') { + $key = esc_attr(get_option('tsk')); + } else { + $key = esc_attr(get_option('lsk')); + } + //Create Plan + $paystack_url = 'https://api.paystack.co/subscription'; + $headers = array( + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . $key + ); + $custom_plan = get_post_meta($payment_array->post_id, '_startdate_plan_code', true); + $days = get_post_meta($payment_array->post_id, '_startdate_days', true); + + $start_date = date("c", strtotime("+" . $days . " days")); + $body = array( + 'start_date' => $start_date, + 'plan' => $custom_plan, + 'customer' => $customer_code + ); + $args = array( + 'body' => json_encode($body), + 'headers' => $headers, + 'timeout' => 60 + ); + + $request = wp_remote_post($paystack_url, $args); + if (!is_wp_error($request)) { + $paystack_response = json_decode(wp_remote_retrieve_body($request)); + $plancode = $paystack_response->data->subscription_code; + // $message.= $message.'Subscribed
'.$plancode.'sssss'; + } + } + + $sendreceipt = get_post_meta($payment_array->post_id, '_sendreceipt', true); + if ($sendreceipt == 'yes') { + $decoded = json_decode($payment_array->metadata); + $fullname = $decoded[1]->value; + kkd_pff_paystack_send_receipt($payment_array->post_id, $currency, $amount_paid, $fullname, $payment_array->email, $paystack_ref, $payment_array->metadata); + kkd_pff_paystack_send_receipt_owner($payment_array->post_id, $currency, $amount_paid, $fullname, $payment_array->email, $paystack_ref, $payment_array->metadata); + } + } + $response = array( + 'result' => $result, + 'message' => $message, + ); + if ($result == 'success' && $redirect != '') { + $response['result'] = 'success2'; + $response['link'] = $redirect; + } + + + echo json_encode($response); + + die(); +} + + +add_action('wp_ajax_kkd_pff_paystack_retry_action', 'kkd_pff_paystack_retry_action'); +add_action('wp_ajax_nopriv_kkd_pff_paystack_retry_action', 'kkd_pff_paystack_retry_action'); +function kkd_pff_paystack_retry_action() +{ + if (trim($_POST['code']) == '') { + $response['result'] = 'failed'; + $response['message'] = 'Cde is required'; + + // Exit here, for not processing further because of the error + exit(json_encode($response)); + } + do_action('kkd_pff_paystack_before_save'); + + global $wpdb; + + $code = sanitize_text_field($_POST['code']); + $newcode = kkd_pff_paystack_generate_code(); // Ensure this function returns a sanitized string + $newcode .= '_2'; + $insert = array(); + $table = $wpdb->prefix . KKD_PFF_PAYSTACK_TABLE; + + $record = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table} WHERE txn_code = %s", $code)); + + if (array_key_exists("0", $record)) { + $dbdata = $record[0]; + $plan = $dbdata->plan; + $quantity = 1; + $wpdb->update($table, array('txn_code_2' => $newcode), array('txn_code' => $code)); + + $currency = get_post_meta($dbdata->post_id, '_currency', true); + $subaccount = get_post_meta($dbdata->post_id, '_subaccount', true); + $txnbearer = get_post_meta($dbdata->post_id, '_txnbearer', true); + $transaction_charge = get_post_meta($dbdata->post_id, '_merchantamount', true); + $transaction_charge = $transaction_charge * 100; + $fixedmetadata = kkd_pff_paystack_meta_as_custom_fields($dbdata->metadata); + $nmeta = json_decode($dbdata->metadata); + foreach ($nmeta as $nkey => $nvalue) { + if ($nvalue->variable_name == 'Quantity') { + $quantity = $nvalue->value; + } + if ($nvalue->variable_name == 'Full_Name') { + $fullname = $nvalue->value; + } + } + } + if ($subaccount == "" || !isset($subaccount)) { + $subaccount = null; + $txnbearer = null; + $transaction_charge = null; + } + if ($transaction_charge == "" || $transaction_charge == 0 || $transaction_charge == null || !isset($transaction_charge)) { + $transaction_charge = null; + } + $response = array( + 'result' => 'success', + 'code' => $newcode, + 'plan' => $plan, + 'quantity' => $quantity, + 'email' => $dbdata->email, + 'name' => $fullname, + 'total' => $dbdata->amount * 100, + 'custom_fields' => $fixedmetadata, + 'currency' => $currency, + 'subaccount' => $subaccount, + 'txnbearer' => $txnbearer, + 'transaction_charge' => $transaction_charge + ); + echo json_encode($response); + + die(); +} +add_action('wp_ajax_kkd_pff_paystack_rconfirm_payment', 'kkd_pff_paystack_rconfirm_payment'); +add_action('wp_ajax_nopriv_kkd_pff_paystack_rconfirm_payment', 'kkd_pff_paystack_rconfirm_payment'); + +function kkd_pff_paystack_rconfirm_payment() +{ + if (trim($_POST['code']) == '') { + $response['error'] = true; + $response['error_message'] = "Did you make a payment?"; + + exit(json_encode($response)); + } + global $wpdb; + $table = $wpdb->prefix . KKD_PFF_PAYSTACK_TABLE; + $code = sanitize_text_field($_POST['code']); + $record = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table} WHERE txn_code_2 = %s", $code)); + if (array_key_exists("0", $record)) { + $payment_array = $record[0]; + $amount = get_post_meta($payment_array->post_id, '_amount', true); + $recur = get_post_meta($payment_array->post_id, '_recur', true); + $currency = get_post_meta($payment_array->post_id, '_currency', true); + $txncharge = get_post_meta($payment_array->post_id, '_txncharge', true); + $redirect = get_post_meta($payment_array->post_id, '_redirect', true); + + + $mode = esc_attr(get_option('mode')); + if ($mode == 'test') { + $key = esc_attr(get_option('tsk')); + } else { + $key = esc_attr(get_option('lsk')); + } + $paystack_url = 'https://api.paystack.co/transaction/verify/' . $code; + $headers = array( + 'Authorization' => 'Bearer ' . $key + ); + $args = array( + 'headers' => $headers, + 'timeout' => 60 + ); + $request = wp_remote_get($paystack_url, $args); + if (!is_wp_error($request) && 200 == wp_remote_retrieve_response_code($request)) { + $paystack_response = json_decode(wp_remote_retrieve_body($request)); + if ('success' == $paystack_response->data->status) { + $amount_paid = $paystack_response->data->amount / 100; + $paystack_ref = $paystack_response->data->reference; + if ($recur == 'optional' || $recur == 'plan') { + $wpdb->update($table, array('paid' => 1, 'amount' => $amount_paid), array('txn_code_2' => $paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + } else { + if ($amount == 0) { + $wpdb->update($table, array('paid' => 1, 'amount' => $amount_paid, 'paid_at' => $paid_at), array('txn_code_2' => $paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + // kkd_pff_paystack_send_receipt($currency,$amount,$name,$payment_array->email,$code,$metadata) + } else { + $usequantity = get_post_meta($payment_array->post_id, '_usequantity', true); + if ($usequantity == 'no') { + $amount = (int) str_replace(' ', '', $amount); + } else { + $quantity = $_POST["quantity"]; + $unitamount = (int) str_replace(' ', '', $amount); + $amount = $quantity * $unitamount; + } + + + if ($txncharge == 'customer') { + $amount = kkd_pff_paystack_add_paystack_charge($amount); + } + if ($amount != $amount_paid) { + $message = "Invalid amount Paid. Amount required is " . $currency . "" . number_format($amount) . ""; + $result = "failed"; + } else { + $wpdb->update($table, array('paid' => 1, 'paid_at' => $paid_at), array('txn_code_2' => $paystack_ref)); + $thankyou = get_post_meta($payment_array->post_id, '_successmsg', true); + $message = $thankyou; + $result = "success"; + } + } + } + } else { + $message = "Transaction Failed/Invalid Code"; + $result = "failed"; + } + } + } else { + $message = "Payment Verification Failed."; + $result = "failed"; + } + + if ($result == 'success') { + //Log to amplitude + $pstk_logger = new paystack_plugin_tracker('pff-paystack', Kkd_Pff_Paystack_Public::fetchPublicKey()); + $pstk_logger->log_transaction_success($code); + $sendreceipt = get_post_meta($payment_array->post_id, '_sendreceipt', true); + if ($sendreceipt == 'yes') { + $decoded = json_decode($payment_array->metadata); + $fullname = $decoded[1]->value; + kkd_pff_paystack_send_receipt($payment_array->post_id, $currency, $amount_paid, $fullname, $payment_array->email, $paystack_ref, $payment_array->metadata); + kkd_pff_paystack_send_receipt_owner($payment_array->post_id, $currency, $amount_paid, $fullname, $payment_array->email, $paystack_ref, $payment_array->metadata); + } + } + $response = array( + 'result' => $result, + 'message' => $message, + ); + if ($result == 'success' && $redirect != '') { + $response['result'] = 'success2'; + $response['link'] = $redirect; + } + + + echo json_encode($response); + + die(); +} diff --git a/public/class-paystack-plugin-tracker.php b/public/class-paystack-plugin-tracker.php new file mode 100644 index 0000000..2f24b8b --- /dev/null +++ b/public/class-paystack-plugin-tracker.php @@ -0,0 +1,71 @@ +plugin_name = $plugin; + $this->public_key = $pk; + } + + /** + * Logs a successful transaction. + * + * @param string $trx_ref The transaction reference. + */ + public function logTransactionSuccess($trx_ref) + { + // Send reference to logger along with plugin name and public key + $url = "https://plugin-tracker.paystackintegrations.com/log/charge_success"; + + $fields = [ + 'plugin_name' => $this->plugin_name, + 'transaction_reference' => $trx_ref, + 'public_key' => $this->public_key, + ]; + + $fields_string = http_build_query($fields); + + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + // Execute post + $result = curl_exec($ch); + } +} diff --git a/public/css/.DS_Store b/public/css/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/public/css/.DS_Store differ diff --git a/assets/css/font-awesome.min.css b/public/css/font-awesome.min.css similarity index 100% rename from assets/css/font-awesome.min.css rename to public/css/font-awesome.min.css diff --git a/assets/css/pff-paystack.css b/public/css/pff-paystack-style.css similarity index 100% rename from assets/css/pff-paystack.css rename to public/css/pff-paystack-style.css diff --git a/assets/fonts/Graphik-Black.otf b/public/fonts/Graphik-Black.otf similarity index 100% rename from assets/fonts/Graphik-Black.otf rename to public/fonts/Graphik-Black.otf diff --git a/assets/fonts/Graphik-BlackItalic.otf b/public/fonts/Graphik-BlackItalic.otf similarity index 100% rename from assets/fonts/Graphik-BlackItalic.otf rename to public/fonts/Graphik-BlackItalic.otf diff --git a/assets/fonts/Graphik-Bold.otf b/public/fonts/Graphik-Bold.otf similarity index 100% rename from assets/fonts/Graphik-Bold.otf rename to public/fonts/Graphik-Bold.otf diff --git a/assets/fonts/Graphik-BoldItalic.otf b/public/fonts/Graphik-BoldItalic.otf similarity index 100% rename from assets/fonts/Graphik-BoldItalic.otf rename to public/fonts/Graphik-BoldItalic.otf diff --git a/assets/fonts/Graphik-Extralight.otf b/public/fonts/Graphik-Extralight.otf similarity index 100% rename from assets/fonts/Graphik-Extralight.otf rename to public/fonts/Graphik-Extralight.otf diff --git a/assets/fonts/Graphik-ExtralightItalic.otf b/public/fonts/Graphik-ExtralightItalic.otf similarity index 100% rename from assets/fonts/Graphik-ExtralightItalic.otf rename to public/fonts/Graphik-ExtralightItalic.otf diff --git a/assets/fonts/Graphik-Light.otf b/public/fonts/Graphik-Light.otf similarity index 100% rename from assets/fonts/Graphik-Light.otf rename to public/fonts/Graphik-Light.otf diff --git a/assets/fonts/Graphik-LightItalic.otf b/public/fonts/Graphik-LightItalic.otf similarity index 100% rename from assets/fonts/Graphik-LightItalic.otf rename to public/fonts/Graphik-LightItalic.otf diff --git a/assets/fonts/Graphik-Medium.otf b/public/fonts/Graphik-Medium.otf similarity index 100% rename from assets/fonts/Graphik-Medium.otf rename to public/fonts/Graphik-Medium.otf diff --git a/assets/fonts/Graphik-MediumItalic.otf b/public/fonts/Graphik-MediumItalic.otf similarity index 100% rename from assets/fonts/Graphik-MediumItalic.otf rename to public/fonts/Graphik-MediumItalic.otf diff --git a/assets/fonts/Graphik-Regular.otf b/public/fonts/Graphik-Regular.otf similarity index 100% rename from assets/fonts/Graphik-Regular.otf rename to public/fonts/Graphik-Regular.otf diff --git a/assets/fonts/Graphik-RegularItalic.otf b/public/fonts/Graphik-RegularItalic.otf similarity index 100% rename from assets/fonts/Graphik-RegularItalic.otf rename to public/fonts/Graphik-RegularItalic.otf diff --git a/assets/fonts/Graphik-Semibold.otf b/public/fonts/Graphik-Semibold.otf similarity index 100% rename from assets/fonts/Graphik-Semibold.otf rename to public/fonts/Graphik-Semibold.otf diff --git a/assets/fonts/Graphik-SemiboldItalic.otf b/public/fonts/Graphik-SemiboldItalic.otf similarity index 100% rename from assets/fonts/Graphik-SemiboldItalic.otf rename to public/fonts/Graphik-SemiboldItalic.otf diff --git a/assets/fonts/Graphik-Super.otf b/public/fonts/Graphik-Super.otf similarity index 100% rename from assets/fonts/Graphik-Super.otf rename to public/fonts/Graphik-Super.otf diff --git a/assets/fonts/Graphik-SuperItalic.otf b/public/fonts/Graphik-SuperItalic.otf similarity index 100% rename from assets/fonts/Graphik-SuperItalic.otf rename to public/fonts/Graphik-SuperItalic.otf diff --git a/assets/fonts/Graphik-Thin.otf b/public/fonts/Graphik-Thin.otf similarity index 100% rename from assets/fonts/Graphik-Thin.otf rename to public/fonts/Graphik-Thin.otf diff --git a/assets/fonts/Graphik-ThinItalic.otf b/public/fonts/Graphik-ThinItalic.otf similarity index 100% rename from assets/fonts/Graphik-ThinItalic.otf rename to public/fonts/Graphik-ThinItalic.otf diff --git a/assets/fonts/fontawesome-webfont-.eot b/public/fonts/fontawesome-webfont-.eot similarity index 100% rename from assets/fonts/fontawesome-webfont-.eot rename to public/fonts/fontawesome-webfont-.eot diff --git a/assets/fonts/fontawesome-webfont-v=4.2.0.eot b/public/fonts/fontawesome-webfont-v=4.2.0.eot similarity index 100% rename from assets/fonts/fontawesome-webfont-v=4.2.0.eot rename to public/fonts/fontawesome-webfont-v=4.2.0.eot diff --git a/assets/fonts/fontawesome-webfont-v=4.2.0.svg b/public/fonts/fontawesome-webfont-v=4.2.0.svg similarity index 100% rename from assets/fonts/fontawesome-webfont-v=4.2.0.svg rename to public/fonts/fontawesome-webfont-v=4.2.0.svg diff --git a/assets/fonts/fontawesome-webfont-v=4.2.0.ttf b/public/fonts/fontawesome-webfont-v=4.2.0.ttf similarity index 100% rename from assets/fonts/fontawesome-webfont-v=4.2.0.ttf rename to public/fonts/fontawesome-webfont-v=4.2.0.ttf diff --git a/assets/fonts/fontawesome-webfont-v=4.2.0.woff b/public/fonts/fontawesome-webfont-v=4.2.0.woff similarity index 100% rename from assets/fonts/fontawesome-webfont-v=4.2.0.woff rename to public/fonts/fontawesome-webfont-v=4.2.0.woff diff --git a/public/index.php b/public/index.php new file mode 100644 index 0000000..e71af0e --- /dev/null +++ b/public/index.php @@ -0,0 +1 @@ +"))}function a(t){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return t.delegate(i,"mouseout",function(){e(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&e(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&e(this).removeClass("ui-datepicker-next-hover")}).delegate(i,"mouseover",o)}function o(){e.datepicker._isDisabledDatepicker(d.inline?d.dpDiv.parent()[0]:d.input[0])||(e(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),e(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&e(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&e(this).addClass("ui-datepicker-next-hover"))}function r(t,i){e.extend(t,i);for(var s in i)null==i[s]&&(t[s]=i[s]);return t}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({scrollParent:function(t){var i=this.css("position"),s="absolute"===i,n=t?/(auto|scroll|hidden)/:/(auto|scroll)/,a=this.parents().filter(function(){var t=e(this);return s&&"static"===t.css("position")?!1:n.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==i&&a.length?a:e(this[0].ownerDocument||document)},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(i){return t(i,!isNaN(e.attr(i,"tabindex")))},tabbable:function(i){var s=e.attr(i,"tabindex"),n=isNaN(s);return(n||s>=0)&&t(i,!n)}}),e("").outerWidth(1).jquery||e.each(["Width","Height"],function(t,i){function s(t,i,s,a){return e.each(n,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),a&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],a=i.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+i]=function(t){return void 0===t?o["inner"+i].call(this):this.each(function(){e(this).css(a,s(this,t)+"px")})},e.fn["outer"+i]=function(t,n){return"number"!=typeof t?o["outer"+i].call(this,t):this.each(function(){e(this).css(a,s(this,t,!0,n)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(void 0!==t)return this.css("zIndex",t);if(this.length)for(var i,s,n=e(this[0]);n.length&&n[0]!==document;){if(i=n.css("position"),("absolute"===i||"relative"===i||"fixed"===i)&&(s=parseInt(n.css("zIndex"),10),!isNaN(s)&&0!==s))return s;n=n.parent()}return 0}}),e.ui.plugin={add:function(t,i,s){var n,a=e.ui[t].prototype;for(n in s)a.plugins[n]=a.plugins[n]||[],a.plugins[n].push([i,s[n]])},call:function(e,t,i,s){var n,a=e.plugins[t];if(a&&(s||e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType))for(n=0;a.length>n;n++)e.options[a[n][0]]&&a[n][1].apply(e.element,i)}};var h=0,l=Array.prototype.slice;e.cleanData=function(t){return function(i){var s,n,a;for(a=0;null!=(n=i[a]);a++)try{s=e._data(n,"events"),s&&s.remove&&e(n).triggerHandler("remove")}catch(o){}t(i)}}(e.cleanData),e.widget=function(t,i,s){var n,a,o,r,h={},l=t.split(".")[0];return t=t.split(".")[1],n=l+"-"+t,s||(s=i,i=e.Widget),e.expr[":"][n.toLowerCase()]=function(t){return!!e.data(t,n)},e[l]=e[l]||{},a=e[l][t],o=e[l][t]=function(e,t){return this._createWidget?(arguments.length&&this._createWidget(e,t),void 0):new o(e,t)},e.extend(o,a,{version:s.version,_proto:e.extend({},s),_childConstructors:[]}),r=new i,r.options=e.widget.extend({},r.options),e.each(s,function(t,s){return e.isFunction(s)?(h[t]=function(){var e=function(){return i.prototype[t].apply(this,arguments)},n=function(e){return i.prototype[t].apply(this,e)};return function(){var t,i=this._super,a=this._superApply;return this._super=e,this._superApply=n,t=s.apply(this,arguments),this._super=i,this._superApply=a,t}}(),void 0):(h[t]=s,void 0)}),o.prototype=e.widget.extend(r,{widgetEventPrefix:a?r.widgetEventPrefix||t:t},h,{constructor:o,namespace:l,widgetName:t,widgetFullName:n}),a?(e.each(a._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete a._childConstructors):i._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){for(var i,s,n=l.call(arguments,1),a=0,o=n.length;o>a;a++)for(i in n[a])s=n[a][i],n[a].hasOwnProperty(i)&&void 0!==s&&(t[i]=e.isPlainObject(s)?e.isPlainObject(t[i])?e.widget.extend({},t[i],s):e.widget.extend({},s):s);return t},e.widget.bridge=function(t,i){var s=i.prototype.widgetFullName||t;e.fn[t]=function(n){var a="string"==typeof n,o=l.call(arguments,1),r=this;return a?this.each(function(){var i,a=e.data(this,s);return"instance"===n?(r=a,!1):a?e.isFunction(a[n])&&"_"!==n.charAt(0)?(i=a[n].apply(a,o),i!==a&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0):e.error("no such method '"+n+"' for "+t+" widget instance"):e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+n+"'")}):(o.length&&(n=e.widget.extend.apply(null,[n].concat(o))),this.each(function(){var t=e.data(this,s);t?(t.option(n||{}),t._init&&t._init()):e.data(this,s,new i(n,this))})),r}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"",options:{disabled:!1,create:null},_createWidget:function(t,i){i=e(i||this.defaultElement||this)[0],this.element=e(i),this.uuid=h++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=e(),this.hoverable=e(),this.focusable=e(),i!==this&&(e.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===i&&this.destroy()}}),this.document=e(i.style?i.ownerDocument:i.document||i),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(t,i){var s,n,a,o=t;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof t)if(o={},s=t.split("."),t=s.shift(),s.length){for(n=o[t]=e.widget.extend({},this.options[t]),a=0;s.length-1>a;a++)n[s[a]]=n[s[a]]||{},n=n[s[a]];if(t=s.pop(),1===arguments.length)return void 0===n[t]?null:n[t];n[t]=i}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=i}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,i,s){var n,a=this;"boolean"!=typeof t&&(s=i,i=t,t=!1),s?(i=n=e(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),e.each(s,function(s,o){function r(){return t||a.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?a[o]:o).apply(a,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||e.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+a.eventNamespace,u=h[2];u?n.delegate(u,l,r):i.bind(l,r)})},_off:function(t,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(i).undelegate(i),this.bindings=e(this.bindings.not(t).get()),this.focusable=e(this.focusable.not(t).get()),this.hoverable=e(this.hoverable.not(t).get())},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var n,a,o=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(e.isFunction(o)&&o.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,n,a){"string"==typeof n&&(n={effect:n});var o,r=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),o=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),o&&e.effects&&e.effects.effect[r]?s[t](n):r!==t&&s[r]?s[r](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}}),e.widget;var u=!1;e(document).mouseup(function(){u=!1}),e.widget("ui.mouse",{version:"1.11.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(i){return!0===e.data(i.target,t.widgetName+".preventClickEvent")?(e.removeData(i.target,t.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(!u){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var i=this,s=1===t.which,n="string"==typeof this.options.cancel&&t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;return s&&!n&&this._mouseCapture(t)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(t)!==!1,!this._mouseStarted)?(t.preventDefault(),!0):(!0===e.data(t.target,this.widgetName+".preventClickEvent")&&e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return i._mouseMove(e)},this._mouseUpDelegate=function(e){return i._mouseUp(e)},this.document.bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),u=!0,!0)):!0}},_mouseMove:function(t){if(this._mouseMoved){if(e.ui.ie&&(!document.documentMode||9>document.documentMode)&&!t.button)return this._mouseUp(t);if(!t.which)return this._mouseUp(t)}return(t.which||t.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(t){return this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),u=!1,!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),function(){function t(e,t,i){return[parseFloat(e[0])*(p.test(e[0])?t/100:1),parseFloat(e[1])*(p.test(e[1])?i/100:1)]}function i(t,i){return parseInt(e.css(t,i),10)||0}function s(t){var i=t[0];return 9===i.nodeType?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(i)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var n,a,o=Math.max,r=Math.abs,h=Math.round,l=/left|center|right/,u=/top|center|bottom/,d=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,p=/%$/,f=e.fn.position;e.position={scrollbarWidth:function(){if(void 0!==n)return n;var t,i,s=e(""),a=s.children()[0];return e("body").append(s),t=a.offsetWidth,s.css("overflow","scroll"),i=a.offsetWidth,t===i&&(i=s[0].clientWidth),s.remove(),n=t-i},getScrollInfo:function(t){var i=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),s=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),n="scroll"===i||"auto"===i&&t.widthi?"left":t>0?"right":"center",vertical:0>a?"top":s>0?"bottom":"middle"};d>m&&m>r(t+i)&&(h.horizontal="center"),c>g&&g>r(s+a)&&(h.vertical="middle"),h.important=o(r(t),r(i))>o(r(s),r(a))?"horizontal":"vertical",n.using.call(this,e,h)}),u.offset(e.extend(N,{using:l}))})},e.ui.position={fit:{left:function(e,t){var i,s=t.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=e.left-t.collisionPosition.marginLeft,h=n-r,l=r+t.collisionWidth-a-n;t.collisionWidth>a?h>0&&0>=l?(i=e.left+h+t.collisionWidth-a-n,e.left+=h-i):e.left=l>0&&0>=h?n:h>l?n+a-t.collisionWidth:n:h>0?e.left+=h:l>0?e.left-=l:e.left=o(e.left-r,e.left)},top:function(e,t){var i,s=t.within,n=s.isWindow?s.scrollTop:s.offset.top,a=t.within.height,r=e.top-t.collisionPosition.marginTop,h=n-r,l=r+t.collisionHeight-a-n;t.collisionHeight>a?h>0&&0>=l?(i=e.top+h+t.collisionHeight-a-n,e.top+=h-i):e.top=l>0&&0>=h?n:h>l?n+a-t.collisionHeight:n:h>0?e.top+=h:l>0?e.top-=l:e.top=o(e.top-r,e.top)}},flip:{left:function(e,t){var i,s,n=t.within,a=n.offset.left+n.scrollLeft,o=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=e.left-t.collisionPosition.marginLeft,u=l-h,d=l+t.collisionWidth-o-h,c="left"===t.my[0]?-t.elemWidth:"right"===t.my[0]?t.elemWidth:0,p="left"===t.at[0]?t.targetWidth:"right"===t.at[0]?-t.targetWidth:0,f=-2*t.offset[0];0>u?(i=e.left+c+p+f+t.collisionWidth-o-a,(0>i||r(u)>i)&&(e.left+=c+p+f)):d>0&&(s=e.left-t.collisionPosition.marginLeft+c+p+f-h,(s>0||d>r(s))&&(e.left+=c+p+f))},top:function(e,t){var i,s,n=t.within,a=n.offset.top+n.scrollTop,o=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=e.top-t.collisionPosition.marginTop,u=l-h,d=l+t.collisionHeight-o-h,c="top"===t.my[1],p=c?-t.elemHeight:"bottom"===t.my[1]?t.elemHeight:0,f="top"===t.at[1]?t.targetHeight:"bottom"===t.at[1]?-t.targetHeight:0,m=-2*t.offset[1];0>u?(s=e.top+p+f+m+t.collisionHeight-o-a,(0>s||r(u)>s)&&(e.top+=p+f+m)):d>0&&(i=e.top-t.collisionPosition.marginTop+p+f+m-h,(i>0||d>r(i))&&(e.top+=p+f+m))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,i,s,n,o,r=document.getElementsByTagName("body")[0],h=document.createElement("div");t=document.createElement(r?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},r&&e.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in s)t.style[o]=s[o];t.appendChild(h),i=r||document.documentElement,i.insertBefore(t,i.firstChild),h.style.cssText="position: absolute; left: 10.7432222px;",n=e(h).offset().left,a=n>10&&11>n,t.innerHTML="",i.removeChild(t)}()}(),e.ui.position,e.widget("ui.menu",{version:"1.11.4",defaultElement:" ",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},items:"> *",menus:"ul",position:{my:"left-1 top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item":function(e){e.preventDefault()},"click .ui-menu-item":function(t){var i=e(t.target);!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&e(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){if(!this.previousFilter){var i=e(t.currentTarget);i.siblings(".ui-state-active").removeClass("ui-state-active"),this.focus(t,i)}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var i=this.active||this.element.find(this.options.items).eq(0);t||this.focus(e,i)},blur:function(t){this._delay(function(){e.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(e){this._closeOnDocumentClick(e)&&this.collapseAll(e),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-menu-icons ui-front").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").removeUniqueId().removeClass("ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var t=e(this);t.data("ui-menu-submenu-carat")&&t.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(t){var i,s,n,a,o=!0;switch(t.keyCode){case e.ui.keyCode.PAGE_UP:this.previousPage(t);break;case e.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case e.ui.keyCode.HOME:this._move("first","first",t);break;case e.ui.keyCode.END:this._move("last","last",t);break;case e.ui.keyCode.UP:this.previous(t);break;case e.ui.keyCode.DOWN:this.next(t);break;case e.ui.keyCode.LEFT:this.collapse(t);break;case e.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case e.ui.keyCode.ENTER:case e.ui.keyCode.SPACE:this._activate(t);break;case e.ui.keyCode.ESCAPE:this.collapse(t);break;default:o=!1,s=this.previousFilter||"",n=String.fromCharCode(t.keyCode),a=!1,clearTimeout(this.filterTimer),n===s?a=!0:n=s+n,i=this._filterMenuItems(n),i=a&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(t.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(t,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}o&&t.preventDefault()},_activate:function(e){this.active.is(".ui-state-disabled")||(this.active.is("[aria-haspopup='true']")?this.expand(e):this.select(e))},refresh:function(){var t,i,s=this,n=this.options.icons.submenu,a=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),a.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-front").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=e(this),i=t.parent(),s=e("").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);i.attr("aria-haspopup","true").prepend(s),t.attr("aria-labelledby",i.attr("id"))}),t=a.add(this.element),i=t.find(this.options.items),i.not(".ui-menu-item").each(function(){var t=e(this);s._isDivider(t)&&t.addClass("ui-widget-content ui-menu-divider")}),i.not(".ui-menu-item, .ui-menu-divider").addClass("ui-menu-item").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!e.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(e,t){"icons"===e&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(t.submenu),"disabled"===e&&this.element.toggleClass("ui-state-disabled",!!t).attr("aria-disabled",t),this._super(e,t)},focus:function(e,t){var i,s;this.blur(e,e&&"focus"===e.type),this._scrollIntoView(t),this.active=t.first(),s=this.active.addClass("ui-state-focus").removeClass("ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),this.active.parent().closest(".ui-menu-item").addClass("ui-state-active"),e&&"keydown"===e.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=t.children(".ui-menu"),i.length&&e&&/^mouse/.test(e.type)&&this._startOpening(i),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(t){var i,s,n,a,o,r;this._hasScroll()&&(i=parseFloat(e.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(e.css(this.activeMenu[0],"paddingTop"))||0,n=t.offset().top-this.activeMenu.offset().top-i-s,a=this.activeMenu.scrollTop(),o=this.activeMenu.height(),r=t.outerHeight(),0>n?this.activeMenu.scrollTop(a+n):n+r>o&&this.activeMenu.scrollTop(a+n-o+r))},blur:function(e,t){t||clearTimeout(this.timer),this.active&&(this.active.removeClass("ui-state-focus"),this.active=null,this._trigger("blur",e,{item:this.active}))},_startOpening:function(e){clearTimeout(this.timer),"true"===e.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(e)},this.delay))},_open:function(t){var i=e.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(t,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:e(t&&t.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(t),this.activeMenu=s},this.delay)},_close:function(e){e||(e=this.active?this.active.parent():this.element),e.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find(".ui-state-active").not(".ui-state-focus").removeClass("ui-state-active")},_closeOnDocumentClick:function(t){return!e(t.target).closest(".ui-menu").length},_isDivider:function(e){return!/[^\-\u2014\u2013\s]/.test(e.text())},collapse:function(e){var t=this.active&&this.active.parent().closest(".ui-menu-item",this.element);t&&t.length&&(this._close(),this.focus(e,t))},expand:function(e){var t=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();t&&t.length&&(this._open(t.parent()),this._delay(function(){this.focus(e,t)}))},next:function(e){this._move("next","first",e)},previous:function(e){this._move("prev","last",e)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(e,t,i){var s;this.active&&(s="first"===e||"last"===e?this.active["first"===e?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[e+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[t]()),this.focus(i,s)},nextPage:function(t){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=e(this),0>i.offset().top-s-n}),this.focus(t,i)):this.focus(t,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(t),void 0)},previousPage:function(t){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=e(this),i.offset().top-s+n>0}),this.focus(t,i)):this.focus(t,this.activeMenu.find(this.options.items).first())),void 0):(this.next(t),void 0)},_hasScroll:function(){return this.element.outerHeight()
",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var t,i,s,n=this.element[0].nodeName.toLowerCase(),a="textarea"===n,o="input"===n; +this.isMultiLine=a?!0:o?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[a||o?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return t=!0,s=!0,i=!0,void 0;t=!1,s=!1,i=!1;var a=e.ui.keyCode;switch(n.keyCode){case a.PAGE_UP:t=!0,this._move("previousPage",n);break;case a.PAGE_DOWN:t=!0,this._move("nextPage",n);break;case a.UP:t=!0,this._keyEvent("previous",n);break;case a.DOWN:t=!0,this._keyEvent("next",n);break;case a.ENTER:this.menu.active&&(t=!0,n.preventDefault(),this.menu.select(n));break;case a.TAB:this.menu.active&&this.menu.select(n);break;case a.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(t)return t=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=e.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(e){return s?(s=!1,e.preventDefault(),void 0):(this._searchTimeout(e),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(e),this._change(e),void 0)}}),this._initSource(),this.menu=e(" ").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var i=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(s){s.target===t.element[0]||s.target===i||e.contains(i,s.target)||t.close()})})},menufocus:function(t,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",t,{item:n})&&t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&e.trim(s).length&&(this.liveRegion.children().hide(),e("
").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,t){var i=t.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",e,{item:i})&&this._value(i.value),this.term=this._value(),this.close(e),this.selectedItem=i}}),this.liveRegion=e("",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),"source"===e&&this._initSource(),"appendTo"===e&&this.menu.element.appendTo(this._appendTo()),"disabled"===e&&t&&this.xhr&&this.xhr.abort()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t&&t[0]||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_initSource:function(){var t,i,s=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(i,s){s(e.ui.autocomplete.filter(t,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(t,n){s.xhr&&s.xhr.abort(),s.xhr=e.ajax({url:i,data:t,dataType:"json",success:function(e){n(e)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){var t=this.term===this._value(),i=this.menu.element.is(":visible"),s=e.altKey||e.ctrlKey||e.metaKey||e.shiftKey;(!t||t&&!i&&!s)&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){return e=null!=e?e:this._value(),this.term=this._value(),e.length").text(i.label).appendTo(t)},_move:function(e,t){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[e](t),void 0):(this.search(null,t),void 0)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(e,t),t.preventDefault())}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,i){var s=RegExp(e.ui.autocomplete.escapeRegex(i),"i");return e.grep(t,function(e){return s.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(t){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=t&&t.length?this.options.messages.results(t.length):this.options.messages.noResults,this.liveRegion.children().hide(),e(" ").text(i).appendTo(this.liveRegion))}}),e.ui.autocomplete,e.extend(e.ui,{datepicker:{version:"1.11.4"}});var d;e.extend(n.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return r(this._defaults,e||{}),this},_attachDatepicker:function(t,i){var s,n,a;s=t.nodeName.toLowerCase(),n="div"===s||"span"===s,t.id||(this.uuid+=1,t.id="dp"+this.uuid),a=this._newInst(e(t),n),a.settings=e.extend({},i||{}),"input"===s?this._connectDatepicker(t,a):n&&this._inlineDatepicker(t,a)},_newInst:function(t,i){var s=t[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:t,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?a(e("")):this.dpDiv}},_connectDatepicker:function(t,i){var s=e(t);i.append=e([]),i.trigger=e([]),s.hasClass(this.markerClassName)||(this._attachments(s,i),s.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(i),e.data(t,"datepicker",i),i.settings.disabled&&this._disableDatepicker(t))},_attachments:function(t,i){var s,n,a,o=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),o&&(i.append=e(""+o+""),t[r?"before":"after"](i.append)),t.unbind("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),s=this._get(i,"showOn"),("focus"===s||"both"===s)&&t.focus(this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),a=this._get(i,"buttonImage"),i.trigger=e(this._get(i,"buttonImageOnly")?e("").addClass(this._triggerClass).attr({src:a,alt:n,title:n}):e("").addClass(this._triggerClass).html(a?e("
").attr({src:a,alt:n,title:n}):n)),t[r?"before":"after"](i.trigger),i.trigger.click(function(){return e.datepicker._datepickerShowing&&e.datepicker._lastInput===t[0]?e.datepicker._hideDatepicker():e.datepicker._datepickerShowing&&e.datepicker._lastInput!==t[0]?(e.datepicker._hideDatepicker(),e.datepicker._showDatepicker(t[0])):e.datepicker._showDatepicker(t[0]),!1}))},_autoSize:function(e){if(this._get(e,"autoSize")&&!e.inline){var t,i,s,n,a=new Date(2009,11,20),o=this._get(e,"dateFormat");o.match(/[DM]/)&&(t=function(e){for(i=0,s=0,n=0;e.length>n;n++)e[n].length>i&&(i=e[n].length,s=n);return s},a.setMonth(t(this._get(e,o.match(/MM/)?"monthNames":"monthNamesShort"))),a.setDate(t(this._get(e,o.match(/DD/)?"dayNames":"dayNamesShort"))+20-a.getDay())),e.input.attr("size",this._formatDate(e,a).length)}},_inlineDatepicker:function(t,i){var s=e(t);s.hasClass(this.markerClassName)||(s.addClass(this.markerClassName).append(i.dpDiv),e.data(t,"datepicker",i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(t),i.dpDiv.css("display","block"))},_dialogDatepicker:function(t,i,s,n,a){var o,h,l,u,d,c=this._dialogInst;return c||(this.uuid+=1,o="dp"+this.uuid,this._dialogInput=e(""),this._dialogInput.keydown(this._doKeyDown),e("body").append(this._dialogInput),c=this._dialogInst=this._newInst(this._dialogInput,!1),c.settings={},e.data(this._dialogInput[0],"datepicker",c)),r(c.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(c,i):i,this._dialogInput.val(i),this._pos=a?a.length?a:[a.pageX,a.pageY]:null,this._pos||(h=document.documentElement.clientWidth,l=document.documentElement.clientHeight,u=document.documentElement.scrollLeft||document.body.scrollLeft,d=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[h/2-100+u,l/2-150+d]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),c.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),e.blockUI&&e.blockUI(this.dpDiv),e.data(this._dialogInput[0],"datepicker",c),this},_destroyDatepicker:function(t){var i,s=e(t),n=e.data(t,"datepicker");s.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),e.removeData(t,"datepicker"),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty(),d===n&&(d=null))},_enableDatepicker:function(t){var i,s,n=e(t),a=e.data(t,"datepicker");n.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),"input"===i?(t.disabled=!1,a.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}))},_disableDatepicker:function(t){var i,s,n=e(t),a=e.data(t,"datepicker");n.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),"input"===i?(t.disabled=!0,a.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}),this._disabledInputs[this._disabledInputs.length]=t)},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;this._disabledInputs.length>t;t++)if(this._disabledInputs[t]===e)return!0;return!1},_getInst:function(t){try{return e.data(t,"datepicker")}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(t,i,s){var n,a,o,h,l=this._getInst(t);return 2===arguments.length&&"string"==typeof i?"defaults"===i?e.extend({},e.datepicker._defaults):l?"all"===i?e.extend({},l.settings):this._get(l,i):null:(n=i||{},"string"==typeof i&&(n={},n[i]=s),l&&(this._curInst===l&&this._hideDatepicker(),a=this._getDateDatepicker(t,!0),o=this._getMinMaxDate(l,"min"),h=this._getMinMaxDate(l,"max"),r(l.settings,n),null!==o&&void 0!==n.dateFormat&&void 0===n.minDate&&(l.settings.minDate=this._formatDate(l,o)),null!==h&&void 0!==n.dateFormat&&void 0===n.maxDate&&(l.settings.maxDate=this._formatDate(l,h)),"disabled"in n&&(n.disabled?this._disableDatepicker(t):this._enableDatepicker(t)),this._attachments(e(t),l),this._autoSize(l),this._setDate(l,a),this._updateAlternate(l),this._updateDatepicker(l)),void 0)},_changeDatepicker:function(e,t,i){this._optionDatepicker(e,t,i)},_refreshDatepicker:function(e){var t=this._getInst(e);t&&this._updateDatepicker(t)},_setDateDatepicker:function(e,t){var i=this._getInst(e);i&&(this._setDate(i,t),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(e,t){var i=this._getInst(e);return i&&!i.inline&&this._setDateFromField(i,t),i?this._getDate(i):null},_doKeyDown:function(t){var i,s,n,a=e.datepicker._getInst(t.target),o=!0,r=a.dpDiv.is(".ui-datepicker-rtl");if(a._keyEvent=!0,e.datepicker._datepickerShowing)switch(t.keyCode){case 9:e.datepicker._hideDatepicker(),o=!1;break;case 13:return n=e("td."+e.datepicker._dayOverClass+":not(."+e.datepicker._currentClass+")",a.dpDiv),n[0]&&e.datepicker._selectDay(t.target,a.selectedMonth,a.selectedYear,n[0]),i=e.datepicker._get(a,"onSelect"),i?(s=e.datepicker._formatDate(a),i.apply(a.input?a.input[0]:null,[s,a])):e.datepicker._hideDatepicker(),!1;case 27:e.datepicker._hideDatepicker();break;case 33:e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(a,"stepBigMonths"):-e.datepicker._get(a,"stepMonths"),"M");break;case 34:e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(a,"stepBigMonths"):+e.datepicker._get(a,"stepMonths"),"M");break;case 35:(t.ctrlKey||t.metaKey)&&e.datepicker._clearDate(t.target),o=t.ctrlKey||t.metaKey;break;case 36:(t.ctrlKey||t.metaKey)&&e.datepicker._gotoToday(t.target),o=t.ctrlKey||t.metaKey;break;case 37:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,r?1:-1,"D"),o=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(a,"stepBigMonths"):-e.datepicker._get(a,"stepMonths"),"M");break;case 38:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,-7,"D"),o=t.ctrlKey||t.metaKey;break;case 39:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,r?-1:1,"D"),o=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(a,"stepBigMonths"):+e.datepicker._get(a,"stepMonths"),"M");break;case 40:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,7,"D"),o=t.ctrlKey||t.metaKey;break;default:o=!1}else 36===t.keyCode&&t.ctrlKey?e.datepicker._showDatepicker(this):o=!1;o&&(t.preventDefault(),t.stopPropagation())},_doKeyPress:function(t){var i,s,n=e.datepicker._getInst(t.target);return e.datepicker._get(n,"constrainInput")?(i=e.datepicker._possibleChars(e.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==t.charCode?t.keyCode:t.charCode),t.ctrlKey||t.metaKey||" ">s||!i||i.indexOf(s)>-1):void 0},_doKeyUp:function(t){var i,s=e.datepicker._getInst(t.target);if(s.input.val()!==s.lastVal)try{i=e.datepicker.parseDate(e.datepicker._get(s,"dateFormat"),s.input?s.input.val():null,e.datepicker._getFormatConfig(s)),i&&(e.datepicker._setDateFromField(s),e.datepicker._updateAlternate(s),e.datepicker._updateDatepicker(s))}catch(n){}return!0},_showDatepicker:function(t){if(t=t.target||t,"input"!==t.nodeName.toLowerCase()&&(t=e("input",t.parentNode)[0]),!e.datepicker._isDisabledDatepicker(t)&&e.datepicker._lastInput!==t){var i,n,a,o,h,l,u;i=e.datepicker._getInst(t),e.datepicker._curInst&&e.datepicker._curInst!==i&&(e.datepicker._curInst.dpDiv.stop(!0,!0),i&&e.datepicker._datepickerShowing&&e.datepicker._hideDatepicker(e.datepicker._curInst.input[0])),n=e.datepicker._get(i,"beforeShow"),a=n?n.apply(t,[t,i]):{},a!==!1&&(r(i.settings,a),i.lastVal=null,e.datepicker._lastInput=t,e.datepicker._setDateFromField(i),e.datepicker._inDialog&&(t.value=""),e.datepicker._pos||(e.datepicker._pos=e.datepicker._findPos(t),e.datepicker._pos[1]+=t.offsetHeight),o=!1,e(t).parents().each(function(){return o|="fixed"===e(this).css("position"),!o}),h={left:e.datepicker._pos[0],top:e.datepicker._pos[1]},e.datepicker._pos=null,i.dpDiv.empty(),i.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),e.datepicker._updateDatepicker(i),h=e.datepicker._checkOffset(i,h,o),i.dpDiv.css({position:e.datepicker._inDialog&&e.blockUI?"static":o?"fixed":"absolute",display:"none",left:h.left+"px",top:h.top+"px"}),i.inline||(l=e.datepicker._get(i,"showAnim"),u=e.datepicker._get(i,"duration"),i.dpDiv.css("z-index",s(e(t))+1),e.datepicker._datepickerShowing=!0,e.effects&&e.effects.effect[l]?i.dpDiv.show(l,e.datepicker._get(i,"showOptions"),u):i.dpDiv[l||"show"](l?u:null),e.datepicker._shouldFocusInput(i)&&i.input.focus(),e.datepicker._curInst=i))}},_updateDatepicker:function(t){this.maxRows=4,d=t,t.dpDiv.empty().append(this._generateHTML(t)),this._attachHandlers(t);var i,s=this._getNumberOfMonths(t),n=s[1],a=17,r=t.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&o.apply(r.get(0)),t.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&t.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",a*n+"em"),t.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),t.dpDiv[(this._get(t,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),t===e.datepicker._curInst&&e.datepicker._datepickerShowing&&e.datepicker._shouldFocusInput(t)&&t.input.focus(),t.yearshtml&&(i=t.yearshtml,setTimeout(function(){i===t.yearshtml&&t.yearshtml&&t.dpDiv.find("select.ui-datepicker-year:first").replaceWith(t.yearshtml),i=t.yearshtml=null},0))},_shouldFocusInput:function(e){return e.input&&e.input.is(":visible")&&!e.input.is(":disabled")&&!e.input.is(":focus")},_checkOffset:function(t,i,s){var n=t.dpDiv.outerWidth(),a=t.dpDiv.outerHeight(),o=t.input?t.input.outerWidth():0,r=t.input?t.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:e(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:e(document).scrollTop());return i.left-=this._get(t,"isRTL")?n-o:0,i.left-=s&&i.left===t.input.offset().left?e(document).scrollLeft():0,i.top-=s&&i.top===t.input.offset().top+r?e(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+a>l&&l>a?Math.abs(a+r):0),i},_findPos:function(t){for(var i,s=this._getInst(t),n=this._get(s,"isRTL");t&&("hidden"===t.type||1!==t.nodeType||e.expr.filters.hidden(t));)t=t[n?"previousSibling":"nextSibling"];return i=e(t).offset(),[i.left,i.top]},_hideDatepicker:function(t){var i,s,n,a,o=this._curInst;!o||t&&o!==e.data(t,"datepicker")||this._datepickerShowing&&(i=this._get(o,"showAnim"),s=this._get(o,"duration"),n=function(){e.datepicker._tidyDialog(o)},e.effects&&(e.effects.effect[i]||e.effects[i])?o.dpDiv.hide(i,e.datepicker._get(o,"showOptions"),s,n):o.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,a=this._get(o,"onClose"),a&&a.apply(o.input?o.input[0]:null,[o.input?o.input.val():"",o]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),e.blockUI&&(e.unblockUI(),e("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(t){if(e.datepicker._curInst){var i=e(t.target),s=e.datepicker._getInst(i[0]);(i[0].id!==e.datepicker._mainDivId&&0===i.parents("#"+e.datepicker._mainDivId).length&&!i.hasClass(e.datepicker.markerClassName)&&!i.closest("."+e.datepicker._triggerClass).length&&e.datepicker._datepickerShowing&&(!e.datepicker._inDialog||!e.blockUI)||i.hasClass(e.datepicker.markerClassName)&&e.datepicker._curInst!==s)&&e.datepicker._hideDatepicker()}},_adjustDate:function(t,i,s){var n=e(t),a=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(a,i+("M"===s?this._get(a,"showCurrentAtPos"):0),s),this._updateDatepicker(a))},_gotoToday:function(t){var i,s=e(t),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(t,i,s){var n=e(t),a=this._getInst(n[0]);a["selected"+("M"===s?"Month":"Year")]=a["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(a),this._adjustDate(n)},_selectDay:function(t,i,s,n){var a,o=e(t);e(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(o[0])||(a=this._getInst(o[0]),a.selectedDay=a.currentDay=e("a",n).html(),a.selectedMonth=a.currentMonth=i,a.selectedYear=a.currentYear=s,this._selectDate(t,this._formatDate(a,a.currentDay,a.currentMonth,a.currentYear)))},_clearDate:function(t){var i=e(t);this._selectDate(i,"")},_selectDate:function(t,i){var s,n=e(t),a=this._getInst(n[0]);i=null!=i?i:this._formatDate(a),a.input&&a.input.val(i),this._updateAlternate(a),s=this._get(a,"onSelect"),s?s.apply(a.input?a.input[0]:null,[i,a]):a.input&&a.input.trigger("change"),a.inline?this._updateDatepicker(a):(this._hideDatepicker(),this._lastInput=a.input[0],"object"!=typeof a.input[0]&&a.input.focus(),this._lastInput=null)},_updateAlternate:function(t){var i,s,n,a=this._get(t,"altField");a&&(i=this._get(t,"altFormat")||this._get(t,"dateFormat"),s=this._getDate(t),n=this.formatDate(i,s,this._getFormatConfig(t)),e(a).each(function(){e(this).val(n)}))},noWeekends:function(e){var t=e.getDay();return[t>0&&6>t,""]},iso8601Week:function(e){var t,i=new Date(e.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),t=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((t-i)/864e5)/7)+1},parseDate:function(t,i,s){if(null==t||null==i)throw"Invalid arguments";if(i="object"==typeof i?""+i:i+"",""===i)return null;var n,a,o,r,h=0,l=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,u="string"!=typeof l?l:(new Date).getFullYear()%100+parseInt(l,10),d=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,c=(s?s.dayNames:null)||this._defaults.dayNames,p=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,f=(s?s.monthNames:null)||this._defaults.monthNames,m=-1,g=-1,v=-1,y=-1,b=!1,_=function(e){var i=t.length>n+1&&t.charAt(n+1)===e;return i&&n++,i},x=function(e){var t=_(e),s="@"===e?14:"!"===e?20:"y"===e&&t?4:"o"===e?3:2,n="y"===e?s:1,a=RegExp("^\\d{"+n+","+s+"}"),o=i.substring(h).match(a);if(!o)throw"Missing number at position "+h;return h+=o[0].length,parseInt(o[0],10)},w=function(t,s,n){var a=-1,o=e.map(_(t)?n:s,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)});if(e.each(o,function(e,t){var s=t[1];return i.substr(h,s.length).toLowerCase()===s.toLowerCase()?(a=t[0],h+=s.length,!1):void 0}),-1!==a)return a+1;throw"Unknown name at position "+h},k=function(){if(i.charAt(h)!==t.charAt(n))throw"Unexpected literal at position "+h;h++};for(n=0;t.length>n;n++)if(b)"'"!==t.charAt(n)||_("'")?k():b=!1;else switch(t.charAt(n)){case"d":v=x("d");break;case"D":w("D",d,c);break;case"o":y=x("o");break;case"m":g=x("m");break;case"M":g=w("M",p,f);break;case"y":m=x("y");break;case"@":r=new Date(x("@")),m=r.getFullYear(),g=r.getMonth()+1,v=r.getDate();break;case"!":r=new Date((x("!")-this._ticksTo1970)/1e4),m=r.getFullYear(),g=r.getMonth()+1,v=r.getDate();break;case"'":_("'")?k():b=!0;break;default:k()}if(i.length>h&&(o=i.substr(h),!/^\s+/.test(o)))throw"Extra/unparsed characters found in date: "+o;if(-1===m?m=(new Date).getFullYear():100>m&&(m+=(new Date).getFullYear()-(new Date).getFullYear()%100+(u>=m?0:-100)),y>-1)for(g=1,v=y;;){if(a=this._getDaysInMonth(m,g-1),a>=v)break;g++,v-=a}if(r=this._daylightSavingAdjust(new Date(m,g-1,v)),r.getFullYear()!==m||r.getMonth()+1!==g||r.getDate()!==v)throw"Invalid date";return r},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(e,t,i){if(!t)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,a=(i?i.dayNames:null)||this._defaults.dayNames,o=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,h=function(t){var i=e.length>s+1&&e.charAt(s+1)===t;return i&&s++,i},l=function(e,t,i){var s=""+t;if(h(e))for(;i>s.length;)s="0"+s;return s},u=function(e,t,i,s){return h(e)?s[t]:i[t]},d="",c=!1;if(t)for(s=0;e.length>s;s++)if(c)"'"!==e.charAt(s)||h("'")?d+=e.charAt(s):c=!1;else switch(e.charAt(s)){case"d":d+=l("d",t.getDate(),2);break;case"D":d+=u("D",t.getDay(),n,a);break;case"o":d+=l("o",Math.round((new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()-new Date(t.getFullYear(),0,0).getTime())/864e5),3);break;case"m":d+=l("m",t.getMonth()+1,2);break;case"M":d+=u("M",t.getMonth(),o,r);break;case"y":d+=h("y")?t.getFullYear():(10>t.getYear()%100?"0":"")+t.getYear()%100;break;case"@":d+=t.getTime();break;case"!":d+=1e4*t.getTime()+this._ticksTo1970;break;case"'":h("'")?d+="'":c=!0;break;default:d+=e.charAt(s)}return d},_possibleChars:function(e){var t,i="",s=!1,n=function(i){var s=e.length>t+1&&e.charAt(t+1)===i;return s&&t++,s};for(t=0;e.length>t;t++)if(s)"'"!==e.charAt(t)||n("'")?i+=e.charAt(t):s=!1;else switch(e.charAt(t)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=e.charAt(t)}return i},_get:function(e,t){return void 0!==e.settings[t]?e.settings[t]:this._defaults[t]},_setDateFromField:function(e,t){if(e.input.val()!==e.lastVal){var i=this._get(e,"dateFormat"),s=e.lastVal=e.input?e.input.val():null,n=this._getDefaultDate(e),a=n,o=this._getFormatConfig(e);try{a=this.parseDate(i,s,o)||n}catch(r){s=t?"":s}e.selectedDay=a.getDate(),e.drawMonth=e.selectedMonth=a.getMonth(),e.drawYear=e.selectedYear=a.getFullYear(),e.currentDay=s?a.getDate():0,e.currentMonth=s?a.getMonth():0,e.currentYear=s?a.getFullYear():0,this._adjustInstDate(e)}},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(t,i,s){var n=function(e){var t=new Date;return t.setDate(t.getDate()+e),t},a=function(i){try{return e.datepicker.parseDate(e.datepicker._get(t,"dateFormat"),i,e.datepicker._getFormatConfig(t))}catch(s){}for(var n=(i.toLowerCase().match(/^c/)?e.datepicker._getDate(t):null)||new Date,a=n.getFullYear(),o=n.getMonth(),r=n.getDate(),h=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=h.exec(i);l;){switch(l[2]||"d"){case"d":case"D":r+=parseInt(l[1],10);break;case"w":case"W":r+=7*parseInt(l[1],10);break;case"m":case"M":o+=parseInt(l[1],10),r=Math.min(r,e.datepicker._getDaysInMonth(a,o));break;case"y":case"Y":a+=parseInt(l[1],10),r=Math.min(r,e.datepicker._getDaysInMonth(a,o))}l=h.exec(i)}return new Date(a,o,r)},o=null==i||""===i?s:"string"==typeof i?a(i):"number"==typeof i?isNaN(i)?s:n(i):new Date(i.getTime());return o=o&&"Invalid Date"==""+o?s:o,o&&(o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)),this._daylightSavingAdjust(o)},_daylightSavingAdjust:function(e){return e?(e.setHours(e.getHours()>12?e.getHours()+2:0),e):null},_setDate:function(e,t,i){var s=!t,n=e.selectedMonth,a=e.selectedYear,o=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=o.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=o.getMonth(),e.drawYear=e.selectedYear=e.currentYear=o.getFullYear(),n===e.selectedMonth&&a===e.selectedYear||i||this._notifyChange(e),this._adjustInstDate(e),e.input&&e.input.val(s?"":this._formatDate(e))},_getDate:function(e){var t=!e.currentYear||e.input&&""===e.input.val()?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return t},_attachHandlers:function(t){var i=this._get(t,"stepMonths"),s="#"+t.id.replace(/\\\\/g,"\\");t.dpDiv.find("[data-handler]").map(function(){var t={prev:function(){e.datepicker._adjustDate(s,-i,"M")},next:function(){e.datepicker._adjustDate(s,+i,"M")},hide:function(){e.datepicker._hideDatepicker()},today:function(){e.datepicker._gotoToday(s)},selectDay:function(){return e.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return e.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return e.datepicker._selectMonthYear(s,this,"Y"),!1}};e(this).bind(this.getAttribute("data-event"),t[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t,i,s,n,a,o,r,h,l,u,d,c,p,f,m,g,v,y,b,_,x,w,k,T,D,S,N,M,C,P,A,I,H,z,F,E,W,O,L,j=new Date,R=this._daylightSavingAdjust(new Date(j.getFullYear(),j.getMonth(),j.getDate())),Y=this._get(e,"isRTL"),J=this._get(e,"showButtonPanel"),B=this._get(e,"hideIfNoPrevNext"),K=this._get(e,"navigationAsDateFormat"),U=this._getNumberOfMonths(e),V=this._get(e,"showCurrentAtPos"),q=this._get(e,"stepMonths"),G=1!==U[0]||1!==U[1],X=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),Q=this._getMinMaxDate(e,"min"),$=this._getMinMaxDate(e,"max"),Z=e.drawMonth-V,et=e.drawYear;if(0>Z&&(Z+=12,et--),$)for(t=this._daylightSavingAdjust(new Date($.getFullYear(),$.getMonth()-U[0]*U[1]+1,$.getDate())),t=Q&&Q>t?Q:t;this._daylightSavingAdjust(new Date(et,Z,1))>t;)Z--,0>Z&&(Z=11,et--);for(e.drawMonth=Z,e.drawYear=et,i=this._get(e,"prevText"),i=K?this.formatDate(i,this._daylightSavingAdjust(new Date(et,Z-q,1)),this._getFormatConfig(e)):i,s=this._canAdjustMonth(e,-1,et,Z)?"":B?"":"",n=this._get(e,"nextText"),n=K?this.formatDate(n,this._daylightSavingAdjust(new Date(et,Z+q,1)),this._getFormatConfig(e)):n,a=this._canAdjustMonth(e,1,et,Z)?"":B?"":"",o=this._get(e,"currentText"),r=this._get(e,"gotoCurrent")&&e.currentDay?X:R,o=K?this.formatDate(o,r,this._getFormatConfig(e)):o,h=e.inline?"":"",l=J?" ":"",u=parseInt(this._get(e,"firstDay"),10),u=isNaN(u)?0:u,d=this._get(e,"showWeek"),c=this._get(e,"dayNames"),p=this._get(e,"dayNamesMin"),f=this._get(e,"monthNames"),m=this._get(e,"monthNamesShort"),g=this._get(e,"beforeShowDay"),v=this._get(e,"showOtherMonths"),y=this._get(e,"selectOtherMonths"),b=this._getDefaultDate(e),_="",w=0;U[0]>w;w++){for(k="",this.maxRows=4,T=0;U[1]>T;T++){if(D=this._daylightSavingAdjust(new Date(et,Z,e.selectedDay)),S=" ui-corner-all",N="",G){if(N+="
"}for(N+=""+(U[0]>0&&T===U[1]-1?"":""):""),k+=N}_+=k}return _+=l,e._keyEvent=!1,_},_generateMonthYearHeader:function(e,t,i,s,n,a,o,r){var h,l,u,d,c,p,f,m,g=this._get(e,"changeMonth"),v=this._get(e,"changeYear"),y=this._get(e,"showMonthAfterYear"),b=""+"
"+(G?"",M=d?" ",P=this._getDaysInMonth(et,Z),et===e.selectedYear&&Z===e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,P)),A=(this._getFirstDayOfMonth(et,Z)-u+7)%7,I=Math.ceil((A+P)/7),H=G?this.maxRows>I?this.maxRows:I:I,this.maxRows=H,z=this._daylightSavingAdjust(new Date(et,Z,1-A)),F=0;H>F;F++){for(N+=""+this._get(e,"weekHeader")+" ":"",x=0;7>x;x++)C=(x+u)%7,M+="=5?" class='ui-datepicker-week-end'":"")+">"+""+p[C]+" ";for(N+=M+"",E=d?" "}Z++,Z>11&&(Z=0,et++),N+=""+this._get(e,"calculateWeek")(z)+" ":"",x=0;7>x;x++)W=g?g.apply(e.input?e.input[0]:null,[z]):[!0,""],O=z.getMonth()!==Z,L=O&&!y||!W[0]||Q&&Q>z||$&&z>$,E+=""+(O&&!v?" ":L?""+z.getDate()+"":""+z.getDate()+"")+" ",z.setDate(z.getDate()+1),z=this._daylightSavingAdjust(z);N+=E+"",_="";if(a||!g)_+=""+o[t]+"";else{for(h=s&&s.getFullYear()===i,l=n&&n.getFullYear()===i,_+=""}if(y||(b+=_+(!a&&g&&v?"":" ")),!e.yearshtml)if(e.yearshtml="",a||!v)b+=""+i+"";else{for(d=this._get(e,"yearRange").split(":"),c=(new Date).getFullYear(),p=function(e){var t=e.match(/c[+\-].*/)?i+parseInt(e.substring(1),10):e.match(/[+\-].*/)?c+parseInt(e,10):parseInt(e,10);return isNaN(t)?c:t},f=p(d[0]),m=Math.max(f,p(d[1]||"")),f=s?Math.max(f,s.getFullYear()):f,m=n?Math.min(m,n.getFullYear()):m,e.yearshtml+="",b+=e.yearshtml,e.yearshtml=null}return b+=this._get(e,"yearSuffix"),y&&(b+=(!a&&g&&v?"":" ")+_),b+=""},_adjustInstDate:function(e,t,i){var s=e.drawYear+("Y"===i?t:0),n=e.drawMonth+("M"===i?t:0),a=Math.min(e.selectedDay,this._getDaysInMonth(s,n))+("D"===i?t:0),o=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(s,n,a)));e.selectedDay=o.getDate(),e.drawMonth=e.selectedMonth=o.getMonth(),e.drawYear=e.selectedYear=o.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(e)},_restrictMinMax:function(e,t){var i=this._getMinMaxDate(e,"min"),s=this._getMinMaxDate(e,"max"),n=i&&i>t?i:t;return s&&n>s?s:n},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&&t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){var t=this._get(e,"numberOfMonths");return null==t?[1,1]:"number"==typeof t?[1,t]:t},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return new Date(e,t,1).getDay()},_canAdjustMonth:function(e,t,i,s){var n=this._getNumberOfMonths(e),a=this._daylightSavingAdjust(new Date(i,s+(0>t?t:n[0]*n[1]),1));return 0>t&&a.setDate(this._getDaysInMonth(a.getFullYear(),a.getMonth())),this._isInRange(e,a)},_isInRange:function(e,t){var i,s,n=this._getMinMaxDate(e,"min"),a=this._getMinMaxDate(e,"max"),o=null,r=null,h=this._get(e,"yearRange");return h&&(i=h.split(":"),s=(new Date).getFullYear(),o=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(o+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||t.getTime()>=n.getTime())&&(!a||t.getTime()<=a.getTime())&&(!o||t.getFullYear()>=o)&&(!r||r>=t.getFullYear())},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return t="string"!=typeof t?t:(new Date).getFullYear()%100+parseInt(t,10),{shortYearCutoff:t,dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,i,s){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);var n=t?"object"==typeof t?t:this._daylightSavingAdjust(new Date(s,i,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),n,this._getFormatConfig(e))}}),e.fn.datepicker=function(t){if(!this.length)return this;e.datepicker.initialized||(e(document).mousedown(e.datepicker._checkExternalClick),e.datepicker.initialized=!0),0===e("#"+e.datepicker._mainDivId).length&&e("body").append(e.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof t||"isDisabled"!==t&&"getDate"!==t&&"widget"!==t?"option"===t&&2===arguments.length&&"string"==typeof arguments[1]?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof t?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this].concat(i)):e.datepicker._attachDatepicker(this,t)}):e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(i))},e.datepicker=new n,e.datepicker.initialized=!1,e.datepicker.uuid=(new Date).getTime(),e.datepicker.version="1.11.4",e.datepicker,e.widget("ui.slider",e.ui.mouse,{version:"1.11.4",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"),this._refresh(),this._setOption("disabled",this.options.disabled),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var t,i,s=this.options,n=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),a="",o=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),t=n.length;i>t;t++)o.push(a);this.handles=n.add(e(o.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.each(function(t){e(this).data("ui-slider-handle-index",t)})},_createRange:function(){var t=this.options,i="";t.range?(t.range===!0&&(t.values?t.values.length&&2!==t.values.length?t.values=[t.values[0],t.values[0]]:e.isArray(t.values)&&(t.values=t.values.slice(0)):t.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?this.range.removeClass("ui-slider-range-min ui-slider-range-max").css({left:"",bottom:""}):(this.range=e("").appendTo(this.element),i="ui-slider-range ui-widget-header ui-corner-all"),this.range.addClass(i+("min"===t.range||"max"===t.range?" ui-slider-range-"+t.range:""))):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(t){var i,s,n,a,o,r,h,l,u=this,d=this.options;return d.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:t.pageX,y:t.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var i=Math.abs(s-u.values(t));(n>i||n===i&&(t===u._lastChangedValue||u.values(t)===d.min))&&(n=i,a=e(this),o=t)}),r=this._start(t,o),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,a.addClass("ui-state-active").focus(),h=a.offset(),l=!e(t.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:t.pageX-h.left-a.width()/2,top:t.pageY-h.top-a.height()/2-(parseInt(a.css("borderTopWidth"),10)||0)-(parseInt(a.css("borderBottomWidth"),10)||0)+(parseInt(a.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},i=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,i),!1},_mouseStop:function(e){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,i,s,n,a;return"horizontal"===this.orientation?(t=this.elementSize.width,i=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,i=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/t,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),a=this._valueMin()+s*n,this._trimAlignValue(a)},_start:function(e,t){var i={handle:this.handles[t],value:this.value()};return this.options.values&&this.options.values.length&&(i.value=this.values(t),i.values=this.values()),this._trigger("start",e,i)},_slide:function(e,t,i){var s,n,a;this.options.values&&this.options.values.length?(s=this.values(t?0:1),2===this.options.values.length&&this.options.range===!0&&(0===t&&i>s||1===t&&s>i)&&(i=s),i!==this.values(t)&&(n=this.values(),n[t]=i,a=this._trigger("slide",e,{handle:this.handles[t],value:i,values:n}),s=this.values(t?0:1),a!==!1&&this.values(t,i))):i!==this.value()&&(a=this._trigger("slide",e,{handle:this.handles[t],value:i}),a!==!1&&this.value(i))},_stop:function(e,t){var i={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(t),i.values=this.values()),this._trigger("stop",e,i)},_change:function(e,t){if(!this._keySliding&&!this._mouseSliding){var i={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(t),i.values=this.values()),this._lastChangedValue=t,this._trigger("change",e,i)}},value:function(e){return arguments.length?(this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0),void 0):this._value()},values:function(t,i){var s,n,a;if(arguments.length>1)return this.options.values[t]=this._trimAlignValue(i),this._refreshValue(),this._change(null,t),void 0;if(!arguments.length)return this._values();if(!e.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(t):this.value();for(s=this.options.values,n=arguments[0],a=0;s.length>a;a+=1)s[a]=this._trimAlignValue(n[a]),this._change(null,a);this._refreshValue()},_setOption:function(t,i){var s,n=0;switch("range"===t&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),e.isArray(this.options.values)&&(n=this.options.values.length),"disabled"===t&&this.element.toggleClass("ui-state-disabled",!!i),this._super(t,i),t){case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue(),this.handles.css("horizontal"===i?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=0;n>s;s+=1)this._change(null,s);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_value:function(){var e=this.options.value;return e=this._trimAlignValue(e)},_values:function(e){var t,i,s;if(arguments.length)return t=this.options.values[e],t=this._trimAlignValue(t);if(this.options.values&&this.options.values.length){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(e){if(this._valueMin()>=e)return this._valueMin();if(e>=this._valueMax())return this._valueMax();var t=this.options.step>0?this.options.step:1,i=(e-this._valueMin())%t,s=e-i;return 2*Math.abs(i)>=t&&(s+=i>0?t:-t),parseFloat(s.toFixed(5))},_calculateNewMax:function(){var e=this.options.max,t=this._valueMin(),i=this.options.step,s=Math.floor(+(e-t).toFixed(this._precision())/i)*i;e=s+t,this.max=parseFloat(e.toFixed(this._precision()))},_precision:function(){var e=this._precisionOf(this.options.step);return null!==this.options.min&&(e=Math.max(e,this._precisionOf(this.options.min))),e},_precisionOf:function(e){var t=""+e,i=t.indexOf(".");return-1===i?0:t.length-i-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshValue:function(){var t,i,s,n,a,o=this.options.range,r=this.options,h=this,l=this._animateOff?!1:r.animate,u={};this.options.values&&this.options.values.length?this.handles.each(function(s){i=100*((h.values(s)-h._valueMin())/(h._valueMax()-h._valueMin())),u["horizontal"===h.orientation?"left":"bottom"]=i+"%",e(this).stop(1,1)[l?"animate":"css"](u,r.animate),h.options.range===!0&&("horizontal"===h.orientation?(0===s&&h.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({width:i-t+"%"},{queue:!1,duration:r.animate})):(0===s&&h.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({height:i-t+"%"},{queue:!1,duration:r.animate}))),t=i}):(s=this.value(),n=this._valueMin(),a=this._valueMax(),i=a!==n?100*((s-n)/(a-n)):0,u["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](u,r.animate),"min"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},r.animate),"max"===o&&"horizontal"===this.orientation&&this.range[l?"animate":"css"]({width:100-i+"%"},{queue:!1,duration:r.animate}),"min"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},r.animate),"max"===o&&"vertical"===this.orientation&&this.range[l?"animate":"css"]({height:100-i+"%"},{queue:!1,duration:r.animate}))},_handleEvents:{keydown:function(t){var i,s,n,a,o=e(t.target).data("ui-slider-handle-index");switch(t.keyCode){case e.ui.keyCode.HOME:case e.ui.keyCode.END:case e.ui.keyCode.PAGE_UP:case e.ui.keyCode.PAGE_DOWN:case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(t.preventDefault(),!this._keySliding&&(this._keySliding=!0,e(t.target).addClass("ui-state-active"),i=this._start(t,o),i===!1))return}switch(a=this.options.step,s=n=this.options.values&&this.options.values.length?this.values(o):this.value(),t.keyCode){case e.ui.keyCode.HOME:n=this._valueMin();break;case e.ui.keyCode.END:n=this._valueMax();break;case e.ui.keyCode.PAGE_UP:n=this._trimAlignValue(s+(this._valueMax()-this._valueMin())/this.numPages);break;case e.ui.keyCode.PAGE_DOWN:n=this._trimAlignValue(s-(this._valueMax()-this._valueMin())/this.numPages);break;case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:if(s===this._valueMax())return;n=this._trimAlignValue(s+a);break;case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(s===this._valueMin())return;n=this._trimAlignValue(s-a)}this._slide(t,o,n)},keyup:function(t){var i=e(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,i),this._change(t,i),e(t.target).removeClass("ui-state-active"))}}})}); \ No newline at end of file diff --git a/assets/js/paystack-public.js b/public/js/paystack-forms-public.js similarity index 59% rename from assets/js/paystack-public.js rename to public/js/paystack-forms-public.js index 01466bd..9fd12a8 100644 --- a/assets/js/paystack-public.js +++ b/public/js/paystack-forms-public.js @@ -1,4 +1,4 @@ -function PffPaystackFee() +function KkdPffPaystackFee() { this.DEFAULT_PERCENTAGE = 0.015; @@ -97,20 +97,18 @@ function PffPaystackFee() "use strict"; $(document).ready( function ($) { - - /*if ( 0 < $(".date-picker").length ) { - $(".date-picker").each( function() { - $(".date-picker").datepicker( - { - dateFormat: "mm/dd/yy", - prevText: '', - nextText: '' - } - ); - } ); - }*/ - - if ( $("#pf-vamount").length ) { + $( + function () { + $(".date-picker").datepicker( + { + dateFormat: "mm/dd/yy", + prevText: '', + nextText: '' + } + ); + } + ); + if ($("#pf-vamount").length) { var amountField = $("#pf-vamount"); calculateTotal(); } else { @@ -129,6 +127,54 @@ function PffPaystackFee() } ); + function checkMinimumVal() + { + if ($("#pf-minimum-hidden").length) { + var min_amount = Number($("#pf-minimum-hidden").val()); + var amt = Number($("#pf-amount").val()); + if (min_amount > 0 && amt < min_amount) { + $("#pf-min-val-warn").text( + "Amount cannot be less than the minimum amount" + ); + return false; + } else { + $("#pf-min-val-warn").text(""); + $("#pf-amount").removeClass("rerror"); + } + } + } + + function format_validate(max, e) + { + var value = amountField.text(); + if (e.which != 8 && value.length > max) { + e.preventDefault(); + } + // Allow: backspace, delete, tab, escape, enter and . + if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 + // Allow: Ctrl+A + || (e.keyCode == 65 && e.ctrlKey === true) + // Allow: Ctrl+C + || (e.keyCode == 67 && e.ctrlKey === true) + // Allow: Ctrl+X + || (e.keyCode == 88 && e.ctrlKey === true) + // Allow: home, end, left, right + || (e.keyCode >= 35 && e.keyCode <= 39) + ) { + // let it happen, don't do anything + calculateFees(); + return; + } + // Ensure that it is a number and stop the keypress + if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) + && (e.keyCode < 96 || e.keyCode > 105) + ) { + e.preventDefault(); + } else { + calculateFees(); + } + } + $.fn.digits = function () { return this.each( function () { @@ -141,6 +187,70 @@ function PffPaystackFee() ); }; + function calculateTotal() + { + var unit; + if ($("#pf-vamount").length) { + unit = $("#paystack-form").find("#pf-vamount").val(); + } else { + unit = $("#pf-amount").val(); + } + var quant = $("#pf-quantity").val(); + var newvalue = unit * quant; + + if (quant == "" || quant == null) { + quant = 1; + } else { + $("#pf-total").val(newvalue); + } + + } + function calculateFees(transaction_amount) + { + setTimeout( + function () { + transaction_amount = transaction_amount || parseInt(amountField.val()); + var currency = $("#pf-currency").val(); + var quant = $("#pf-quantity").val(); + if ($("#pf-vamount").length) { + var name = $("#pf-vamount option:selected").attr("data-name"); + $("#pf-vname").val(name); + } + if (transaction_amount == "" + || transaction_amount == 0 + || transaction_amount.length == 0 + || transaction_amount == null + || isNaN(transaction_amount) + ) { + var total = 0; + var fees = 0; + } else { + var obj = new KkdPffPaystackFee(); + + obj.withAdditionalCharge(kkd_pff_settings.fee.adc); + obj.withThreshold(kkd_pff_settings.fee.ths); + obj.withCap(kkd_pff_settings.fee.cap); + obj.withPercentage(kkd_pff_settings.fee.prc); + if (quant) { + transaction_amount = transaction_amount * quant; + } + var total = obj.addFor(transaction_amount * 100) / 100; + var fees = total - transaction_amount; + } + $(".pf-txncharge") + .hide() + .html(currency + " " + fees.toFixed(2)) + .show() + .digits(); + $(".pf-txntotal") + .hide() + .html(currency + " " + total.toFixed(2)) + .show() + .digits(); + }, 100 + ); + } + calculateFees(); $(".pf-number").keydown( @@ -175,6 +285,11 @@ function PffPaystackFee() } ); + function validateEmail(email) + { + var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + return re.test(email); + } $(".paystack-form").on( "submit", function (e) { var requiredFieldIsInvalid = false; @@ -192,18 +307,15 @@ function PffPaystackFee() var email = $(this) .find("#pf-email") .val(); - var amount; if ($("#pf-vamount").length) { - amount = $("#pf-vamount").val(); + amount = $("#paystack-form").find("#pf-vamount").val(); calculateTotal(); } else { amount = $(this) .find("#pf-amount") .val(); } - - if (Number(amount) > 0) { } else { $(this) @@ -283,7 +395,6 @@ function PffPaystackFee() dataType: "JSON", success: function (data) { $.unblockUI(); - data.custom_fields.push( { "display_name": "Plugin", @@ -291,18 +402,16 @@ function PffPaystackFee() "value": "pff-paystack" } ) - if ( data.result == "success" ) { + if (data.result == "success") { var names = data.name.split(" "); var firstName = names[0] || ""; var lastName = names[1] || ""; var quantity = data.quantity; - - $("#pf-nonce").val(data.invoiceNonce); - + // console.log(firstName+ " - "+lastName); if (data.plan == "none" || data.plan == "" || data.plan == "no") { var handler = PaystackPop.setup( { - key: pffSettings.key, + key: kkd_pff_settings.key, email: data.email, amount: data.total, firstname: firstName, @@ -318,45 +427,53 @@ function PffPaystackFee() $.post( $form.attr("action"), { - action: "pff_paystack_confirm_payment", - code: response.trxref, - quantity: quantity, - nonce: data.confirmNonce - }, + action: "kkd_pff_paystack_confirm_payment", + code: response.trxref, + quantity: quantity + }, function (newdata) { - data = JSON.parse(newdata); - if (data.result == "success2") { - window.location.href = data.link; - } - if (data.result == "success") { - $(".paystack-form")[0].reset(); - $("html,body").animate( - { scrollTop: $(".paystack-form").offset().top - 110 }, - 500 - ); - - self.before('' + data.message + ''); - $(this) - .find("input, select, textarea") - .each( - function () { - $(this).css( - { - "border-color": "#d1d1d1", - "background-color": "#fff" - } - ); - } - ); - calculateFees(); - - $.unblockUI(); - } else { - self.before('' + data.message + ''); - $.unblockUI(); - } - } - ); + data = JSON.parse(newdata); + if (data.result == "success2") { + window.location.href = data.link; + } + if (data.result == "success") { + $(".paystack-form")[0].reset(); + $("html,body").animate( + { scrollTop: $(".paystack-form").offset().top - 110 }, + 500 + ); + + self.before('' + data.message + ''); + $(this) + .find("input, select, textarea") + .each( + function () { + $(this).css( + { + "border-color": "#d1d1d1", + "background-color": "#fff" + } + ); + } + ); + $(".pf-txncharge") + .hide() + .html("NGN0") + .show() + .digits(); + $(".pf-txntotal") + .hide() + .html("NGN0") + .show() + .digits(); + + $.unblockUI(); + } else { + self.before('' + data.message + ''); + $.unblockUI(); + } + } + ); }, onClose: function () { } } @@ -364,7 +481,7 @@ function PffPaystackFee() } else { var handler = PaystackPop.setup( { - key: pffSettings.key, + key: kkd_pff_settings.key, email: data.email, plan: data.plan, firstname: firstName, @@ -380,9 +497,8 @@ function PffPaystackFee() $.post( $form.attr("action"), { - action: "pff_paystack_confirm_payment", - code: response.trxref, - nonce: data.confirmNonce + action: "kkd_pff_paystack_confirm_payment", + code: response.trxref }, function (newdata) { data = JSON.parse(newdata); @@ -409,9 +525,18 @@ function PffPaystackFee() ); } ); - calculateFees(); - - $.unblockUI(); + $(".pf-txncharge") + .hide() + .html("NGN0") + .show() + .digits(); + $(".pf-txntotal") + .hide() + .html("NGN0") + .show() + .digits(); + + $.unblockUI(); } else { self.before('' + data.message + ''); $.unblockUI(); @@ -426,9 +551,8 @@ function PffPaystackFee() handler.openIframe(); } else { - alert(data.error_message); + alert(data.message); } - }, error: function (xhr, status, error) { console.log("An error occurred"); @@ -475,13 +599,11 @@ function PffPaystackFee() var firstName = names[0] || ""; var lastName = names[1] || ""; var quantity = data.quantity; - - $("#pf-nonce").val(data.retryNonce); - + // console.log(firstName+ " - "+lastName); if (data.plan == "none" || data.plan == "" || data.plan == "no") { var handler = PaystackPop.setup( { - key: pffSettings.key, + key: kkd_pff_settings.key, email: data.email, amount: data.total, firstname: firstName, @@ -497,26 +619,47 @@ function PffPaystackFee() $.post( $form.attr("action"), { - action: "pff_paystack_confirm_payment", + action: "kkd_pff_paystack_rconfirm_payment", code: response.trxref, - quantity: quantity, - retry: true, - nonce: data.confirmNonce - }, + quantity: quantity + }, function (newdata) { data = JSON.parse(newdata); if (data.result == "success2") { window.location.href = data.link; } if (data.result == "success") { - // Get the current URL - const currentUrl = window.location.href; - - // Use URL object to parse the current URL - const url = new URL( currentUrl ); + $(".retry-form")[0].reset(); + $("html,body").animate( + { scrollTop: $(".retry-form").offset().top - 110 }, + 500 + ); - // Redirect to the same URL without query parameters - window.location.href = url.origin + url.pathname; + self.before('' + data.message + ''); + $(this) + .find("input, select, textarea") + .each( + function () { + $(this).css( + { + "border-color": "#d1d1d1", + "background-color": "#fff" + } + ); + } + ); + $(".pf-txncharge") + .hide() + .html("NGN0") + .show() + .digits(); + $(".pf-txntotal") + .hide() + .html("NGN0") + .show() + .digits(); + $("#submitbtn").remove(); + $.unblockUI(); } else { self.before('' + data.message + ''); $.unblockUI(); @@ -530,7 +673,7 @@ function PffPaystackFee() } else { var handler = PaystackPop.setup( { - key: pffSettings.key, + key: kkd_pff_settings.key, email: data.email, plan: data.plan, firstname: firstName, @@ -546,10 +689,8 @@ function PffPaystackFee() $.post( $form.attr("action"), { - action: "pff_paystack_confirm_payment", - code: response.trxref, - retry: true, - nonce: data.confirmNonce + action: "kkd_pff_paystack_rconfirm_payment", + code: response.trxref }, function (newdata) { data = JSON.parse(newdata); @@ -557,14 +698,37 @@ function PffPaystackFee() window.location.href = data.link; } if (data.result == "success") { - // Get the current URL - const currentUrl = window.location.href; - - // Use URL object to parse the current URL - const url = new URL(currentUrl); + $(".retry-form")[0].reset(); + $("html,body").animate( + { scrollTop: $(".retry-form").offset().top - 110 }, + 500 + ); - // Redirect to the same URL without query parameters - window.location.href = url.origin + url.pathname; + self.before('' + data.message + ''); + $(this) + .find("input, select, textarea") + .each( + function () { + $(this).css( + { + "border-color": "#d1d1d1", + "background-color": "#fff" + } + ); + } + ); + $(".pf-txncharge") + .hide() + .html("NGN0") + .show() + .digits(); + $(".pf-txntotal") + .hide() + .html("NGN0") + .show() + .digits(); + $("#submitbtn").remove(); + $.unblockUI(); } else { self.before('' + data.message + ''); $.unblockUI(); @@ -592,119 +756,6 @@ function PffPaystackFee() ); } ); - - - function checkMinimumVal() { - if ($("#pf-minimum-hidden").length) { - var min_amount = Number($("#pf-minimum-hidden").val()); - var amt = Number($("#pf-amount").val()); - if (min_amount > 0 && amt < min_amount) { - $("#pf-min-val-warn").text( "Amount cannot be less than the minimum amount"); - return false; - } else { - $("#pf-min-val-warn").text(""); - $("#pf-amount").removeClass("rerror"); - } - } - } - - function format_validate(max, e) { - var value = amountField.text(); - if (e.which != 8 && value.length > max) { - e.preventDefault(); - } - // Allow: backspace, delete, tab, escape, enter and . - if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 - // Allow: Ctrl+A - || (e.keyCode == 65 && e.ctrlKey === true) - // Allow: Ctrl+C - || (e.keyCode == 67 && e.ctrlKey === true) - // Allow: Ctrl+X - || (e.keyCode == 88 && e.ctrlKey === true) - // Allow: home, end, left, right - || (e.keyCode >= 35 && e.keyCode <= 39) - ) { - // let it happen, don't do anything - calculateFees(); - return; - } - // Ensure that it is a number and stop the keypress - if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) - && (e.keyCode < 96 || e.keyCode > 105) - ) { - e.preventDefault(); - } else { - calculateFees(); - } - } - - function calculateTotal() { - var unit; - if ($("#pf-vamount").length) { - unit = $("#pf-vamount").val(); - } else { - unit = $("#pf-amount").val(); - } - var quant = $("#pf-quantity").val(); - var newvalue = unit * quant; - - if (quant == "" || quant == null) { - quant = 1; - } else { - $("#pf-total").val(newvalue); - } - - } - function calculateFees(transaction_amount) { - setTimeout( - function () { - transaction_amount = transaction_amount || parseInt(amountField.val()); - var currency = $("#pf-currency").val(); - var quant = $("#pf-quantity").val(); - if ($("#pf-vamount").length) { - var name = $("#pf-vamount option:selected").attr("data-name"); - $("#pf-vname").val(name); - } - if (transaction_amount == "" - || transaction_amount == 0 - || transaction_amount.length == 0 - || transaction_amount == null - || isNaN(transaction_amount) - ) { - var total = 0; - var fees = 0; - } else { - var obj = new PffPaystackFee(); - - obj.withAdditionalCharge(pffSettings.fee.adc); - obj.withThreshold(pffSettings.fee.ths); - obj.withCap(pffSettings.fee.cap); - obj.withPercentage(pffSettings.fee.prc); - if (quant) { - transaction_amount = transaction_amount * quant; - } - var total = obj.addFor(transaction_amount * 100) / 100; - var fees = total - transaction_amount; - } - $(".pf-txncharge") - .hide() - .html(currency + " " + fees.toFixed(2)) - .show() - .digits(); - $(".pf-txntotal") - .hide() - .html(currency + " " + total.toFixed(2)) - .show() - .digits(); - }, 100 - ); - } - - function validateEmail(email) { - var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - return re.test(email); - } - } ); })(jQuery); \ No newline at end of file diff --git a/readme.txt b/readme.txt index 8ab7241..d90e2cf 100644 --- a/readme.txt +++ b/readme.txt @@ -1,11 +1,10 @@ === Payment Forms for Paystack === -Contributors: paystack, kendysond, steveamaza, sourcecodeink, krugazul, feedmymedia +Contributors: paystack, kendysond, steveamaza, sourcecodeink Donate link: https://paystack.com/demo -Tags: paystack, recurrent payments, donation, forms, payments -Requires at least: 5.0 -Tested up to: 6.6 -Stable tag: 4.0.0 -Requires PHP: 7.2 +Tags: paystack, recurrent payments, nigeria, mastercard, visa, target, Naira, payments, verve, donation, church, NGO, form, contact form 7, form +Requires at least: 3.1 +Tested up to: 6.4 +Stable tag: 3.4.2 License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html @@ -88,12 +87,11 @@ If you get stuck, you can ask for help in the [Payment Forms for Paystack Plugin = Payment Forms for Paystack is awesome! Can I contribute? = -Yes you can! Join in on our [GitHub repository](https://github.com/PaystackOSS/plugin-payment-forms-for-wordpress) :) +Yes you can! Join in on our [GitHub repository](https://github.com/PaystackHQ/wordpress-payment-forms-for-paystack) :) + + == Changelog == -= 4.0.0 = -* An entire plugin rewrite, keeping the same functionality. -* Tested with WordPress 6.2 = 3.4.0 = * Support for WordPress 5.9 * Support for PHP 8 diff --git a/uninstall.php b/uninstall.php new file mode 100644 index 0000000..e006432 --- /dev/null +++ b/uninstall.php @@ -0,0 +1,6 @@ +