예제 #1
0
파일: template.php 프로젝트: JSpier/smacamp
/**
 * Converted to WP 2.0
 * Archives an invoice, or multiple invoices.
 *
 * @global type $wpdb
 *
 * @param type $invoice_id
 *
 * @return type
 */
function wpi_archive_invoice($invoice_id)
{
    //** Check to see if array is passed or single. */
    if (is_array($invoice_id)) {
        $counter = 0;
        foreach ($invoice_id as $single_invoice_id) {
            $this_invoice = new WPI_Invoice();
            $this_invoice->load_invoice("id={$single_invoice_id}");
            $this_invoice->set("status=archive");
            $this_invoice->add_entry(__("Archived.", WPI));
            if ($this_invoice->save_invoice()) {
                $counter++;
            }
        }
        return __("{$counter}  invoice(s) archived.", WPI);
    } else {
        $this_invoice = new WPI_Invoice();
        $this_invoice->load_invoice("id={$invoice_id}");
        $this_invoice->set("status=archive");
        $this_invoice->add_entry(__("Archived.", WPI));
        if ($this_invoice->save_invoice()) {
            return __('Successfully archived.', WPI);
        }
    }
}
 /**
  * This function handles the processing of the payments - it should be overrideen in child classes
  * @param string $args The args for the fucnction
  * @since 3.0
  */
 function process_payment(){
   global $wpi_settings, $invoice;
   /** Pull the invoice */
   $the_invoice = new WPI_Invoice();
   $invoice = $the_invoice->load_invoice("return=true&id=".wpi_invoice_id_to_post_id($_REQUEST['invoice_id']));
   /** Call the child function based on the wpi_type variable sent */
   $wpi_settings['installed_gateways'][$_REQUEST['type']]['object']->process_payment();
   die();
 }
예제 #3
0
 /**
  * Track Successful Payment
  * @param $invoice
  * @since 1.7.5
  */
 public function track_successful_payment($invoice)
 {
     if ($this->was_referred()) {
         $new_invoice = new WPI_Invoice();
         $new_invoice->load_invoice("id={$invoice->data['invoice_id']}");
         $this->insert_pending_referral($new_invoice->data['total_payments'] ? $new_invoice->data['total_payments'] : $new_invoice->data['net'], $new_invoice->data['invoice_id'], $new_invoice->data['post_title']);
         if ($new_invoice->data['post_status'] == 'paid') {
             $this->complete_referral($new_invoice->data['invoice_id']);
         }
     }
 }
/**
    Converted to WP 2.0
    Archives an invoice, or multiple invoices.
*/
    function wpi_archive_invoice($invoice_id) {
        global $wpdb;
        // Check to see if array is passed or single.
        if(is_array($invoice_id))
        {
            $counter=0;
            foreach ($invoice_id as $single_invoice_id) {
                $this_invoice = new WPI_Invoice();
                $this_invoice->load_invoice("id=$single_invoice_id");
                $this_invoice->set("status=archive");
                $this_invoice->add_entry(__("Archived.", WPI));
                if($this_invoice->save_invoice())
                    $counter++;
            }
            return __("$counter  invoice(s) archived.", WPI);
        } else {
            $this_invoice = new WPI_Invoice();
            $this_invoice->load_invoice("id=$invoice_id");
            $this_invoice->set("status=archive");
            $this_invoice->add_entry(__("Archived.", WPI));
            if($this_invoice->save_invoice())
                return __('Successfully archived.', WPI);
        }
    }
예제 #5
0
 /**
  * Handler for PayPal IPN queries
  * @author korotkov@ud
  * Full callback URL: http://domain/wp-admin/admin-ajax.php?action=wpi_gateway_server_callback&type=wpi_paypal
  */
 static function server_callback()
 {
     if (empty($_POST)) {
         die(__('Direct access not allowed', WPI));
     }
     $invoice = new WPI_Invoice();
     $invoice->load_invoice("id={$_POST['invoice']}");
     /** Verify callback request */
     if (self::_ipn_verified($invoice)) {
         switch ($_POST['txn_type']) {
             /** New PayPal Subscription */
             case 'subscr_signup':
                 /** PayPal Subscription created */
                 WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['invoice']), 'invoice', 'update', '', __('PayPal Subscription created', WPI));
                 wp_invoice_mark_as_pending($_POST['invoice']);
                 do_action('wpi_paypal_subscr_signup_ipn', $_POST);
                 break;
             case 'subscr_cancel':
                 /** PayPal Subscription cancelled */
                 WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['invoice']), 'invoice', 'update', '', __('PayPal Subscription cancelled', WPI));
                 do_action('wpi_paypal_subscr_cancel_ipn', $_POST);
                 break;
             case 'subscr_failed':
                 /** PayPal Subscription failed */
                 WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['invoice']), 'invoice', 'update', '', __('PayPal Subscription payment failed', WPI));
                 do_action('wpi_paypal_subscr_failed_ipn', $_POST);
                 break;
             case 'subscr_payment':
                 /** Payment of Subscription */
                 switch ($_POST['payment_status']) {
                     case 'Completed':
                         /** Add payment amount */
                         $event_note = sprintf(__('%1s paid for subscription %2s', WPI), WPI_Functions::currency_format(abs($_POST['mc_gross']), $_POST['invoice']), $_POST['subscr_id']);
                         $event_amount = (double) $_POST['mc_gross'];
                         $event_type = 'add_payment';
                         /** Log balance changes */
                         $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                         $invoice->save_invoice();
                         send_notification($invoice->data);
                         break;
                     default:
                         break;
                 }
                 do_action('wpi_paypal_subscr_payment_ipn', $_POST);
                 break;
             case 'subscr_eot':
                 /** PayPal Subscription end of term */
                 WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['invoice']), 'invoice', 'update', '', __('PayPal Subscription term is finished', WPI));
                 wp_invoice_mark_as_paid($_POST['invoice'], $check = false);
                 do_action('wpi_paypal_subscr_eot_ipn', $_POST);
                 break;
             case 'subscr_modify':
                 /** PayPal Subscription modified */
                 WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['invoice']), 'invoice', 'update', '', __('PayPal Subscription modified', WPI));
                 do_action('wpi_paypal_subscr_modify_ipn', $_POST);
                 break;
             case 'web_accept':
                 /** PayPal simple button */
                 switch ($_POST['payment_status']) {
                     case 'Pending':
                         /** Mark invoice as Pending */
                         wp_invoice_mark_as_pending($_POST['invoice']);
                         do_action('wpi_paypal_pending_ipn', $_POST);
                         break;
                     case 'Completed':
                         /** Add payment amount */
                         $event_note = sprintf(__('%s paid via PayPal', WPI), WPI_Functions::currency_format(abs($_POST['mc_gross']), $_POST['invoice']));
                         $event_amount = (double) $_POST['mc_gross'];
                         $event_type = 'add_payment';
                         /** Log balance changes */
                         $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                         /** Log payer email */
                         $payer_email = sprintf(__("PayPal Payer email: %s", WPI), $_POST['payer_email']);
                         $invoice->add_entry("attribute=invoice&note={$payer_email}&type=update");
                         $invoice->save_invoice();
                         /** ... and mark invoice as paid */
                         wp_invoice_mark_as_paid($_POST['invoice'], $check = true);
                         send_notification($invoice->data);
                         do_action('wpi_paypal_complete_ipn', $_POST);
                         break;
                     default:
                         break;
                 }
                 break;
             case 'cart':
                 /** PayPal Cart. Used for SPC */
                 switch ($_POST['payment_status']) {
                     case 'Pending':
                         /** Mark invoice as Pending */
                         wp_invoice_mark_as_pending($_POST['invoice']);
                         do_action('wpi_paypal_pending_ipn', $_POST);
                         break;
                     case 'Completed':
                         /** Add payment amount */
                         $event_note = sprintf(__('%s paid via PayPal', WPI), WPI_Functions::currency_format(abs($_POST['mc_gross']), $_POST['invoice']));
                         $event_amount = (double) $_POST['mc_gross'];
                         $event_type = 'add_payment';
                         /** Log balance changes */
                         $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                         /** Log payer email */
                         $payer_email = sprintf(__("PayPal Payer email: %s", WPI), $_POST['payer_email']);
                         $invoice->add_entry("attribute=invoice&note={$payer_email}&type=update");
                         $invoice->save_invoice();
                         /** ... and mark invoice as paid */
                         wp_invoice_mark_as_paid($_POST['invoice'], $check = true);
                         send_notification($invoice->data);
                         do_action('wpi_paypal_complete_ipn', $_POST);
                         break;
                     default:
                         break;
                 }
                 break;
             default:
                 break;
         }
         echo ' ';
     }
 }
