public function onFooter()
 {
     wp_enqueue_script('wpam_contact_info');
     wp_localize_script('wpam_contact_info', 'currencyL10n', array('fixedLabel' => sprintf(__('Bounty Rate (%s per Sale)', 'wpam'), WPAM_MoneyHelper::getDollarSign()), 'percentLabel' => __('Bounty Rate (% of Sale)', 'wpam'), 'okLabel' => __('OK', 'wpam')));
     $response = new WPAM_Pages_TemplateResponse('widget_form_errors', $this->response->viewData);
     echo $response->render();
 }
 private function executeRequest($method, array $fields)
 {
     $currency = WPAM_MoneyHelper::getCurrencyCode();
     $fields = array_merge($fields, array('USER' => $this->apiUser, 'PWD' => $this->apiPassword, 'VERSION' => '65.0', 'SIGNATURE' => $this->apiSignature, 'METHOD' => $method, 'CURRENCYCODE' => $currency));
     WPAM_Logger::log_debug('PayPal MassPay post data:');
     WPAM_Logger::log_debug_array($fields);
     $postData = http_build_query($fields, NULL, '&');
     $response = $this->executePayPalRequest($postData);
     WPAM_Logger::log_debug('PayPal MassPay response:');
     WPAM_Logger::log_debug_array($response);
     return new WPAM_PayPal_Response($response);
 }
 private function executeRequest($method, array $fields)
 {
     $currency = WPAM_MoneyHelper::getCurrencyCode();
     $fields = array_merge($fields, array('USER' => $this->apiUser, 'PWD' => $this->apiPassword, 'VERSION' => '65.0', 'SIGNATURE' => $this->apiSignature, 'METHOD' => $method, 'CURRENCYCODE' => $currency));
     $uploads_dir = wp_upload_dir();
     if (WPAM_DEBUG) {
         file_put_contents($uploads_dir['basedir'] . '/paypal.txt', print_r($fields, true));
     }
     $postData = http_build_query($fields, NULL, '&');
     $response = $this->executePayPalRequest($postData);
     if (WPAM_DEBUG) {
         file_put_contents($uploads_dir['basedir'] . '/paypal.txt', print_r($response, true), FILE_APPEND);
     }
     return new WPAM_PayPal_Response($response);
 }
 public static function award_commission($args)
 {
     global $wpdb;
     $txn_id = $args['txn_id'];
     $amount = $args['amount'];
     $aff_id = $args['aff_id'];
     $affiliate = '';
     if (isset($aff_id) && is_numeric($aff_id)) {
         //aff_id contains affiliate ID from the new cookie system (wpam_id)
         $query = "SELECT * FROM " . WPAM_AFFILIATES_TBL . " WHERE affiliateId = %d";
         $affiliate = $wpdb->get_row($wpdb->prepare($query, $aff_id));
     } else {
         //TODO start - We only need this code for now to get the affiliate ID for a purchase. Later with the new tracking system it can be deleted
         $query = "\r\n            SELECT a.*\r\n            FROM " . WPAM_TRACKING_TOKENS_PURCHASE_LOGS_TBL . " pl\r\n            INNER JOIN " . WPAM_TRACKING_TOKENS_TBL . " tt ON (tt.trackingTokenId = pl.trackingTokenId)\r\n            INNER JOIN " . WPAM_AFFILIATES_TBL . " a ON (a.affiliateId = tt.sourceAffiliateId)\r\n            WHERE\r\n            pl.purchaseLogId = %s\r\n            ";
         $affiliate = $wpdb->get_row($wpdb->prepare($query, $txn_id));
     }
     //TODO end - later affiliate ID can be tracked directly from the cookie instead of ref_key
     if ($affiliate != null && $affiliate->status == "active") {
         //Filter for overriding the commission from an addon/plugin
         $override = "";
         $override = apply_filters('wpam_commission_tracking_override', $override, $affiliate, $args);
         if (!empty($override)) {
             //commission has been overriden by another addon/plugin
             WPAM_Logger::log_debug('*** Commission for this sale has been overriden by an addon/plugin via filter. ***');
             return;
         }
         $creditAmount = '';
         if ($affiliate->bountyType == 'percent') {
             $creditAmount = $amount * ($affiliate->bountyAmount / 100.0);
         } else {
             if ($affiliate->bountyType == 'fixed') {
                 $creditAmount = $affiliate->bountyAmount;
             }
         }
         $creditAmount = round($creditAmount, 2);
         //checking to see if "do not record zero amount commission" option is enabled
         if (get_option(WPAM_PluginConfig::$AffdoNotRecordZeroAmtCommission) == 1) {
             if ($creditAmount <= 0) {
                 WPAM_Logger::log_debug('The commission amount for this transaction is 0 or less so this will not be recorded.');
                 return;
             }
         }
         $creditAmount = apply_filters('wpam_credit_amount', $creditAmount, $amount, $txn_id);
         $currency = WPAM_MoneyHelper::getCurrencyCode();
         $description = "Credit for sale of {$amount} {$currency} (PURCHASE LOG ID = {$txn_id})";
         $query = "\r\n            SELECT *\r\n            FROM " . WPAM_TRANSACTIONS_TBL . "\r\n            WHERE referenceId = %s    \r\n            ";
         $txn_record = $wpdb->get_row($wpdb->prepare($query, $txn_id));
         if ($txn_record != null) {
             //found a record
             WPAM_Logger::log_debug('Commission for this sale has already been awarded. PURCHASE LOG ID: ' . $txn_id . ', Purchase amount: ' . $amount);
         } else {
             $table = WPAM_TRANSACTIONS_TBL;
             $data = array();
             $data['dateModified'] = date("Y-m-d H:i:s", time());
             $data['dateCreated'] = date("Y-m-d H:i:s", time());
             $data['referenceId'] = $txn_id;
             $data['affiliateId'] = $affiliate->affiliateId;
             $data['type'] = 'credit';
             $data['description'] = $description;
             $data['amount'] = $creditAmount;
             $wpdb->insert($table, $data);
             /*
             if($strRefKey){
                 $db->getEventRepository()->quickInsert( time(), $binConverter->stringToBin( $strRefKey ), 'purchase' );
             }
             */
         }
     }
 }
