/**
  * Renders the referrals section.
  */
 public static function section()
 {
     if (isset($_POST['submit'])) {
         if (wp_verify_nonce($_POST[AFFILIATES_ADMIN_SETTINGS_NONCE], 'admin')) {
             // timeout
             $timeout = intval($_POST['timeout']);
             if ($timeout < 0) {
                 $timeout = 0;
             }
             update_option('aff_cookie_timeout_days', $timeout);
             // direct referrals?
             delete_option('aff_use_direct');
             add_option('aff_use_direct', !empty($_POST['use-direct']), '', 'no');
             // default status
             if (!empty($_POST['status']) && Affiliates_Utility::verify_referral_status_transition($_POST['status'], $_POST['status'])) {
                 update_option('aff_default_referral_status', $_POST['status']);
             } else {
                 update_option('aff_default_referral_status', AFFILIATES_REFERRAL_STATUS_ACCEPTED);
             }
             // allow duplicates?
             delete_option('aff_duplicates');
             add_option('aff_duplicates', !empty($_POST['duplicates']), '', 'no');
             // auto
             delete_option('aff_allow_auto');
             add_option('aff_allow_auto', !empty($_POST['allow_auto']) ? 'yes' : 'no', '', 'no');
             delete_option('aff_allow_auto_coupons');
             add_option('aff_allow_auto_coupons', !empty($_POST['allow_auto_coupons']) ? 'yes' : 'no', '', 'no');
             self::settings_saved_notice();
         }
     }
     $timeout = get_option('aff_cookie_timeout_days', AFFILIATES_COOKIE_TIMEOUT_DAYS);
     $use_direct = get_option('aff_use_direct', false);
     $duplicates = get_option('aff_duplicates', false);
     $allow_auto = get_option('aff_allow_auto', 'no') == 'yes';
     $allow_auto_coupons = get_option('aff_allow_auto_coupons', 'no') == 'yes';
     $default_status = get_option('aff_default_referral_status', AFFILIATES_REFERRAL_STATUS_ACCEPTED);
     $status_descriptions = array(AFFILIATES_REFERRAL_STATUS_ACCEPTED => __('Accepted', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_CLOSED => __('Closed', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_PENDING => __('Pending', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_REJECTED => __('Rejected', AFFILIATES_PLUGIN_DOMAIN));
     $status_select = "<select name='status'>";
     foreach ($status_descriptions as $status_key => $status_value) {
         if ($status_key == $default_status) {
             $selected = "selected='selected'";
         } else {
             $selected = "";
         }
         $status_select .= "<option value='{$status_key}' {$selected}>{$status_value}</option>";
     }
     $status_select .= "</select>";
     echo '<form action="" name="options" method="post">' . '<div>' . '<h3>' . __('Referral timeout', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<label>' . '<input class="timeout" name="timeout" type="text" value="' . esc_attr(intval($timeout)) . '" />' . ' ' . __('Days', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p class="description">' . __('This is the number of days since a visitor accessed your site via an affiliate link, for which a suggested referral will be valid.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<p>' . __('If you enter 0, referrals will only be valid until the visitor closes the browser (session).', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<p>' . sprintf(__('The default value is %d. In this case, if a visitor comes to your site via an affiliate link, a suggested referral will be valid until %d days after she or he clicked that affiliate link.', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_COOKIE_TIMEOUT_DAYS, AFFILIATES_COOKIE_TIMEOUT_DAYS) . '</p>';
     echo '<h3>' . __('Direct referrals', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<label>' . '<input name="use-direct" type="checkbox" ' . ($use_direct ? 'checked="checked"' : '') . '/>' . ' ' . __('Store direct referrals', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p class="description">' . __('If this option is enabled, whenever a referral is suggested and no affiliate is attributable to it, the referral will be attributed to Direct.', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
     echo '<h3>' . __('Default referral status', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . $status_select . '</p>';
     echo '<h3>' . __('Duplicate referrals', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<label>' . '<input name="duplicates" type="checkbox" ' . ($duplicates ? 'checked="checked"' : '') . '/>' . ' ' . __('Allow duplicate referrals', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p class="description">' . __('Allow to record duplicate referrals for the same affiliate (based on amount, currency, internal type and reference).', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
     echo '<h3>' . __('Auto-referrals', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<label>' . sprintf('<input type="checkbox" name="allow_auto" %s" />', $allow_auto == 'yes' ? ' checked="checked" ' : '') . ' ' . __('Allow auto-referrals', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p class="description">' . __('If this option is enabled, affiliates are allowed to refer themselves.', AFFILIATES_PLUGIN_DOMAIN) . ' ' . __('This option allows an affiliate to earn a commission on a transaction that involves the affiliate as a customer or lead.', AFFILIATES_PLUGIN_DOMAIN) . ' ' . __('Auto-referrals are identified as such, when a transaction is processed for the same user or user email as the affiliate’s, or when it involves the use of a coupon assigned to the affiliate.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<p>' . '<label>' . sprintf('<input type="checkbox" name="allow_auto_coupons" %s" />', $allow_auto_coupons ? ' checked="checked" ' : '') . ' ' . __('Allow auto-coupons', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p class="description">' . __('Allow affiliates to apply coupons that are assigned to them.', AFFILIATES_PLUGIN_DOMAIN) . ' ' . __('Verification is supported for coupons managed through WooCommerce.', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
     echo '<p>' . wp_nonce_field('admin', AFFILIATES_ADMIN_SETTINGS_NONCE, true, false) . '<input class="button button-primary" type="submit" name="submit" value="' . __('Save', AFFILIATES_PLUGIN_DOMAIN) . '"/>' . '</p>' . '</div>' . '</form>';
     affiliates_footer();
 }
 /**
  * Save widget options
  * 
  * @see WP_Widget::update()
  */
 function update($new_instance, $old_instance)
 {
     $settings = $old_instance;
     if (!empty($new_instance['title'])) {
         $settings['title'] = strip_tags($new_instance['title']);
     } else {
         unset($settings['title']);
     }
     if (!empty($new_instance['terms_post_id'])) {
         $terms_post_id = $new_instance['terms_post_id'];
         if ($post = get_post($terms_post_id)) {
             $settings['terms_post_id'] = $post->ID;
         } else {
             if ($post = Affiliates_Utility::get_post_by_title($terms_post_id)) {
                 $settings['terms_post_id'] = $post->ID;
             } else {
                 unset($settings['terms_post_id']);
             }
         }
     }
     return $settings;
 }
 /**
  * Updates the user meta.
  * 
  * @param int $user_id
  */
 public static function edit_user_profile_update($user_id)
 {
     global $wpdb;
     if (!affiliates_user_is_affiliate($user_id)) {
         return;
     }
     require_once AFFILIATES_CORE_LIB . '/class-affiliates-settings.php';
     require_once AFFILIATES_CORE_LIB . '/class-affiliates-settings-registration.php';
     $registration_fields = Affiliates_Settings_Registration::get_fields();
     // remove fields not stored as user meta
     foreach (Affiliates_Registration::get_skip_meta_fields() as $key) {
         unset($registration_fields[$key]);
     }
     unset($registration_fields['first_name']);
     unset($registration_fields['last_name']);
     // update user meta
     if (!empty($registration_fields)) {
         foreach ($registration_fields as $name => $field) {
             $meta_value = isset($_POST[$name]) ? $_POST[$name] : '';
             $meta_value = Affiliates_Utility::filter($meta_value);
             update_user_meta($user_id, $name, maybe_unserialize($meta_value));
         }
     }
     // The affiliate entry must be updated using the profile_update action
     // as we don't have the updated user info here yet.
 }
function affiliates_admin_options()
{
    global $wp, $wpdb, $affiliates_options, $wp_roles;
    if (!current_user_can(AFFILIATES_ADMINISTER_OPTIONS)) {
        wp_die(__('Access denied.', AFFILIATES_PLUGIN_DOMAIN));
    }
    $robots_table = _affiliates_get_tablename('robots');
    echo '<div>' . '<h2>' . __('Affiliates options', AFFILIATES_PLUGIN_DOMAIN) . '</h2>' . '</div>';
    $pages_generated_info = '';
    //
    // handle page generation form submission
    //
    if (isset($_POST['generate'])) {
        if (wp_verify_nonce($_POST[AFFILIATES_ADMIN_OPTIONS_GEN_NONCE], 'admin')) {
            require_once AFFILIATES_CORE_LIB . '/class-affiliates-generator.php';
            $post_ids = Affiliates_Generator::setup_pages();
            foreach ($post_ids as $post_id) {
                $link = '<a href="' . get_permalink($post_id) . '" target="_blank">' . get_the_title($post_id) . '</a>';
                $pages_generated_info .= '<div class="info">' . __(sprintf('The %s page has been created.', $link), AFFILIATES_PLUGIN_DOMAIN) . '</div>';
            }
        }
    }
    //
    // handle options form submission
    //
    if (isset($_POST['submit'])) {
        if (wp_verify_nonce($_POST[AFFILIATES_ADMIN_OPTIONS_NONCE], 'admin')) {
            // timeout
            $timeout = intval($_POST['timeout']);
            if ($timeout < 0) {
                $timeout = 0;
            }
            update_option('aff_cookie_timeout_days', $timeout);
            // robots
            $robots = wp_filter_nohtml_kses(trim($_POST['robots']));
            $wpdb->query("DELETE FROM {$robots_table};");
            if (!empty($robots)) {
                $robots = str_replace(",", "\n", $robots);
                $robots = str_replace("\r", "", $robots);
                $robots = explode("\n", $robots);
                foreach ($robots as $robot) {
                    $robot = trim($robot);
                    if (!empty($robot)) {
                        $query = $wpdb->prepare("INSERT INTO {$robots_table} (name) VALUES (%s);", $robot);
                        $wpdb->query($query);
                    }
                }
            }
            delete_option('aff_registration');
            add_option('aff_registration', !empty($_POST['registration']), '', 'no');
            delete_option('aff_notify_admin');
            add_option('aff_notify_admin', !empty($_POST['notify_admin']), '', 'no');
            $pname = !empty($_POST['pname']) ? trim($_POST['pname']) : get_option('aff_pname', AFFILIATES_PNAME);
            $forbidden_names = array();
            if (!empty($wp->public_query_vars)) {
                $forbidden_names += $wp->public_query_vars;
            }
            if (!empty($wp->private_query_vars)) {
                $forbidden_names += $wp->private_query_vars;
            }
            if (!empty($wp->extra_query_vars)) {
                $forbidden_names += $wp->extra_query_vars;
            }
            if (!preg_match('/[a-z_]+/', $pname, $matches) || !isset($matches[0]) || $pname !== $matches[0]) {
                $pname = get_option('aff_pname', AFFILIATES_PNAME);
                echo '<div class="error">' . __('The Affiliate URL parameter name <strong>has not been changed</strong>, the suggested name <em>is not valid</em>. Only lower case letters and the underscore _ are allowed.', AFFILIATES_PLUGIN_DOMAIN) . '</div>';
            } else {
                if (in_array($pname, $forbidden_names)) {
                    $pname = get_option('aff_pname', AFFILIATES_PNAME);
                    echo '<div class="error">' . __('The Affiliate URL parameter name <strong>has not been changed</strong>, the suggested name <em>is forbidden</em>.', AFFILIATES_PLUGIN_DOMAIN) . '</div>';
                }
            }
            if ($pname !== get_option('aff_pname', AFFILIATES_PNAME)) {
                $old_pname = get_option('aff_pname', $pname);
                update_option('aff_pname', $pname);
                affiliates_update_rewrite_rules();
                echo '<div class="info">' . '<p>' . sprintf(__('The Affiliate URL parameter name <strong>has been changed</strong> from <em><strong>%s</strong></em> to <em><strong>%s</strong></em>.', AFFILIATES_PLUGIN_DOMAIN), $old_pname, $pname) . '</p>' . '<p class="warning">' . __('If your affiliates are using affiliate links based on the previous Affiliate URL parameter name, they <strong>NEED</strong> to update their affiliate links.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<p class="warning">' . __('Unless the incoming affiliate links reflect the current Affiliate URL parameter name, no affiliate hits, visits or referrals will be recorded.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '</div>';
            }
            $redirect = !empty($_POST['redirect']);
            if ($redirect) {
                if (get_option('aff_redirect', null) === null) {
                    add_option('aff_redirect', 'yes', '', 'no');
                } else {
                    update_option('aff_redirect', 'yes');
                }
            } else {
                delete_option('aff_redirect');
            }
            $encoding_id = $_POST['id_encoding'];
            if (key_exists($encoding_id, affiliates_get_id_encodings())) {
                // important: must use normal update_option/get_option otherwise we'd have a per-user encoding
                update_option('aff_id_encoding', $encoding_id);
            }
            $rolenames = $wp_roles->get_names();
            $caps = array(AFFILIATES_ACCESS_AFFILIATES => __('Access affiliates', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_ADMINISTER_AFFILIATES => __('Administer affiliates', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_ADMINISTER_OPTIONS => __('Administer options', AFFILIATES_PLUGIN_DOMAIN));
            foreach ($rolenames as $rolekey => $rolename) {
                $role = $wp_roles->get_role($rolekey);
                foreach ($caps as $capkey => $capname) {
                    $role_cap_id = $rolekey . '-' . $capkey;
                    if (!empty($_POST[$role_cap_id])) {
                        $role->add_cap($capkey);
                    } else {
                        $role->remove_cap($capkey);
                    }
                }
            }
            // prevent locking out
            _affiliates_assure_capabilities();
            if (!affiliates_is_sitewide_plugin()) {
                delete_option('aff_delete_data');
                add_option('aff_delete_data', !empty($_POST['delete-data']), '', 'no');
            }
            // direct referrals?
            delete_option('aff_use_direct');
            add_option('aff_use_direct', !empty($_POST['use-direct']), '', 'no');
            // default status
            if (!empty($_POST['status']) && Affiliates_Utility::verify_referral_status_transition($_POST['status'], $_POST['status'])) {
                update_option('aff_default_referral_status', $_POST['status']);
            } else {
                update_option('aff_default_referral_status', AFFILIATES_REFERRAL_STATUS_ACCEPTED);
            }
            // allow duplicates?
            delete_option('aff_duplicates');
            add_option('aff_duplicates', !empty($_POST['duplicates']), '', 'no');
        }
    }
    $use_direct = get_option('aff_use_direct', true);
    $duplicates = get_option('aff_duplicates', false);
    $timeout = get_option('aff_cookie_timeout_days', AFFILIATES_COOKIE_TIMEOUT_DAYS);
    $default_status = get_option('aff_default_referral_status', AFFILIATES_REFERRAL_STATUS_ACCEPTED);
    $status_descriptions = array(AFFILIATES_REFERRAL_STATUS_ACCEPTED => __('Accepted', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_CLOSED => __('Closed', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_PENDING => __('Pending', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_REJECTED => __('Rejected', AFFILIATES_PLUGIN_DOMAIN));
    $status_select = "<select name='status'>";
    foreach ($status_descriptions as $status_key => $status_value) {
        if ($status_key == $default_status) {
            $selected = "selected='selected'";
        } else {
            $selected = "";
        }
        $status_select .= "<option value='{$status_key}' {$selected}>{$status_value}</option>";
    }
    $status_select .= "</select>";
    $robots = '';
    $db_robots = $wpdb->get_results("SELECT name FROM {$robots_table}", OBJECT);
    foreach ($db_robots as $db_robot) {
        $robots .= $db_robot->name . "\n";
    }
    $registration = get_option('aff_registration', get_option('users_can_register', false));
    $notify_admin = get_option('aff_notify_admin', get_option('aff_notify_admin', true));
    $pname = get_option('aff_pname', AFFILIATES_PNAME);
    $redirect = get_option('aff_redirect', false);
    $id_encoding = get_option('aff_id_encoding', AFFILIATES_NO_ID_ENCODING);
    $id_encoding_select = '';
    $encodings = affiliates_get_id_encodings();
    if (!empty($encodings)) {
        $id_encoding_select .= '<label class="id-encoding" for="id_encoding">' . __('Affiliate ID Encoding', AFFILIATES_PLUGIN_DOMAIN) . '</label>';
        $id_encoding_select .= '<select class="id-encoding" name="id_encoding">';
        foreach ($encodings as $key => $value) {
            if ($id_encoding == $key) {
                $selected = ' selected="selected" ';
            } else {
                $selected = '';
            }
            $id_encoding_select .= '<option ' . $selected . ' value="' . esc_attr($key) . '">' . esc_attr($value) . '</option>';
        }
        $id_encoding_select .= '</select>';
    }
    $rolenames = $wp_roles->get_names();
    $caps = array(AFFILIATES_ACCESS_AFFILIATES => __('Access affiliates', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_ADMINISTER_AFFILIATES => __('Administer affiliates', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_ADMINISTER_OPTIONS => __('Administer options', AFFILIATES_PLUGIN_DOMAIN));
    $caps_table = '<table class="affiliates-permissions">';
    $caps_table .= '<thead>';
    $caps_table .= '<tr>';
    $caps_table .= '<td class="role">';
    $caps_table .= __('Role', AFFILIATES_PLUGIN_DOMAIN);
    $caps_table .= '</td>';
    foreach ($caps as $cap) {
        $caps_table .= '<td class="cap">';
        $caps_table .= $cap;
        $caps_table .= '</td>';
    }
    $caps_table .= '</tr>';
    $caps_table .= '</thead>';
    $caps_table .= '<tbody>';
    foreach ($rolenames as $rolekey => $rolename) {
        $role = $wp_roles->get_role($rolekey);
        $caps_table .= '<tr>';
        $caps_table .= '<td>';
        $caps_table .= translate_user_role($rolename);
        $caps_table .= '</td>';
        foreach ($caps as $capkey => $capname) {
            if ($role->has_cap($capkey)) {
                $checked = ' checked="checked" ';
            } else {
                $checked = '';
            }
            $caps_table .= '<td class="checkbox">';
            $role_cap_id = $rolekey . '-' . $capkey;
            $caps_table .= '<input type="checkbox" name="' . $role_cap_id . '" id="' . $role_cap_id . '" ' . $checked . '/>';
            $caps_table .= '</td>';
        }
        $caps_table .= '</tr>';
    }
    $caps_table .= '</tbody>';
    $caps_table .= '</table>';
    $delete_data = get_option('aff_delete_data', false);
    //
    // Generator form
    //
    echo '<form action="" name="options" method="post">' . '<div>' . '<h3>' . __('Page generation', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . __('Press the button to generate an affiliate area.', AFFILIATES_PLUGIN_DOMAIN) . ' ' . '<input class="generate button" name="generate" type="submit" value="' . __('Generate', AFFILIATES_PLUGIN_DOMAIN) . '" />' . wp_nonce_field('admin', AFFILIATES_ADMIN_OPTIONS_GEN_NONCE, true, false) . '</p>' . $pages_generated_info . '</div>' . '</form>';
    //
    // print the options form
    //
    echo '<form action="" name="options" method="post">' . '<div>' . '<h3>' . __('Referral timeout', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<label>' . '<input class="timeout" name="timeout" type="text" value="' . esc_attr(intval($timeout)) . '" />' . ' ' . __('Days', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p class="description">' . __('This is the number of days since a visitor accessed your site via an affiliate link, for which a suggested referral will be valid.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<p>' . __('If you enter 0, referrals will only be valid until the visitor closes the browser (session).', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<p>' . __('The default value is 1. In this case, if a visitor comes to your site via an affiliate link, a suggested referral will be valid until one day after she or he clicked that affiliate link.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<h3>' . __('Direct referrals', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<label>' . '<input name="use-direct" type="checkbox" ' . ($use_direct ? 'checked="checked"' : '') . '/>' . ' ' . __('Store direct referrals', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p class="description">' . __('If this option is enabled, whenever a referral is suggested and no affiliate is attributable to it, the referral will be attributed to Direct.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<h3>' . __('Default referral status', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . $status_select . '</p>' . '<h3>' . __('Duplicate referrals', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<label>' . '<input name="duplicates" type="checkbox" ' . ($duplicates ? 'checked="checked"' : '') . '/>' . ' ' . __('Allow duplicate referrals', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p class="description">' . __('Allow to record duplicate referrals for the same affiliate (based on amount, currency, internal type and reference).', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<h3>' . __('Robots', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<textarea id="robots" name="robots" rows="10" cols="45">' . wp_filter_nohtml_kses($robots) . '</textarea>' . '</p>' . '<p>' . __('Hits on affiliate links from these robots will be marked or not recorded. Put one entry on each line.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<h3>' . __('Affiliate registration', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<label>' . '<input name="registration" type="checkbox" ' . ($registration ? 'checked="checked"' : '') . '/>' . ' ' . __('Allow affiliate registration', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p>' . '<label>' . '<input name="notify_admin" type="checkbox" ' . ($notify_admin ? 'checked="checked"' : '') . '/>' . ' ' . __('Notify the site admin when a new affiliate is registered', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<h3>' . __('Affiliate URL parameter name', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<input class="pname" name="pname" type="text" value="' . esc_attr($pname) . '" />' . '</p>' . '<p>' . sprintf(__('The current Affiliate URL parameter name is: <b>%s</b>', AFFILIATES_PLUGIN_DOMAIN), $pname) . '</p>' . '<p>' . sprintf(__('The default Affiliate URL parameter name is <em>%s</em>.', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_PNAME) . '</p>' . '<p class="description warning">' . __('CAUTION: If you change this setting and have distributed affiliate links or permalinks, make sure that these are updated. Unless the incoming affiliate links reflect the current URL parameter name, no affiliate hits, visits or referrals will be recorded.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<h3>' . __('Redirection', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<label>' . sprintf('<input class="redirect" name="redirect" type="checkbox" %s/>', $redirect ? ' checked="checked" ' : '') . ' ' . __('Redirect', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p class="description">' . __('Redirect to destination without Affiliate URL parameter, after a hit on an affiliate link has been detected.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<h3>' . __('Affiliate ID encoding', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . $id_encoding_select . '</p>' . '<p>' . sprintf(__('The current encoding in effect is: <b>%s</b>', AFFILIATES_PLUGIN_DOMAIN), $encodings[$id_encoding]) . '</p>' . '<p class="description warning">' . __('CAUTION: If you change this setting and have distributed affiliate links or permalinks, make sure that these are updated. Unless the incoming affiliate links reflect the current encoding, no affiliate hits, visits or referrals will be recorded.', AFFILIATES_PLUGIN_DOMAIN) . '</p>' . '<h3>' . __('Permissions', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . $caps_table . '<p class="description">' . __('A minimum set of permissions will be preserved.', AFFILIATES_PLUGIN_DOMAIN) . '<br/>' . __('If you lock yourself out, please ask an administrator to help.', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
    if (!affiliates_is_sitewide_plugin()) {
        echo '<h3>' . __('Deactivation and data persistence', AFFILIATES_PLUGIN_DOMAIN) . '</h3>' . '<p>' . '<label>' . '<input name="delete-data" type="checkbox" ' . ($delete_data ? 'checked="checked"' : '') . '/>' . ' ' . __('Delete all plugin data on deactivation', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>' . '<p class="description warning">' . __('CAUTION: If this option is active while the plugin is deactivated, ALL affiliate and referral data will be DELETED. If you want to retrieve data about your affiliates and their referrals and are going to deactivate the plugin, make sure to back up your data or do not enable this option. By enabling this option you agree to be solely responsible for any loss of data or any other consequences thereof.', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
    }
    echo '<p>' . wp_nonce_field('admin', AFFILIATES_ADMIN_OPTIONS_NONCE, true, false) . '<input class="button" type="submit" name="submit" value="' . __('Save', AFFILIATES_PLUGIN_DOMAIN) . '"/>' . '</p>' . '</div>' . '</form>';
    affiliates_footer();
}
 /**
  * Affiliate field info.
  * 
  * user_id - print for ... requires AFFILIATES_ADMIN...
  * name - field name or names, empty includes all by default
  * edit - yes or no
  * load_styles - yes or no
  * 
  * @param array $atts
  * @param string $content
  * @return string
  */
 public static function affiliates_fields($atts, $content = null)
 {
     $output = '';
     if (is_user_logged_in()) {
         $atts = shortcode_atts(array('edit' => 'yes', 'load_styles' => 'yes', 'name' => '', 'user_id' => null), $atts);
         $atts['load_styles'] = strtolower(trim($atts['load_styles']));
         if ($atts['load_styles'] == 'yes') {
             wp_enqueue_style('affiliates-fields');
         }
         $atts['edit'] = strtolower(trim($atts['edit']));
         $fields = null;
         if (!empty($atts['name'])) {
             $fields = array_map('strtolower', array_map('trim', explode(',', $atts['name'])));
         }
         if (current_user_can(AFFILIATES_ADMINISTER_AFFILIATES) && !empty($atts['user_id'])) {
             $user_id = intval(trim($atts['user_id']));
         } else {
             $user_id = get_current_user_id();
         }
         $user = get_user_by('id', $user_id);
         if (affiliates_user_is_affiliate($user_id)) {
             require_once AFFILIATES_CORE_LIB . '/class-affiliates-settings.php';
             require_once AFFILIATES_CORE_LIB . '/class-affiliates-settings-registration.php';
             $registration_fields = Affiliates_Settings_Registration::get_fields();
             if ($atts['edit'] != 'yes') {
                 unset($registration_fields['password']);
             }
             if (!empty($fields)) {
                 $_registration_fields = array();
                 foreach ($fields as $name) {
                     if (isset($registration_fields[$name])) {
                         $_registration_fields[$name] = $registration_fields[$name];
                     }
                 }
                 $registration_fields = $_registration_fields;
             }
             // handle form submission
             if ($atts['edit'] === 'yes') {
                 if (!empty($_POST['affiliate-nonce']) && wp_verify_nonce($_POST['affiliate-nonce'], 'save')) {
                     if (!empty($registration_fields)) {
                         $error = false;
                         // gather field values
                         foreach ($registration_fields as $name => $field) {
                             if ($field['enabled']) {
                                 $value = isset($_POST[$name]) ? $_POST[$name] : '';
                                 $value = Affiliates_Utility::filter($value);
                                 if ($field['required'] && empty($value) && !(is_user_logged_in() && isset($field['type']) && $field['type'] == 'password')) {
                                     $error = true;
                                     $output .= '<div class="error">';
                                     $output .= __('<strong>ERROR</strong>', AFFILIATES_PLUGIN_DOMAIN);
                                     $output .= ' : ';
                                     $output .= sprintf(__('Please fill out the field <em>%s</em>.', AFFILIATES_PLUGIN_DOMAIN), $field['label']);
                                     $output .= '</div>';
                                 }
                                 $registration_fields[$name]['value'] = $value;
                                 // password check
                                 $type = isset($field['type']) ? $field['type'] : 'text';
                                 if ($type == 'password') {
                                     if (!empty($value)) {
                                         $value2 = isset($_POST[$name . '2']) ? $_POST[$name . '2'] : '';
                                         $value2 = Affiliates_Utility::filter($value2);
                                         if ($value !== $value2) {
                                             $error = true;
                                             $output .= '<div class="error">';
                                             $output .= __('<strong>ERROR</strong>', AFFILIATES_PLUGIN_DOMAIN);
                                             $output .= ' : ';
                                             $output .= sprintf(__('The passwords for the field <em>%s</em> do not match.', AFFILIATES_PLUGIN_DOMAIN), $field['label']);
                                             $output .= '</div>';
                                         }
                                     }
                                 }
                             }
                         }
                         $userdata = array();
                         foreach ($registration_fields as $name => $field) {
                             if ($registration_fields[$name]['enabled']) {
                                 $userdata[$name] = $registration_fields[$name]['value'];
                             }
                         }
                         if (!$error) {
                             $updated_user_id = Affiliates_Registration::update_affiliate_user($user_id, $userdata);
                             if (is_wp_error($updated_user_id)) {
                                 $error_messages = implode('<br/>', $updated_user_id->get_error_messages());
                                 if (!empty($error_messages)) {
                                     $output .= '<div class="error">';
                                     $output .= $error_messages;
                                     $output .= '</div>';
                                 }
                             } else {
                                 $output .= '<div class="updated">';
                                 $output .= __('Saved', AFFILIATES_PLUGIN_DOMAIN);
                                 $output .= '</div>';
                             }
                         }
                     }
                 }
             }
             // show form
             $n = 0;
             if (!empty($registration_fields)) {
                 if ($atts['edit'] === 'yes') {
                     $output .= '<form class="affiliates-fields" method="post">';
                     $output .= '<div>';
                 } else {
                     $output .= '<div class="affiliates-fields">';
                     $output .= '<div>';
                 }
                 foreach ($registration_fields as $name => $field) {
                     if ($field['enabled']) {
                         $n++;
                         $output .= '<div class="field">';
                         $output .= '<label>';
                         $output .= esc_html(stripslashes($field['label']));
                         // @todo i18n
                         $type = isset($field['type']) ? $field['type'] : 'text';
                         $extra = $atts['edit'] != 'yes' ? ' readonly="readonly" ' : '';
                         switch ($name) {
                             case 'user_login':
                                 $extra .= ' readonly="readonly" ';
                                 $value = $user->user_login;
                                 break;
                             case 'user_email':
                                 $value = $user->user_email;
                                 break;
                             case 'user_url':
                                 $value = $user->user_url;
                                 break;
                             case 'password':
                                 $value = '';
                                 break;
                             default:
                                 $value = get_user_meta($user_id, $name, true);
                         }
                         $output .= sprintf('<input type="%s" class="%s" name="%s" value="%s" %s %s />', esc_attr($type), 'regular-text ' . esc_attr($name) . ($type != 'password' && $field['required'] ? ' required ' : ''), esc_attr($name), esc_attr(stripslashes($value)), $type != 'password' && $field['required'] ? ' required="required" ' : '', $extra);
                         $output .= '</label>';
                         $output .= '</div>';
                         if ($type == 'password') {
                             // the second passwort field is also not required
                             $output .= '<div class="field">';
                             $output .= '<label>';
                             $output .= sprintf(__('Repeat %s', AFFILIATES_PLUGIN_DOMAIN), esc_html(stripslashes($field['label'])));
                             // @todo i18n
                             $output .= sprintf('<input type="%s" class="%s" name="%s" value="%s" %s %s />', esc_attr($type), 'regular-text ' . esc_attr($name), esc_attr($name . '2'), esc_attr($value), '', $extra);
                             $output .= '</label>';
                             $output .= '</div>';
                         }
                     }
                 }
                 if ($atts['edit'] === 'yes') {
                     $output .= wp_nonce_field('save', 'affiliate-nonce', true, false);
                     $output .= '<div class="save">';
                     $output .= sprintf('<input class="button" type="submit" name="save" value="%s" />', __('Save', AFFILIATES_PLUGIN_DOMAIN));
                     $output .= '</div>';
                     $output .= '</div>';
                     $output .= '</form>';
                 } else {
                     $output .= '</div>';
                     $output .= '</div>';
                 }
             }
         }
     }
     return $output;
 }
 /**
  * Save widget options
  * 
  * @see WP_Widget::update()
  */
 function update($new_instance, $old_instance)
 {
     $settings = $old_instance;
     $settings['title'] = strip_tags($new_instance['title']);
     if (!empty($new_instance['amount'])) {
         $settings['amount'] = Affiliates_Utility::verify_referral_amount($new_instance['amount']);
     } else {
         unset($settings['amount']);
     }
     if (!empty($new_instance['currency_id'])) {
         $settings['currency_id'] = Affiliates_Utility::verify_currency_id($new_instance['currency_id']);
     } else {
         unset($settings['currency_id']);
     }
     return $settings;
 }
 /**
  * Filters mail header injection, html, ... 
  * @param string $unfiltered_value
  */
 static function filter($unfiltered_value)
 {
     $mail_filtered_value = preg_replace('/(%0A|%0D|content-type:|to:|cc:|bcc:)/i', '', $unfiltered_value);
     return stripslashes(wp_filter_nohtml_kses(Affiliates_Utility::filter_xss(trim(strip_tags($mail_filtered_value)))));
 }
function affiliates_admin_hits_affiliate()
{
    global $wpdb, $affiliates_options;
    $output = '';
    if (!current_user_can(AFFILIATES_ACCESS_AFFILIATES)) {
        wp_die(__('Access denied.', AFFILIATES_PLUGIN_DOMAIN));
    }
    if (isset($_POST['from_date']) || isset($_POST['thru_date']) || isset($_POST['clear_filters']) || isset($_POST['affiliate_id']) || isset($_POST['expanded']) || isset($_POST['expanded_hits']) || isset($_POST['expanded_referrals']) || isset($_POST['show_inoperative'])) {
        if (!wp_verify_nonce($_POST[AFFILIATES_ADMIN_HITS_AFF_FILTER_NONCE], 'admin')) {
            wp_die(__('Access denied.', AFFILIATES_PLUGIN_DOMAIN));
        }
    }
    // filters
    $from_date = $affiliates_options->get_option('hits_affiliate_from_date', null);
    $thru_date = $affiliates_options->get_option('hits_affiliate_thru_date', null);
    $affiliate_id = $affiliates_options->get_option('hits_affiliate_affiliate_id', null);
    $status = $affiliates_options->get_option('hits_affiliate_status', null);
    $expanded = $affiliates_options->get_option('hits_affiliate_expanded', null);
    // @todo input ist not shown, eventually remove unless ...
    $expanded_referrals = $affiliates_options->get_option('hits_affiliate_expanded_referrals', null);
    $expanded_hits = $affiliates_options->get_option('hits_affiliate_expanded_hits', null);
    $show_inoperative = $affiliates_options->get_option('hits_affiliate_show_inoperative', null);
    if (isset($_POST['clear_filters'])) {
        $affiliates_options->delete_option('hits_affiliate_from_date');
        $affiliates_options->delete_option('hits_affiliate_thru_date');
        $affiliates_options->delete_option('hits_affiliate_affiliate_id');
        $affiliates_options->delete_option('hits_affiliate_status');
        $affiliates_options->delete_option('hits_affiliate_expanded');
        $affiliates_options->delete_option('hits_affiliate_expanded_referrals');
        $affiliates_options->delete_option('hits_affiliate_expanded_hits');
        $affiliates_options->delete_option('hits_affiliate_show_inoperative');
        $from_date = null;
        $thru_date = null;
        $affiliate_id = null;
        $status = null;
        $expanded = null;
        $expanded_hits = null;
        $expanded_referrals = null;
        $show_inoperative = null;
    } else {
        if (isset($_POST['submitted'])) {
            // filter by date(s)
            if (!empty($_POST['from_date'])) {
                $from_date = date('Y-m-d', strtotime($_POST['from_date']));
                $affiliates_options->update_option('hits_affiliate_from_date', $from_date);
            } else {
                $from_date = null;
                $affiliates_options->delete_option('hits_affiliate_from_date');
            }
            if (!empty($_POST['thru_date'])) {
                $thru_date = date('Y-m-d', strtotime($_POST['thru_date']));
                $affiliates_options->update_option('hits_affiliate_thru_date', $thru_date);
            } else {
                $thru_date = null;
                $affiliates_options->delete_option('hits_affiliate_thru_date');
            }
            if ($from_date && $thru_date) {
                if (strtotime($from_date) > strtotime($thru_date)) {
                    $thru_date = null;
                    $affiliates_options->delete_option('hits_affiliate_thru_date');
                }
            }
            // filter by affiliate id
            if (!empty($_POST['affiliate_id'])) {
                $affiliate_id = affiliates_check_affiliate_id($_POST['affiliate_id']);
                if ($affiliate_id) {
                    $affiliates_options->update_option('hits_affiliate_affiliate_id', $affiliate_id);
                }
            } else {
                if (isset($_POST['affiliate_id'])) {
                    // empty && isset => '' => all
                    $affiliate_id = null;
                    $affiliates_options->delete_option('hits_affiliate_affiliate_id');
                }
            }
            if (!empty($_POST['status'])) {
                if (is_array($_POST['status'])) {
                    $stati = array();
                    foreach ($_POST['status'] as $status) {
                        if ($status = Affiliates_Utility::verify_referral_status_transition($status, $status)) {
                            $stati[] = $status;
                        }
                    }
                    if (count($stati) > 0) {
                        $status = $stati;
                        $affiliates_options->update_option('hits_affiliate_status', $stati);
                    } else {
                        $status = null;
                        $affiliates_options->delete_option('hits_affiliate_status');
                    }
                }
            } else {
                $status = null;
                $affiliates_options->delete_option('hits_affiliate_status');
            }
            // expanded details?
            if (!empty($_POST['expanded'])) {
                $expanded = true;
                $affiliates_options->update_option('hits_affiliate_expanded', true);
            } else {
                $expanded = false;
                $affiliates_options->delete_option('hits_affiliate_expanded');
            }
            if (!empty($_POST['expanded_hits'])) {
                $expanded_hits = true;
                $affiliates_options->update_option('hits_affiliate_expanded_hits', true);
            } else {
                $expanded_hits = false;
                $affiliates_options->delete_option('hits_affiliate_expanded_hits');
            }
            if (!empty($_POST['expanded_referrals'])) {
                $expanded_referrals = true;
                $affiliates_options->update_option('hits_affiliate_expanded_referrals', true);
            } else {
                $expanded_referrals = false;
                $affiliates_options->delete_option('hits_affiliate_expanded_referrals');
            }
            if (!empty($_POST['show_inoperative'])) {
                $show_inoperative = true;
                $affiliates_options->update_option('hits_affiliate_show_inoperative', true);
            } else {
                $show_inoperative = false;
                $affiliates_options->delete_option('hits_affiliate_show_inoperative');
            }
        }
    }
    if (isset($_POST['row_count'])) {
        if (!wp_verify_nonce($_POST[AFFILIATES_ADMIN_HITS_AFF_NONCE_1], 'admin')) {
            wp_die(__('Access denied.', AFFILIATES_PLUGIN_DOMAIN));
        }
    }
    if (isset($_POST['paged'])) {
        if (!wp_verify_nonce($_POST[AFFILIATES_ADMIN_HITS_AFF_NONCE_2], 'admin')) {
            wp_die(__('Access denied.', AFFILIATES_PLUGIN_DOMAIN));
        }
    }
    $current_url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $current_url = remove_query_arg('paged', $current_url);
    $affiliates_table = _affiliates_get_tablename('affiliates');
    $referrals_table = _affiliates_get_tablename('referrals');
    $hits_table = _affiliates_get_tablename('hits');
    $output .= '<div>' . '<h1>' . __('Affiliates & Referrals', AFFILIATES_PLUGIN_DOMAIN) . '</h1>' . '</div>';
    $row_count = isset($_POST['row_count']) ? intval($_POST['row_count']) : 0;
    if ($row_count <= 0) {
        $row_count = $affiliates_options->get_option('hits_affiliate_per_page', AFFILIATES_HITS_AFFILIATE_PER_PAGE);
    } else {
        $affiliates_options->update_option('hits_affiliate_per_page', $row_count);
    }
    $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
    if ($offset < 0) {
        $offset = 0;
    }
    $paged = isset($_REQUEST['paged']) ? intval($_REQUEST['paged']) : 0;
    if ($paged < 0) {
        $paged = 0;
    }
    $orderby = isset($_GET['orderby']) ? $_GET['orderby'] : null;
    switch ($orderby) {
        case 'date':
        case 'visits':
        case 'hits':
        case 'referrals':
        case 'ratio':
        case 'name':
            break;
        default:
            $orderby = 'name';
    }
    $order = isset($_GET['order']) ? $_GET['order'] : null;
    switch ($order) {
        case 'asc':
        case 'ASC':
            $switch_order = 'DESC';
            break;
        case 'desc':
        case 'DESC':
            $switch_order = 'ASC';
            break;
        default:
            $order = 'ASC';
            $switch_order = 'DESC';
    }
    $filters = " WHERE 1=%d ";
    $filter_params = array(1);
    // We now have the desired dates from the user's point of view, i.e. in her timezone.
    // If supported, adjust the dates for the site's timezone:
    if ($from_date) {
        $from_datetime = DateHelper::u2s($from_date);
    }
    if ($thru_date) {
        $thru_datetime = DateHelper::u2s($thru_date, 24 * 3600);
    }
    if ($from_date && $thru_date) {
        $filters .= " AND datetime >= %s AND datetime < %s ";
        $filter_params[] = $from_datetime;
        $filter_params[] = $thru_datetime;
    } else {
        if ($from_date) {
            $filters .= " AND datetime >= %s ";
            $filter_params[] = $from_datetime;
        } else {
            if ($thru_date) {
                $filters .= " AND datetime < %s ";
                $filter_params[] = $thru_datetime;
            }
        }
    }
    if ($affiliate_id) {
        $filters .= " AND h.affiliate_id = %d ";
        $filter_params[] = $affiliate_id;
    }
    // how many are there ?
    $count_query = $wpdb->prepare("SELECT affiliate_id FROM {$hits_table} h\n\t\t{$filters}\n\t\tGROUP BY affiliate_id\n\t\t", $filter_params);
    $wpdb->query($count_query);
    $count = $wpdb->num_rows;
    if ($count > $row_count) {
        $paginate = true;
    } else {
        $paginate = false;
    }
    $pages = ceil($count / $row_count);
    if ($paged > $pages) {
        $paged = $pages;
    }
    if ($paged != 0) {
        $offset = ($paged - 1) * $row_count;
    }
    // Get the summarized results, these are grouped by date.
    // Note: Referrals on dates without a hit will not be included.
    // @see notes about this in affiliates_admin_hits()
    $date_condition = "";
    if ($from_date && $thru_date) {
        $date_condition = " AND datetime >= '" . $from_datetime . "' AND datetime < '" . $thru_datetime . "' ";
    } else {
        if ($from_date) {
            $date_condition = " AND datetime >= '" . $from_datetime . "' ";
        } else {
            if ($thru_date) {
                $date_condition = " AND datetime < '" . $thru_datetime . "' ";
            }
        }
    }
    $status_condition = "";
    if (is_array($status) && count($status) > 0) {
        $status_condition = " AND status IN ('" . implode("','", $status) . "') ";
    }
    $query = $wpdb->prepare("\n\t\t\tSELECT\n\t\t\t\t*,\n\t\t\t\tcount(distinct ip) visits,\n\t\t\t\tsum(count) hits,\n\t\t\t\t(SELECT COUNT(*) FROM {$referrals_table} WHERE affiliate_id = h.affiliate_id {$date_condition} {$status_condition} ) referrals,\n\t\t\t\t((SELECT COUNT(*) FROM {$referrals_table} WHERE affiliate_id = h.affiliate_id {$date_condition} {$status_condition} )/COUNT(DISTINCT ip)) ratio\n\t\t\tFROM {$hits_table} h\n\t\t\tLEFT JOIN {$affiliates_table} a ON h.affiliate_id = a.affiliate_id\n\t\t\t{$filters}\n\t\t\tGROUP BY h.affiliate_id\n\t\t\tORDER BY {$orderby} {$order}\n\t\t\tLIMIT {$row_count} OFFSET {$offset}\n\t\t\t", $filter_params);
    $results = $wpdb->get_results($query, OBJECT);
    $column_display_names = array('name' => __('Affiliate', AFFILIATES_PLUGIN_DOMAIN), 'visits' => __('Visitors', AFFILIATES_PLUGIN_DOMAIN), 'hits' => __('Hits', AFFILIATES_PLUGIN_DOMAIN), 'referrals' => __('Referrals', AFFILIATES_PLUGIN_DOMAIN), 'ratio' => __('Ratio', AFFILIATES_PLUGIN_DOMAIN));
    $output .= '<div id="" class="hits-affiliates-overview">';
    $affiliates = affiliates_get_affiliates(true, !$show_inoperative);
    $affiliates_select = '';
    if (!empty($affiliates)) {
        $affiliates_select .= '<label class="affiliate-id-filter">';
        $affiliates_select .= __('Affiliate', AFFILIATES_PLUGIN_DOMAIN);
        $affiliates_select .= ' ';
        $affiliates_select .= '<select class="affiliate-id-filter" name="affiliate_id">';
        $affiliates_select .= '<option value="">--</option>';
        foreach ($affiliates as $affiliate) {
            if ($affiliate_id == $affiliate['affiliate_id']) {
                $selected = ' selected="selected" ';
            } else {
                $selected = '';
            }
            $affiliates_select .= '<option ' . $selected . ' value="' . esc_attr($affiliate['affiliate_id']) . '">' . esc_attr(stripslashes($affiliate['name'])) . '</option>';
        }
        $affiliates_select .= '</select>';
        $affiliates_select .= '</label>';
    }
    $status_descriptions = array(AFFILIATES_REFERRAL_STATUS_ACCEPTED => __('Accepted', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_CLOSED => __('Closed', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_PENDING => __('Pending', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_REJECTED => __('Rejected', AFFILIATES_PLUGIN_DOMAIN));
    $status_icons = array(AFFILIATES_REFERRAL_STATUS_ACCEPTED => "<img class='icon' alt='" . __('Accepted', AFFILIATES_PLUGIN_DOMAIN) . "' src='" . AFFILIATES_PLUGIN_URL . "images/accepted.png'/>", AFFILIATES_REFERRAL_STATUS_CLOSED => "<img class='icon' alt='" . __('Closed', AFFILIATES_PLUGIN_DOMAIN) . "' src='" . AFFILIATES_PLUGIN_URL . "images/closed.png'/>", AFFILIATES_REFERRAL_STATUS_PENDING => "<img class='icon' alt='" . __('Pending', AFFILIATES_PLUGIN_DOMAIN) . "' src='" . AFFILIATES_PLUGIN_URL . "images/pending.png'/>", AFFILIATES_REFERRAL_STATUS_REJECTED => "<img class='icon' alt='" . __('Rejected', AFFILIATES_PLUGIN_DOMAIN) . "' src='" . AFFILIATES_PLUGIN_URL . "images/rejected.png'/>");
    $status_checkboxes = '';
    foreach ($status_descriptions as $key => $label) {
        $checked = empty($status) || is_array($status) && in_array($key, $status) ? ' checked="checked" ' : '';
        $status_checkboxes .= '<label style="padding-right:1em;">';
        $status_checkboxes .= sprintf('<input type="checkbox" name="status[]" value="%s" %s />', esc_attr($key), $checked);
        $status_checkboxes .= $status_icons[$key] . ' ' . $label;
        $status_checkboxes .= '</label>';
    }
    $output .= '<div class="filters">' . '<label class="description" for="setfilters">' . __('Filters', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '<form id="setfilters" action="" method="post">' . '<div class="filter-section">' . $affiliates_select . '</div>' . '<div class="filter-section">' . '<label class="from-date-filter">' . __('From', AFFILIATES_PLUGIN_DOMAIN) . ' ' . '<input class="datefield from-date-filter" name="from_date" type="text" value="' . esc_attr($from_date) . '"/>' . '</label>' . ' ' . '<label class="thru-date-filter">' . __('Until', AFFILIATES_PLUGIN_DOMAIN) . ' ' . '<input class="datefield thru-date-filter" name="thru_date" type="text" class="datefield" value="' . esc_attr($thru_date) . '"/>' . '</label>' . '</div>' . '<div class="filter-section">' . '<span style="padding-right:1em">' . __('Status', AFFILIATES_PLUGIN_DOMAIN) . '</span>' . ' ' . $status_checkboxes . '</div>' . '<div class="filter-section">' . '<label class="expanded-filter">' . '<input class="expanded-filter" name="expanded_referrals" type="checkbox" ' . ($expanded_referrals ? 'checked="checked"' : '') . '/>' . ' ' . __('Expand referrals', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . ' ' . '<label class="expanded-filter">' . '<input class="expanded-filter" name="expanded_hits" type="checkbox" ' . ($expanded_hits ? 'checked="checked"' : '') . '/>' . ' ' . __('Expand hits', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . ' ' . '<label class="show-inoperative-filter">' . '<input class="show-inoperative-filter" name="show_inoperative" type="checkbox" ' . ($show_inoperative ? 'checked="checked"' : '') . '/>' . ' ' . __('Include inoperative affiliates', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</div>' . '<div class="filter-buttons">' . wp_nonce_field('admin', AFFILIATES_ADMIN_HITS_AFF_FILTER_NONCE, true, false) . '<input class="button" type="submit" value="' . __('Apply', AFFILIATES_PLUGIN_DOMAIN) . '"/>' . '<input class="button" type="submit" name="clear_filters" value="' . __('Clear', AFFILIATES_PLUGIN_DOMAIN) . '"/>' . '<input type="hidden" value="submitted" name="submitted"/>' . '</div>' . '</form>' . '</div>';
    $output .= '
		<div class="page-options">
			<form id="setrowcount" action="" method="post">
				<div>
					<label for="row_count">' . __('Results per page', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '<input name="row_count" type="text" size="2" value="' . esc_attr($row_count) . '" />
					' . wp_nonce_field('admin', AFFILIATES_ADMIN_HITS_AFF_NONCE_1, true, false) . '
					<input class="button" type="submit" value="' . __('Apply', AFFILIATES_PLUGIN_DOMAIN) . '"/>
				</div>
			</form>
		</div>
		';
    if ($paginate) {
        require_once AFFILIATES_CORE_LIB . '/class-affiliates-pagination.php';
        $pagination = new Affiliates_Pagination($count, null, $row_count);
        $output .= '<form id="posts-filter" method="post" action="">';
        $output .= '<div>';
        $output .= wp_nonce_field('admin', AFFILIATES_ADMIN_HITS_AFF_NONCE_2, true, false);
        $output .= '</div>';
        $output .= '<div class="tablenav top">';
        $output .= $pagination->pagination('top');
        $output .= '</div>';
        $output .= '</form>';
    }
    $output .= '
		<table id="" class="wp-list-table widefat fixed" cellspacing="0">
		<thead>
			<tr>
			';
    foreach ($column_display_names as $key => $column_display_name) {
        $options = array('orderby' => $key, 'order' => $switch_order);
        $class = "";
        if (strcmp($key, $orderby) == 0) {
            $lorder = strtolower($order);
            $class = "{$key} manage-column sorted {$lorder}";
        } else {
            $class = "{$key} manage-column sortable";
        }
        $column_display_name = '<a href="' . esc_url(add_query_arg($options, $current_url)) . '"><span>' . $column_display_name . '</span><span class="sorting-indicator"></span></a>';
        $output .= "<th scope='col' class='{$class}'>{$column_display_name}</th>";
    }
    $output .= '</tr>
		</thead>
		<tbody>
		';
    if (count($results) > 0) {
        for ($i = 0; $i < count($results); $i++) {
            $result = $results[$i];
            $output .= '<tr class=" ' . ($i % 2 == 0 ? 'even' : 'odd') . '">';
            $affiliate = affiliates_get_affiliate($result->affiliate_id);
            $output .= "<td class='affiliate-name'>" . stripslashes(wp_filter_nohtml_kses($affiliate['name'])) . "</td>";
            $output .= "<td class='visits'>{$result->visits}</td>";
            $output .= "<td class='hits'>{$result->hits}</td>";
            $output .= "<td class='referrals'>{$result->referrals}</td>";
            $output .= "<td class='ratio'>{$result->ratio}</td>";
            $output .= '</tr>';
            if ($expanded || $expanded_referrals || $expanded_hits) {
                //
                // expanded : referrals ----------------------------------------
                //
                if ($expanded_referrals) {
                    // get the detailed results for referrals
                    $referrals_filters = " WHERE r.affiliate_id = %d ";
                    $referrals_filter_params = array($result->affiliate_id);
                    if ($from_date && $thru_date) {
                        $referrals_filters .= " AND datetime >= %s AND datetime < %s ";
                        $referrals_filter_params[] = $from_datetime;
                        $referrals_filter_params[] = $thru_datetime;
                    } else {
                        if ($from_date) {
                            $referrals_filters .= " AND datetime >= %s ";
                            $referrals_filter_params[] = $from_datetime;
                        } else {
                            if ($thru_date) {
                                $referrals_filters .= " datetime < %s ";
                                $referrals_filter_params[] = $thru_datetime;
                            }
                        }
                    }
                    $referrals_orderby = "datetime {$order}";
                    $referrals_query = $wpdb->prepare("SELECT *\n\t\t\t\t\t\tFROM {$referrals_table} r\n\t\t\t\t\t\tLEFT JOIN {$affiliates_table} a ON r.affiliate_id = a.affiliate_id\n\t\t\t\t\t\t{$referrals_filters}\n\t\t\t\t\t\tORDER BY {$referrals_orderby}\n\t\t\t\t\t\t", $referrals_filter_params);
                    $referrals = $wpdb->get_results($referrals_query, OBJECT);
                    if (count($referrals) > 0) {
                        $output .= '<tr class=" ' . ($i % 2 == 0 ? 'even' : 'odd') . '">';
                        $output .= '<td colspan="5">';
                        $output .= '<div class="details-referrals">';
                        $output .= '<p class="description">' . __('Referrals', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
                        $output .= '
							<table id="details-referrals-' . esc_attr($result->date) . '" class="details-referrals" cellspacing="0">
							<thead>
							<tr>
							<th scope="col" class="datetime">' . __('Time', AFFILIATES_PLUGIN_DOMAIN) . '</th>
							<th scope="col" class="post-id">' . __('Post', AFFILIATES_PLUGIN_DOMAIN) . '</th>
							<th scope="col" class="affiliate-id">' . __('Affiliate', AFFILIATES_PLUGIN_DOMAIN) . '</th>
							</tr>
							</thead>
							<tbody>
							';
                        foreach ($referrals as $referral) {
                            $output .= '<tr class="details-referrals ' . ($i % 2 == 0 ? 'even' : 'odd') . '">';
                            $output .= "<td class='datetime'>" . DateHelper::s2u($referral->datetime) . "</td>";
                            $link = get_permalink($referral->post_id);
                            $title = get_the_title($referral->post_id);
                            $output .= '<td class="post-id"><a href="' . esc_attr($link) . '" target="_blank">' . stripslashes(wp_filter_nohtml_kses($title)) . '</a></td>';
                            $output .= "<td class='affiliate-id'>" . stripslashes(wp_filter_nohtml_kses($referral->name)) . "</td>";
                            $output .= '</tr>';
                        }
                        $output .= '</tbody></table>';
                        $output .= '</div>';
                        // .details-referrals
                        $output .= '</td></tr>';
                    }
                }
                // if $expanded_referrals
                //
                // expanded : hits ----------------------------------------
                //
                if ($expanded_hits) {
                    // get the detailed results for hits
                    $details_orderby = "date {$order}, time {$order}";
                    $details_filters = " WHERE h.affiliate_id = %d ";
                    $details_filter_params = array($result->affiliate_id);
                    if ($from_date && $thru_date) {
                        $details_filters .= " AND datetime >= %s AND datetime < %s ";
                        $details_filter_params[] = $from_datetime;
                        $details_filter_params[] = $thru_datetime;
                    } else {
                        if ($from_date) {
                            $details_filters .= " AND datetime >= %s ";
                            $details_filter_params[] = $from_datetime;
                        } else {
                            if ($thru_date) {
                                $details_filters .= " datetime < %s ";
                                $details_filter_params[] = $thru_datetime;
                            }
                        }
                    }
                    $details_query = $wpdb->prepare("SELECT *\n\t\t\t\t\t\tFROM {$hits_table} h\n\t\t\t\t\t\tLEFT JOIN {$affiliates_table} a ON h.affiliate_id = a.affiliate_id\n\t\t\t\t\t\t{$details_filters}\n\t\t\t\t\t\tORDER BY {$details_orderby}\n\t\t\t\t\t\t", $details_filter_params);
                    $hits = $wpdb->get_results($details_query, OBJECT);
                    $output .= '<tr class=" ' . ($i % 2 == 0 ? 'even' : 'odd') . '">';
                    $output .= '<td colspan="5">';
                    $output .= '<div class="details-hits">';
                    $output .= '<p class="description">' . __('Hits', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
                    $output .= '
						<table id="details-hits-' . esc_attr($result->date) . '" class="details-hits" cellspacing="0">
						<thead>
						<tr>
						<th scope="col" class="date">' . __('Date', AFFILIATES_PLUGIN_DOMAIN) . '</th>
						<th scope="col" class="time">' . __('Time', AFFILIATES_PLUGIN_DOMAIN) . '</th>
						<th scope="col" class="ip">' . __('IP', AFFILIATES_PLUGIN_DOMAIN) . '</th>
						<th scope="col" class="count">' . __('Count', AFFILIATES_PLUGIN_DOMAIN) . '</th>
						<th scope="col" class="affiliate-id">' . __('Affiliate', AFFILIATES_PLUGIN_DOMAIN) . '</th>
						</tr>
						</thead>
						<tbody>
						';
                    foreach ($hits as $hit) {
                        $output .= '<tr class="details ' . ($i % 2 == 0 ? 'even' : 'odd') . '">';
                        //						$output .= "<td class='date'>$hit->date</td>";
                        $output .= '<td class="date">' . DateHelper::formatDate(DateHelper::s2u($hit->datetime)) . '</td>';
                        //						$output .= "<td class='time'>$hit->time</td>";
                        $output .= '<td class="time">' . DateHelper::formatTime(DateHelper::s2u($hit->datetime)) . '</td>';
                        $output .= "<td class='ip'>" . long2ip($hit->ip) . "</td>";
                        $output .= "<td class='count'>{$hit->count}</td>";
                        $output .= "<td class='affiliate-id'>" . stripslashes(wp_filter_nohtml_kses($hit->name)) . "</td>";
                        $output .= '</tr>';
                    }
                    $output .= '</tbody></table>';
                    $output .= '</div>';
                    // .details-hits
                    $output .= '</td></tr>';
                }
                // if $expanded_hits
            }
            // expanded
        }
    } else {
        $output .= '<tr><td colspan="5">' . __('There are no results.', AFFILIATES_PLUGIN_DOMAIN) . '</td></tr>';
    }
    $output .= '</tbody>';
    $output .= '</table>';
    if ($paginate) {
        require_once AFFILIATES_CORE_LIB . '/class-affiliates-pagination.php';
        $pagination = new Affiliates_Pagination($count, null, $row_count);
        $output .= '<div class="tablenav bottom">';
        $output .= $pagination->pagination('bottom');
        $output .= '</div>';
    }
    $output .= '</div>';
    // .visits-overview
    echo $output;
    affiliates_footer();
}
 public static function update_status($new_status, $params = null)
 {
     global $wpdb;
     $output = "";
     $from_date = isset($params['from_date']) ? $params['from_date'] : null;
     $from_datetime = $from_date ? DateHelper::u2s($from_date) : null;
     $thru_date = isset($params['thru_date']) ? $params['thru_date'] : null;
     $thru_datetime = $thru_date ? DateHelper::u2s($thru_date, 24 * 3600) : null;
     $referral_status = isset($params['referral_status']) ? Affiliates_Utility::verify_referral_status_transition($params['referral_status'], $params['referral_status']) : null;
     $currency_id = isset($params['currency_id']) ? Affiliates_Utility::verify_currency_id($params['currency_id']) : null;
     $orderby = isset($params['orderby']) ? $params['orderby'] : null;
     $order = isset($params['order']) ? $params['order'] : null;
     switch ($orderby) {
         case 'affiliate_id':
         case 'name':
         case 'email':
             $orderby = 'a.' . $orderby;
             break;
         case 'user_login':
             $orderby = 'au.' . $orderby;
             break;
         case 'currency_id':
             $orderby = 'r.' . $orderby;
             break;
         default:
             $orderby = 'a.name';
     }
     switch ($order) {
         case 'asc':
         case 'ASC':
         case 'desc':
         case 'DESC':
             break;
         default:
             $order = 'ASC';
     }
     if (isset($params['tables'])) {
         $output .= "<h1>" . __("Closing referrals", AFFILIATES_PLUGIN_DOMAIN) . "</h1>";
         $output .= "<div class='closing-referrals-overview'>";
         $affiliates_table = $params['tables']['affiliates'];
         $affiliates_users_table = $params['tables']['affiliates_users'];
         $referrals_table = $params['tables']['referrals'];
         $users_table = $params['tables']['users'];
         $filters = array(" 1=%d ");
         $filter_params = array(1);
         if ($from_datetime && $thru_datetime) {
             $filters[] = " r.datetime >= %s AND r.datetime < %s ";
             $filter_params[] = $from_datetime;
             $filter_params[] = $thru_datetime;
         } else {
             if ($from_datetime) {
                 $filters[] = " r.datetime >= %s ";
                 $filter_params[] = $from_datetime;
             } else {
                 if ($thru_datetime) {
                     $filters[] = " r.datetime < %s ";
                     $filter_params[] = $thru_datetime;
                 }
             }
         }
         if ($referral_status) {
             $filters[] = " r.status = %s ";
             $filter_params[] = $referral_status;
         }
         if ($currency_id) {
             $filters[] = " r.currency_id = %s ";
             $filter_params[] = $currency_id;
         }
         if (!empty($filters)) {
             $filters = " WHERE " . implode(" AND ", $filters);
         } else {
             $filters = '';
         }
         $order_by = '';
         if ($orderby && $order) {
             $order_by .= " ORDER BY {$orderby} {$order} ";
         }
         $step = isset($params['step']) ? intval($params['step']) : 1;
         switch ($step) {
             case 1:
                 $results = $wpdb->get_results($wpdb->prepare("\n\t\t\t\t\t\tSELECT a.*, r.*, u.user_login\n\t\t\t\t\t\tFROM {$referrals_table} r\n\t\t\t\t\t\tLEFT JOIN {$affiliates_table} a ON r.affiliate_id = a.affiliate_id\n\t\t\t\t\t\tLEFT JOIN {$affiliates_users_table} au ON a.affiliate_id = au.affiliate_id\n\t\t\t\t\t\tLEFT JOIN {$users_table} u on au.user_id = u.ID\n\t\t\t\t\t\t{$filters}\n\t\t\t\t\t\t{$order_by}\n\t\t\t\t\t\t", $filter_params));
                 $output .= "<div class='manage'>";
                 $output .= "<div class='warning'>";
                 $output .= "<p>";
                 $output .= "<strong>";
                 $output .= __("Please review the list of referrals that will be <em>closed</em>.", AFFILIATES_PLUGIN_DOMAIN);
                 $output .= "</strong>";
                 $output .= "</p>";
                 $output .= "</div>";
                 // .warning
                 $output .= "<p>";
                 $output .= __("Usually only referrals that are <em>accepted</em> and have been paid out should be <em>closed</em>. If there are unwanted or too many referrals shown, restrict your filter settings.", AFFILIATES_PLUGIN_DOMAIN);
                 $output .= "</p>";
                 $output .= "<p>";
                 $output .= __("If these referrals can be closed, click the confirmation button below.", AFFILIATES_PLUGIN_DOMAIN);
                 $output .= "</p>";
                 $output .= "</div>";
                 $output .= '<div id="referrals-overview" class="referrals-overview">';
                 $output .= self::render_results($results);
                 $output .= '</div>';
                 // .referrals-overview
                 if (count($results > 0)) {
                     $mp_params = "";
                     if (!empty($from_date)) {
                         $mp_params .= "&from_date=" . urlencode($from_date);
                     }
                     if (!empty($thru_date)) {
                         $mp_params .= "&thru_date=" . urlencode($thru_date);
                     }
                     if (!empty($referral_status)) {
                         $mp_params .= "&referral_status=" . urlencode($referral_status);
                     }
                     if (!empty($currency_id)) {
                         $mp_params .= "&currency_id=" . urlencode($currency_id);
                     }
                     if (!empty($orderby)) {
                         $mp_params .= "&orderby=" . urlencode($orderby);
                     }
                     if (!empty($order)) {
                         $mp_params .= "&order=" . urlencode($order);
                     }
                     $output .= '<div class="manage confirm">';
                     $current_url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                     $current_url = remove_query_arg('paged', $current_url);
                     $current_url = remove_query_arg('action', $current_url);
                     $current_url = remove_query_arg('affiliate_id', $current_url);
                     $output .= '<style type="text/css">';
                     $output .= '.close-referrals img, .close-referrals .label { vertical-align: middle; }';
                     $output .= '</style>';
                     $output .= "<p>";
                     $output .= __("Close these referrals by clicking:", AFFILIATES_PLUGIN_DOMAIN);
                     $output .= "</p>";
                     $output .= "<a title='" . __('Click to close these referrals', AFFILIATES_PLUGIN_DOMAIN) . "' " . "class='close-referrals button' " . "href='" . esc_url($current_url) . "&action=close_referrals&step=2" . $mp_params . "'>" . "<img class='icon' alt='" . __('Close referrals', AFFILIATES_PLUGIN_DOMAIN) . "' src='" . AFFILIATES_PLUGIN_URL . "images/closed.png'/>" . "<span class='label'>" . __('Close Referrals', AFFILIATES_PLUGIN_DOMAIN) . "</span>" . "</a>";
                     $output .= "<div class='warning'>";
                     $output .= "<p>";
                     $output .= "<strong>";
                     $output .= __("This action can not be undone*.", AFFILIATES_PLUGIN_DOMAIN);
                     $output .= "</strong>";
                     $output .= "</p>";
                     $output .= "<p>";
                     $output .= "<span style='font-size:0.8em;'>";
                     $output .= __("*To undo, each referral would have to be set to the desired status individually.", AFFILIATES_PLUGIN_DOMAIN);
                     $output .= "</span>";
                     $output .= "</p>";
                     $output .= "</div>";
                     // .warning
                     $output .= '</div>';
                     // .manage.confirm
                 }
                 break;
                 // step 1 - ask for confirmation confirmation
             // step 1 - ask for confirmation confirmation
             case 2:
                 // try to make the changes
                 $results = $wpdb->get_results($wpdb->prepare("\n\t\t\t\t\t\tSELECT a.*, r.*, u.user_login\n\t\t\t\t\t\tFROM {$referrals_table} r\n\t\t\t\t\t\tLEFT JOIN {$affiliates_table} a ON r.affiliate_id = a.affiliate_id\n\t\t\t\t\t\tLEFT JOIN {$affiliates_users_table} au ON a.affiliate_id = au.affiliate_id\n\t\t\t\t\t\tLEFT JOIN {$users_table} u on au.user_id = u.ID\n\t\t\t\t\t\t{$filters}\n\t\t\t\t\t\t{$order_by}\n\t\t\t\t\t\t", $filter_params));
                 $updated = array();
                 $omitted = array();
                 $failed = array();
                 foreach ($results as $result) {
                     if ($s = Affiliates_Utility::verify_referral_status_transition($result->status, $new_status)) {
                         if ($wpdb->query($wpdb->prepare("UPDATE {$referrals_table} SET status = %s WHERE affiliate_id = %d AND post_id = %d AND datetime = %s ", $s, $result->affiliate_id, $result->post_id, $result->datetime))) {
                             $result->status = $s;
                             $updated[] = $result;
                         } else {
                             $failed[] = $result;
                         }
                     } else {
                         $omitted[] = $result;
                     }
                 }
                 // always show at least the updated table because this will
                 // also give information if no results have been updated
                 $status_descriptions = array(AFFILIATES_REFERRAL_STATUS_ACCEPTED => __('Accepted', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_CLOSED => __('Closed', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_PENDING => __('Pending', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_REJECTED => __('Rejected', AFFILIATES_PLUGIN_DOMAIN));
                 $output .= "<h2>" . __("Updated", AFFILIATES_PLUGIN_DOMAIN) . "</h2>";
                 $output .= "<p>";
                 $output .= sprintf(__("These referrals have been updated to <em>%s</em>.", AFFILIATES_PLUGIN_DOMAIN), isset($status_descriptions[$new_status]) ? $status_descriptions[$new_status] : $new_status);
                 $output .= "</p>";
                 $output .= self::render_results($updated);
                 if (count($omitted) > 0) {
                     $output .= "<h2>" . __("Omitted", AFFILIATES_PLUGIN_DOMAIN) . "</h2>";
                     $output .= "<p>";
                     $output .= sprintf(__("These referrals have been omitted because their status must not be changed to <em>%s</em>.", AFFILIATES_PLUGIN_DOMAIN), isset($status_descriptions[$new_status]) ? $status_descriptions[$new_status] : $new_status);
                     $output .= "</p>";
                     $output .= self::render_results($omitted);
                 }
                 if (count($failed) > 0) {
                     $output .= "<h2>" . __("Failed", AFFILIATES_PLUGIN_DOMAIN) . "</h2>";
                     $output .= "<p>";
                     $output .= sprintf(__("These referrals could not be updated to <em>%s</em>.", AFFILIATES_PLUGIN_DOMAIN), isset($status_descriptions[$new_status]) ? $status_descriptions[$new_status] : $new_status);
                     $output .= "</p>";
                     $output .= self::render_results($failed);
                 }
                 break;
                 // step 2 -commit changes
         }
         $output .= "</div>";
         // .closing-referrals-overview
     }
     return $output;
 }
/**
 * Referrals screen.
 */
function affiliates_admin_referrals()
{
    global $wpdb, $affiliates_options;
    $output = '';
    if (!current_user_can(AFFILIATES_ACCESS_AFFILIATES)) {
        wp_die(__('Access denied.', AFFILIATES_PLUGIN_DOMAIN));
    }
    // $_GET actions
    if (isset($_GET['action'])) {
        switch ($_GET['action']) {
            case 'edit':
                require_once AFFILIATES_CORE_LIB . '/affiliates-admin-referral-edit.php';
                if (isset($_GET['referral_id'])) {
                    return affiliates_admin_referral_edit(intval($_GET['referral_id']));
                } else {
                    return affiliates_admin_referral_edit();
                }
                break;
            case 'remove':
                if (isset($_GET['referral_id'])) {
                    require_once AFFILIATES_CORE_LIB . '/affiliates-admin-referral-remove.php';
                    return affiliates_admin_referral_remove($_GET['referral_id']);
                }
                break;
        }
    }
    if (isset($_POST['from_date']) || isset($_POST['thru_date']) || isset($_POST['clear_filters']) || isset($_POST['affiliate_id']) || isset($_POST['status']) || isset($_POST['search']) || isset($_POST['expanded']) || isset($_POST['expanded_data']) || isset($_POST['expanded_description']) || isset($_POST['show_inoperative'])) {
        if (!wp_verify_nonce($_POST[AFFILIATES_ADMIN_HITS_FILTER_NONCE], 'admin')) {
            wp_die(__('Access denied.', AFFILIATES_PLUGIN_DOMAIN));
        }
    }
    $affiliates_table = _affiliates_get_tablename('affiliates');
    $referrals_table = _affiliates_get_tablename('referrals');
    $hits_table = _affiliates_get_tablename('hits');
    $posts_table = $wpdb->prefix . 'posts';
    // actions
    if (isset($_POST['affiliate_id']) && isset($_POST['post_id']) && isset($_POST['datetime']) && isset($_POST['action'])) {
        if (isset($_POST['status'])) {
            $referral = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$referrals_table} WHERE affiliate_id = %d AND post_id = %d AND datetime = %s", intval($_POST['affiliate_id']), intval($_POST['post_id']), $_POST['datetime']));
            if ($referral) {
                if (Affiliates_Utility::verify_referral_status_transition($referral->status, $_POST['status'])) {
                    $wpdb->query($wpdb->prepare("UPDATE {$referrals_table} SET status = %s WHERE affiliate_id = %d AND post_id = %d AND datetime = %s AND status = %s", $_POST['status'], intval($referral->affiliate_id), intval($referral->post_id), $referral->datetime, $referral->status));
                }
            }
        }
    }
    // filters
    $from_date = $affiliates_options->get_option('referrals_from_date', null);
    $thru_date = $affiliates_options->get_option('referrals_thru_date', null);
    $affiliate_id = $affiliates_options->get_option('referrals_affiliate_id', null);
    $status = $affiliates_options->get_option('referrals_status', null);
    $search = $affiliates_options->get_option('referrals_search', null);
    $search_description = $affiliates_options->get_option('referrals_search_description', null);
    $expanded = $affiliates_options->get_option('referrals_expanded', null);
    $expanded_description = $affiliates_options->get_option('referrals_expanded_description', null);
    $expanded_data = $affiliates_options->get_option('referrals_expanded_data', null);
    $show_inoperative = $affiliates_options->get_option('referrals_show_inoperative', null);
    if (!isset($_POST['action']) && isset($_POST['clear_filters'])) {
        $affiliates_options->delete_option('referrals_from_date');
        $affiliates_options->delete_option('referrals_thru_date');
        $affiliates_options->delete_option('referrals_affiliate_id');
        $affiliates_options->delete_option('referrals_status');
        $affiliates_options->delete_option('referrals_search');
        $affiliates_options->delete_option('referrals_expanded');
        $affiliates_options->delete_option('referrals_expanded_description');
        $affiliates_options->delete_option('referrals_expanded_data');
        $affiliates_options->delete_option('referrals_show_inoperative');
        $from_date = null;
        $thru_date = null;
        $affiliate_id = null;
        $status = null;
        $search = null;
        $search_description = null;
        $expanded = null;
        $expanded_data = null;
        $expanded_description = null;
        $show_inoperative = null;
    } else {
        if (!isset($_POST['action']) && isset($_POST['submitted'])) {
            // filter by date(s)
            if (!empty($_POST['from_date'])) {
                $from_date = date('Y-m-d', strtotime($_POST['from_date']));
                $affiliates_options->update_option('referrals_from_date', $from_date);
            } else {
                $from_date = null;
                $affiliates_options->delete_option('referrals_from_date');
            }
            if (!empty($_POST['thru_date'])) {
                $thru_date = date('Y-m-d', strtotime($_POST['thru_date']));
                $affiliates_options->update_option('referrals_thru_date', $thru_date);
            } else {
                $thru_date = null;
                $affiliates_options->delete_option('referrals_thru_date');
            }
            if ($from_date && $thru_date) {
                if (strtotime($from_date) > strtotime($thru_date)) {
                    $thru_date = null;
                    $affiliates_options->delete_option('referrals_thru_date');
                }
            }
            // filter by affiliate id
            if (!empty($_POST['affiliate_id'])) {
                $affiliate_id = affiliates_check_affiliate_id($_POST['affiliate_id']);
                if ($affiliate_id) {
                    $affiliates_options->update_option('referrals_affiliate_id', $affiliate_id);
                }
            } else {
                if (isset($_POST['affiliate_id'])) {
                    // empty && isset => '' => all
                    $affiliate_id = null;
                    $affiliates_options->delete_option('referrals_affiliate_id');
                }
            }
            if (!empty($_POST['status'])) {
                if ($status = Affiliates_Utility::verify_referral_status_transition($_POST['status'], $_POST['status'])) {
                    $affiliates_options->update_option('referrals_status', $status);
                } else {
                    $status = null;
                    $affiliates_options->delete_option('referrals_status');
                }
            } else {
                $status = null;
                $affiliates_options->delete_option('referrals_status');
            }
            if (!empty($_POST['search'])) {
                $search = $_POST['search'];
                $affiliates_options->update_option('referrals_search', $_POST['search']);
            } else {
                $search = null;
                $affiliates_options->delete_option('referrals_search');
            }
            if (!empty($_POST['search_description'])) {
                $search_description = true;
                $affiliates_options->update_option('referrals_search_description', true);
            } else {
                $search_description = false;
                $affiliates_options->delete_option('referrals_search_description');
            }
            // expanded details?
            if (!empty($_POST['expanded'])) {
                $expanded = true;
                $affiliates_options->update_option('referrals_expanded', true);
            } else {
                $expanded = false;
                $affiliates_options->delete_option('referrals_expanded');
            }
            if (!empty($_POST['expanded_data'])) {
                $expanded_data = true;
                $affiliates_options->update_option('referrals_expanded_data', true);
            } else {
                $expanded_data = false;
                $affiliates_options->delete_option('referrals_expanded_data');
            }
            if (!empty($_POST['expanded_description'])) {
                $expanded_description = true;
                $affiliates_options->update_option('referrals_expanded_description', true);
            } else {
                $expanded_description = false;
                $affiliates_options->delete_option('referrals_expanded_description');
            }
            if (!empty($_POST['show_inoperative'])) {
                $show_inoperative = true;
                $affiliates_options->update_option('referrals_show_inoperative', true);
            } else {
                $show_inoperative = false;
                $affiliates_options->delete_option('referrals_show_inoperative');
            }
        }
    }
    if (isset($_POST['row_count'])) {
        if (!wp_verify_nonce($_POST[AFFILIATES_ADMIN_HITS_NONCE_1], 'admin')) {
            wp_die(__('Access denied.', AFFILIATES_PLUGIN_DOMAIN));
        }
    }
    if (isset($_POST['paged'])) {
        if (!wp_verify_nonce($_POST[AFFILIATES_ADMIN_HITS_NONCE_2], 'admin')) {
            wp_die(__('Access denied.', AFFILIATES_PLUGIN_DOMAIN));
        }
    }
    $current_url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $current_url = remove_query_arg('paged', $current_url);
    $output .= '<div>' . '<h2>' . __('Referrals', AFFILIATES_PLUGIN_DOMAIN) . '</h2>' . '</div>';
    $output .= '<div class="manage add">';
    $output .= sprintf('<a title="%s" class="add button" href="%s"><img class="icon" alt="%s" src="%s" /><span class="label">%s</span></a>', __('Click to add a referral manually', AFFILIATES_PLUGIN_DOMAIN), esc_url(add_query_arg('action', 'edit', $current_url)), __('Add', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_PLUGIN_URL . 'images/add.png', __('Add', AFFILIATES_PLUGIN_DOMAIN));
    $output .= '</div>';
    $row_count = isset($_POST['row_count']) ? intval($_POST['row_count']) : 0;
    if ($row_count <= 0) {
        $row_count = $affiliates_options->get_option('referrals_per_page', AFFILIATES_HITS_PER_PAGE);
    } else {
        $affiliates_options->update_option('referrals_per_page', $row_count);
    }
    $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
    if ($offset < 0) {
        $offset = 0;
    }
    $paged = isset($_GET['paged']) ? intval($_GET['paged']) : 0;
    if ($paged < 0) {
        $paged = 0;
    }
    $orderby = isset($_GET['orderby']) ? $_GET['orderby'] : null;
    switch ($orderby) {
        case 'datetime':
        case 'name':
        case 'post_title':
        case 'amount':
        case 'currency_id':
        case 'status':
            break;
        default:
            $orderby = 'datetime';
    }
    $order = isset($_GET['order']) ? $_GET['order'] : null;
    switch ($order) {
        case 'asc':
        case 'ASC':
            $switch_order = 'DESC';
            break;
        case 'desc':
        case 'DESC':
            $switch_order = 'ASC';
            break;
        default:
            $order = 'DESC';
            $switch_order = 'ASC';
    }
    if ($from_date || $thru_date || $affiliate_id || $status || $search) {
        $filters = " WHERE ";
    } else {
        $filters = '';
    }
    $filter_params = array();
    // We have the desired dates from the user's point of view, i.e. in her timezone.
    // If supported, adjust the dates for the site's timezone:
    if ($from_date) {
        $from_datetime = DateHelper::u2s($from_date);
    }
    if ($thru_date) {
        $thru_datetime = DateHelper::u2s($thru_date, 24 * 3600);
    }
    if ($from_date && $thru_date) {
        $filters .= " datetime >= %s AND datetime < %s ";
        $filter_params[] = $from_datetime;
        $filter_params[] = $thru_datetime;
    } else {
        if ($from_date) {
            $filters .= " datetime >= %s ";
            $filter_params[] = $from_datetime;
        } else {
            if ($thru_date) {
                $filters .= " datetime < %s ";
                $filter_params[] = $thru_datetime;
            }
        }
    }
    if ($affiliate_id) {
        if ($from_date || $thru_date) {
            $filters .= " AND ";
        }
        $filters .= " r.affiliate_id = %d ";
        $filter_params[] = $affiliate_id;
    }
    if ($status) {
        if ($from_date || $thru_date || $affiliate_id) {
            $filters .= " AND ";
        }
        $filters .= " r.status = %s ";
        $filter_params[] = $status;
    }
    if ($search) {
        if ($from_date || $thru_date || $affiliate_id || $status) {
            $filters .= " AND ";
        }
        if ($search_description) {
            $filters .= " ( r.data LIKE '%%%s%%' OR r.description LIKE '%%%s%%' ) ";
            $filter_params[] = $search;
            $filter_params[] = $search;
        } else {
            $filters .= " r.data LIKE '%%%s%%' ";
            $filter_params[] = $search;
        }
    }
    // how many are there ?
    $count_query = $wpdb->prepare("SELECT count(*) FROM {$referrals_table} r\n\t\t{$filters}\n\t\t", $filter_params);
    $count = $wpdb->get_var($count_query);
    if ($count > $row_count) {
        $paginate = true;
    } else {
        $paginate = false;
    }
    $pages = ceil($count / $row_count);
    if ($paged > $pages) {
        $paged = $pages;
    }
    if ($paged != 0) {
        $offset = ($paged - 1) * $row_count;
    }
    $query = $wpdb->prepare("\n\t\tSELECT r.*, a.affiliate_id, a.name \n\t\tFROM {$referrals_table} r\n\t\tLEFT JOIN {$affiliates_table} a ON r.affiliate_id = a.affiliate_id\n\t\tLEFT JOIN {$posts_table} p ON r.post_id = p.ID\n\t\t{$filters}\n\t\tORDER BY {$orderby} {$order}\n\t\tLIMIT {$row_count} OFFSET {$offset}\n\t\t", $filter_params + $filter_params);
    $results = $wpdb->get_results($query, OBJECT);
    $column_display_names = array('datetime' => __('Date', AFFILIATES_PLUGIN_DOMAIN), 'post_title' => __('Post', AFFILIATES_PLUGIN_DOMAIN), 'name' => __('Affiliate', AFFILIATES_PLUGIN_DOMAIN), 'amount' => __('Amount', AFFILIATES_PLUGIN_DOMAIN), 'currency_id' => __('Currency', AFFILIATES_PLUGIN_DOMAIN), 'status' => __('Status', AFFILIATES_PLUGIN_DOMAIN), 'edit' => __('', AFFILIATES_PLUGIN_DOMAIN), 'remove' => __('', AFFILIATES_PLUGIN_DOMAIN));
    $column_count = count($column_display_names);
    $output .= '<div id="referrals-overview" class="referrals-overview">';
    $affiliates = affiliates_get_affiliates(true, !$show_inoperative);
    $affiliates_select = '';
    if (!empty($affiliates)) {
        $affiliates_select .= '<label class="affiliate-id-filter" for="affiliate_id">' . __('Affiliate', AFFILIATES_PLUGIN_DOMAIN) . '</label>';
        $affiliates_select .= '<select class="affiliate-id-filter" name="affiliate_id">';
        $affiliates_select .= '<option value="">--</option>';
        foreach ($affiliates as $affiliate) {
            if ($affiliate_id == $affiliate['affiliate_id']) {
                $selected = ' selected="selected" ';
            } else {
                $selected = '';
            }
            $affiliates_select .= '<option ' . $selected . ' value="' . esc_attr($affiliate['affiliate_id']) . '">' . esc_attr(stripslashes($affiliate['name'])) . '</option>';
        }
        $affiliates_select .= '</select>';
    }
    $status_descriptions = array(AFFILIATES_REFERRAL_STATUS_ACCEPTED => __('Accepted', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_CLOSED => __('Closed', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_PENDING => __('Pending', AFFILIATES_PLUGIN_DOMAIN), AFFILIATES_REFERRAL_STATUS_REJECTED => __('Rejected', AFFILIATES_PLUGIN_DOMAIN));
    $status_icons = array(AFFILIATES_REFERRAL_STATUS_ACCEPTED => "<img class='icon' alt='" . __('Accepted', AFFILIATES_PLUGIN_DOMAIN) . "' src='" . AFFILIATES_PLUGIN_URL . "images/accepted.png'/>", AFFILIATES_REFERRAL_STATUS_CLOSED => "<img class='icon' alt='" . __('Closed', AFFILIATES_PLUGIN_DOMAIN) . "' src='" . AFFILIATES_PLUGIN_URL . "images/closed.png'/>", AFFILIATES_REFERRAL_STATUS_PENDING => "<img class='icon' alt='" . __('Pending', AFFILIATES_PLUGIN_DOMAIN) . "' src='" . AFFILIATES_PLUGIN_URL . "images/pending.png'/>", AFFILIATES_REFERRAL_STATUS_REJECTED => "<img class='icon' alt='" . __('Rejected', AFFILIATES_PLUGIN_DOMAIN) . "' src='" . AFFILIATES_PLUGIN_URL . "images/rejected.png'/>");
    $status_select = '<label class="status-filter" for="status">' . __('Status', AFFILIATES_PLUGIN_DOMAIN) . '</label>';
    $status_select .= '<select name="status">';
    $status_select .= '<option value="" ' . (empty($status) ? ' selected="selected" ' : '') . '>--</option>';
    foreach ($status_descriptions as $key => $label) {
        $selected = $key == $status ? ' selected="selected" ' : '';
        $status_select .= '<option ' . $selected . ' value="' . esc_attr($key) . '">' . $label . '</option>';
    }
    $status_select .= '</select>';
    $output .= '<div class="filters">' . '<label class="description" for="setfilters">' . __('Filters', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '<form id="setfilters" action="" method="post">' . '<p>' . $affiliates_select . $status_select . ' <label class="search-filter" for="search" title="Search in data">' . __('Search', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . ' <input class="search-filter" name="search" type="text" value="' . esc_attr($search) . '"/>' . ' ' . sprintf('<label class="search-description-filter" title="%s">', __('Also search in descriptions', AFFILIATES_PLUGIN_DOMAIN)) . '<input class="search-description-filter" name="search_description" type="checkbox" ' . ($search_description ? 'checked="checked"' : '') . '/>' . ' ' . __('Descriptions', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '</p>
				<p>' . '<label class="from-date-filter" for="from_date">' . __('From', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '<input class="datefield from-date-filter" name="from_date" type="text" value="' . esc_attr($from_date) . '"/>' . '<label class="thru-date-filter" for="thru_date">' . __('Until', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '<input class="datefield thru-date-filter" name="thru_date" type="text" class="datefield" value="' . esc_attr($thru_date) . '"/>' . '</p>
				<p>' . wp_nonce_field('admin', AFFILIATES_ADMIN_HITS_FILTER_NONCE, true, false) . '<input class="button" type="submit" value="' . __('Apply', AFFILIATES_PLUGIN_DOMAIN) . '"/>' . '<label class="expanded-filter">' . '<input class="expanded-filter" name="expanded" type="checkbox" ' . ($expanded ? 'checked="checked"' : '') . '/>' . ' ' . __('Expand details', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '<label class="expanded-filter">' . '<input class="expanded-filter" name="expanded_description" type="checkbox" ' . ($expanded_description ? 'checked="checked"' : '') . '/>' . ' ' . __('Expand descriptions', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '<label class="expanded-filter">' . '<input class="expanded-filter" name="expanded_data" type="checkbox" ' . ($expanded_data ? 'checked="checked"' : '') . '/>' . ' ' . __('Expand data', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '<label class="show-inoperative-filter">' . '<input class="show-inoperative-filter" name="show_inoperative" type="checkbox" ' . ($show_inoperative ? 'checked="checked"' : '') . '/>' . ' ' . __('Include inoperative affiliates', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '<input class="button" type="submit" name="clear_filters" value="' . __('Clear', AFFILIATES_PLUGIN_DOMAIN) . '"/>' . '<input type="hidden" value="submitted" name="submitted"/>' . '</p>' . '</form>' . '</div>';
    $output .= '
		<div class="page-options">
			<form id="setrowcount" action="" method="post">
				<div>
					<label for="row_count">' . __('Results per page', AFFILIATES_PLUGIN_DOMAIN) . '</label>' . '<input name="row_count" type="text" size="2" value="' . esc_attr($row_count) . '" />
					' . wp_nonce_field('admin', AFFILIATES_ADMIN_HITS_NONCE_1, true, false) . '
					<input class="button" type="submit" value="' . __('Apply', AFFILIATES_PLUGIN_DOMAIN) . '"/>
				</div>
			</form>
		</div>
		';
    if ($paginate) {
        require_once AFFILIATES_CORE_LIB . '/class-affiliates-pagination.php';
        $pagination = new Affiliates_Pagination($count, null, $row_count);
        $output .= '<form id="posts-filter" method="post" action="">';
        $output .= '<div>';
        $output .= wp_nonce_field('admin', AFFILIATES_ADMIN_HITS_NONCE_2, true, false);
        $output .= '</div>';
        $output .= '<div class="tablenav top">';
        $output .= $pagination->pagination('top');
        $output .= '</div>';
        $output .= '</form>';
    }
    $output .= '
		<table id="referrals" class="referrals wp-list-table widefat fixed" cellspacing="0">
		<thead>
			<tr>
			';
    foreach ($column_display_names as $key => $column_display_name) {
        $options = array('orderby' => $key, 'order' => $switch_order);
        $class = "";
        if (strcmp($key, $orderby) == 0) {
            $lorder = strtolower($order);
            $class = "{$key} manage-column sorted {$lorder}";
        } else {
            $class = "{$key} manage-column sortable";
        }
        $column_display_name = '<a href="' . esc_url(add_query_arg($options, $current_url)) . '"><span>' . $column_display_name . '</span><span class="sorting-indicator"></span></a>';
        $output .= "<th scope='col' class='{$class}'>{$column_display_name}</th>";
    }
    $output .= '</tr>
		</thead>
		<tbody>
		';
    if (count($results) > 0) {
        for ($i = 0; $i < count($results); $i++) {
            $result = $results[$i];
            $output .= '<tr class="details-referrals ' . ($i % 2 == 0 ? 'even' : 'odd') . '">';
            $output .= '<td class="datetime">' . DateHelper::s2u($result->datetime) . '</td>';
            $link = get_permalink($result->post_id);
            $title = get_the_title($result->post_id);
            $output .= '<td class="post_title"><a href="' . esc_attr($link) . '" target="_blank">' . wp_filter_nohtml_kses($title) . '</a></td>';
            $output .= "<td class='name'>" . stripslashes(wp_filter_nohtml_kses($result->name)) . "</td>";
            $output .= "<td class='amount'>" . stripslashes(wp_filter_nohtml_kses($result->amount)) . "</td>";
            $output .= "<td class='currency_id'>" . stripslashes(wp_filter_nohtml_kses($result->currency_id)) . "</td>";
            $output .= "<td class='status'>";
            $output .= isset($status_icons[$result->status]) ? $status_icons[$result->status] : '';
            $output .= "<form method='post' action=''>";
            $output .= "<div>";
            $output .= "<select name='status'>";
            foreach ($status_descriptions as $status_key => $status_value) {
                if ($status_key == $result->status) {
                    $selected = "selected='selected'";
                } else {
                    $selected = "";
                }
                $output .= "<option value='{$status_key}' {$selected}>{$status_value}</option>";
            }
            $output .= "</select>";
            $output .= '<input class="button" type="submit" value="' . __('Set', AFFILIATES_PLUGIN_DOMAIN) . '"/>';
            $output .= '<input name="affiliate_id" type="hidden" value="' . esc_attr($result->affiliate_id) . '"/>';
            $output .= '<input name="post_id" type="hidden" value="' . esc_attr($result->post_id) . '"/>';
            $output .= '<input name="datetime" type="hidden" value="' . esc_attr($result->datetime) . '"/>';
            $output .= '<input name="action" type="hidden" value="set_status"/>';
            $output .= wp_nonce_field('admin', AFFILIATES_ADMIN_HITS_FILTER_NONCE, true, false);
            $output .= "</div>";
            $output .= "</form>";
            $output .= "</td>";
            $output .= '<td class="edit">';
            $edit_url = add_query_arg('referral_id', $result->referral_id, add_query_arg('action', 'edit', $current_url));
            $output .= sprintf('<a href="%s">', esc_url(add_query_arg('paged', $paged, $edit_url)));
            $output .= sprintf('<img src="%s" alt="%s"/>', AFFILIATES_PLUGIN_URL . 'images/edit.png', __('Edit', AFFILIATES_PLUGIN_DOMAIN));
            $output .= '</a>';
            $output .= '</td>';
            $output .= '<td class="remove">';
            $remove_url = add_query_arg('referral_id', $result->referral_id, add_query_arg('action', 'remove', $current_url));
            $output .= sprintf('<a href="%s">', esc_url(add_query_arg('paged', $paged, $remove_url)));
            $output .= sprintf('<img src="%s" alt="%s"/>', AFFILIATES_PLUGIN_URL . 'images/remove.png', __('Remove', AFFILIATES_PLUGIN_DOMAIN));
            $output .= '</a>';
            $output .= '</td>';
            $output .= '</tr>';
            $data = $result->data;
            if (!empty($data) && $expanded) {
                if ($expanded_data) {
                    $data_view_style = '';
                    $expander = AFFILIATES_EXPANDER_RETRACT;
                } else {
                    $data_view_style = ' style="display:none;" ';
                    $expander = AFFILIATES_EXPANDER_EXPAND;
                }
                $data = unserialize($data);
                if ($data) {
                    $output .= '<tr class="data ' . ($i % 2 == 0 ? 'even' : 'odd') . '">';
                    $output .= "<td colspan='{$column_count}'>";
                    $output .= '<div class="view-toggle">';
                    $output .= "<div class='expander'>{$expander}</div>";
                    $output .= '<div class="view-toggle-label">' . __('Data', AFFILIATES_PLUGIN_DOMAIN) . '</div>';
                    $output .= "<div class='view' {$data_view_style}>";
                    $output .= '<table class="referral-data wp-list-table widefat fixed" cellspacing="0">';
                    if (is_array($data)) {
                        foreach ($data as $key => $info) {
                            $title = __($info['title'], $info['domain']);
                            $value = $info['value'];
                            $output .= "<tr id='referral-data-{$i}'>";
                            $output .= '<td class="referral-data-title">';
                            $output .= stripslashes(wp_filter_nohtml_kses($title));
                            $output .= '</td>';
                            $output .= '<td class="referral-data-value">';
                            // @todo revise
                            // $output .= wp_filter_nohtml_kses( $value );
                            $output .= stripslashes($value);
                            $output .= '</td>';
                            $output .= '</tr>';
                        }
                    } else {
                        $output .= "<tr id='referral-data-{$i}'>";
                        $output .= '<td class="referral-data-title">';
                        $output .= __('Data', AFFILIATES_PLUGIN_DOMAIN);
                        $output .= '</td>';
                        $output .= '<td class="referral-data-value">';
                        // @todo revise
                        //$output .= wp_filter_nohtml_kses( $data );
                        $output .= stripslashes($value);
                        $output .= '</td>';
                        $output .= '</tr>';
                    }
                    $output .= '</table>';
                    $output .= '</div>';
                    // .view
                    $output .= '</div>';
                    // .view-toggle
                    $output .= '</td>';
                    $output .= '</tr>';
                }
            }
            if (!empty($result->description) && $expanded) {
                if ($expanded_description) {
                    $description_view_style = '';
                    $expander = AFFILIATES_EXPANDER_RETRACT;
                } else {
                    $description_view_style = ' style="display:none;" ';
                    $expander = AFFILIATES_EXPANDER_EXPAND;
                }
                $output .= sprintf("<tr id='referral-description-%d' class='%s'>", $i, $i % 2 == 0 ? 'even' : 'odd') . '<td colspan="' . $column_count . '">' . '<div class="view-toggle">' . "<div class='expander'>{$expander}</div>" . '<div class="view-toggle-label">' . __('Description', AFFILIATES_PLUGIN_DOMAIN) . '</div>' . "<div class='view' {$description_view_style}>" . wp_filter_kses(addslashes($result->description)) . '</div>' . '</div>' . '</td>' . '</tr>';
            }
        }
    } else {
        $output .= '<tr><td colspan="' . $column_count . '">' . __('There are no results.', AFFILIATES_PLUGIN_DOMAIN) . '</td></tr>';
    }
    $output .= '</tbody>';
    $output .= '</table>';
    if ($paginate) {
        require_once AFFILIATES_CORE_LIB . '/class-affiliates-pagination.php';
        $pagination = new Affiliates_Pagination($count, null, $row_count);
        $output .= '<div class="tablenav bottom">';
        $output .= $pagination->pagination('bottom');
        $output .= '</div>';
    }
    $output .= '</div>';
    // .referrals-overview
    echo $output;
    affiliates_footer();
}
 /**
  * Registration form.
  * 
  * @see Affiliates_Registration::$defaults for accepted parameters
  * 
  * @param array $options form options
  * @return string rendered registration form
  */
 public static function render_form($options = array())
 {
     wp_enqueue_style('affiliates');
     self::$submit_button_label = __('Sign Up', AFFILIATES_PLUGIN_DOMAIN);
     $output = '';
     //
     // Existing affiliate
     //
     if ($is_affiliate = affiliates_user_is_affiliate()) {
         $output .= '<div class="affiliates-registration registered">';
         $output .= '<p>';
         $output .= __('You are already registered as an affiliate.', AFFILIATES_PLUGIN_DOMAIN);
         $output .= '</p>';
         if (isset($options['registered_profile_link_url'])) {
             $output .= '<p>';
             $output .= '<a href="' . esc_url($options['registered_profile_link_url']) . '">';
             if (isset($options['registered_profile_link_text'])) {
                 $output .= wp_filter_kses($options['registered_profile_link_text']);
             } else {
                 $output .= __('Access your profile', AFFILIATES_PLUGIN_DOMAIN);
             }
             $output .= '</a>';
             $output .= '</p>';
         }
         $output .= '</div>';
         return $output;
     }
     //
     // Registration closed
     //
     if (!get_option('aff_registration', get_option('users_can_register', false))) {
         $output .= '<p>' . __('Registration is currently closed.', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
         return $output;
     }
     require_once AFFILIATES_CORE_LIB . '/class-affiliates-settings.php';
     require_once AFFILIATES_CORE_LIB . '/class-affiliates-settings-registration.php';
     $registration_fields = Affiliates_Settings_Registration::get_fields();
     //
     // Gather user info
     //
     $user = null;
     if ($is_logged_in = is_user_logged_in()) {
         $user = wp_get_current_user();
         if (isset($registration_fields['first_name']) && $registration_fields['first_name']['enabled']) {
             $first_name = $user->first_name;
             $first_name = sanitize_user_field('first_name', $first_name, $user->ID, 'display');
             $registration_fields['first_name']['value'] = $first_name;
         }
         if (isset($registration_fields['last_name']) && $registration_fields['last_name']['enabled']) {
             $last_name = $user->last_name;
             $last_name = sanitize_user_field('last_name', $last_name, $user->ID, 'display');
             $registration_fields['last_name']['value'] = $last_name;
         }
         if (isset($registration_fields['user_login']) && $registration_fields['user_login']['enabled']) {
             $user_login = $user->user_login;
             $user_login = sanitize_user_field('user_login', $user_login, $user->ID, 'display');
             $registration_fields['user_login']['value'] = $user_login;
         }
         if (isset($registration_fields['user_email']) && $registration_fields['user_email']['enabled']) {
             $user_email = $user->user_email;
             $user_email = sanitize_user_field('email', $user_email, $user->ID, 'display');
             $registration_fields['user_email']['value'] = $user_email;
         }
         if (isset($registration_fields['user_url']) && $registration_fields['user_url']['enabled']) {
             $url = $user->user_url;
             $url = sanitize_user_field('user_url', $url, $user->ID, 'display');
             $registration_fields['user_url']['value'] = $url;
         }
     }
     $submit_name = 'affiliates-registration-submit';
     $nonce = 'affiliates-registration-nonce';
     $nonce_action = 'affiliates-registration';
     $send = false;
     $captcha = '';
     $error = false;
     if (!empty($_POST[$submit_name])) {
         if (!wp_verify_nonce($_POST[$nonce], $nonce_action)) {
             $error = true;
             // fail but don't give clues
         }
         $captcha = !empty($_POST[Affiliates_Utility::get_captcha_field_id()]) ? $_POST[Affiliates_Utility::get_captcha_field_id()] : null;
         if (!Affiliates_Utility::captcha_validates($captcha)) {
             $error = true;
             // dumbot
         }
         // gather field values
         foreach ($registration_fields as $name => $field) {
             if ($field['enabled']) {
                 $value = isset($_POST[$name]) ? $_POST[$name] : '';
                 $value = Affiliates_Utility::filter($value);
                 if ($field['required'] && empty($value)) {
                     $error = true;
                     $output .= '<div class="error">';
                     $output .= __('<strong>ERROR</strong>', AFFILIATES_PLUGIN_DOMAIN);
                     $output .= ' : ';
                     $output .= sprintf(__('Please fill out the field <em>%s</em>.', AFFILIATES_PLUGIN_DOMAIN), $field['label']);
                     $output .= '</div>';
                 }
                 $registration_fields[$name]['value'] = $value;
             }
         }
         $error = apply_filters('affiliates_registration_error_validate', $error);
         if (!$error) {
             $userdata = array();
             foreach ($registration_fields as $name => $field) {
                 if ($registration_fields[$name]['enabled']) {
                     $userdata[$name] = $registration_fields[$name]['value'];
                 }
             }
             // don't try to create a new user on multiple renderings
             global $affiliate_user_id, $new_affiliate_registered, $stored_affiliate;
             if (!isset($affiliate_user_id)) {
                 if (!$is_logged_in) {
                     // allow plugins to be aware of new user account being created
                     do_action('affiliates_before_register_affiliate', $userdata);
                     // create the affiliate user account
                     $affiliate_user_id = self::register_affiliate($userdata);
                     $new_affiliate_registered = true;
                     do_action('affiliates_after_register_affiliate', $userdata);
                 } else {
                     $affiliate_user_id = $user->ID;
                     $new_affiliate_registered = true;
                 }
             }
             // register as affiliate
             if (!is_wp_error($affiliate_user_id)) {
                 // add affiliate entry
                 $send = true;
                 if (!isset($stored_affiliate)) {
                     if ($new_affiliate_registered) {
                         $affiliate_id = self::store_affiliate($affiliate_user_id, $userdata);
                         // update user including meta
                         self::update_affiliate_user($affiliate_user_id, $userdata);
                         do_action('affiliates_stored_affiliate', $affiliate_id, $affiliate_user_id);
                     }
                     $stored_affiliate = true;
                 }
                 $is_widget = isset($options['is_widget']) && ($options['is_widget'] === true || $options['is_widget'] == 'true');
                 $redirect = isset($options['redirect']) && ($options['redirect'] === true || $options['redirect'] == 'true');
                 $redirect_url = empty($_REQUEST['redirect_to']) ? apply_filters('affiliates_registration_login_redirect_url', get_site_url(get_current_blog_id(), 'wp-login.php?checkemail=confirm')) : $_REQUEST['redirect_to'];
                 if ($redirect && !$is_widget && !headers_sent()) {
                     wp_safe_redirect($redirect_url);
                     exit;
                 } else {
                     $output .= '<p>' . __('Thanks for signing up!', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
                     if (!$is_logged_in) {
                         $output .= '<p>' . __('Please check your email for the confirmation link.', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
                         if ($redirect && !$is_widget) {
                             $output .= '<script type="text/javascript">window.location="' . esc_url($redirect_url) . '";</script>';
                         } else {
                             $output .= '<p>';
                             $output .= sprintf(__('Log in <a href="%s">here</a>.', AFFILIATES_PLUGIN_DOMAIN), esc_url(apply_filters('affiliates_registration_login_redirect_url', get_site_url(get_current_blog_id(), 'wp-login.php?checkemail=confirm'))));
                             $output .= '</p>';
                         }
                     } else {
                         if (isset($options['registered_profile_link_url'])) {
                             $output .= '<p>';
                             $output .= '<a href="' . esc_url($options['registered_profile_link_url']) . '">';
                             if (isset($options['registered_profile_link_text'])) {
                                 $output .= wp_filter_kses($options['registered_profile_link_text']);
                             } else {
                                 $output .= __('Access your profile', AFFILIATES_PLUGIN_DOMAIN);
                             }
                             $output .= '</a>';
                             $output .= '</p>';
                         }
                     }
                 }
             } else {
                 // is_wp_error( $affiliate_user_id ), user registration failed
                 $error = true;
                 $wp_error = $affiliate_user_id;
                 if ($wp_error->get_error_code()) {
                     $errors = array();
                     $messages = array();
                     foreach ($wp_error->get_error_codes() as $code) {
                         $severity = $wp_error->get_error_data($code);
                         foreach ($wp_error->get_error_messages($code) as $error) {
                             if ('message' == $severity) {
                                 $messages[] = $error;
                             } else {
                                 $errors[] = $error;
                             }
                         }
                     }
                     if (!empty($errors)) {
                         $output .= '<div class="error">';
                         $output .= apply_filters('login_errors', implode('<br />', $errors));
                         $output .= '</div>';
                     }
                     if (!empty($messages)) {
                         $output .= '<div class="message">';
                         $output .= apply_filters('login_messages', implode('<br />', $messages));
                         $output .= '</div>';
                     }
                 }
             }
         }
     }
     // Registration form
     if (!$send) {
         if (isset($options['terms_post_id'])) {
             $terms_post = get_post($options['terms_post_id']);
             if ($terms_post) {
                 $terms_post_link = '<a target="_blank" href="' . esc_url(get_permalink($terms_post->ID)) . '">' . get_the_title($terms_post->ID) . '</a>';
                 $terms = sprintf(apply_filters('affiliates_terms_post_link_text', __('By signing up, you indicate that you have read and agree to the %s.', AFFILIATES_PLUGIN_DOMAIN)), $terms_post_link);
             }
         }
         $output .= '<div class="affiliates-registration" id="affiliates-registration">';
         $output .= '<img id="affiliates-registration-throbber" src="' . AFFILIATES_PLUGIN_URL . 'images/affiliates-throbber.gif" style="display:none" />';
         $output .= '<form id="affiliates-registration-form" method="post">';
         $output .= '<div>';
         $output .= apply_filters('affiliates_registration_before_fields', '');
         $output .= self::render_fields($registration_fields);
         $output .= apply_filters('affiliates_registration_after_fields', '');
         if (isset($terms)) {
             $output .= '<div class="terms">' . $terms . '</div>';
         }
         $output .= Affiliates_Utility::captcha_get($captcha);
         $output .= wp_nonce_field($nonce_action, $nonce, true, false);
         if (isset($options['redirect_to'])) {
             $output .= '<input type="hidden" name="redirect_to" value="' . esc_url($options['redirect_to']) . '" />';
         }
         $output .= '<div class="sign-up">';
         $output .= '<input type="submit" name="' . $submit_name . '" value="' . self::$submit_button_label . '" />';
         $output .= '</div>';
         $output .= '</div>';
         $output .= '</form>';
         $output .= '</div>';
     }
     return $output;
 }
 /**
  * Fields:
  * 
  * - first_name
  * - last_name
  * - user_login
  * - email
  * - url
  * 
  * first name + last name => affiliate name
  * 
  * Form options :
  * - terms_post_id
  * - redirect_to
  * - is_widget
  * 
  * @param array $options form options
  * @return string rendered registration form
  */
 static function render_form($options = array())
 {
     $output = '';
     $ext = '';
     // currently not relevant
     if ($is_logged_in = is_user_logged_in()) {
         $user = wp_get_current_user();
         // sanitize_user_object is deprecated in WP 3.3 beta3
         //$user       = sanitize_user_object( $user );
         $first_name = $user->first_name;
         $first_name = sanitize_user_field('first_name', $first_name, $user->ID, 'display');
         $last_name = $user->last_name;
         $last_name = sanitize_user_field('last_name', $last_name, $user->ID, 'display');
         $user_login = $user->user_login;
         $user_login = sanitize_user_field('user_login', $user_login, $user->ID, 'display');
         $email = $user->user_email;
         $email = sanitize_user_field('email', $email, $user->ID, 'display');
         $url = $user->user_url;
         $url = sanitize_user_field('user_url', $url, $user->ID, 'display');
     } else {
         $user = null;
     }
     if ($is_affiliate = affiliates_user_is_affiliate()) {
         $output .= '<div class="affiliates-registration registered">';
         $output .= '<p>';
         $output .= __('You are already registered as an affiliate.', AFFILIATES_PLUGIN_DOMAIN);
         $output .= '</p>';
         if (isset($options['registered_profile_link_url'])) {
             $output .= '<p>';
             $output .= '<a href="' . esc_url($options['registered_profile_link_url']) . '">';
             if (isset($options['registered_profile_link_text'])) {
                 $output .= wp_filter_kses($options['registered_profile_link_text']);
             } else {
                 $output .= __('Access your profile', AFFILIATES_PLUGIN_DOMAIN);
             }
             $output .= '</a>';
             $output .= '</p>';
         }
         $output .= '</div>';
         return $output;
     }
     if (!get_option('aff_registration', get_option('users_can_register', false))) {
         $output .= '<p>' . __('Registration is currently closed.', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
         return $output;
     }
     $method = 'post';
     $action = "";
     $submit_name = 'affiliates-registration-submit';
     $nonce = 'affiliates-registration-nonce';
     $nonce_action = 'affiliates-registration';
     $send = false;
     $first_name_class = ' class="required" ';
     $last_name_class = ' class="required" ';
     $user_login_class = ' class="required" ';
     $email_class = ' class="required" ';
     $url_class = '';
     if (isset($options['terms_post_id'])) {
         $terms_post = get_post($options['terms_post_id']);
         if ($terms_post) {
             $terms_post_link = '<a target="_blank" href="' . esc_url(get_permalink($terms_post->ID)) . '">' . get_the_title($terms_post->ID) . '</a>';
             $terms = sprintf(__('By signing up, you indicate that you have read and agree to the %s.', AFFILIATES_PLUGIN_DOMAIN), $terms_post_link);
         }
     }
     $captcha = '';
     $error = false;
     if (!empty($_POST[$submit_name])) {
         if (!wp_verify_nonce($_POST[$nonce], $nonce_action)) {
             $error = true;
             // fail but don't give clues
         }
         $captcha = $_POST[Affiliates_Utility::get_captcha_field_id()];
         if (!Affiliates_Utility::captcha_validates($captcha)) {
             $error = true;
             // dumbot
         }
         if (!$is_logged_in) {
             $first_name = isset($_POST['first_name']) ? Affiliates_Utility::filter($_POST['first_name']) : '';
             $last_name = isset($_POST['last_name']) ? Affiliates_Utility::filter($_POST['last_name']) : '';
             $user_login = isset($_POST['user_login']) ? Affiliates_Utility::filter($_POST['user_login']) : '';
             $email = isset($_POST['email']) ? Affiliates_Utility::filter($_POST['email']) : '';
             $url = isset($_POST['url']) ? Affiliates_Utility::filter($_POST['url']) : '';
         } else {
             $first_name = $user->first_name;
             $last_name = $user->last_name;
             $user_login = $user->user_login;
             $email = $user->user_email;
             $url = $user->user_url;
         }
         if (empty($first_name)) {
             $first_name_class = ' class="required missing" ';
             $error = true;
         }
         if (empty($last_name)) {
             $last_name_class = ' class="required missing" ';
             $error = true;
         }
         if (empty($user_login)) {
             $user_login_class = ' class="required missing" ';
             $error = true;
         }
         if (empty($email) || !is_email($email)) {
             $email_class = ' class="required missing" ';
             $error = true;
         }
         $error = apply_filters('affiliates_registration_error_validate', $error);
         if (!$error) {
             $userdata = array('first_name' => $first_name, 'last_name' => $last_name, 'user_login' => $user_login, 'email' => $email, 'user_url' => $url);
             // don't try to create a new user on multiple renderings
             global $affiliate_user_id, $new_affiliate_registered;
             if (!isset($affiliate_user_id)) {
                 if (!$is_logged_in) {
                     // allow plugins to be aware of new user account being created
                     do_action('affiliates_before_register_affiliate', $userdata);
                     // create the affiliate user account
                     $affiliate_user_id = self::register_affiliate($userdata);
                     $new_affiliate_registered = true;
                     do_action('affiliates_after_register_affiliate', $userdata);
                 } else {
                     $affiliate_user_id = $user->ID;
                     $new_affiliate_registered = true;
                 }
             }
             // register as affiliate
             if (!is_wp_error($affiliate_user_id)) {
                 // add affiliate entry
                 $send = true;
                 if ($new_affiliate_registered) {
                     $affiliate_id = self::store_affiliate($affiliate_user_id, $userdata);
                     do_action('affiliates_stored_affiliate', $affiliate_id, $affiliate_user_id);
                 }
                 $is_widget = isset($options['is_widget']) && ($options['is_widget'] === true || $options['is_widget'] == 'true');
                 $redirect = isset($options['redirect']) && ($options['redirect'] === true || $options['redirect'] == 'true');
                 $redirect_url = empty($_REQUEST['redirect_to']) ? get_home_url(get_current_blog_id(), 'wp-login.php?checkemail=confirm') : $_REQUEST['redirect_to'];
                 if ($redirect && !$is_widget && !headers_sent()) {
                     wp_safe_redirect($redirect_url);
                     exit;
                 } else {
                     $output .= '<p>' . __('Thanks for signing up!', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
                     if (!$is_logged_in) {
                         $output .= '<p>' . __('Please check your email for the confirmation link.', AFFILIATES_PLUGIN_DOMAIN) . '</p>';
                         if ($redirect && !$is_widget) {
                             $output .= '<script type="text/javascript">window.location="' . esc_url($redirect_url) . '";</script>';
                         } else {
                             $output .= '<p>' . sprintf(__('Log in <a href="%s">here</a>.', AFFILIATES_PLUGIN_DOMAIN), get_home_url(get_current_blog_id(), 'wp-login.php?checkemail=confirm')) . '</p>';
                         }
                     } else {
                         if (isset($options['registered_profile_link_url'])) {
                             $output .= '<p>';
                             $output .= '<a href="' . esc_url($options['registered_profile_link_url']) . '">';
                             if (isset($options['registered_profile_link_text'])) {
                                 $output .= wp_filter_kses($options['registered_profile_link_text']);
                             } else {
                                 $output .= __('Access your profile', AFFILIATES_PLUGIN_DOMAIN);
                             }
                             $output .= '</a>';
                             $output .= '</p>';
                         }
                     }
                 }
             } else {
                 $error = true;
                 $wp_error = $affiliate_user_id;
                 if ($wp_error->get_error_code()) {
                     $errors = '';
                     $messages = '';
                     foreach ($wp_error->get_error_codes() as $code) {
                         switch ($code) {
                             case 'empty_username':
                             case 'invalid_username':
                             case 'username_exists':
                                 $user_login_class = ' class="required missing" ';
                                 break;
                             case 'empty_email':
                             case 'invalid_email':
                             case 'email_exists':
                                 $email_class = ' class="required missing" ';
                                 break;
                         }
                         $severity = $wp_error->get_error_data($code);
                         foreach ($wp_error->get_error_messages($code) as $error) {
                             if ('message' == $severity) {
                                 $messages .= '	' . $error . "<br />\n";
                             } else {
                                 $errors .= '	' . $error . "<br />\n";
                             }
                         }
                     }
                     if (!empty($errors)) {
                         echo '<div id="login_error">' . apply_filters('login_errors', $errors) . "</div>\n";
                     }
                     if (!empty($messages)) {
                         echo '<p class="message">' . apply_filters('login_messages', $messages) . "</p>\n";
                     }
                 }
             }
         }
     } else {
         if (!$is_logged_in) {
             $first_name = '';
             $last_name = '';
             $user_login = '';
             $email = '';
             $url = '';
         }
     }
     if (!$send) {
         $output .= '<div class="affiliates-registration" id="affiliates-registration' . $ext . '">';
         $output .= '<img id="affiliates-registration-throbber' . $ext . '" src="' . AFFILIATES_PLUGIN_URL . 'images/affiliates-throbber.gif" style="display:none" />';
         $output .= '<form id="affiliates-registration-form' . $ext . '" action="' . $action . '" method="' . $method . '">';
         $output .= '<div>';
         $field_disabled = "";
         if ($is_logged_in) {
             $field_disabled = ' disabled="disabled" ';
             if (empty($first_name) || empty($last_name)) {
                 $output .= '<p>';
                 $output .= sprintf(__('<p>Please fill in the required information in your <a href="%s">profile</a> first.</p>'), esc_url(admin_url("profile.php")));
                 $output .= '</p>';
             }
         }
         $output .= apply_filters('affiliates_registration_before_fields', '');
         $output .= '<label ' . $first_name_class . ' id="affiliates-registration-form' . $ext . '-first-name-label" for="first_name">' . __('First Name', AFFILIATES_PLUGIN_DOMAIN) . '</label>';
         $output .= '<input ' . $field_disabled . ' id="affiliates-registration-form' . $ext . '-first-name" name="first_name" type="text" value="' . esc_attr($first_name) . '"/>';
         $output .= '<label ' . $last_name_class . ' id="affiliates-registration-form' . $ext . '-last-name-label" for="last_name">' . __('Last Name', AFFILIATES_PLUGIN_DOMAIN) . '</label>';
         $output .= '<input ' . $field_disabled . ' id="affiliates-registration-form' . $ext . '-last-name" name="last_name" type="text" value="' . esc_attr($last_name) . '"/>';
         $output .= '<label ' . $user_login_class . ' id="affiliates-registration-form' . $ext . '-user-login-label" for="user_login">' . __('Username', AFFILIATES_PLUGIN_DOMAIN) . '</label>';
         $output .= '<input ' . $field_disabled . ' id="affiliates-registration-form' . $ext . '-user-login" name="user_login" type="text" value="' . esc_attr($user_login) . '"/>';
         $output .= '<label ' . $email_class . ' id="affiliates-registration-form' . $ext . '-email-label" for="email">' . __('Email', AFFILIATES_PLUGIN_DOMAIN) . '</label>';
         $output .= '<input ' . $field_disabled . ' id="affiliates-registration-form' . $ext . '-email" name="email" type="text" value="' . esc_attr($email) . '"/>';
         $output .= '<label ' . $url_class . ' id="affiliates-registration-form' . $ext . '-url-label" for="url">' . __('Website', AFFILIATES_PLUGIN_DOMAIN) . '</label>';
         $output .= '<input ' . $field_disabled . ' id="affiliates-registration-form' . $ext . '-url" name="url" type="text" value="' . esc_attr($url) . '"/>';
         $output .= apply_filters('affiliates_registration_after_fields', '');
         if (isset($terms)) {
             $output .= '<p class="terms">' . $terms . '</p>';
         }
         $output .= Affiliates_Utility::captcha_get($captcha);
         $output .= wp_nonce_field($nonce_action, $nonce, true, false);
         if (isset($options['redirect_to'])) {
             $output .= '<input type="hidden" name="redirect_to" value="' . esc_url($options['redirect_to']) . '" />';
         }
         $output .= '<input type="submit" name="' . $submit_name . '" value="' . self::$submit_button_label . '" />';
         $output .= '</div>';
         $output .= '</form>';
         $output .= '</div>';
     }
     return $output;
 }
예제 #13
0
/**
 * Update the referral.
 * @param array $attributes to update, supports: affiliate_id, post_id, datetime, description, amount, currency_id, status, reference
 * @return array with keys, values and old_values or null if nothing was updated
 */
function affiliates_update_referral($referral_id, $attributes)
{
    global $wpdb;
    $result = null;
    $referral = null;
    $referrals_table = _affiliates_get_tablename('referrals');
    if ($referrals = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$referrals_table} WHERE referral_id = %d", intval($referral_id)))) {
        if (count($referrals) > 0) {
            $referral = $referrals[0];
        }
    }
    if ($referral !== null) {
        $set = array();
        $keys = array();
        $values = array();
        $old_values = array();
        foreach ($attributes as $key => $value) {
            $current_value = isset($referral->{$key}) ? $referral->{$key} : null;
            if ($current_value !== $value) {
                switch ($key) {
                    case 'affiliate_id':
                    case 'post_id':
                        $set[] = " {$key} = %d ";
                        $keys[] = $key;
                        $values[] = intval($value);
                        $old_values[] = $current_value;
                        break;
                    case 'datetime':
                    case 'description':
                    case 'reference':
                        $set[] = " {$key} = %s ";
                        $keys[] = $key;
                        $values[] = $value;
                        $old_values[] = $current_value;
                        break;
                    case 'status':
                        // Just check that this is a valid status:
                        if (!empty($value) && Affiliates_Utility::verify_referral_status_transition($value, $value)) {
                            $set[] = " {$key} = %s ";
                            $keys[] = $key;
                            $values[] = $value;
                            $old_values[] = $current_value;
                        }
                        break;
                    case 'amount':
                        if ($value = Affiliates_Utility::verify_referral_amount($value)) {
                            $set[] = " {$key} = %s ";
                            $keys[] = $key;
                            $values[] = $value;
                            $old_values[] = $current_value;
                        }
                        break;
                    case 'currency_id':
                        if ($value = Affiliates_Utility::verify_currency_id($value)) {
                            $set[] = " {$key} = %s ";
                            $keys[] = $key;
                            $values[] = $value;
                            $old_values[] = $current_value;
                        }
                        break;
                }
            }
        }
        if (count($set) > 0) {
            $set = implode(' , ', $set);
            if ($wpdb->query($wpdb->prepare("UPDATE {$referrals_table} SET {$set} WHERE referral_id = %d", array_merge($values, array(intval($referral_id)))))) {
                $result = array('keys' => $keys, 'values' => $values, 'old_values' => $old_values);
                do_action('affiliates_updated_referral', intval($referral_id), $keys, $values, $old_values);
            }
        }
    }
    return $result;
}