예제 #6
0
파일: wpi_ui.php 프로젝트: JSpier/smacamp
 /**
  * Does our preprocessing for the manage invoice page, adds our meta boxes, and checks invoice data
  *
  * @since 3.0
  */
 static function page_manage_invoice_preprocess($screen_id)
 {
     global $wpi_settings, $this_invoice, $wpdb;
     // Check if invoice_id already exists
     $invoice_id_exists = false;
     if (!empty($_REQUEST['wpi'])) {
         if (!empty($_REQUEST['wpi']['new_invoice'])) {
             if (wpi_check_invoice($_REQUEST['wpi']['new_invoice']['invoice_id'])) {
                 $invoice_id_exists = true;
             }
         }
         if (!empty($_REQUEST['wpi']['existing_invoice'])) {
             if (wpi_check_invoice($_REQUEST['wpi']['existing_invoice']['invoice_id'])) {
                 $invoice_id_exists = true;
             }
         }
     }
     if ($invoice_id_exists) {
         // Select status of invoice from DB
         $status = $wpdb->get_var("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = '{$_REQUEST['wpi']['existing_invoice']['invoice_id']}' AND meta_key = 'status'");
     }
     // New Invoice
     if (isset($_REQUEST['wpi']['new_invoice']) && empty($invoice_id_exists)) {
         $this_invoice = new WPI_Invoice();
         $this_invoice->create_new_invoice("invoice_id={$_REQUEST['wpi']['new_invoice']['invoice_id']}");
         // If we are copying from a template
         if (!empty($_REQUEST['wpi']['new_invoice']['template_copy'])) {
             $this_invoice->load_template("id={$_REQUEST['wpi']['new_invoice']['template_copy']}");
         }
         // Set user and determine type
         $this_invoice->load_user("email={$_REQUEST['wpi']['new_invoice']['user_email']}");
         // Add custom data if user doesn't exist.
         if (empty($this_invoice->data['user_data'])) {
             $this_invoice->data['user_data'] = array('user_email' => $_REQUEST['wpi']['new_invoice']['user_email']);
         }
         $new_invoice = true;
         // Enter in GET values
         if (isset($_GET['prefill']['subject'])) {
             $this_invoice->data['subject'] = $_GET['prefill']['subject'];
         }
         if (!empty($_GET['prefill']['is_quote']) && $_GET['prefill']['is_quote'] == 'true') {
             $this_invoice->data['is_quote'] = true;
             $this_invoice->data['status'] = "quote";
         }
     } else {
         if (!empty($invoice_id_exists)) {
             // Existing Invoice
             $this_invoice = new WPI_Invoice();
             if (isset($_REQUEST['wpi']['existing_invoice']['invoice_id'])) {
                 $ID = $_REQUEST['wpi']['existing_invoice']['invoice_id'];
             } else {
                 if (isset($_REQUEST['wpi']['new_invoice']['invoice_id'])) {
                     $ID = $_REQUEST['wpi']['new_invoice']['invoice_id'];
                 }
             }
             $this_invoice->load_invoice("id={$ID}");
         }
     }
     add_meta_box('postbox_payment_methods', __('Payment Settings', WPI), 'postbox_payment_methods', $screen_id, 'normal', 'high');
     if (is_object($this_invoice) && isset($this_invoice->data['type']) && $this_invoice->data['type'] == 'single_payment') {
         add_meta_box('postbox_overview', __('Overview', WPI), 'postbox_overview', $screen_id, 'side', 'high');
     } else {
         add_meta_box('postbox_publish', __('Publish', WPI), 'postbox_publish', $screen_id, 'side', 'high');
     }
     add_meta_box('postbox_user_existing', __('User Information', WPI), 'postbox_user_existing', $screen_id, 'side', 'low');
 }
예제 #7
0
 /**
  * Run import process
  *
  * @global object $wpdb
  * @global array $wpi_settings
  */
 function do_import()
 {
     global $wpdb, $wpi_settings;
     /* Get plugin Singleton object */
     $core = WPI_Core::getInstance();
     /* Try to import General Plugin Settings from old version */
     $legacy_settings = self::get_legacy_settings();
     if (!empty($legacy_settings)) {
         $core->Settings->SaveSettings($legacy_settings);
         $core->Functions->log(__("Web Invoice setting options were successfully imported.", WPI));
     }
     /* Boolean variables which show 'legacy logs' data migration's status */
     $legacy_logs = false;
     $legacy_logs_import_error = false;
     /* Try to import Invoices from Web Invoice plugin */
     $legacy_invoices = self::get_legacy_invoices();
     if (is_array($legacy_invoices) && !empty($legacy_invoices)) {
         $errors = false;
         foreach ($legacy_invoices as $i) {
             $invoice_id = $core->Functions->save_invoice($i, array('type' => 'import'));
             if ($invoice_id) {
                 //* Try to get Logs of Invoices from the old version */
                 $logs = self::get_legacy_logs_by_id($invoice_id);
                 if (!empty($logs)) {
                     /* Imports logs to new table. */
                     if (self::import_logs($logs)) {
                         $legacy_logs = true;
                     } else {
                         $legacy_logs_import_error = true;
                     }
                 }
                 //* If invoice has 'paid' status we should add log of payment. */
                 if ($i['post_status'] == 'paid') {
                     $invoice = new WPI_Invoice();
                     $invoice->load_invoice("id={$invoice_id}");
                     if ($i['recurring']['active'] == 'on' && !empty($i['recurring']['cycles'])) {
                         $event_amount = $i['amount'] * $i['recurring']['cycles'];
                     } else {
                         $event_amount = $i['amount'];
                     }
                     $event_note = "Automatically created using Web Invoice log data";
                     $event_note = $core->Functions->currency_format(abs($event_amount), $invoice_id) . " paid in - {$event_note}";
                     $timestamp = time();
                     $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type=add_payment&time={$timestamp}");
                     $invoice->save_invoice();
                 }
             } else {
                 $errors = true;
             }
         }
         if ($errors == true) {
             $core->Functions->log(__("Invoices from Web Invoice plugin were migrated with errors.", WPI));
         } else {
             $core->Functions->log(__("Invoices from Web Invoice plugin were successfully migrated.", WPI));
         }
     }
     if ($legacy_logs == true) {
         if ($legacy_logs_import_error == false) {
             $core->Functions->log(__("Log data from Web Invoice plugin were successfully migrated.", WPI));
         } else {
             $core->Functions->log(__("Log data from Web Invoice plugin were migrated with errors.", WPI));
         }
     }
     //* Mark as imported */
     update_option('wpi_web_invoice_imported', 1);
 }