function wpam_display_manual_commission_tab()
{
    /*
    $data['dateModified'] = date("Y-m-d H:i:s", time());
    $data['dateCreated'] = date("Y-m-d H:i:s", time());
    $data['referenceId'] = $txn_id;
    $data['affiliateId'] = $affiliate->affiliateId;
    $data['type'] = 'credit';
    $data['description'] = $description;
    $data['amount'] = $creditAmount;
    $wpdb->insert( $table, $data);
    */
    if (isset($_POST['wpam_manual_commission_save'])) {
        $nonce = $_REQUEST['_wpnonce'];
        if (!wp_verify_nonce($nonce, 'wpam_manual_commission_save')) {
            wp_die('Error! Nonce Security Check Failed! Go back to the manual commission menu and add a commission again.');
        }
        $error_msg = '';
        $aff_id = trim($_POST["wpam_aff_id"]);
        if (empty($aff_id)) {
            $error_msg .= '<p>' . __('You need to enter an affiliate ID', 'affiliates-manager') . '</p>';
        }
        $commission_amt = trim($_POST["wpam_commission_amt"]);
        if (!is_numeric($commission_amt)) {
            $error_msg .= '<p>' . __('You need to enter a numeric commission amount', 'affiliates-manager') . '</p>';
        }
        $purchase_amt = trim($_POST["wpam_purchase_amt"]);
        if (!is_numeric($purchase_amt)) {
            $error_msg .= '<p>' . __('You need to enter a numeric purchase amount', 'affiliates-manager') . '</p>';
        }
        $txn_id = trim($_POST["wpam_txn_id"]);
        if (empty($txn_id)) {
            $txn_id = uniqid();
        }
        $date_created = trim($_POST["wpam_date_created"]);
        if (empty($date_created)) {
            $date_created = date("Y-m-d");
        }
        $time_created = date("H:i:s");
        $selected_date = $date_created . " " . $time_created;
        $mysql_date_created = date("Y-m-d H:i:s", strtotime($selected_date));
        global $wpdb;
        $table = WPAM_TRANSACTIONS_TBL;
        $query = "\r\n        SELECT *\r\n        FROM " . $table . "\r\n        WHERE referenceId = %s    \r\n        ";
        $txn_record = $wpdb->get_row($wpdb->prepare($query, $txn_id));
        if ($txn_record != null) {
            //found a record
            $error_msg .= '<p>' . __('A commission with this transaction ID already exists', 'affiliates-manager') . '</p>';
        }
        if (empty($error_msg)) {
            //no error in form submission
            $currency = WPAM_MoneyHelper::getCurrencyCode();
            $description = "Credit for sale of {$purchase_amt} {$currency} (PURCHASE LOG ID = {$txn_id})";
            $data = array();
            $data['dateModified'] = $mysql_date_created;
            $data['dateCreated'] = $mysql_date_created;
            $data['referenceId'] = $txn_id;
            $data['affiliateId'] = $aff_id;
            $data['type'] = 'credit';
            $data['description'] = $description;
            $data['amount'] = $commission_amt;
            $wpdb->insert($table, $data);
            echo '<div id="message" class="updated fade"><p><strong>';
            echo __('Commission added!', 'affiliates-manager');
            echo '</strong></p></div>';
        } else {
            echo '<div id="message" class="error fade"><p><strong>';
            echo $error_msg;
            echo '</strong></p></div>';
        }
    }
    ?>
    <p><?php 
    _e('This tab allows you to manually award commission to an affiliate.', 'affiliates-manager');
    ?>
</p>
    <div id="poststuff"><div id="post-body">
            
    <form method="post" action="">
    <?php 
    wp_nonce_field('wpam_manual_commission_save');
    ?>
    <table class="form-table" border="0" cellspacing="0" cellpadding="6" style="max-width:650px;">

    <tr valign="top">
    <th scope="row"><label for="wpam_aff_id"><?php 
    _e('Affiliate ID', 'affiliates-manager');
    ?>
</label></th>
    <td><input name="wpam_aff_id" type="text" id="wpam_aff_id" size="15" value="" class="regular-text">
    <p class="description"><?php 
    _e('Enter the affiliate ID. Example: ', 'affiliates-manager');
    ?>
1</p></td>
    </tr>
    
    <tr valign="top">
    <th scope="row"><label for="wpam_commission_amt"><?php 
    _e('Commission Amount', 'affiliates-manager');
    ?>
</label></th>
    <td><input name="wpam_commission_amt" type="text" id="wpam_commission_amt" size="15" value="" class="regular-text">
    <p class="description"><?php 
    _e('Enter the commission amount. Example: ', 'affiliates-manager');
    ?>
5.00</p></td>
    </tr>
    
    <tr valign="top">
    <th scope="row"><label for="wpam_purchase_amt"><?php 
    _e('Purchase Amount', 'affiliates-manager');
    ?>
</label></th>
    <td><input name="wpam_purchase_amt" type="text" id="wpam_purchase_amt" size="15" value="" class="regular-text">
    <p class="description"><?php 
    _e('Enter the purchase amount. Example: ', 'affiliates-manager');
    ?>
15.00</p></td>
    </tr>
    
    <tr valign="top">
    <th scope="row"><label for="wpam_txn_id"><?php 
    _e('Transaction ID', 'affiliates-manager');
    ?>
</label></th>
    <td><input name="wpam_txn_id" type="text" id="wpam_txn_id" size="15" value="" class="regular-text">
    <p class="description"><?php 
    _e('Enter the unique transaction ID (leave empty to generate a unique ID). Example: ', 'affiliates-manager');
    ?>
1423</p></td>
    </tr>
    
    <tr valign="top">
    <th scope="row"><label for="wpam_date_created"><?php 
    _e('Date', 'affiliates-manager');
    ?>
</label></th>
    <td><input name="wpam_date_created" type="text" id="wpam_date_created" size="15" value="<?php 
    echo date("Y-m-d");
    ?>
" class="regular-text">
    <p class="description"><?php 
    _e('Enter the date in yyyy-mm-dd format. Example: ', 'affiliates-manager');
    ?>
2015-09-17</p></td>
    </tr>

    <td width="25%" align="left">
    <div class="submit">
        <input type="submit" name="wpam_manual_commission_save" class="button-primary" value="Save &raquo;" />
    </div>                
    </td> 

    </tr>

    </table>

    </form>
            
    </div></div>
    <script>
    jQuery(function($) {
        $( "#wpam_date_created" ).datepicker({
            dateFormat: 'yy-mm-dd'
        });
    });
    </script>
    <?php 
}
			<td>
				<label for="ddBountyType"><?php 
        _e('Bounty Type *', 'wpam');
        ?>
