';
}
public function wpspcAddCustomValue($custom_field_val) {
if (isset($_COOKIE['wpam_id'])) {
$name = 'wpam_tracking';
$value = $_COOKIE['wpam_id'];
$new_val = $name . '=' . $value;
$custom_field_val = $custom_field_val . '&' . $new_val;
WPAM_Logger::log_debug('Simple WP Cart Integration - Adding custom field value. New value: ' . $custom_field_val);
} else if (isset($_COOKIE[WPAM_PluginConfig::$RefKey])) {
$name = 'wpam_tracking';
$value = $_COOKIE[WPAM_PluginConfig::$RefKey];
$new_val = $name . '=' . $value;
$custom_field_val = $custom_field_val . '&' . $new_val;
WPAM_Logger::log_debug('Simple WP Cart Integration - Adding custom field value. New value: ' . $custom_field_val);
}
return $custom_field_val;
}
public function wpspcProcessTransaction($ipn_data) {
$custom_data = $ipn_data['custom'];
WPAM_Logger::log_debug('Simple WP Cart Integration - IPN processed hook fired. Custom field value: ' . $custom_data);
$custom_values = array();
parse_str($custom_data, $custom_values);
if (isset($custom_values['wpam_tracking']) && !empty($custom_values['wpam_tracking'])) {
$tracking_value = $custom_values['wpam_tracking'];
WPAM_Logger::log_debug('Simple WP Cart Integration - Tracking data present. Need to track affiliate commission. Tracking value: ' . $tracking_value);
$purchaseLogId = $ipn_data['txn_id'];
$purchaseAmount = $ipn_data['mc_gross']; //TODO - later calculate sub-total only
$buyer_email = $ipn_data['payer_email'];
$strRefKey = $tracking_value;
$requestTracker = new WPAM_Tracking_RequestTracker();
$requestTracker->handleCheckoutWithRefKey($purchaseLogId, $purchaseAmount, $strRefKey, $buyer_email);
WPAM_Logger::log_debug('Simple WP Cart Integration - Commission tracked for transaction ID: ' . $purchaseLogId . ', Purchase amt: ' . $purchaseAmount . ', Buyer Email: ' . $buyer_email);
}
}
public function onWpscCheckout(array $purchaseInfo) {
if ($purchaseInfo['purchase_log']['processed'] >= 2) {
$purchaseAmount = $purchaseInfo['purchase_log']['totalprice'] - $purchaseInfo['purchase_log']['base_shipping'];
$purchaseLogId = $purchaseInfo['purchase_log']['id'];
$buyer_email = wpsc_get_buyers_email($purchaseLogId);
$requestTracker = new WPAM_Tracking_RequestTracker();
$requestTracker->handleCheckout($purchaseLogId, $purchaseAmount, $buyer_email);
}
}
public function WooCheckoutUpdateOrderMeta($order_id, $posted) {
$wpam_refkey = "";
if (isset($_COOKIE['wpam_id'])) {
$wpam_refkey = $_COOKIE['wpam_id'];
} else if (isset($_COOKIE[WPAM_PluginConfig::$RefKey])) { //remove this block when we don't expect wpam_refkey cookie anymore
$wpam_refkey = $_COOKIE[WPAM_PluginConfig::$RefKey];
}
if (!empty($wpam_refkey)) {//Save the wpam_refkey in the order meta
if (is_numeric($wpam_refkey)) { //wpam_id cookie is found and contains affiliate ID.
update_post_meta($order_id, '_wpam_id', $wpam_refkey);
$wpam_refkey = get_post_meta($order_id, '_wpam_id', true);
WPAM_Logger::log_debug("WooCommerce Integration - Saving wpam_id (" . $wpam_refkey . ") with order. Order ID: " . $order_id);
} else { //remove this block when we don't expect wpam_refkey cookie anymore
update_post_meta($order_id, '_wpam_refkey', $wpam_refkey);
$wpam_refkey = get_post_meta($order_id, '_wpam_refkey', true);
WPAM_Logger::log_debug("WooCommerce Integration - Saving wpam_refkey (" . $wpam_refkey . ") with order. Order ID: " . $order_id);
}
}
}
public function WooCommerceProcessTransaction($order_id) {
//affiliates manager code
WPAM_Logger::log_debug('WooCommerce Integration - Order processed. Order ID: ' . $order_id);
if (wpam_has_purchase_record($order_id)) {
WPAM_Logger::log_debug('WooCommerce Integration - Affiliate commission for this transaction was awarded once. No need to process anything.');
return;
}
WPAM_Logger::log_debug('WooCommerce Integration - Checking if affiliate commission needs to be awarded.');
$order = new WC_Order($order_id);
if (in_array('_subscription_switch_data', get_post_custom_keys($order_id))) {
WPAM_Logger::log_debug("WooCommerce Integration - This is a subscription payment order since the _subscription_switch_data meta is set.", 2);
WPAM_Logger::log_debug("The commission will be calculated via the recurring payemnt api call.", 2);
return;
}
$recurring_payment_method = get_post_meta($order_id, '_recurring_payment_method', true);
if (!empty($recurring_payment_method)) {
WPAM_Logger::log_debug("WooCommerce Integration - This is a recurring payment order. Subscription payment method: " . $recurring_payment_method, 2);
WPAM_Logger::log_debug("The commission will be calculated via the recurring payemnt api call.", 2);
return;
}
$subscription_renewal = get_post_meta($order_id, '_subscription_renewal', true);
if (!empty($subscription_renewal)) {
WPAM_Logger::log_debug("WooCommerce Integration - This is a subscription payment order since the subscription_renewal meta is set.", 2);
WPAM_Logger::log_debug("The commission will be calculated via the recurring payment api call.", 2);
return;
}
$post = get_post($order_id);
$post_name = $post->post_name;
WPAM_Logger::log_debug("WooCommerce Integration - Order CPT name: " . $post_name);
if (stripos($post_name, 'subscription') !== false) {
//This is an order for subscription. The recurring payment api hook will handle it .
WPAM_Logger::log_debug("WooCommerce Integration - This is a recurring payment order. The commission will be calculated via the recurring payemnt api call.", 2);
return;
}
$order_status = $order->get_status();
WPAM_Logger::log_debug("WooCommerce Integration - Order status: " . $order_status);
if (strtolower($order_status) != "completed" && strtolower($order_status) != "processing") {
WPAM_Logger::log_debug("WooCommerce Integration - Order status for this transaction is not in a 'completed' or 'processing' state. Commission will not be awarded at this stage.", 2);
WPAM_Logger::log_debug("WooCommerce Integration - Commission for this transaction will be awarded when you set the order status to completed or processing.", 2);
return;
}
$total = $order->get_total();
$shipping = $order->get_total_shipping();
$tax = $order->get_total_tax();
$fees = wpam_get_total_woocommerce_order_fees($order);
WPAM_Logger::log_debug('WooCommerce Integration - Total amount: ' . $total . ', Total shipping: ' . $shipping . ', Total tax: ' . $tax . ', Fees: '. $fees);
$purchaseAmount = $total - $shipping - $tax - $fees;
$buyer_email = $order->get_billing_email();
$wpam_refkey = get_post_meta($order_id, '_wpam_refkey', true);
$wpam_id = get_post_meta($order_id, '_wpam_id', true);
if (!empty($wpam_id)) {
$wpam_refkey = $wpam_id;
}
$wpam_refkey = apply_filters('wpam_woo_override_refkey', $wpam_refkey, $order);
if (empty($wpam_refkey)) {
WPAM_Logger::log_debug("WooCommerce Integration - could not get wpam_id/wpam_refkey from cookie. This is not an affiliate sale", 4);
return;
}
$requestTracker = new WPAM_Tracking_RequestTracker();
WPAM_Logger::log_debug('WooCommerce Integration - awarding commission for order ID: ' . $order_id . ', Purchase amount: ' . $purchaseAmount . ', Affiliate ID: ' . $wpam_refkey . ', Buyer Email: ' . $buyer_email);
$requestTracker->handleCheckoutWithRefKey($order_id, $purchaseAmount, $wpam_refkey, $buyer_email);
}
public function WooCommerceRefundTransaction($order_id) {
WPAM_Logger::log_debug('WooCommerce integration - order refunded. Order ID: ' . $order_id);
//$order = new WC_Order($order_id);
$txn_id = $order_id;
WPAM_Commission_Tracking::refund_commission($txn_id);
}
public function jigoshopNewOrder($order_id) {
$order = new jigoshop_order($order_id);
$total = floatval($order->order_subtotal);
if ($order->order_discount) {
$total = $total - floatval($order->order_discount);
}
if ($total < 0) {
$total = 0;
}
$buyer_email = '';
WPAM_Logger::log_debug('JigoShop Integration - new order received. Order ID: ' . order_id . '. Purchase amt: ' . $total);
$requestTracker = new WPAM_Tracking_RequestTracker();
$requestTracker->handleCheckout($order_id, $total, $buyer_email);
}
public function edd_store_custom_fields($payment_meta) {
WPAM_Logger::log_debug('Easy Digital Downlaods Integration - payment_meta filter triggered');
if (isset($_COOKIE['wpam_id'])) {
$strRefKey = $_COOKIE['wpam_id'];
$payment_meta['wpam_refkey'] = $strRefKey;
WPAM_Logger::log_debug('Easy Digital Downlaods Integration - refkey: ' . $strRefKey);
} else if (isset($_COOKIE[WPAM_PluginConfig::$RefKey])) {
$strRefKey = $_COOKIE[WPAM_PluginConfig::$RefKey];
$payment_meta['wpam_refkey'] = $strRefKey;
WPAM_Logger::log_debug('Easy Digital Downlaods Integration - refkey: ' . $strRefKey);
}
return $payment_meta;
}
public function edd_on_complete_purchase($payment_id) {
WPAM_Logger::log_debug('Easy Digital Downlaods Integration - complete purchase hook triggered for Order ID: ' . $payment_id . '. Checking if affiliate commission needs to be awarded.');
$payment_meta = edd_get_payment_meta($payment_id);
$strRefKey = "";
if (isset($payment_meta['wpam_refkey']) && !empty($payment_meta['wpam_refkey'])) {
$strRefKey = $payment_meta['wpam_refkey'];
WPAM_Logger::log_debug('Easy Digital Downlaods Integration - This purchase was referred by an affiliate, refkey: ' . $strRefKey);
} else {
WPAM_Logger::log_debug('Easy Digital Downlaods Integration - refkey not found in the payment_meta. This purchase was not referred by an affiliate');
return;
}
$purchaseAmount = edd_get_payment_amount($payment_id);
$buyer_email = $payment_meta['email'];
WPAM_Logger::log_debug('Easy Digital Downlaods Integration - Awarding commission for Order ID: ' . $payment_id . '. Purchase amt: ' . $purchaseAmount . ', Buyer Email: ' . $buyer_email);
$requestTracker = new WPAM_Tracking_RequestTracker();
$requestTracker->handleCheckoutWithRefKey($payment_id, $purchaseAmount, $strRefKey, $buyer_email);
}
public function onExchangeCheckout($transaction_id, $method, $method_id, $status, $customer_id, $cart_object, $args) {
$purchaseAmount = it_exchange_get_transaction_subtotal($transaction_id, false);
$buyer_email = '';
$requestTracker = new WPAM_Tracking_RequestTracker();
$requestTracker->handleCheckout($transaction_id, $purchaseAmount, $buyer_email);
return $transaction_id;
}
public function onAdminMenu() {
//let the hackery begin! #63
global $menu;
$menu_parent_slug = 'wpam-affiliates';
//show this to affiliates, but not admins / affiliate managers
if (!current_user_can(WPAM_PluginConfig::$AdminCap) && current_user_can(WPAM_PluginConfig::$AffiliateCap)) {
//$icon_url = esc_url( self::$ICON_URL );
//I won't necessarily guarantee this will work in the future
$new_menu = array(
__('Affiliates', 'affiliates-manager'),
'read',
$this->affiliateHomePage->getLink(),
null,
'menu-top',
null,
'dashicons-groups',
);
$menu[] = $new_menu;
}
//show to non-affiliates
if (!current_user_can(WPAM_PluginConfig::$AffiliateCap) && !current_user_can(WPAM_PluginConfig::$AdminCap)) {
add_menu_page(
__('Affiliates', 'affiliates-manager'), __('Be An Affiliate', 'affiliates-manager'), 'read', 'newaffiliate', array($this, 'becomeAffiliate'), 'dashicons-groups'
);
}
//Add main affiliates menu object
add_menu_page(__('Affiliate Management', 'affiliates-manager'), __('Affiliates', 'affiliates-manager'), WPAM_PluginConfig::$AdminCap, 'wpam-affiliates', array(), 'dashicons-groups', '25.3');
$page = $this->adminPages[0];
//Add the child pages
$children = $page->getChildren();
//Add my affiliates submenu page
$childPage1 = $children[0];
add_submenu_page($page->getId(), $childPage1->getName(), $childPage1->getMenuName(), $childPage1->getRequiredCap(), $childPage1->getId(), array($childPage1, "process"));
//Add new affiliate submenu page
$childPage2 = $children[1];
add_submenu_page($page->getId(), $childPage2->getName(), $childPage2->getMenuName(), $childPage2->getRequiredCap(), $childPage2->getId(), array($childPage2, "process"));
//Add my creatives submenu page
$childPage3 = $children[2];
add_submenu_page($page->getId(), $childPage3->getName(), $childPage3->getMenuName(), $childPage3->getRequiredCap(), $childPage3->getId(), array($childPage3, "process"));
//Add paypal payments submenu page
$childPage4 = $children[3];
add_submenu_page($page->getId(), $childPage4->getName(), $childPage4->getMenuName(), $childPage4->getRequiredCap(), $childPage4->getId(), array($childPage4, "process"));
//Add settings submenu page
$settings_obj = new WPAM_Pages_Admin_SettingsPage();
add_submenu_page($menu_parent_slug, __('Settings', 'affiliates-manager'), __('Settings', 'affiliates-manager'), WPAM_PluginConfig::$AdminCap, 'wpam-settings', array($settings_obj, 'render_settings_page'));
//Add manage payouts submenu page
include_once(WPAM_BASE_DIRECTORY . "/source/Admin-menu/wpam-manage-payouts-menu.php");
add_submenu_page($menu_parent_slug, __("Affiliates Manager Manage Payouts", 'affiliates-manager'), __("Manage Payouts", 'affiliates-manager'), WPAM_PluginConfig::$AdminCap, 'wpam-manage-payouts', 'wpam_display_manage_payouts_menu');
//Add clicks submenu page
include_once(WPAM_BASE_DIRECTORY . "/source/Admin-menu/wpam-clicks-menu.php");
add_submenu_page($menu_parent_slug, __("Affiliates Manager Click Tracking", 'affiliates-manager'), __("Click Tracking", 'affiliates-manager'), WPAM_PluginConfig::$AdminCap, 'wpam-clicktracking', 'wpam_display_clicks_menu');
//Add commission submenu page
include_once(WPAM_BASE_DIRECTORY . "/source/Admin-menu/wpam-commission-menu.php");
add_submenu_page($menu_parent_slug, __("Affiliates Manager Commission Data", 'affiliates-manager'), __("Commissions", 'affiliates-manager'), WPAM_PluginConfig::$AdminCap, 'wpam-commission', 'wpam_display_commission_menu');
//Add addons submenu page
include_once(WPAM_BASE_DIRECTORY . "/source/Admin-menu/wpam-addons-menu.php");
add_submenu_page($menu_parent_slug, __("Affiliates Manager Add-ons", 'affiliates-manager'), __("Add-ons", 'affiliates-manager'), WPAM_PluginConfig::$AdminCap, 'wpam-addons', 'wpam_display_addons_menu');
//Hook for addons to create their menu
do_action('wpam_after_main_admin_menu', $menu_parent_slug);
}
//for public pages
public function onTemplateRedirect() {
if (!is_array(self::$PUBLIC_PAGE_IDS)) {
self::$PUBLIC_PAGE_IDS = array(
$this->publicPages[WPAM_Plugin::PAGE_NAME_HOME]->getPageId(),
$this->publicPages[WPAM_Plugin::PAGE_NAME_REGISTER]->getPageId());
}
//get the current page
$page_id = NULL;
$page = get_page($page_id);
//register front-end scripts
if (isset($page->ID) && in_array($page->ID, self::$PUBLIC_PAGE_IDS)) {
//add jquery dialog + some style
$this->enqueueDialog();
wp_register_style('wpam_jquery_ui_theme', WPAM_URL . '/style/jquery-ui/smoothness/jquery-ui.css');
wp_enqueue_style('wpam_jquery_ui_theme');
wp_register_style('wpam_style', WPAM_URL . "/style/style.css");
wp_enqueue_style('wpam_style');
//#45 add a datepicker
wp_enqueue_script('jquery-ui-datepicker');
wp_register_script('wpam_contact_info', WPAM_URL . '/js/contact_info.js', array('jquery-ui-dialog'));
wp_register_script('wpam_tnc', WPAM_URL . '/js/tnc.js', array('jquery-ui-dialog'));
wp_register_script('wpam_payment_method', WPAM_URL . '/js/payment_method.js');
}
}
/**
* There's an upstream bug with JQuery UI Button that will probably be
* fixed in JQuery UI 1.9, so we need to override the default WP one until
* it's fixed and the fixed version is included in WP.
*
* @see http://bugs.jqueryui.com/ticket/7680
*/
private function enqueueDialog() {
//things seem to be working OK with dialog/button as of WP 3.4, so we'll just use the included version
wp_enqueue_script('jquery-ui-button');
wp_enqueue_script('jquery-ui-dialog');
}
//#79 sync email when it's actually changed
public function filterUserEmail($email) {
$user = wp_get_current_user();
$newEmail = get_option($user->ID . '_new_email');
if (!empty($newEmail) && isset($_GET['newuseremail'])) {
$db = new WPAM_Data_DataAccess();
$affiliate = $db->getAffiliateRepository()->loadByUserId($user->ID);
$affiliate->email = $email;
$db->getAffiliateRepository()->update($affiliate);
}
return $email;
}
public function onSavePage($page_id, $page) {
if ($page->post_type == 'page') {
if (strpos($page->post_content, WPAM_PluginConfig::$ShortCodeHome) !== false) {
update_option(WPAM_PluginConfig::$HomePageId, $page->ID);
} elseif (strpos($page->post_content, WPAM_PluginConfig::$ShortCodeRegister) !== false) {
update_option(WPAM_PluginConfig::$RegPageId, $page->ID);
}
}
}
public function showAdminMessages() {
/* hide this error since the currency code and symbol comes from the general settings
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 '
' . sprintf( __( 'WP Affiliate Manager was unable to load your currency from your WPLANG setting: %s', 'affiliates-manager' ), $this->locale ) . ' ' .
sprintf( __( 'Your currency will be displayed as %s and PayPal payments will be paid in %s', 'affiliates-manager' ), $currency, $code ) . '
';
if ( WPAM_DEBUG ){
echo "';
}
}
*/
}
public function onAjaxRequest() {
//die(print_r($_REQUEST, true));
$jsonHandler = new WPAM_Util_JsonHandler();
$_REQUEST = wpam_sanitize_array($_REQUEST);
try {
switch ($_REQUEST['handler']) {
case 'approveApplication':
$response = $jsonHandler->approveApplication($_REQUEST['affiliateId'], $_REQUEST['bountyType'], $_REQUEST['bountyAmount']);
break;
case 'declineApplication':
$response = $jsonHandler->declineApplication($_REQUEST['affiliateId']);
break;
case 'blockApplication':
$response = $jsonHandler->blockApplication($_REQUEST['affiliateId']);
break;
case 'activateAffiliate':
$response = $jsonHandler->activateApplication($_REQUEST['affiliateId']);
break;
case 'deactivateAffiliate':
$response = $jsonHandler->deactivateApplication($_REQUEST['affiliateId']);
break;
case 'setCreativeStatus':
$response = $jsonHandler->setCreativeStatus($_REQUEST['creativeId'], $_REQUEST['status']);
break;
case 'addTransaction':
$response = $jsonHandler->addTransaction($_REQUEST['affiliateId'], $_REQUEST['type'], $_REQUEST['amount'], $_REQUEST['description']);
break;
case 'deleteCreative':
$response = $jsonHandler->deleteCreative($_REQUEST['creativeId']);
break;
default: throw new Exception(__('Invalid JSON handler.', 'affiliates-manager'));
}
} catch (Exception $e) {
$response = new JsonResponse(JsonResponse::STATUS_ERROR, $e->getMessage());
}
die(json_encode($response)); //required to return a proper result
}
private function output_csv($items, $export_keys, $filename = 'data.csv') {
header("Content-Type: text/csv; charset=utf-8");
header("Content-Disposition: attachment; filename=" . $filename);
header("Pragma: no-cache");
header("Expires: 0");
$output = fopen('php://output', 'w'); //open output stream
fputcsv($output, $export_keys); //let's put column names first
foreach ($items as $item) {
unset($csv_line);
foreach ($export_keys as $key => $value) {
if (isset($item[$key])) {
$csv_line[] = $item[$key];
}
}
fputcsv($output, $csv_line);
}
}
public function handle_csv_download() {
if (isset($_POST['wpam-export-affiliates-to-csv'])) {
$nonce = $_REQUEST['_wpnonce'];
if (!wp_verify_nonce($nonce, 'wpam-export-affiliates-to-csv-nonce')) {
die(_e('Nonce check failed for export My Affiliates to CSV!', 'affiliates-manager'));
}
include_once(WPAM_BASE_DIRECTORY . '/classes/ListAffiliatesTable.php');
$affiliates = new WPAM_List_Affiliates_Table();
$affiliates->prepare_items(true);
$export_keys = array(
'affiliateId' => 'Affiliate ID',
'status' => 'Status',
'balance' => 'Balance',
'earnings' => 'Earnings',
'firstName' => 'First Name',
'lastName' => 'Last Name',
'email' => 'Email',
'companyName' => 'Company',
'dateCreated' => 'Date Joined',
'websiteUrl' => 'Website',
);
$this->output_csv($affiliates->items, $export_keys, 'MyAffiliates.csv');
die();
}
}
}