예제 #8
0
 /**
  * Handler for Silent Post Url
  */
 static function server_callback()
 {
     $arb = false;
     $fields = array();
     foreach ($_REQUEST as $name => $value) {
         $fields[$name] = $value;
         if ($name == 'x_subscription_id') {
             $arb = true;
         }
     }
     // Handle recurring billing payments
     if ($arb == true && $fields['x_response_code'] == 1) {
         $paynum = $fields['x_subscription_paynum'];
         $subscription_id = $fields['x_subscription_id'];
         $amount = $fields['x_amount'];
         $invoice_id = wpi_post_id_to_invoice_id(wpi_subscription_id_to_post_id($subscription_id));
         $invoice_obj = new WPI_Invoice();
         $invoice_obj->load_invoice("id={$invoice_id}");
         // Add payment amount
         $event_note = WPI_Functions::currency_format(abs($amount), $invoice_id) . ". ARB payment {$paynum} of {$invoice_obj->data['recurring']['wpi_authorize']['cycles']}";
         $event_amount = $amount;
         $event_type = 'add_payment';
         $invoice_obj->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
         // Complete subscription if last payment done
         if ($invoice_obj->data['recurring']['wpi_authorize']['cycles'] <= $paynum) {
             WPI_Functions::log_event(wpi_invoice_id_to_post_id($invoice_id), 'invoice', 'update', '', __('Subscription completely paid', WPI));
             wp_invoice_mark_as_paid($invoice_id);
         }
         $invoice_obj->save_invoice();
     }
 }
 <?php echo WPI_UI::input("name=wpi[new_invoice][invoice_id]&value=".rand(10000000, 90000000)."&type=hidden"); ?>
 <table class="form-table" id="get_user_info">
   <tr class="invoice_main">
     <th><label for="wp_invoice_userlookup"><?php _e('E-mail Address:', WPI); ?></label></th>
     <td>
       <?php WPI_UI::draw_user_auto_complete_field(); ?>
       <input type="submit" class="button" id="wp_invoice_create_new_invoice" value="<?php esc_attr(_e('Create New', WPI)); ?>">
       <?php if($wpi_settings['total_invoice_count']) { ?>
         <span id="wp_invoice_copy_invoice" class="wp_invoice_click_me">copy from another</span><br />
         <div class="wp_invoice_copy_invoice">
           <?php $all_invoices = $wpdb->get_results("SELECT ID FROM ".$wpdb->posts." WHERE post_type = 'wpi_object' AND post_title != ''"); ?>
             <select name="wpi[new_invoice][template_copy]">
             <option><?php _e('-- Select Invoice --', WPI) ?></option>
             <?php foreach ($all_invoices as $invoice) {
                     $invoice_id = wpi_post_id_to_invoice_id($invoice->ID);
                     $invoice_obj = new WPI_Invoice();
                     $invoice_obj->load_invoice("id=".$invoice_id);
                     //print_r( $invoice_obj );
                     if ( $invoice_obj->data['type'] != 'single_payment' ) :
             ?>
             <option value="<?php echo $invoice_id; ?>">
               <?php 
                 if( $invoice_obj->data['type'] == 'recurring' ) {
               ?> 
               <?php _e('[Recurring]', WPI) ?> 
               <?php } ?> 
               <?php 
                 echo $invoice_obj->data['post_title'] . " - " .$wpi_settings['currency']['symbol'][$invoice_obj->data['default_currency_code']] . wp_invoice_currency_format($invoice_obj->data['subtotal']); 
               ?>
               <?php 
                 if ( !empty( $invoice_obj->data['total_discount'] ) && $invoice_obj->data['total_discount'] > 0 ) {
    /**
     * Handles validation when somebody is attempting to view an invoice.  
     * If validation is passsed, we add the necessary
     * filters to display the invoice header and page content;
     * Global $invoice_id variable set by WPI_Functions::validate_page_hash();
     */
    function template_redirect() {
      global $wpdb, $invoice_id, $wpi_user_id, $wpi_settings, $wpi_invoice_object, $post;
      
      //** Alwys load styles without checking if given page has an invoice */
      wp_enqueue_style('wpi-theme-specific');
      wp_enqueue_style('wpi-default-style');
      
      /* Determine if the current page is invoice's page */
      if ($wpi_settings['web_invoice_page'] != $post->ID) {
        return;
      }
      
      // If invoice_id is passed, run validate_page_hash  to make sure this is the right page and invoice_id exists
      if (isset($_GET['invoice_id'])) {
        
        if (WPI_Functions::validate_page_hash(mysql_escape_string($_GET['invoice_id']))) {
          
          /** load global invoice object */
          $post_id = wpi_invoice_id_to_post_id($invoice_id);
          
          $wpi_invoice_object = new WPI_Invoice();
          $wpi_invoice_object->load_invoice("id=$post_id");
          $wpi_invoice_object->data;
          
          add_filter('viewable_invoice_types', array( $this, 'viewable_types' ));
          
          //* Determine if current invoice object is "viewable" */
          if(!in_array($wpi_invoice_object->data['post_status'], apply_filters('viewable_invoice_types', array('active')))) {
            return;
          }
          
          // Load front end scripts
          wp_enqueue_script('jquery.validate');
          wp_enqueue_script('wpi-gateways');
          wp_enqueue_script('jquery.maskedinput');
          wp_enqueue_script('wpi-frontend-scripts');

          //** Apply Filters to the invoice description */
          add_action('wpi_description', 'wpautop');
          add_action('wpi_description', 'wptexturize');
          add_action('wpi_description', 'shortcode_unautop');
          add_action('wpi_description', 'convert_chars');
          add_action('wpi_description', 'capital_P_dangit');
          
          // Declare the variable that will hold our AJAX url for JavaScript purposes
          wp_localize_script('jquery', 'wpi_ajax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
          
          add_action('wp_head', array('WPI_UI', 'frontend_header'));
          
          if ($wpi_settings['replace_page_title_with_subject'] == 'true' || $wpi_settings['hide_page_title'] == 'true') {
            add_action('wp_title', array('WPI_UI', 'wp_title'), 0, 3);
          }
          
          if ($wpi_settings['replace_page_heading_with_subject'] == 'true' || $wpi_settings['hide_page_title'] == 'true') {
            add_action('the_title', array('WPI_UI', 'the_title'), 0, 2);
          }
          
          add_action('the_content', array('WPI_UI', 'the_content'));
          
          if ( $wpi_settings['where_to_display'] == 'replace_tag' ) {
            add_shortcode('wp-invoice', array('WPI_UI', 'the_content_shortcode'));
          }
        
        } else {
          /* Show 404 when invoice doesn't exist */
          $not_found = get_query_template('404');
          require_once $not_found;
          die();
        }
        
      }
      
      // Fixed WordPress filters if page is being opened in HTTPS mode
      if (isset($_SERVER['HTTPS']) && $_SERVER["HTTPS"] == "on") {
        if(function_exists('force_ssl')) {
          add_filter('option_siteurl', 'force_ssl');
          add_filter('option_home', 'force_ssl');
          add_filter('option_url', 'force_ssl');
          add_filter('option_wpurl', 'force_ssl');
          add_filter('option_stylesheet_url', 'force_ssl');
          add_filter('option_template_url', 'force_ssl');
          add_filter('script_loader_src', 'force_ssl');
        }
      }
      
      // Lookup functionality
      if(isset($_POST['wp_invoice_lookup_input'])) {
        header("location:" . get_invoice_permalink($_POST['wp_invoice_lookup_input']));
        //exit;
      }
    }
  /**
   * Revalidate all the invoices
   *
   * @author korotkov@ud
   * @global object $wpdb
   */
  function total_revalidate() {
    global $wpdb;

    /** Recalculate all invoices */
    $invoices = $wpdb->get_col("
      SELECT ID
      FROM {$wpdb->posts}
      WHERE post_type = 'wpi_object'
    ");

    foreach ($invoices as $post_id) {
      $invoice_id = wpi_post_id_to_invoice_id($post_id);
      $this_invoice = new WPI_Invoice();
      $this_invoice->load_invoice("id={$invoice_id}");
      $this_invoice->save_invoice();
    }
  }
예제 #12
0
 /**
  * Handle Bulk Action's request
  *
  */
 public function process_bulk_action()
 {
     $action = $this->current_action();
     $status = false;
     //** Set status */
     switch ($action) {
         case 'trash':
             $status = 'trashed';
             break;
         case 'delete':
             $status = 'deleted';
             break;
         case 'untrash':
             $status = 'restored';
             break;
         case 'unarchive':
             $status = 'un-archived';
             break;
         case 'archive':
             $status = 'archived';
             break;
     }
     $invoice_ids = array();
     if (!empty($_REQUEST['post_ids'])) {
         foreach ((array) $_REQUEST['post_ids'] as $ID) {
             $this_invoice = new WPI_Invoice();
             $this_invoice->load_invoice("id={$ID}");
             $invoice_id = $this_invoice->data['invoice_id'];
             switch ($action) {
                 case 'trash':
                     if ($this_invoice->trash()) {
                         $invoice_ids[] = $invoice_id;
                     }
                     break;
                 case 'delete':
                     if ($this_invoice->delete()) {
                         $invoice_ids[] = $invoice_id;
                     }
                     break;
                 case 'untrash':
                     if ($this_invoice->untrash()) {
                         $invoice_ids[] = $invoice_id;
                     }
                     break;
                 case 'unarchive':
                     if ($this_invoice->unarchive()) {
                         $invoice_ids[] = $invoice_id;
                     }
                     break;
                 case 'archive':
                     if ($this_invoice->archive()) {
                         $invoice_ids[] = $invoice_id;
                     }
                     break;
             }
         }
     }
     if ($status) {
         $this->message = 'Successfully ' . $status;
     }
 }
예제 #13
0
 /**
  * Handler for 2Checkout Callback
  * @author Craig Christenson
  * Full callback URL: http://domain/wp-admin/admin-ajax.php?action=wpi_gateway_server_callback&type=wpi_twocheckout
  */
 static function server_callback()
 {
     if (empty($_REQUEST)) {
         die(__('Direct access not allowed', WPI));
     }
     $invoice = new WPI_Invoice();
     $invoice->load_invoice("id={$_REQUEST['merchant_order_id']}");
     /** Verify callback request */
     if (self::_ipn_verified($invoice)) {
         if ($_REQUEST['key']) {
             $event_note = sprintf(__('%s paid via 2Checkout', WPI), WPI_Functions::currency_format(abs($_REQUEST['total']), $_REQUEST['merchant_order_id']));
             $event_amount = (double) $_REQUEST['total'];
             $event_type = 'add_payment';
             /** Log balance changes */
             $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
             /** Log payer email */
             $payer_email = sprintf(__("2Checkout buyer email: %s", WPI), $_REQUEST['email']);
             $invoice->add_entry("attribute=invoice&note={$payer_email}&type=update");
             $invoice->save_invoice();
             /** ... and mark invoice as paid */
             wp_invoice_mark_as_paid($_REQUEST['invoice_id'], $check = true);
             send_notification($invoice->data);
             echo '<script type="text/javascript">window.location="' . get_invoice_permalink($invoice->data['ID']) . '";</script>';
             /** Handle INS messages */
         } elseif ($_POST['md5_hash']) {
             switch ($_POST['message_type']) {
                 case 'FRAUD_STATUS_CHANGED':
                     if ($_POST['fraud_status'] == 'pass') {
                         WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Passed 2Checkout fraud review.', WPI));
                     } elseif (condition) {
                         WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Failed 2Checkout fraud review.', WPI));
                         wp_invoice_mark_as_pending($_POST['vendor_order_id']);
                     }
                     break;
                 case 'RECURRING_STOPPED':
                     WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Recurring billing stopped.', WPI));
                     break;
                 case 'RECURRING_INSTALLMENT_FAILED':
                     WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Recurring installment failed.', WPI));
                     break;
                 case 'RECURRING_INSTALLMENT_SUCCESS':
                     $event_note = sprintf(__('%1s paid for subscription %2s', WPI), WPI_Functions::currency_format(abs($_POST['item_rec_list_amount_1']), $_POST['vendor_order_id']), $_POST['sale_id']);
                     $event_amount = (double) $_POST['item_rec_list_amount_1'];
                     $event_type = 'add_payment';
                     $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                     $invoice->save_invoice();
                     send_notification($invoice->data);
                     break;
                 case 'RECURRING_COMPLETE':
                     WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Recurring installments completed.', WPI));
                     wp_invoice_mark_as_paid($_POST['invoice'], $check = false);
                     break;
                 case 'RECURRING_RESTARTED':
                     WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Recurring sale restarted.', WPI));
                     break;
                 default:
                     break;
             }
         }
     }
 }
 /**
  * Generate HTML for a single row on the users.php admin panel.
  *
  */
 function single_row( $object ) {
   global $wpi_settings, $post;
   
   $object = (array) $object;
   
   $post = new WPI_Invoice();
   $post->load_invoice("id={$object['ID']}");
   $post = (object)$post->data;
   
   $post_owner = ( get_current_user_id() == $post->post_author ? 'self' : 'other' );
   $edit_link = admin_url("admin.php?page=wpi_page_manage_invoice&wpi[existing_invoice][invoice_id]={$post->ID}");
   $title = _draft_or_post_title($post->ID);
   $post_type_object = get_post_type_object( $post->post_type );
   $can_edit_post = current_user_can( $post_type_object->cap->edit_post, $post->ID );
   
   $result = "<tr id='object-{$object['ID']}' class='wpi_parent_element'>";
   
   list( $columns, $hidden ) = $this->get_column_info();
   
   foreach ( $columns as $column => $column_display_name ) {
     $class = "class=\"$column column-$column\"";
     $style = '';
     
     if ( in_array( $column, $hidden ) ) {
       $style = ' style="display:none;"';
     }
     
     $attributes = "$class$style";
     
     $result .= "<td {$attributes}>";
     
     $r = "";
     switch($column) {
     
       case 'cb':
         if ( $can_edit_post ) {
           $r .= '<input type="checkbox" name="post[]" value="'. get_the_ID() . '"/>';
         } else {
           $r .= '&nbsp;';
         }
       break;
       
       case 'post_title':
         $attributes = 'class="post-title page-title column-title"' . $style;
         if ( $can_edit_post && $post->post_status != 'trash' && $post->post_status != 'archived' ) { 
           $r .= '<a class="row-title" href="' . $edit_link . '" title="' . esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;', WPI ), $title ) ) . '">' . $title . '</a>';
         } else { 
           $r .= $title;
         } 
         $r .= (isset( $parent_name ) ? ' | ' . $post_type_object->labels->parent_item_colon . ' ' . esc_html( $parent_name ) : '');
         
         $actions = array();
         if ( $can_edit_post && 'trash' != $post->post_status && 'archived' != $post->post_status ) {
          $actions['edit'] = '<a href="' . get_edit_post_link( $post->ID, true ) . '" title="' . esc_attr( __( 'Edit this item', WPI ) ) . '">' . __( 'Edit', WPI ) . '</a>';
         }
         
         if ( 'archived' == $post->post_status ) {
           $actions['unarchive'] = '<a href="' . wp_nonce_url( admin_url( sprintf( $post_type_object->_edit_link . '&amp;action=unarchive', $post->ID ) ), 'unarchive-' . $post->post_type . '_' . $post->ID ) . '" title="' . esc_attr( __( 'Un-Archive this item', WPI ) ) . '">' . __( 'Un-Archive', WPI ) . '</a>';
         } else if ( 'trash' != $post->post_status && 'pending' != $post->post_status ) {
           $actions['archive'] = '<a href="' . wp_nonce_url( admin_url( sprintf( $post_type_object->_edit_link . '&amp;action=archive', $post->ID ) ), 'archive-' . $post->post_type . '_' . $post->ID ) . '" title="' . esc_attr( __( 'Archive this item', WPI ) ) . '">' . __( 'Archive', WPI ) . '</a>';
         }
         
         if ( current_user_can( $post_type_object->cap->delete_post, $post->ID ) ) {
           if ( 'trash' == $post->post_status ) {
             $actions['untrash'] = "<a title='" . esc_attr( __( 'Restore this item from the Trash', WPI ) ) . "' href='" . wp_nonce_url( admin_url( sprintf( $post_type_object->_edit_link . '&amp;action=untrash', $post->ID ) ), 'untrash-' . $post->post_type . '_' . $post->ID ) . "'>" . __( 'Restore', WPI ) . "</a>";
           } elseif ( EMPTY_TRASH_DAYS && 'pending' != $post->post_status ) {
             $actions['trash'] = "<a class='submitdelete' title='" . esc_attr( __( 'Move this item to the Trash', WPI ) ) . "' href='" . get_delete_post_link( $post->ID ) . "'>" . __( 'Trash', WPI ) . "</a>";
           }
           
           if ( 'trash' == $post->post_status || !EMPTY_TRASH_DAYS ) {
             $actions['delete'] = "<a class='submitdelete permanently' title='" . esc_attr( __( 'Delete this item permanently', WPI ) ) . "' href='" . get_delete_post_link( $post->ID, '', true ) . "'>" . __( 'Delete Permanently', WPI ) . "</a>";
           }
         }
         
         if ( 'trash' != $post->post_status && 'archived' != $post->post_status ) {
           $actions['view'] = '<a target="_blank" href="' . get_invoice_permalink( $post->invoice_id ) . '" title="' . esc_attr( sprintf( __( 'View &#8220;%s&#8221;', WPI ), $title ) ) . '" rel="permalink">' . __( 'View', WPI ) . '</a>';
         }
         
         $actions = apply_filters( is_post_type_hierarchical( $post->post_type ) ? 'page_row_actions' : 'post_row_actions', $actions, $post );
         $r .= $this->row_actions( $actions );
       break;
       
       case 'post_modified':
         if ( !empty( $post->post_status ) ) {
           if ( $post->post_status == 'paid' ) {
             $r .= get_post_status_object($post->post_status)->label.' '.human_time_diff(strtotime($post->post_modified), (time() + get_option('gmt_offset')*60*60)).' ago';
           } else {
             $r .= human_time_diff(strtotime($post->post_modified), (time() + get_option('gmt_offset')*60*60)).' ago';
           }
         } else {
           $r .= date(get_option('date_format'), strtotime($post->post_date));
         }
       break;
       
       case 'invoice_id':
         $invoice_id = $post->{$column};
         /* If custom_id exists we use it as invoice_id */
         if(!empty($post->custom_id)) {
           $invoice_id = $post->custom_id;
         }
         $r .= '<a href="' . get_invoice_permalink($post->{$column}) . '" target="_blank">'.apply_filters("wpi_attribute_{$column}", $invoice_id ,$post).'</a>';
       break;
       
       case 'post_status':
         $r .= get_post_status_object($post->post_status)->label;
       break;
       
       case 'user_email':
       
         //** Get User Edit Link */
         if(class_exists('WP_CRM_Core')) {
         $edit_user_url = admin_url("admin.php?page=wp_crm_add_new&user_id={$post->user_data['ID']}");
         } else {
         $edit_user_url =  admin_url("user-edit.php?user_id={$post->user_data['ID']}");
         }
         
         $r .= '<ul>';
         $r .= '<li><a href="'.$edit_user_url.'">' . $post->user_data['display_name'] . '</a></li>';
         $r .= '<li>' . $post->user_data['user_email'] . '</li>';
         $r .= '</ul>';
       break;
       
       case 'type':
         $r .= $wpi_settings['types'][$post->type]['label'];
       break;
       
       case 'total':
         if ( !empty( $post->subtotal ) ) {
           if ( $post->type != 'single_payment' ) {
             $r .= (!empty($wpi_settings['currency']['symbol'][$post->default_currency_code])?$wpi_settings['currency']['symbol'][$post->default_currency_code]:'$') . wp_invoice_currency_format( !empty( $post->total_payments )?$post->total_payments:0 )
                   ." <span style='color:#aaaaaa;'>" . __('of', WPI) ." ".
                   (!empty($wpi_settings['currency']['symbol'][$post->default_currency_code])?$wpi_settings['currency']['symbol'][$post->default_currency_code]:'$') . wp_invoice_currency_format($post->subtotal-(!empty($post->total_discount)?$post->total_discount:0)+(!empty($post->total_tax)?$post->total_tax:0))
                   ."</span>";
           } else {
             $r .= (!empty($wpi_settings['currency']['symbol'][$post->default_currency_code])?$wpi_settings['currency']['symbol'][$post->default_currency_code]:'$') . wp_invoice_currency_format( !empty( $post->total_payments )?$post->total_payments:0 );
           }
         } else {
           $r .= (!empty($wpi_settings['currency']['symbol'][$post->default_currency_code])?$wpi_settings['currency']['symbol'][$post->default_currency_code]:'$') . wp_invoice_currency_format(0);
         }
          
       break;
       
       default:
         $r .= apply_filters("wpi_attribute_{$column}", $post->{$column}, $post);
       break;
     }
     
     //** Need to insert some sort of space in there to avoid DataTable error that occures when "null" is returned */
     $ajax_cells[] = $r;
   
     $result .= $r;
     $result .= "</td>";
   }
   
   $result .= '</tr>';
   
   if($this->_args['ajax']) {
     return $ajax_cells;
   }
   
   return $result;
 }
예제 #15
0
 /**
  * Merchant CB handler
  */
 static function server_callback()
 {
     if (empty($_POST)) {
         die(__('Direct access not allowed', WPI));
     }
     $invoice = new WPI_Invoice();
     $invoice->load_invoice("id={$_POST['ik_pm_no']}");
     if ($_POST['ik_inv_st'] != 'success') {
         header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error [Cannot process payment]', true, 500);
         return;
     }
     if (!self::_hash_verified($invoice)) {
         header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error [Hash or Shop ID is wrong]', true, 500);
         return;
     }
     if (get_post_meta($invoice->data['ID'], 'wpi_processed_by_interkassa', 1) == 'true') {
         header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error [Already processed]', true, 500);
         return;
     }
     update_post_meta($invoice->data['ID'], 'wpi_processed_by_interkassa', 'true');
     /** Add payment amount */
     $event_note = sprintf(__('%s paid via InterKassa [%s]', WPI), WPI_Functions::currency_format(abs($_POST['ik_am']), $_POST['ik_pm_no']), $_POST['ik_pw_via']);
     $event_amount = (double) $_POST['ik_am'];
     $event_type = 'add_payment';
     //** Log balance changes */
     $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
     //** Log payer email */
     $trans_id = sprintf(__("Transaction ID: %s", WPI), $_POST['ik_trn_id']);
     $invoice->add_entry("attribute=invoice&note={$trans_id}&type=update");
     $invoice->save_invoice();
     //** ... and mark invoice as paid */
     wp_invoice_mark_as_paid($_POST['ik_pm_no'], $check = true);
     send_notification($invoice->data);
     echo 'OK';
 }
예제 #16
0
 /**
  * Handles validation when somebody is attempting to view an invoice.
  * If validation is passsed, we add the necessary
  * filters to display the invoice header and page content;
  * Global $invoice_id variable set by WPI_Functions::validate_page_hash();
  */
 function template_redirect()
 {
     global $invoice_id, $wpi_settings, $wpi_invoice_object, $post, $current_user;
     //** Alwys load styles without checking if given page has an invoice */
     wp_enqueue_style('wpi-theme-specific');
     wp_enqueue_style('wpi-default-style');
     //** Determine if the current page is invoice's page */
     if (empty($post->ID) || $wpi_settings['web_invoice_page'] != $post->ID) {
         return;
     }
     //** If invoice_id is passed, run validate_page_hash  to make sure this is the right page and invoice_id exists */
     if (isset($_GET['invoice_id'])) {
         if (WPI_Functions::validate_page_hash(esc_sql($_GET['invoice_id']))) {
             //** load global invoice object */
             $post_id = wpi_invoice_id_to_post_id($invoice_id);
             $wpi_invoice_object = new WPI_Invoice();
             $wpi_invoice_object->load_invoice("id={$post_id}");
             add_filter('viewable_invoice_types', array($this, 'viewable_types'));
             //** Determine if current invoice object is "viewable" */
             if (!in_array($wpi_invoice_object->data['post_status'], apply_filters('viewable_invoice_types', array('active')))) {
                 return;
             }
             if (isset($wpi_settings['logged_in_only']) && $wpi_settings['logged_in_only'] == 'true') {
                 if (!current_user_can(WPI_UI::get_capability_by_level($wpi_settings['user_level'])) && !WPI_Functions::user_is_invoice_recipient($wpi_invoice_object)) {
                     //** Show 404 when invoice doesn't exist */
                     $not_found = get_query_template('404');
                     require_once $not_found;
                     die;
                 }
             }
             //** Load front end scripts */
             wp_enqueue_script('jquery.validate');
             wp_enqueue_script('wpi-gateways');
             wp_enqueue_script('jquery.maskedinput');
             wp_enqueue_script('wpi-frontend-scripts');
             if (!empty($wpi_settings['ga_event_tracking']) && $wpi_settings['ga_event_tracking']['enabled'] == 'true') {
                 wp_enqueue_script('wpi-ga-tracking', WPI_URL . "/core/js/wpi.ga.tracking.js", array('jquery'));
             }
             //** Apply Filters to the invoice description */
             add_action('wpi_description', 'wpautop');
             add_action('wpi_description', 'wptexturize');
             add_action('wpi_description', 'shortcode_unautop');
             add_action('wpi_description', 'convert_chars');
             add_action('wpi_description', 'capital_P_dangit');
             //** Declare the variable that will hold our AJAX url for JavaScript purposes */
             wp_localize_script('wpi-gateways', 'wpi_ajax', array('url' => admin_url('admin-ajax.php')));
             add_action('wp_head', array('WPI_UI', 'frontend_header'));
             if ($wpi_settings['replace_page_title_with_subject'] == 'true' || $wpi_settings['hide_page_title'] == 'true') {
                 add_action('wp_title', array('WPI_UI', 'wp_title'), 0, 3);
             }
             if ($wpi_settings['replace_page_heading_with_subject'] == 'true' || $wpi_settings['hide_page_title'] == 'true') {
                 add_action('the_title', array('WPI_UI', 'the_title'), 0, 2);
             }
             add_action('the_content', array('WPI_UI', 'the_content'), 20);
         } else {
             //** Show 404 when invoice doesn't exist */
             $not_found = get_query_template('404');
             require_once $not_found;
             die;
         }
     }
     //** Fixed WordPress filters if page is being opened in HTTPS mode */
     if (isset($_SERVER['HTTPS']) && $_SERVER["HTTPS"] == "on") {
         if (function_exists('force_ssl')) {
             add_filter('option_siteurl', 'force_ssl');
             add_filter('option_home', 'force_ssl');
             add_filter('option_url', 'force_ssl');
             add_filter('option_wpurl', 'force_ssl');
             add_filter('option_stylesheet_url', 'force_ssl');
             add_filter('option_template_url', 'force_ssl');
             add_filter('script_loader_src', 'force_ssl');
         }
     }
     //** Lookup functionality */
     if (isset($_POST['wp_invoice_lookup_input'])) {
         if (!empty($current_user->ID)) {
             $id = get_invoice_id($_POST['wp_invoice_lookup_input']);
             if (empty($id)) {
                 //** Show 404 when invoice doesn't exist */
                 $not_found = get_query_template('404');
                 require_once $not_found;
                 die;
             }
             $invoice = get_invoice($id);
             if (current_user_can('level_10') || $current_user->data->user_email == $invoice['user_email']) {
                 header("location:" . get_invoice_permalink($_POST['wp_invoice_lookup_input']));
                 die;
             } else {
                 //** Show 404 when invoice doesn't exist */
                 $not_found = get_query_template('404');
                 require_once $not_found;
                 die;
             }
         } else {
             //** Show 404 when invoice doesn't exist */
             $not_found = get_query_template('404');
             require_once $not_found;
             die;
         }
     }
 }
예제 #17
0
 /**
  *
  */
 static function server_callback()
 {
     global $wpdb;
     //** Get request body */
     $body = @file_get_contents('php://input');
     $event_object = json_decode($body);
     switch ($event_object->type) {
         //** Used only for subscriptions since single payments processed without Webhook */
         case 'charge.succeeded':
             $post_id = $wpdb->get_col("SELECT post_id\r\n          FROM {$wpdb->postmeta}\r\n          WHERE meta_key = '_stripe_customer_id'\r\n            AND meta_value = '{$event_object->data->object->customer}'");
             $invoice_object = new WPI_Invoice();
             $invoice_object->load_invoice("id=" . $post_id[0]);
             if (empty($invoice_object->data['ID'])) {
                 die("Can't load invoice");
             }
             if (!class_exists('Stripe')) {
                 require_once WPI_Path . '/third-party/stripe/lib/Stripe.php';
             }
             $pk = trim($invoice_object->data['billing']['wpi_stripe']['settings'][$invoice_object->data['billing']['wpi_stripe']['settings']['mode']['value'] . '_secret_key']['value']);
             Stripe::setApiKey($pk);
             $event = Stripe_Event::retrieve($event_object->id);
             if ($event->data->object->paid == 1) {
                 $event_amount = (double) ($event->data->object->amount / 100);
                 $event_note = WPI_Functions::currency_format(abs($event_amount), $invoice_object->data['invoice_id']) . ' ' . __('Stripe Subscription Payment', WPI);
                 $event_type = 'add_payment';
                 $invoice_object->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                 $invoice_object->save_invoice();
             }
             break;
         case 'customer.subscription.deleted':
             $post_id = $wpdb->get_col("SELECT post_id\r\n          FROM {$wpdb->postmeta}\r\n          WHERE meta_key = '_stripe_customer_id'\r\n            AND meta_value = '{$event_object->data->object->customer}'");
             $invoice_object = new WPI_Invoice();
             $invoice_object->load_invoice("id=" . $post_id[0]);
             if (empty($invoice_object->data['ID'])) {
                 die("Can't load invoice");
             }
             if (!class_exists('Stripe')) {
                 require_once WPI_Path . '/third-party/stripe/lib/Stripe.php';
             }
             $pk = trim($invoice_object->data['billing']['wpi_stripe']['settings'][$invoice_object->data['billing']['wpi_stripe']['settings']['mode']['value'] . '_secret_key']['value']);
             Stripe::setApiKey($pk);
             $event = Stripe_Event::retrieve($event_object->id);
             if ($event->data->object->status == 'canceled') {
                 $invoice_object->add_entry("attribute=invoice&note=" . __('Stripe Subscription has been canceled', WPI) . "&type=update");
                 $invoice_object->save_invoice();
                 wp_invoice_mark_as_paid($invoice_object->data['invoice_id']);
             }
             break;
         default:
             break;
     }
 }
 /**
  * This function prints out our invoice data for debugging purposes
  * @since 3.0
 */
 function debug_get_invoice(){
   global $wpi_settings;
   if(!isset($_REQUEST['invoice_id'])) die(__("Please enter an invoice id.", WPI));
   $this_invoice = new WPI_Invoice();
   $this_invoice->load_invoice("id=".$_REQUEST['invoice_id']);
   echo WPI_Functions::pretty_print_r($this_invoice->data);
   die();
 }
예제 #19
0
 /**
  * Update invoice by ID
  *
  * @global Array $wpi_settings
  *
  * @param Array $args
  *
  * @return WP_Error|WPI_Invoice
  */
 function update_invoice($args = array())
 {
     global $wpi_settings;
     //** Default arguments */
     $defaults = array('ID' => false, 'subject' => false, 'description' => false, 'type' => false, 'deposit' => false, 'due_date' => false, 'tax' => false, 'tax_method' => false, 'recurring' => false, 'discount' => false, 'items' => array(), 'charges' => array());
     //** Parse arguments */
     extract($args = wp_parse_args($args, $defaults));
     //** Check */
     if (!$ID) {
         return new WP_Error('wp.invoice', __('Argument "ID" is required.', WPI), $args);
     }
     //** New Invoice object */
     $invoice = new WPI_Invoice();
     //** Load invoice by ID */
     $invoice->load_invoice(array('id' => $ID));
     $set = array();
     //** Subject */
     if ($subject) {
         $subject = trim($subject);
         if (!empty($subject)) {
             $set['subject'] = $subject;
             $set['post_title'] = $subject;
         }
     }
     //** Description */
     if ($description) {
         $description = trim($description);
         if (!empty($description)) {
             $set['description'] = $description;
         }
     }
     if ($type) {
         //** If type is registered */
         if (!array_key_exists($type, $wpi_settings['types'])) {
             return new WP_Error('wp.invoice', __('Unknown invoice type.', WPI), $args);
         }
         //** If recurring */
         if ($type == 'recurring') {
             $recurring = array_filter($recurring);
             if (empty($recurring['unit']) || empty($recurring['cycles'])) {
                 return new WP_Error('wp.invoice', __('Method requires correct "recurring" argument if "type" is recurring.', WPI), $args);
             }
             if (!empty($deposit)) {
                 return new WP_Error('wp.invoice', __('Cannot use "deposit" with "recurring" type.', WPI), $args);
             }
         }
         //** If quote */
         if ($type == 'quote') {
             if (!empty($deposit)) {
                 return new WP_Error('wp.invoice', __('Cannot use "deposit" with "quote" type.', WPI), $args);
             }
         }
         $set['type'] = $type;
         //** If quote */
         if ($type == 'quote') {
             $set['status'] = $type;
             $set['is_quote'] = 'true';
         }
         //** Recurring */
         if ($type == 'recurring') {
             $invoice->create_schedule($recurring);
         }
     }
     //** Partial payments */
     if ($deposit) {
         $set['deposit_amount'] = (double) $deposit;
     }
     if ($due_date) {
         $set['due_date_year'] = $due_date['year'];
         $set['due_date_month'] = $due_date['month'];
         $set['due_date_day'] = $due_date['day'];
     }
     if ($tax) {
         $set['tax'] = $tax;
     }
     if ($tax_method) {
         if ($tax_method != 'before_discount' && $tax_method != 'after_discount') {
             return new WP_Error('wp.invoice', __('Unknown "tax_method".', WPI), $args);
         }
         $set['tax_method'] = $tax_method;
     }
     if ($discount) {
         if (empty($discount['name'])) {
             return new WP_Error('wp.invoice', __('Discount name is required.', WPI), $args);
         }
         if (empty($discount['type'])) {
             return new WP_Error('wp.invoice', __('Discount type is required. ("amount" or "percent").', WPI), $args);
         }
         if (empty($discount['amount'])) {
             return new WP_Error('wp.invoice', __('Discount amount is required.', WPI), $args);
         }
         $invoice->data['discount'] = array();
         $invoice->add_discount($discount);
     }
     if ($items) {
         //** Items */
         foreach ($items as $item) {
             //** Do not allow to save melformed items */
             if (empty($item['name']) || empty($item['quantity']) || empty($item['price'])) {
                 return new WP_Error('wp.invoice', __('One or more "items" have malformed structure. Cannot create Invoice.', WPI), $args);
             }
             //** Global tax has higher priority */
             if (!empty($tax)) {
                 $item['tax_rate'] = $tax;
             }
             //** Check types */
             if (!is_numeric($item['quantity'])) {
                 return new WP_Error('wp.invoice', __('One or more "items" have wrong "quantity" value. Cannot create Invoice.', WPI), $args);
             }
             if (!is_numeric($item['price'])) {
                 return new WP_Error('wp.invoice', __('One or more "items" have wrong "price" value. Cannot create Invoice.', WPI), $args);
             }
             if (!empty($item['tax_rate'])) {
                 if (!is_numeric($item['tax_rate'])) {
                     return new WP_Error('wp.invoice', __('One or more "items" have wrong "tax_rate" value. Cannot create Invoice.', WPI), $args);
                 }
             }
         }
     }
     if ($charges) {
         //** Charges */
         foreach ($charges as $charge) {
             //** Do not allow to save melformed items */
             if (empty($charge['name']) || empty($charge['amount'])) {
                 return new WP_Error('wp.invoice', __('One or more "charges" have malformed structure. Cannot create Invoice.', WPI), $args);
             }
             //** Global tax has higher priority */
             if (!empty($tax)) {
                 $charge['tax'] = $tax;
             }
             //** Check types */
             if (!is_numeric($charge['amount'])) {
                 return new WP_Error('wp.invoice', __('One or more "charges" have wrong "amount" value. Cannot create Invoice.', WPI), $args);
             }
             if (!empty($charge['tax'])) {
                 if (!is_numeric($charge['tax'])) {
                     return new WP_Error('wp.invoice', __('One or more "charges" have wrong "tax" value. Cannot create Invoice.', WPI), $args);
                 }
             }
         }
     }
     //** If passed validation - save item */
     if ($charges) {
         $invoice->data['itemized_charges'] = array();
         foreach ($charges as $charge) {
             $invoice->line_charge($charge);
         }
     }
     if ($items) {
         $invoice->data['itemized_list'] = array();
         foreach ($items as $item) {
             $invoice->line_item($item);
         }
     }
     $invoice->set($set);
     $invoice->save_invoice();
     $invoice = new WPI_Invoice();
     //** Load invoice by ID */
     $invoice->load_invoice(array('id' => $ID));
     return $invoice;
 }
예제 #20
0
 /**
  * Handles saving and updating
  * Can also handle AJAX save/update function
  *
  * @param type $invoice
  * @param type $args
  *
  * @return boolean
  */
 static function save_invoice($invoice, $args = '')
 {
     //** Set function additional params */
     $defaults = array('type' => 'default');
     extract(wp_parse_args($args, $defaults), EXTR_SKIP);
     if ($type != 'import') {
         if (!wp_verify_nonce($_REQUEST['nonce'], 'wpi-update-invoice')) {
             die('Security check');
         }
     }
     //** Init New Invoice object from passed variables */
     $ni = new WPI_Invoice();
     //** ID */
     $ni->set(array('ID' => $invoice['ID']));
     //** invoice_id */
     $ni->set(array('invoice_id' => $invoice['invoice_id']));
     //** subject */
     $ni->set(array('subject' => $invoice['subject']));
     //** description */
     $ni->set(array('description' => $invoice['description']));
     //** deposit */
     if ($invoice['deposit'] == 'on' || $invoice['deposit'] == 'true') {
         $ni->set(array('deposit_amount' => $invoice['deposit_amount']));
     } else {
         $ni->set(array('deposit_amount' => 0));
     }
     //** Due date */
     $ni->set(array('due_date_year' => $invoice['due_date_year']));
     $ni->set(array('due_date_month' => $invoice['due_date_month']));
     $ni->set(array('due_date_day' => $invoice['due_date_day']));
     //** Currency */
     $ni->set(array('default_currency_code' => $invoice['default_currency_code']));
     //** Terms? */
     if (!empty($invoice['meta']['terms'])) {
         $ni->set(array('terms' => $invoice['meta']['terms']));
     }
     //** Tax */
     $ni->set(array('tax' => $invoice['meta']['tax']));
     //** Custom ID */
     $ni->set(array('custom_id' => $invoice['meta']['custom_id']));
     //** type is 'invoice' by default */
     $invoice_type = 'invoice';
     //** If $invoice object has type definition then use it */
     if (!empty($invoice['type'])) {
         $invoice_type = $invoice['type'];
     }
     //** Save status of invoice (quote or not quote) */
     if (isset($invoice['quote'])) {
         if ($invoice['quote'] == "on") {
             $ni->set(array('status' => 'quote'));
             $ni->set(array('is_quote' => 'true'));
             $invoice_type = 'quote';
         } else {
             $ni->set(array('status' => 'null'));
         }
     }
     //** But if recurring settings are defined then invoice type should be recurring */
     if ($invoice['recurring']['active'] == 'on' && !empty($invoice['recurring'])) {
         $ni->create_schedule($invoice['recurring']);
         $invoice_type = 'recurring';
     }
     //** Finally set invoice type */
     $ni->set(array('type' => $invoice_type));
     //** Set invoice status */
     $status = !empty($invoice['post_status']) ? $invoice['post_status'] : 'active';
     $ni->set(array('post_status' => $status));
     //** Add discounts if exist */
     if (is_array($invoice['meta']['discount'])) {
         foreach ($invoice['meta']['discount'] as $discount) {
             if (!empty($discount['name']) && !empty($discount['amount'])) {
                 $ni->add_discount(array('name' => $discount['name'], 'type' => $discount['type'], 'amount' => $discount['amount']));
             }
         }
     }
     //** Ability to change payment method */
     if (!empty($invoice['client_change_payment_method'])) {
         $ni->set(array('client_change_payment_method' => $invoice['client_change_payment_method']));
     }
     //** Ability to turn off all payment methods and turn on manual that way */
     if (!empty($invoice['use_manual_payment'])) {
         $ni->set(array('use_manual_payment' => $invoice['use_manual_payment']));
     }
     //** Default payment method */
     $ni->set(array('default_payment_method' => $invoice['default_payment_method']));
     //** Tax method */
     $ni->set(array('tax_method' => $invoice['tax_method']));
     //** Manually set billing settings due to the complexity of the hierarchy */
     $ni->data['billing'] = !empty($invoice['billing']) ? $invoice['billing'] : array();
     //** Add line items */
     foreach ($invoice['itemized_list'] as $line_item) {
         $ni->line_item(array('name' => $line_item['name'], 'description' => $line_item['description'], 'quantity' => $line_item['quantity'], 'price' => $line_item['price'], 'tax_rate' => $line_item['tax']));
     }
     //** Add line items for charges */
     if (!empty($invoice['itemized_charges'])) {
         foreach ($invoice['itemized_charges'] as $charge_item) {
             $ni->line_charge(array('name' => $charge_item['name'], 'amount' => $charge_item['amount'], 'tax' => $charge_item['tax']));
         }
     }
     /**
      * Save Invoice Object to DB and update user
      * (trimming is a precaution because it could cause problems in inserted in DB w/ whitespace on end)
      */
     $ni->set(array('user_email' => trim($invoice['user_data']['user_email'])));
     if ($type != 'import') {
         WPI_Functions::update_user($invoice['user_data']);
     }
     $invoice_id = $ni->save_invoice();
     if ($invoice_id) {
         return $invoice_id;
     } else {
         return false;
     }
 }