</label>
			</td>
			<td>
				<select id="ddBountyType" name="ddBountyType">
		<?php 
        $select = array('percent' => __('Percentage of Sales', 'wpam'), 'fixed' => __('Fixed Amount per Sale', 'wpam'));
        $selected = isset($this->viewData['bountyType']) ? $this->viewData['bountyType'] : NULL;
        foreach ($select as $value => $name) {
            $selected_html = $value == $selected ? ' selected="selected"' : '';
            echo "<option value='{$value}'{$selected_html}>{$name}</option>\n";
        }
        $currency = WPAM_MoneyHelper::getDollarSign();
        $label = isset($this->viewData['bountyType']) && $this->viewData['bountyType'] == 'fixed' ? sprintf(__('Bounty Rate (%s per Sale) *', 'wpam'), $currency) : __('Bounty Rate (% of Sale) *', 'wpam');
        $bountyAmount = isset($this->viewData['bountyAmount']) ? $this->viewData['bountyAmount'] : '';
        ?>
				</select>
			</td>
		</tr>
		<tr>
			<td><label id='lblBountyAmount' for='txtBountyAmount'><?php 
        echo $label;
        ?>
</label></td>
			<td><input type='text' id='txtBountyAmount' name='txtBountyAmount' size='5' value='<?php 
        echo $bountyAmount;
        ?>
'/></td>
?>
" style="display: none">
	<table>
		<tbody>
		<tr>
			<td width="150" style="vertical-align:top"><label for="txtAdjustmentAmount"><?php 
_e('Payout Amount ', 'affiliates-manager');
?>
</label></td>
			<td>
				<input name="payoutAmountType" type="radio" id="rbPayoutCurrentBalance" value="currentBalance" checked="checked" />
				<label for="rbPayoutCurrentBalance"><?php 
_e('Current balance', 'affiliates-manager');
?>
 (<?php 
echo WPAM_MoneyHelper::getDollarSign(), $this->viewData['accountStanding'];
?>
)</label><br />

				<input name="payoutAmountType" type="radio" id="rbPayoutOtherAmount" value="otherAmount">
				<label for="rbPayoutOtherAmount"><?php 
_e('Other amount', 'affiliates-manager');
?>
</label><br>
				<input type="text" id="txtPayoutAmount" name="txtPayoutAmount" size="10" style="display: none;" value="<?php 
echo sprintf("%01.2f", $this->viewData['accountStanding']);
?>
"/>
			</td>
		</tr>
		</tbody>
    public function showAdminMessages()
    {
        if (empty($this->setloc)) {
            //don't bother showing this warning if they were trying to use 'en_US'
            if ($this->locale == 'en_US') {
                return;
            }
            $code = WPAM_MoneyHelper::getCurrencyCode();
            $currency = WPAM_MoneyHelper::getDollarSign();
            echo '<div id="message" class="error">
			<p><strong>' . sprintf(__('WP Affiliate Manager was unable to load your currency from your WPLANG setting: %s', 'wpam'), $this->locale) . '<br/>' . sprintf(__('Your currency will be displayed as %s and PayPal payments will be paid in %s', 'wpam'), $currency, $code) . '</strong></p></div>';
            if (WPAM_DEBUG) {
                echo "<!-- LC_MONETARY {$this->locale}, isset: ", var_export($this->setloc, true), PHP_EOL, var_export(localeconv(), true), ' -->';
            }
        }
    }
 public function handleCheckoutWithRefKey($purchaseLogId, $purchaseAmount, $strRefKey)
 {
     $db = new WPAM_Data_DataAccess();
     $binConverter = new WPAM_Util_BinConverter();
     $affiliate = NULL;
     // keeping this block and "($affiliate !== NULL)" seperate to
     // help indicate any problems
     // (purchase log recorded w/o a purchase event)
     if (!empty($strRefKey)) {
         $trackingToken = $db->getTrackingTokenRepository()->loadBy(array('trackingKey' => $strRefKey));
         if ($trackingToken !== NULL) {
             $ttpl = $db->getTrackingTokenPurchaseLogRepository()->loadBy(array('trackingTokenId' => $trackingToken->trackingTokenId, 'purchaseLogId' => $purchaseLogId));
             if ($ttpl === NULL) {
                 $trackingTokenPurchaseLog = new WPAM_Data_Models_TrackingTokenPurchaseLogModel();
                 $trackingTokenPurchaseLog->trackingTokenId = $trackingToken->trackingTokenId;
                 $trackingTokenPurchaseLog->purchaseLogId = $purchaseLogId;
                 $db->getTrackingTokenPurchaseLogRepository()->insert($trackingTokenPurchaseLog);
                 //this will be handled further down if the affiliate is set and the purchase was successful
                 //$db->getEventRepository()->quickInsert(time(), $strRefKey, 'purchase');
             }
         }
     }
     $affiliate = $db->getAffiliateRepository()->loadByPurchaseLogId($purchaseLogId);
     if ($affiliate !== NULL && $affiliate->isActive()) {
         if ($strRefKey) {
             $db->getEventRepository()->quickInsert(time(), $binConverter->stringToBin($strRefKey), 'purchase');
         }
         $creditAmount = $this->calculateCreditAmount($affiliate, $purchaseAmount);
         $creditAmount = apply_filters('wpam_credit_amount', $creditAmount, $purchaseAmount, $purchaseLogId);
         $currency = WPAM_MoneyHelper::getCurrencyCode();
         $description = "Credit for sale of {$purchaseAmount} {$currency} (PURCHASE LOG ID = {$purchaseLogId})";
         $existingCredit = $db->getTransactionRepository()->loadBy(array('referenceId' => $purchaseLogId));
         if ($existingCredit === NULL) {
             $credit = new WPAM_Data_Models_TransactionModel();
             $credit->dateCreated = time();
             $credit->referenceId = $purchaseLogId;
             $credit->affiliateId = $affiliate->affiliateId;
             $credit->type = 'credit';
             $credit->description = $description;
             $credit->amount = $creditAmount;
             $db->getTransactionRepository()->insert($credit);
         } else {
             $existingCredit->dateModified = time();
             $existingCredit->description = $description;
             $existingCredit->amount = $creditAmount;
             $db->getTransactionRepository()->update($existingCredit);
         }
     }
 }