diff --git a/README.md b/README.md deleted file mode 100644 index 3ae7916..0000000 --- a/README.md +++ /dev/null @@ -1,39 +0,0 @@ -

WooCommerce

- -

-License: GPL v3 -WordPress.org version -WordPress.org downloads -WordPress.org rating -WordPress.org rating -WordPress.org rating -

- -myCred is an intelligent and adaptive points management system that allows you to build brand loyalty by rewarding your customers through store reward systems, community leaderboards, monetizing your website content, etc. - -myCred allows THREE different ways through which you can award your users: - -* **Points -** Set events and triggers to allow real-time tracking and automatically award your users with points. -* **Ranks -** Set ranks within your leaderboards and reward your users with significant perks after they reach a certain milestone. -* **Badges -** Boost your users' participation by rewarding them for their exceptional performance. - -## Documentation -You can find extensive documentation on myCred add-ons in the myCred Codex. You can also find a list of frequently asked questions on the myCred website. - -* Chapter I - Introduction -* Chapter II - Getting Started -* Chapter III - Add-ons -* Chapter IV - Premium Add-ons -* Chapter V - For Developers -* Chapter VI - Reference Guides - -## Support -This repository is not suitable for support. Please don't use our issue tracker for support requests, but for core myCred issues only. Support can take place through the appropriate channels: - -* If you have a problem, you may want to start with the self-help guide. -* The myCred support portal for customers who have purchased themes or extensions. -* You can consult myCred's online community with your question. -* You can submit a customization request. -* Our community forum on wp.org is available for all users. - -

Made with 💜 by myCred.

diff --git a/abstracts/index.php b/abstracts/index.php index 1580272..4e6c07c 100644 --- a/abstracts/index.php +++ b/abstracts/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/abstracts/mycred-abstract-hook.php b/abstracts/mycred-abstract-hook.php index a543560..cf1c1fe 100644 --- a/abstracts/mycred-abstract-hook.php +++ b/abstracts/mycred-abstract-hook.php @@ -1,613 +1,538 @@ $value ) { - $this->$key = $value; - } - } - - // Grab myCRED Settings - $this->core = mycred($type); - $this->point_types = mycred_get_types(); - - if ($type != '' ) { - $this->core->cred_id = sanitize_text_field($type); - $this->mycred_type = $this->core->cred_id; - } - - if ($this->mycred_type != MYCRED_DEFAULT_TYPE_KEY ) { - $this->is_main_type = false; - } - - // Grab settings - if ($hook_prefs !== null ) { - - // Assign prefs if set - if (isset($hook_prefs[ $this->id ]) ) { - $this->prefs = $hook_prefs[ $this->id ]; - } - - // Defaults must be set - if (! isset($this->defaults) ) { - $this->defaults = array(); - } - - } - - // Apply default settings if needed - if (! empty($this->defaults) ) { - $this->prefs = mycred_apply_defaults($this->defaults, $this->prefs); - } - - } - - /** - * Run - * Must be over-ridden by sub-class! - * - * @since 0.1 - * @version 1.0 - */ - public function run() - { - - wp_die('function myCRED_Hook::run() must be over-ridden in a sub-class.'); - - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.0 - */ - public function preferences() - { +if ( ! class_exists( 'myCRED_Hook' ) ) : + abstract class myCRED_Hook { + + /** + * Unique Hook ID + */ + public $id = false; + + /** + * The Hooks settings + */ + public $prefs = false; + + /** + * The current point type key + */ + public $mycred_type = MYCRED_DEFAULT_TYPE_KEY; + + /** + * The myCRED object for the current type + */ + public $core = false; - echo '

' . esc_html__('This Hook has no settings', 'mycred') . '

'; + /** + * Array of all existing point types + */ + public $point_types = array(); - } + /** + * Indicates if the current instance is for the main point type or not + */ + public $is_main_type = true; - /** - * Sanitise Preference - * - * @since 0.1 - * @version 1.0 - */ - public function sanitise_preferences( $data ) - { + /** + * Construct + */ + public function __construct( $args = array(), $hook_prefs = NULL, $type = MYCRED_DEFAULT_TYPE_KEY ) { - return $data; + if ( ! empty( $args ) ) { + foreach ( $args as $key => $value ) { + $this->$key = $value; + } + } - } + // Grab myCRED Settings + $this->core = mycred( $type ); + $this->point_types = mycred_get_types(); - /** - * Get Field Name - * Returns the field name for the current hook - * - * @since 0.1 - * @version 1.1 - */ - public function field_name( $field = '' ) - { + if ( $type != '' ) { + $this->core->cred_id = sanitize_text_field( $type ); + $this->mycred_type = $this->core->cred_id; + } - if (is_array($field) ) { + if ( $this->mycred_type != MYCRED_DEFAULT_TYPE_KEY ) + $this->is_main_type = false; - $array = array(); - foreach ( $field as $parent => $child ) { + // Grab settings + if ( $hook_prefs !== NULL ) { - if (! is_numeric($parent) ) { - $array[] = $parent; - } + // Assign prefs if set + if ( isset( $hook_prefs[ $this->id ] ) ) + $this->prefs = $hook_prefs[ $this->id ]; - if (! empty($child) && ! is_array($child) ) { - $array[] = $child; - } + // Defaults must be set + if ( ! isset( $this->defaults ) ) + $this->defaults = array(); - } - $field = '[' . implode('][', $array) . ']'; + } - } - else { + // Apply default settings if needed + if ( ! empty( $this->defaults ) ) + $this->prefs = mycred_apply_defaults( $this->defaults, $this->prefs ); - $field = '[' . $field . ']'; + } - } + /** + * Run + * Must be over-ridden by sub-class! + * @since 0.1 + * @version 1.0 + */ + public function run() { - $option_id = apply_filters('mycred_option_id', 'mycred_pref_hooks'); - if (! $this->is_main_type ) { - $option_id = $option_id . '_' . $this->mycred_type; - } + wp_die( 'function myCRED_Hook::run() must be over-ridden in a sub-class.' ); - return $option_id . '[hook_prefs][' . $this->id . ']' . $field; + } - } + /** + * Preferences + * @since 0.1 + * @version 1.0 + */ + public function preferences() { - /** - * Get Field ID - * Returns the field id for the current hook - * - * @since 0.1 - * @version 1.2 - */ - public function field_id( $field = '' ) - { + echo '

' . esc_html__( 'This Hook has no settings', 'mycred' ) . '

'; - global $mycred_field_id; + } - if (is_array($field) ) { + /** + * Sanitise Preference + * @since 0.1 + * @version 1.0 + */ + public function sanitise_preferences( $data ) { - $array = array(); - foreach ( $field as $parent => $child ) { + return $data; - if (! is_numeric($parent) ) { - $array[] = str_replace('_', '-', $parent); - } + } - if (! empty($child) && ! is_array($child) ) { - $array[] = str_replace('_', '-', $child); - } + /** + * Get Field Name + * Returns the field name for the current hook + * @since 0.1 + * @version 1.1 + */ + public function field_name( $field = '' ) { - } - $field = implode('-', $array); + if ( is_array( $field ) ) { - } - else { + $array = array(); + foreach ( $field as $parent => $child ) { - $field = str_replace('_', '-', $field); + if ( ! is_numeric( $parent ) ) + $array[] = $parent; - } + if ( ! empty( $child ) && ! is_array( $child ) ) + $array[] = $child; - $option_id = 'mycred_pref_hooks'; - if (! $this->is_main_type ) { - $option_id = $option_id . '_' . $this->mycred_type; - } + } + $field = '[' . implode( '][', $array ) . ']'; - $option_id = str_replace('_', '-', $option_id); + } + else { - // $mycred_field_id - This little trick is used when widgets are not in a sidebar - // Adding __i__ to IDs will prevent duplicate IDs ever existing on the same page, causing - // scripts or HTML structures from working, like having a checkbox/radio selected when you click on - // the label and not on the input field. + $field = '[' . $field . ']'; - return $option_id . '-' . str_replace('_', '-', $this->id) . '-' . $field . $mycred_field_id; + } - } + $option_id = apply_filters( 'mycred_option_id', 'mycred_pref_hooks' ); + if ( ! $this->is_main_type ) + $option_id = $option_id . '_' . $this->mycred_type; - /** - * Check Limit - * - * @since 1.6 - * @version 1.3 - */ - public function over_hook_limit( $instance = '', $reference = '', $user_id = null, $ref_id = null ) - { + return $option_id . '[hook_prefs][' . $this->id . ']' . $field; - // If logging is disabled, we cant use this feature - if (! MYCRED_ENABLE_LOGGING ) { return false; - } + } - // Enforce limit if this function is used incorrectly - if (! isset($this->prefs[ $instance ]) && $instance != '' ) { - return true; - } + /** + * Get Field ID + * Returns the field id for the current hook + * @since 0.1 + * @version 1.2 + */ + public function field_id( $field = '' ) { - global $wpdb, $mycred_log_table; + global $mycred_field_id; - // Prep - $wheres = array(); - $now = current_time('timestamp'); + if ( is_array( $field ) ) { - // If hook uses multiple instances - if (isset($this->prefs[ $instance ]['limit']) ) { - $prefs = $this->prefs[ $instance ]['limit']; - } + $array = array(); + foreach ( $field as $parent => $child ) { - // Else if hook uses single instance - elseif (isset($this->prefs['limit']) ) { - $prefs = $this->prefs['limit']; - } + if ( ! is_numeric( $parent ) ) + $array[] = str_replace( '_', '-', $parent ); - // no support for limits - else { - return false; - } + if ( ! empty( $child ) && ! is_array( $child ) ) + $array[] = str_replace( '_', '-', $child ); - // If the user ID is not set use the current one - if ($user_id === null ) { - $user_id = get_current_user_id(); - } + } + $field = implode( '-', $array ); - // If this an existance check or just a regular limit check? - $exists_check = false; - if ($ref_id !== null && strlen($ref_id) > 0 ) { - $exists_check = true; - } + } + else { - if (count(explode('/', $prefs)) != 2 ) { - $prefs = '0/x'; - } + $field = str_replace( '_', '-', $field ); - // Set to "no limit" - if (! $exists_check && $prefs === '0/x' ) { return false; - } + } - // Prep settings - list ( $amount, $period ) = explode('/', $prefs); - $amount = (int) $amount; + $option_id = 'mycred_pref_hooks'; + if ( ! $this->is_main_type ) + $option_id = $option_id . '_' . $this->mycred_type; - // We start constructing the query. - $wheres[] = $wpdb->prepare("user_id = %d", $user_id); - $wheres[] = $wpdb->prepare("ref = %s", $reference); - $wheres[] = $wpdb->prepare("ctype = %s", $this->mycred_type); + $option_id = str_replace( '_', '-', $option_id ); - if ($exists_check ) { - $wheres[] = $wpdb->prepare("ref_id = %d", $ref_id); - } + // $mycred_field_id - This little trick is used when widgets are not in a sidebar + // Adding __i__ to IDs will prevent duplicate IDs ever existing on the same page, causing + // scripts or HTML structures from working, like having a checkbox/radio selected when you click on + // the label and not on the input field. - // If check is based on time - if (! in_array($period, array( 't', 'x' )) ) { + return $option_id . '-' . str_replace( '_', '-', $this->id ) . '-' . $field . $mycred_field_id; - // Per day - if ($period == 'd' ) { - $from = mktime(0, 0, 0, date('n', $now), date('j', $now), date('Y', $now)); - } + } - // Per week - elseif ($period == 'w' ) { - $from = mktime(0, 0, 0, date("n", $now), date("j", $now) - date("N", $now) + 1); - } - - // Per Month - elseif ($period == 'm' ) { - $from = mktime(0, 0, 0, date("n", $now), 1, date('Y', $now)); - } - - $wheres[] = $wpdb->prepare("time BETWEEN %d AND %d", $from, $now); - - } - - $over_limit = false; - - if (! empty($wheres) ) { - - // Put all wheres together into one string - $wheres = implode(" AND ", $wheres); - - $query = "SELECT COUNT(*) FROM {$mycred_log_table} WHERE {$wheres};"; - - //Lets play for others - $query = apply_filters('mycred_hook_limit_query', $query, $instance, $reference, $user_id, $ref_id, $wheres, $this); - - // Count - $count = $wpdb->get_var($query); - if ($count === null ) { $count = 0; - } - - // Existence check has first priority - if ($count > 0 && $exists_check ) { - $over_limit = true; - } - - // Limit check is second priority - elseif ($period != 'x' && $count >= $amount ) { - $over_limit = true; - } - - } - - return apply_filters('mycred_over_hook_limit', $over_limit, $instance, $reference, $user_id, $ref_id, $this); - - } - - /** - * Get Limit Types - * - * @since 1.6 - * @version 1.0 - */ - public function get_limit_types() - { - - return apply_filters( - 'mycred_hook_limits', array( - 'x' => __('No limit', 'mycred'), - 'd' => __('/ Day', 'mycred'), - 'w' => __('/ Week', 'mycred'), - 'm' => __('/ Month', 'mycred'), - 't' => __('in Total', 'mycred') - ), $this - ); - - } - - /** - * Select Limit - * - * @since 1.6 - * @version 1.0 - */ - public function hook_limit_setting( $name = '', $id = '', $selected = '' ) - { - - // Convert string value into an array - $check = explode('/', $selected); - $count = count($check); - - if ($count == 0 || ( $count == 1 && $check[0] == 0 ) ) { - $selected = array( 0, 'x' ); - - } elseif ($count == 1 && $check[0] != '' && is_numeric($check[0]) ) { - $selected = array( (int) $check[0], 'd' ); - - } else { - $selected = $check; - } - - // Hide value field if no limit is set - $hide = 'text'; - if ($selected[1] == 'x' ) { - $hide = 'hidden'; - } - - // The limit value field - $output = '
'; - - // Get limit options - $options = $this->get_limit_types(); - - // Adjust the field name - $name = str_replace('[limit]', '[limit_by]', $name); - $name = str_replace('[alimit]', '[alimit_by]', $name); - $name = apply_filters('mycred_hook_limit_name_by', $name, $this); - - // Adjust the field id - $id = str_replace('limit', 'limit-by', $id); - $id = str_replace('alimit', 'alimit-by', $id); - $id = apply_filters('mycred_hook_limit_id_by', $id, $this); - - // Generate dropdown menu - $output .= '
'; - - return $output; - - } - - /** - * Impose Limits Dropdown - * - * @since 0.1 - * @version 1.3 - */ - public function impose_limits_dropdown( $pref_id = '', $use_select = true ) - { - - $settings = ''; - $limits = array( - '' => __('No limit', 'mycred'), - 'twentyfour' => __('Once every 24 hours', 'mycred'), - 'sevendays' => __('Once every 7 days', 'mycred'), - 'daily' => __('Once per day (reset at midnight)', 'mycred') - ); - $limits = apply_filters('mycred_hook_impose_limits', $limits, $this); - - echo ''; - - } - - /** - * Has Entry - * Moved to myCRED_Settings - * - * @since 0.1 - * @version 1.3 - */ - public function has_entry( $action = '', $ref_id = '', $user_id = '', $data = '', $point_type = '' ) - { - - // If logging is disabled, we cant use this feature - if (! MYCRED_ENABLE_LOGGING ) { return false; - } - - if ($point_type == '' ) { - $point_type = $this->mycred_type; - } - - return $this->core->has_entry($action, $ref_id, $user_id, $data, $point_type); - - } - - /** - * Available Template Tags - * - * @since 1.4 - * @version 1.0 - */ - public function available_template_tags( $available = array(), $custom = '' ) - { - - return $this->core->available_template_tags($available, $custom); - - } - - /** - * Over Daily Limit - * - * @since 1.0 - * @version 1.1.1 - */ - public function is_over_daily_limit( $ref = '', $user_id = 0, $max = 0, $ref_id = null ) - { - - // If logging is disabled, we cant use this feature - if (! MYCRED_ENABLE_LOGGING ) { return false; - } - - // Prep - $reply = true; - - // DB Query - $total = $this->limit_query($ref, $user_id, strtotime('today midnight', $this->now), $this->now, $ref_id); - - if ($total < $max ) { - $reply = false; - } - - return apply_filters('mycred_hook_over_daily_limit', $reply, $ref, $user_id, $max); - - } - - /** - * Include Post Type - * Checks if a given post type should be excluded - * - * @since 0.1 - * @version 1.1 - */ - public function include_post_type( $post_type ) - { - - // Exclude Core - $excludes = array( 'post', 'page' ); - if (in_array($post_type, apply_filters('mycred_post_type_excludes', $excludes)) ) { return false; - } - - return true; - - } - - /** - * Limit Query - * Queries the myCRED log for the number of occurances of the specified - * refernece and optional reference id for a specific user between two dates. - * - * @param $ref (string) reference to search for, required - * @param $user_id (int) user id to search for, required - * @param $start (int) unix timestamp for start date, required - * @param $end (int) unix timestamp for the end date, required - * @param $ref_id (int) optional reference id to include in search - * @returns number of entries found (int) or NULL if required params are missing - * @since 1.4 - * @version 1.2 - */ - public function limit_query( $ref = '', $user_id = 0, $start = 0, $end = 0, $ref_id = null ) - { - - // If logging is disabled, we cant use this feature - if (! MYCRED_ENABLE_LOGGING ) { return 0; - } - - // Minimum requirements - if (empty($ref) || $user_id == 0 || $start == 0 || $end == 0 ) { - return null; - } - - global $wpdb, $mycred_log_table; - - // Prep - $reply = true; - $wheres = array(); - - $wheres[] = $wpdb->prepare("ref = %s", $ref); - $wheres[] = $wpdb->prepare("user_id = %d", $user_id); - $wheres[] = $wpdb->prepare("time BETWEEN %d AND %d", $start, $end); - $wheres[] = $wpdb->prepare("ctype = %s", $this->mycred_type); - - if ($ref_id !== null ) { - $wheres[] = $wpdb->prepare("ref_id = %d", $ref_id); - } - - $wheres = implode(" AND ", $wheres); - - // DB Query - $total = $wpdb->get_var("SELECT COUNT(*) FROM {$mycred_log_table} WHERE {$wheres};"); - if ($total === null ) { $total = 0; - } - - return apply_filters('mycred_hook_limit_query', $total, $ref, $user_id, $ref_id, $start, $end); - - } - - } + /** + * Check Limit + * @since 1.6 + * @version 1.3 + */ + public function over_hook_limit( $instance = '', $reference = '', $user_id = NULL, $ref_id = NULL ) { + + // If logging is disabled, we cant use this feature + if ( ! MYCRED_ENABLE_LOGGING ) return false; + + // Enforce limit if this function is used incorrectly + if ( ! isset( $this->prefs[ $instance ] ) && $instance != '' ) + return true; + + global $wpdb, $mycred_log_table; + + // Prep + $wheres = array(); + $now = current_time( 'timestamp' ); + + // If hook uses multiple instances + if ( isset( $this->prefs[ $instance ]['limit'] ) ) + $prefs = $this->prefs[ $instance ]['limit']; + + // Else if hook uses single instance + elseif ( isset( $this->prefs['limit'] ) ) + $prefs = $this->prefs['limit']; + + // no support for limits + else { + return false; + } + + // If the user ID is not set use the current one + if ( $user_id === NULL ) + $user_id = get_current_user_id(); + + // If this an existance check or just a regular limit check? + $exists_check = false; + if ( $ref_id !== NULL && strlen( $ref_id ) > 0 ) + $exists_check = true; + + if ( count( explode( '/', $prefs ) ) != 2 ) + $prefs = '0/x'; + + // Set to "no limit" + if ( ! $exists_check && $prefs === '0/x' ) return false; + + // Prep settings + list ( $amount, $period ) = explode( '/', $prefs ); + $amount = (int) $amount; + + // We start constructing the query. + $wheres[] = $wpdb->prepare( "user_id = %d", $user_id ); + $wheres[] = $wpdb->prepare( "ref = %s", $reference ); + $wheres[] = $wpdb->prepare( "ctype = %s", $this->mycred_type ); + + if ( $exists_check ) + $wheres[] = $wpdb->prepare( "ref_id = %d", $ref_id ); + + // If check is based on time + if ( ! in_array( $period, array( 't', 'x' ) ) ) { + + // Per day + if ( $period == 'd' ) + $from = mktime( 0, 0, 0, date( 'n', $now ), date( 'j', $now ), date( 'Y', $now ) ); + + // Per week + elseif ( $period == 'w' ) + $from = mktime( 0, 0, 0, date( "n", $now ), date( "j", $now ) - date( "N", $now ) + 1 ); + + // Per Month + elseif ( $period == 'm' ) + $from = mktime( 0, 0, 0, date( "n", $now ), 1, date( 'Y', $now ) ); + + $wheres[] = $wpdb->prepare( "time BETWEEN %d AND %d", $from, $now ); + + } + + $over_limit = false; + + if ( ! empty( $wheres ) ) { + + // Put all wheres together into one string + $wheres = implode( " AND ", $wheres ); + + $query = "SELECT COUNT(*) FROM {$mycred_log_table} WHERE {$wheres};"; + + //Lets play for others + $query = apply_filters( 'mycred_hook_limit_query', $query, $instance, $reference, $user_id, $ref_id, $wheres, $this ); + + // Count + $count = $wpdb->get_var( $query ); + if ( $count === NULL ) $count = 0; + + // Existence check has first priority + if ( $count > 0 && $exists_check ) + $over_limit = true; + + // Limit check is second priority + elseif ( $period != 'x' && $count >= $amount ) + $over_limit = true; + + } + + return apply_filters( 'mycred_over_hook_limit', $over_limit, $instance, $reference, $user_id, $ref_id, $this ); + + } + + /** + * Get Limit Types + * @since 1.6 + * @version 1.0 + */ + public function get_limit_types() { + + return apply_filters( 'mycred_hook_limits', array( + 'x' => __( 'No limit', 'mycred' ), + 'd' => __( '/ Day', 'mycred' ), + 'w' => __( '/ Week', 'mycred' ), + 'm' => __( '/ Month', 'mycred' ), + 't' => __( 'in Total', 'mycred' ) + ), $this ); + + } + + /** + * Select Limit + * @since 1.6 + * @version 1.0 + */ + public function hook_limit_setting( $name = '', $id = '', $selected = '' ) { + + // Convert string value into an array + $check = explode( '/', $selected ); + $count = count( $check ); + + if ( $count == 0 || ( $count == 1 && $check[0] == 0 ) ) + $selected = array( 0, 'x' ); + + elseif ( $count == 1 && $check[0] != '' && is_numeric( $check[0] ) ) + $selected = array( (int) $check[0], 'd' ); + + else + $selected = $check; + + // Hide value field if no limit is set + $hide = 'text'; + if ( $selected[1] == 'x' ) + $hide = 'hidden'; + + // The limit value field + $output = '
'; + + // Get limit options + $options = $this->get_limit_types(); + + // Adjust the field name + $name = str_replace( '[limit]', '[limit_by]', $name ); + $name = str_replace( '[alimit]', '[alimit_by]', $name ); + $name = apply_filters( 'mycred_hook_limit_name_by', $name, $this ); + + // Adjust the field id + $id = str_replace( 'limit', 'limit-by', $id ); + $id = str_replace( 'alimit', 'alimit-by', $id ); + $id = apply_filters( 'mycred_hook_limit_id_by', $id, $this ); + + // Generate dropdown menu + $output .= '
'; + + return $output; + + } + + /** + * Impose Limits Dropdown + * @since 0.1 + * @version 1.3 + */ + public function impose_limits_dropdown( $pref_id = '', $use_select = true ) { + + $settings = ''; + $limits = array( + '' => __( 'No limit', 'mycred' ), + 'twentyfour' => __( 'Once every 24 hours', 'mycred' ), + 'sevendays' => __( 'Once every 7 days', 'mycred' ), + 'daily' => __( 'Once per day (reset at midnight)', 'mycred' ) + ); + $limits = apply_filters( 'mycred_hook_impose_limits', $limits, $this ); + + echo ''; + + } + + /** + * Has Entry + * Moved to myCRED_Settings + * @since 0.1 + * @version 1.3 + */ + public function has_entry( $action = '', $ref_id = '', $user_id = '', $data = '', $point_type = '' ) { + + // If logging is disabled, we cant use this feature + if ( ! MYCRED_ENABLE_LOGGING ) return false; + + if ( $point_type == '' ) + $point_type = $this->mycred_type; + + return $this->core->has_entry( $action, $ref_id, $user_id, $data, $point_type ); + + } + + /** + * Available Template Tags + * @since 1.4 + * @version 1.0 + */ + public function available_template_tags( $available = array(), $custom = '' ) { + + return $this->core->available_template_tags( $available, $custom ); + + } + + /** + * Over Daily Limit + * @since 1.0 + * @version 1.1.1 + */ + public function is_over_daily_limit( $ref = '', $user_id = 0, $max = 0, $ref_id = NULL ) { + + // If logging is disabled, we cant use this feature + if ( ! MYCRED_ENABLE_LOGGING ) return false; + + // Prep + $reply = true; + + // DB Query + $total = $this->limit_query( $ref, $user_id, strtotime( 'today midnight', $this->now ), $this->now, $ref_id ); + + if ( $total < $max ) + $reply = false; + + return apply_filters( 'mycred_hook_over_daily_limit', $reply, $ref, $user_id, $max ); + + } + + /** + * Include Post Type + * Checks if a given post type should be excluded + * @since 0.1 + * @version 1.1 + */ + public function include_post_type( $post_type ) { + + // Exclude Core + $excludes = array( 'post', 'page' ); + if ( in_array( $post_type, apply_filters( 'mycred_post_type_excludes', $excludes ) ) ) return false; + + return true; + + } + + /** + * Limit Query + * Queries the myCRED log for the number of occurances of the specified + * refernece and optional reference id for a specific user between two dates. + * @param $ref (string) reference to search for, required + * @param $user_id (int) user id to search for, required + * @param $start (int) unix timestamp for start date, required + * @param $end (int) unix timestamp for the end date, required + * @param $ref_id (int) optional reference id to include in search + * @returns number of entries found (int) or NULL if required params are missing + * @since 1.4 + * @version 1.2 + */ + public function limit_query( $ref = '', $user_id = 0, $start = 0, $end = 0, $ref_id = NULL ) { + + // If logging is disabled, we cant use this feature + if ( ! MYCRED_ENABLE_LOGGING ) return 0; + + // Minimum requirements + if ( empty( $ref ) || $user_id == 0 || $start == 0 || $end == 0 ) + return NULL; + + global $wpdb, $mycred_log_table; + + // Prep + $reply = true; + $wheres = array(); + + $wheres[] = $wpdb->prepare( "ref = %s", $ref ); + $wheres[] = $wpdb->prepare( "user_id = %d", $user_id ); + $wheres[] = $wpdb->prepare( "time BETWEEN %d AND %d", $start, $end ); + $wheres[] = $wpdb->prepare( "ctype = %s", $this->mycred_type ); + + if ( $ref_id !== NULL ) + $wheres[] = $wpdb->prepare( "ref_id = %d", $ref_id ); + + $wheres = implode( " AND ", $wheres ); + + // DB Query + $total = $wpdb->get_var( "SELECT COUNT(*) FROM {$mycred_log_table} WHERE {$wheres};" ); + if ( $total === NULL ) $total = 0; + + return apply_filters( 'mycred_hook_limit_query', $total, $ref, $user_id, $ref_id, $start, $end ); + + } + + } endif; diff --git a/abstracts/mycred-abstract-module.php b/abstracts/mycred-abstract-module.php index d7f0ede..1213491 100644 --- a/abstracts/mycred-abstract-module.php +++ b/abstracts/mycred-abstract-module.php @@ -1,834 +1,725 @@ module_id = $module_id; - $this->core = mycred($type); + $this->module_id = $module_id; + $this->core = mycred( $type ); - if (! empty($type) ) { - $this->core->cred_id = sanitize_text_field($type); - $this->mycred_type = $this->core->cred_id; - } + if ( ! empty( $type ) ) { + $this->core->cred_id = sanitize_text_field( $type ); + $this->mycred_type = $this->core->cred_id; + } - if ($this->mycred_type != MYCRED_DEFAULT_TYPE_KEY ) { - $this->is_main_type = false; - } + if ( $this->mycred_type != MYCRED_DEFAULT_TYPE_KEY ) + $this->is_main_type = false; - $this->point_types = mycred_get_types(); + $this->point_types = mycred_get_types(); - // Default arguments - $defaults = array( - 'module_name' => '', - 'option_id' => '', - 'defaults' => array(), - 'labels' => array( - 'menu' => '', - 'page_title' => '' - ), - 'register' => true, - 'screen_id' => '', - 'add_to_core' => false, - 'accordion' => false, - 'cap' => 'plugin', - 'menu_pos' => 10, - 'main_menu' => false - ); - $args = wp_parse_args($args, $defaults); + // Default arguments + $defaults = array( + 'module_name' => '', + 'option_id' => '', + 'defaults' => array(), + 'labels' => array( + 'menu' => '', + 'page_title' => '' + ), + 'register' => true, + 'screen_id' => '', + 'add_to_core' => false, + 'accordion' => false, + 'cap' => 'plugin', + 'menu_pos' => 10, + 'main_menu' => false + ); + $args = wp_parse_args( $args, $defaults ); - $this->module_name = $args['module_name']; - $this->option_id = $args['option_id']; + $this->module_name = $args['module_name']; + $this->option_id = $args['option_id']; - if (! $this->is_main_type ) { - $this->option_id .= '_' . $this->mycred_type; - } + if ( ! $this->is_main_type ) + $this->option_id .= '_' . $this->mycred_type; - $this->settings_name = 'myCRED-' . $this->module_name; - if (! $this->is_main_type ) { - $this->settings_name .= '-' . $this->mycred_type; - } + $this->settings_name = 'myCRED-' . $this->module_name; + if ( ! $this->is_main_type ) + $this->settings_name .= '-' . $this->mycred_type; - $this->labels = $args['labels']; - $this->register = $args['register']; - $this->screen_id = $args['screen_id']; + $this->labels = $args['labels']; + $this->register = $args['register']; + $this->screen_id = $args['screen_id']; - if (! $this->is_main_type && ! empty($this->screen_id) ) { - $this->screen_id = 'mycred_' . $this->mycred_type . substr($this->screen_id, 6); - } + if ( ! $this->is_main_type && ! empty( $this->screen_id ) ) + $this->screen_id = 'mycred_' . $this->mycred_type . substr( $this->screen_id, 6 ); - $this->add_to_core = $args['add_to_core']; - $this->accordion = $args['accordion']; - $this->cap = $args['cap']; - $this->menu_pos = $args['menu_pos']; + $this->add_to_core = $args['add_to_core']; + $this->accordion = $args['accordion']; + $this->cap = $args['cap']; + $this->menu_pos = $args['menu_pos']; - $this->default_prefs = $args['defaults']; - $this->now = current_time('timestamp'); - $this->main_menu = $args['main_menu']; + $this->default_prefs = $args['defaults']; + $this->now = current_time( 'timestamp' ); + $this->main_menu = $args['main_menu']; - $this->set_settings(); + $this->set_settings(); - } + } - /** - * Set Settings - * - * @since 0.1 - * @version 1.2.1 - */ - public function set_settings() - { + /** + * Set Settings + * @since 0.1 + * @version 1.2.1 + */ + public function set_settings() { - $module = $this->module_name; + $module = $this->module_name; - // Reqest not to register any settings - if ($this->register === false ) { + // Reqest not to register any settings + if ( $this->register === false ) { - // If settings does not exist apply defaults - if (! isset($this->core->$module) ) { - $this->$module = $this->default_prefs; - } + // If settings does not exist apply defaults + if ( ! isset( $this->core->$module ) ) + $this->$module = $this->default_prefs; - // Else append settings - else { - $this->$module = $this->core->$module; - } + // Else append settings + else + $this->$module = $this->core->$module; - // Apply defaults in case new settings have been applied - if (! empty($this->default_prefs) ) { - $this->$module = wp_parse_args($this->$module, $this->default_prefs); - } + // Apply defaults in case new settings have been applied + if ( ! empty( $this->default_prefs ) ) + $this->$module = wp_parse_args( $this->$module, $this->default_prefs ); - } + } - // Request to register settings - else { + // Request to register settings + else { - // Option IDs must be provided - if (! empty($this->option_id) ) { + // Option IDs must be provided + if ( ! empty( $this->option_id ) ) { - // Array = more then one - if (is_array($this->option_id) ) { + // Array = more then one + if ( is_array( $this->option_id ) ) { - // General settings needs not to be loaded - $pattern = 'mycred_pref_core'; - //$matches = array_filter( $this->option_id, function( $a ) use ( $pattern ) { return preg_grep( $a, $pattern ); } ); - //if ( ! empty( $matches ) ) - $this->$module = $this->core; - - // Loop and grab - foreach ( $this->option_id as $option_id => $option_name ) { - - $settings = mycred_get_option($option_name, false); - - if ($settings === false && array_key_exists($option_id, $defaults) ) { - $this->$module[ $option_name ] = $this->default_prefs[ $option_id ]; - } else { - $this->$module[ $option_name ] = $settings; - } - - // Apply defaults in case new settings have been applied - if (array_key_exists($option_id, $this->default_prefs) ) { - $this->$module[ $option_name ] = wp_parse_args($this->$module[ $option_name ], $this->default_prefs[ $option_id ]); - } - - } - - } - - // String = one - else { - - // General settings needs not to be loaded - if (str_replace('mycred_pref_core', '', $this->option_id) == '' ) { - $this->$module = $this->core; - } - - // Grab the requested option - else { - - $this->$module = mycred_get_option($this->option_id, false); - - if ($this->$module === false && ! empty($this->default_prefs) ) { - $this->$module = $this->default_prefs; - } - - // Apply defaults in case new settings have been applied - if (! empty($this->default_prefs) ) { - $this->$module = wp_parse_args($this->$module, $this->default_prefs); - } - - } - - } - - if (is_array($this->$module) ) { - - foreach ( $this->$module as $key => $value ) { - $this->$key = $value; - } - - } - - } - - } - - } - - /** - * Load - * - * @since 0.1 - * @version 1.0.1 - */ - public function load() - { - - if (! empty($this->screen_id) && ! empty($this->labels['menu']) ) { - add_action('mycred_add_menu', array( $this, 'add_menu' ), $this->menu_pos); - add_action('admin_init', array( $this, 'set_entries_per_page' )); - } - - if ($this->register === true && ! empty($this->option_id) ) { - add_action('mycred_admin_init', array( $this, 'register_settings' ), $this->menu_pos); - } - - if ($this->add_to_core === true ) { - add_action('mycred_after_core_prefs', array( $this, 'after_general_settings' )); - add_filter('mycred_save_core_prefs', array( $this, 'sanitize_extra_settings' ), 90, 3); - } - - add_action('mycred_pre_init', array( $this, 'module_pre_init' )); - add_action('mycred_init', array( $this, 'module_init' )); - add_action('mycred_admin_init', array( $this, 'module_admin_init' ), $this->menu_pos+1); - add_action('mycred_widgets_init', array( $this, 'module_widgets_init' )); - add_action('mycred_admin_enqueue', array( $this, 'scripts_and_styles' ), $this->menu_pos); - - } - - /** - * myCRED Ready - * No longer available as of version 1.4 - * - * @since 1.1.1 - * @version 1.0 - */ - public function module_ready() - { - } - - /** - * Plugins Loaded (pre init) - * - * @since 0.1 - * @version 1.0 - */ - public function module_pre_init() - { - } - - /** - * Init - * - * @since 0.1 - * @version 1.0 - */ - public function module_init() - { - } - - /** - * Admin Init - * - * @since 0.1 - * @version 1.0 - */ - public function module_admin_init() - { - } - - /** - * Widgets Init - * - * @since 0.1 - * @version 1.0 - */ - public function module_widgets_init() - { - } - - /** - * Get - * - * @since 0.1 - * @version 1.0 - */ - public function get() - { - } - - /** - * Call - * Either runs a given class method or function. - * Defaults to an empty array if class/function does not exist - * - * @since 0.1 - * @version 1.0.3 - */ - public function call( $call, $callback, $return = null ) - { - - // Class - if (is_array($callback) && class_exists($callback[0]) ) { - - $class = $callback[0]; - $methods = get_class_methods($class); - if (in_array($call, $methods) ) { - $new = new $class($this); - return $new->$call($return); - } - - } - - // Function - elseif (! is_array($callback) ) { - - if (function_exists($callback) ) { - - if ($return !== null ) { - return call_user_func($callback, $return, $this); - } else { - return call_user_func($callback, $this); - } - - } - - } - - if ($return !== null ) { - return array(); - } - - } - - /** - * If Installed - * Checks if hooks have been installed - * - * @returns (bool) true or false - * @since 0.1 - * @version 1.0 - */ - public function is_installed() - { - - $module_name = $this->module_name; - if ($this->$module_name === false ) { return false; - } - return true; - - } - - /** - * Is Active - * - * @param $key (string) required key to check for - * @returns (bool) true or false - * @since 0.1 - * @version 1.1 - */ - public function is_active( $key = '' ) - { - - $module = $this->module_name; - $is_active = false; - - if (! isset($this->active) && ! empty($key) ) { - - if (isset($this->$module['active']) ) { - $active = $this->$module['active']; - } - - if (in_array($key, $active) ) { - $is_active = true; - } - - } - - elseif (isset($this->active) && ! empty($key) ) { - - if (in_array($key, $this->active) ) { - $is_active = true; - } - - } - - return apply_filters('mycred_module_is_active', $is_active, $module, $key, $this); - - } - - /** - * Add Admin Menu Item - * - * @since 0.1 - * @version 1.3 - */ - public function add_menu() - { - - // In case we are using the Master Template feautre on multisites, and this is not the main - // site in the network, bail. - if ($this->module_id != 'myCRED_Log_Module' && mycred_override_settings() && ! mycred_is_main_site() ) { return; - } - - // Minimum requirements - if (! empty($this->labels) && ! empty($this->screen_id) ) { - - // Menu Slug - $menu_slug = ( ! $this->is_main_type ) ? MYCRED_SLUG . '_' . $this->mycred_type : MYCRED_SLUG; - $label_menu = $label_title = 'Surprise'; - - // Capability - $capability = ( $this->cap == 'plugin' ) ? $this->core->get_point_admin_capability() : $this->core->get_point_editor_capability(); - - // Menu Label - if (isset($this->labels['menu']) ) { - $label_menu = $this->labels['menu']; - - } elseif (isset($this->labels['page_title']) ) { - $label_menu = $this->labels['page_title']; - } - - // Page Title - if (isset($this->labels['page_title']) ) { - $label_title = $this->labels['page_title']; - - } elseif (isset($this->labels['menu']) ) { - $label_title = $this->labels['menu']; - } - - if ($this->main_menu ) { - $menu_slug = MYCRED_MAIN_SLUG; - } - - // Add Submenu Page - $page = add_submenu_page( - $menu_slug, - $label_menu, - $label_title, - $capability, - $this->screen_id, - array( $this, 'admin_page' ) - ); - - add_action('admin_print_styles-' . $page, array( $this, 'settings_page_enqueue' )); - add_action('load-' . $page, array( $this, 'screen_options' )); - - } - - } - - /** - * Register Scripts & Styles - * - * @since 1.7 - * @version 1.0 - */ - public function scripts_and_styles() - { - } + // General settings needs not to be loaded + $pattern = 'mycred_pref_core'; + //$matches = array_filter( $this->option_id, function( $a ) use ( $pattern ) { return preg_grep( $a, $pattern ); } ); + //if ( ! empty( $matches ) ) + $this->$module = $this->core; - /** - * Save Log Entries per page - * - * @since 0.1 - * @version 1.0.1 - */ - public function set_entries_per_page() - { - - if (! isset($_REQUEST['wp_screen_options']['option']) || ! isset($_REQUEST['wp_screen_options']['value']) || ! isset( $_GET['page'] ) ) { - return; - } - - $settings_key = 'mycred_epp_' . sanitize_key( $_GET['page'] ); + // Loop and grab + foreach ( $this->option_id as $option_id => $option_name ) { - if ($_REQUEST['wp_screen_options']['option'] == $settings_key ) { - $value = absint($_REQUEST['wp_screen_options']['value']); - mycred_update_user_meta(get_current_user_id(), $settings_key, '', $value); - } - - } - - /** - * Register Settings - * - * @since 0.1 - * @version 1.1 - */ - public function register_settings() - { - - if (empty($this->option_id) || $this->register === false ) { return; - } - - register_setting($this->settings_name, $this->option_id, array( $this, 'sanitize_settings' )); - - } - - /** - * Screen Options - * - * @since 1.4 - * @version 1.0 - */ - public function screen_options() - { - - $this->set_entries_per_page(); - - } - - /** - * Add Metabox Class - * - * @since 1.7 - * @version 1.0 - */ - public function metabox_classes( $classes ) - { - - $classes[] = 'mycred-metabox'; - - return $classes; - - } - - /** - * Enqueue Scripts & Styles - * Scripts and styles to enqueu on module admin pages. - * - * @since 1.4 - * @version 1.0.1 - */ - public function settings_page_enqueue() - { - - wp_dequeue_script('bpge_admin_js_acc'); - - // Load Accordion - if ($this->accordion ) { - - wp_enqueue_style('mycred-admin'); - wp_enqueue_script('mycred-accordion'); - - ?> + $settings = mycred_get_option( $option_name, false ); + + if ( $settings === false && array_key_exists( $option_id, $defaults ) ) + $this->$module[ $option_name ] = $this->default_prefs[ $option_id ]; + else + $this->$module[ $option_name ] = $settings; + + // Apply defaults in case new settings have been applied + if ( array_key_exists( $option_id, $this->default_prefs ) ) + $this->$module[ $option_name ] = wp_parse_args( $this->$module[ $option_name ], $this->default_prefs[ $option_id ] ); + + } + + } + + // String = one + else { + + // General settings needs not to be loaded + if ( str_replace( 'mycred_pref_core', '', $this->option_id ) == '' ) + $this->$module = $this->core; + + // Grab the requested option + else { + + $this->$module = mycred_get_option( $this->option_id, false ); + + if ( $this->$module === false && ! empty( $this->default_prefs ) ) + $this->$module = $this->default_prefs; + + // Apply defaults in case new settings have been applied + if ( ! empty( $this->default_prefs ) ) + $this->$module = wp_parse_args( $this->$module, $this->default_prefs ); + + } + + } + + if ( is_array( $this->$module ) ) { + + foreach ( $this->$module as $key => $value ) { + $this->$key = $value; + } + + } + + } + + } + + } + + /** + * Load + * @since 0.1 + * @version 1.0.1 + */ + public function load() { + + if ( ! empty( $this->screen_id ) && ! empty( $this->labels['menu'] ) ) { + add_action( 'mycred_add_menu', array( $this, 'add_menu' ), $this->menu_pos ); + add_action( 'admin_init', array( $this, 'set_entries_per_page' ) ); + } + + if ( $this->register === true && ! empty( $this->option_id ) ) + add_action( 'mycred_admin_init', array( $this, 'register_settings' ), $this->menu_pos ); + + if ( $this->add_to_core === true ) { + add_action( 'mycred_after_core_prefs', array( $this, 'after_general_settings' ) ); + add_filter( 'mycred_save_core_prefs', array( $this, 'sanitize_extra_settings' ), 90, 3 ); + } + + add_action( 'mycred_pre_init', array( $this, 'module_pre_init' ) ); + add_action( 'mycred_init', array( $this, 'module_init' ) ); + add_action( 'mycred_admin_init', array( $this, 'module_admin_init' ), $this->menu_pos+1 ); + add_action( 'mycred_widgets_init', array( $this, 'module_widgets_init' ) ); + add_action( 'mycred_admin_enqueue', array( $this, 'scripts_and_styles' ), $this->menu_pos ); + + } + + /** + * myCRED Ready + * No longer available as of version 1.4 + * @since 1.1.1 + * @version 1.0 + */ + public function module_ready() { } + + /** + * Plugins Loaded (pre init) + * @since 0.1 + * @version 1.0 + */ + public function module_pre_init() { } + + /** + * Init + * @since 0.1 + * @version 1.0 + */ + public function module_init() { } + + /** + * Admin Init + * @since 0.1 + * @version 1.0 + */ + public function module_admin_init() { } + + /** + * Widgets Init + * @since 0.1 + * @version 1.0 + */ + public function module_widgets_init() { } + + /** + * Get + * @since 0.1 + * @version 1.0 + */ + public function get() { } + + /** + * Call + * Either runs a given class method or function. + * Defaults to an empty array if class/function does not exist + * @since 0.1 + * @version 1.0.3 + */ + public function call( $call, $callback, $return = NULL ) { + + // Class + if ( is_array( $callback ) && class_exists( $callback[0] ) ) { + + $class = $callback[0]; + $methods = get_class_methods( $class ); + if ( in_array( $call, $methods ) ) { + $new = new $class( $this ); + return $new->$call( $return ); + } + + } + + // Function + elseif ( ! is_array( $callback ) ) { + + if ( function_exists( $callback ) ) { + + if ( $return !== NULL ) + return call_user_func( $callback, $return, $this ); + else + return call_user_func( $callback, $this ); + + } + + } + + if ( $return !== NULL ) + return array(); + + } + + /** + * If Installed + * Checks if hooks have been installed + * + * @returns (bool) true or false + * @since 0.1 + * @version 1.0 + */ + public function is_installed() { + + $module_name = $this->module_name; + if ( $this->$module_name === false ) return false; + return true; + + } + + /** + * Is Active + * @param $key (string) required key to check for + * @returns (bool) true or false + * @since 0.1 + * @version 1.1 + */ + public function is_active( $key = '' ) { + + $module = $this->module_name; + $is_active = false; + + if ( ! isset( $this->active ) && ! empty( $key ) ) { + + if ( isset( $this->$module['active'] ) ) + $active = $this->$module['active']; + + if ( in_array( $key, $active ) ) + $is_active = true; + + } + + elseif ( isset( $this->active ) && ! empty( $key ) ) { + + if ( in_array( $key, $this->active ) ) + $is_active = true; + + } + + return apply_filters( 'mycred_module_is_active', $is_active, $module, $key, $this ); + + } + + /** + * Add Admin Menu Item + * @since 0.1 + * @version 1.3 + */ + public function add_menu() { + + // In case we are using the Master Template feautre on multisites, and this is not the main + // site in the network, bail. + if ( $this->module_id != 'myCRED_Log_Module' && mycred_override_settings() && ! mycred_is_main_site() ) return; + + // Minimum requirements + if ( ! empty( $this->labels ) && ! empty( $this->screen_id ) ) { + + // Menu Slug + $menu_slug = ( ! $this->is_main_type ) ? MYCRED_SLUG . '_' . $this->mycred_type : MYCRED_SLUG; + $label_menu = $label_title = 'Surprise'; + + // Capability + $capability = ( $this->cap == 'plugin' ) ? $this->core->get_point_admin_capability() : $this->core->get_point_editor_capability(); + + // Menu Label + if ( isset( $this->labels['menu'] ) ) + $label_menu = $this->labels['menu']; + + elseif ( isset( $this->labels['page_title'] ) ) + $label_menu = $this->labels['page_title']; + + // Page Title + if ( isset( $this->labels['page_title'] ) ) + $label_title = $this->labels['page_title']; + + elseif ( isset( $this->labels['menu'] ) ) + $label_title = $this->labels['menu']; + + if ( $this->main_menu ) + $menu_slug = MYCRED_MAIN_SLUG; + + // Add Submenu Page + $page = add_submenu_page( + $menu_slug, + $label_menu, + $label_title, + $capability, + $this->screen_id, + array( $this, 'admin_page' ) + ); + + add_action( 'admin_print_styles-' . $page, array( $this, 'settings_page_enqueue' ) ); + add_action( 'load-' . $page, array( $this, 'screen_options' ) ); + + } + + } + + /** + * Register Scripts & Styles + * @since 1.7 + * @version 1.0 + */ + public function scripts_and_styles() { } + + /** + * Save Log Entries per page + * @since 0.1 + * @version 1.0.1 + */ + public function set_entries_per_page() { + + if ( ! isset( $_REQUEST['wp_screen_options']['option'] ) || ! isset( $_REQUEST['wp_screen_options']['value'] ) || ! isset( $_GET['page'] ) ) return; + + $settings_key = 'mycred_epp_' . sanitize_key( $_GET['page'] ); + + if ( $_REQUEST['wp_screen_options']['option'] == $settings_key ) { + $value = absint( $_REQUEST['wp_screen_options']['value'] ); + mycred_update_user_meta( get_current_user_id(), $settings_key, '', $value ); + } + + } + + /** + * Register Settings + * @since 0.1 + * @version 1.1 + */ + public function register_settings() { + + if ( empty( $this->option_id ) || $this->register === false ) return; + + register_setting( $this->settings_name, $this->option_id, array( $this, 'sanitize_settings' ) ); + + } + + /** + * Screen Options + * @since 1.4 + * @version 1.0 + */ + public function screen_options() { + + $this->set_entries_per_page(); + + } + + /** + * Add Metabox Class + * @since 1.7 + * @version 1.0 + */ + public function metabox_classes( $classes ) { + + $classes[] = 'mycred-metabox'; + + return $classes; + + } + + /** + * Enqueue Scripts & Styles + * Scripts and styles to enqueu on module admin pages. + * @since 1.4 + * @version 1.0.1 + */ + public function settings_page_enqueue() { + + wp_dequeue_script( 'bpge_admin_js_acc' ); + + // Load Accordion + if ( $this->accordion ) { + + wp_enqueue_style( 'mycred-admin' ); + wp_enqueue_script( 'mycred-accordion' ); + +?> - settings_header(); - - } - - /** - * Settings Header - * Scripts and styles to insert after scripts are printed. - * - * @since 0.1 - * @version 1.2 - */ - public function settings_header() - { - } - - /** - * Admin Page - * - * @since 0.1 - * @version 1.0 - */ - public function admin_page() - { - } - - /** - * Update Notice - * - * @since 1.4 - * @version 1.0 - */ - public function update_notice( $get = 'settings-updated', $class = 'updated', $message = '' ) - { - - if (empty($message) ) { - $message = __('Settings Updated', 'mycred'); - } - - if (isset($_GET[ $get ]) ) { - echo '

' . esc_html( $message ) . '

'; - } - - } - - /** - * Sanitize Settings - * - * @since 0.1 - * @version 1.0 - */ - public function sanitize_settings( $post ) - { - - return $post; - - } - - /** - * After General Settings - * - * @since 0.1 - * @version 1.0 - */ - public function after_general_settings( $mycred = null ) - { - } +settings_header(); + + } + + /** + * Settings Header + * Scripts and styles to insert after scripts are printed. + * @since 0.1 + * @version 1.2 + */ + public function settings_header() { } + + /** + * Admin Page + * @since 0.1 + * @version 1.0 + */ + public function admin_page() { } + + /** + * Update Notice + * @since 1.4 + * @version 1.0 + */ + public function update_notice( $get = 'settings-updated', $class = 'updated', $message = '' ) { + + if ( empty( $message ) ) + $message = __( 'Settings Updated', 'mycred' ); + + if ( isset( $_GET[ $get ] ) ) + echo '

' . esc_html( $message ) . '

'; + + } + + /** + * Sanitize Settings + * @since 0.1 + * @version 1.0 + */ + public function sanitize_settings( $post ) { + + return $post; + + } + + /** + * After General Settings + * @since 0.1 + * @version 1.0 + */ + public function after_general_settings( $mycred = NULL ) { } + + /** + * Sanitize Core Settings + * @since 0.1 + * @version 1.0 + */ + public function sanitize_extra_settings( $new_data, $data, $core ) { + + return $new_data; + + } + + /** + * Input Field Name Value + * @since 0.1 + * @version 1.0 + */ + public function field_name( $name = '' ) { + + if ( is_array( $name ) ) { + + $array = array(); + foreach ( $name as $parent => $child ) { + + if ( ! is_numeric( $parent ) ) + $array[] = $parent; + + if ( ! empty( $child ) && ! is_array( $child ) ) + $array[] = $child; + + } + $name = '[' . implode( '][', $array ) . ']'; + + } + else { + + $name = '[' . $name . ']'; + + } + + if ( $this->add_to_core === true ) + $name = '[' . $this->module_name . ']' . $name; + + if ( $this->option_id != '' ) + return $this->option_id . $name; + + return 'mycred_pref_core' . $name; + + } - /** - * Sanitize Core Settings - * - * @since 0.1 - * @version 1.0 - */ - public function sanitize_extra_settings( $new_data, $data, $core ) - { - - return $new_data; - - } - - /** - * Input Field Name Value - * - * @since 0.1 - * @version 1.0 - */ - public function field_name( $name = '' ) - { - - if (is_array($name) ) { - - $array = array(); - foreach ( $name as $parent => $child ) { - - if (! is_numeric($parent) ) { - $array[] = $parent; - } - - if (! empty($child) && ! is_array($child) ) { - $array[] = $child; - } - - } - $name = '[' . implode('][', $array) . ']'; - - } - else { - - $name = '[' . $name . ']'; - - } - - if ($this->add_to_core === true ) { - $name = '[' . $this->module_name . ']' . $name; - } - - if ($this->option_id != '' ) { - return $this->option_id . $name; - } - - return 'mycred_pref_core' . $name; - - } - - /** - * Input Field Id Value - * - * @since 0.1 - * @version 1.0 - */ - public function field_id( $id = '' ) - { + /** + * Input Field Id Value + * @since 0.1 + * @version 1.0 + */ + public function field_id( $id = '' ) { - if (is_array($id) ) { + if ( is_array( $id ) ) { - $array = array(); - foreach ( $id as $parent => $child ) { + $array = array(); + foreach ( $id as $parent => $child ) { - if (! is_numeric($parent) ) { - $array[] = str_replace('_', '-', $parent); - } + if ( ! is_numeric( $parent ) ) + $array[] = str_replace( '_', '-', $parent ); - if (! empty($child) && ! is_array($child) ) { - $array[] = str_replace('_', '-', $child); - } + if ( ! empty( $child ) && ! is_array( $child ) ) + $array[] = str_replace( '_', '-', $child ); - } - $id = implode('-', $array); + } + $id = implode( '-', $array ); - } - else { + } + else { - $id = str_replace('_', '-', $id); + $id = str_replace( '_', '-', $id ); - } + } - if ($this->add_to_core === true ) { - $id = 'prefs' . $id; - } + if ( $this->add_to_core === true ) + $id = 'prefs' . $id; - $id = strtolower($this->module_name) . $id; - $id = strtolower($id); - $id = str_replace(array( '[', ']' ), '', $id); - $id = str_replace(array( '_', '-' ), '', $id); + $id = strtolower( $this->module_name ) . $id; + $id = strtolower( $id ); + $id = str_replace( array( '[', ']' ), '', $id ); + $id = str_replace( array( '_', '-' ), '', $id ); - return $id; + return $id; - } + } - /** - * Available Template Tags - * - * @since 1.4 - * @version 1.0 - */ - public function available_template_tags( $available = array() ) - { + /** + * Available Template Tags + * @since 1.4 + * @version 1.0 + */ + public function available_template_tags( $available = array() ) { - return $this->core->available_template_tags($available); + return $this->core->available_template_tags( $available ); - } + } - /** - * Get Settings URL - * - * @since 1.4 - * @version 1.0.1 - */ - public function get_settings_url( $module = '' ) - { + /** + * Get Settings URL + * @since 1.4 + * @version 1.0.1 + */ + public function get_settings_url( $module = '' ) { - $variables = array( 'page' => MYCRED_SLUG . '-settings' ); - if (! empty($module) ) { - $variables['open-tab'] = $module; - } + $variables = array( 'page' => MYCRED_SLUG . '-settings' ); + if ( ! empty( $module ) ) + $variables['open-tab'] = $module; - $url = add_query_arg($variables, admin_url('admin.php')); + $url = add_query_arg( $variables, admin_url( 'admin.php' ) ); - return esc_url($url); + return esc_url( $url ); - } + } - /** - * Request to Entry - * - * @since 1.6 - * @version 1.0 - */ - public function request_to_entry( $request = array() ) - { + /** + * Request to Entry + * @since 1.6 + * @version 1.0 + */ + public function request_to_entry( $request = array() ) { - if (empty($request) ) { return false; - } + if ( empty( $request ) ) return false; - $entry = new stdClass(); + $entry = new stdClass(); - $entry->id = -1; - $entry->ref = $request['ref']; - $entry->ref_id = $request['ref_id']; - $entry->user_id = $request['user_id']; - $entry->time = $this->now; - $entry->entry = $request['entry']; - $entry->data = $request['data']; - $entry->ctype = $request['type']; + $entry->id = -1; + $entry->ref = $request['ref']; + $entry->ref_id = $request['ref_id']; + $entry->user_id = $request['user_id']; + $entry->time = $this->now; + $entry->entry = $request['entry']; + $entry->data = $request['data']; + $entry->ctype = $request['type']; - return $entry; + return $entry; - } + } - } + } endif; diff --git a/abstracts/mycred-abstract-object.php b/abstracts/mycred-abstract-object.php index 7075383..afd84d9 100644 --- a/abstracts/mycred-abstract-object.php +++ b/abstracts/mycred-abstract-object.php @@ -1,117 +1,103 @@ $array_value ) { + foreach ( $name as $key => $array_value ) { - // Example 1: array( 'balance' => 'mycred_default' ) - // $this->balance['mycred_default'] - if (isset($this->$key) ) { + // Example 1: array( 'balance' => 'mycred_default' ) + // $this->balance['mycred_default'] + if ( isset( $this->$key ) ) { - if ($array_value != '' && is_array($this->$key) && ! empty($this->$key) && array_key_exists($array_value, $this->$key) ) { - $value = $this->$key[ $array_value ]; - } + if ( $array_value != '' && is_array( $this->$key ) && ! empty( $this->$key ) && array_key_exists( $array_value, $this->$key ) ) + $value = $this->$key[ $array_value ]; - } + } - // Example 2: array( 'total' ) - // $this->total - elseif (isset($this->$array_value) ) { - $value = $this->$array_value; - } + // Example 2: array( 'total' ) + // $this->total + elseif ( isset( $this->$array_value ) ) + $value = $this->$array_value; - } + } - } - elseif (! is_array($name) && ! empty($name) ) { + } + elseif ( ! is_array( $name ) && ! empty( $name ) ) { - if (isset($this->$name) ) { - $value = $this->$name; - } + if ( isset( $this->$name ) ) + $value = $this->$name; - } + } - return $value; + return $value; - } + } - /** - * Set - */ - public function set( $name = '', $new_value = false ) - { + /** + * Set + */ + public function set( $name = '', $new_value = false ) { - if ($name == '' ) { return false; - } + if ( $name == '' ) return false; - if (is_array($name) && ! empty($name) ) { + if ( is_array( $name ) && ! empty( $name ) ) { - foreach ( $name as $key => $array_value ) { + foreach ( $name as $key => $array_value ) { - // Example 1: array( 'balance' => 'mycred_default' ) - // $this->balance['mycred_default'] - if (isset($this->$key) ) { + // Example 1: array( 'balance' => 'mycred_default' ) + // $this->balance['mycred_default'] + if ( isset( $this->$key ) ) { - if ($array_value != '' ) { + if ( $array_value != '' ) { - if (! is_array($this->$key) ) { - $this->$key = array(); - } - - $this->$key[ $array_value ] = $new_value; + if ( ! is_array( $this->$key ) ) + $this->$key = array(); + + $this->$key[ $array_value ] = $new_value; - } + } - } + } - // Example 2: array( 'total' ) - // $this->total - elseif (isset($this->$array_value) ) { - $this->$value = $new_value; - } + // Example 2: array( 'total' ) + // $this->total + elseif ( isset( $this->$array_value ) ) + $this->$value = $new_value; - } + } - } - elseif (! is_array($name) && ! empty($name) && isset($this->$name) ) { + } + elseif ( ! is_array( $name ) && ! empty( $name ) && isset( $this->$name ) ) { - $this->$name = $new_value; + $this->$name = $new_value; - } + } - return true; + return true; - } + } - } + } endif; diff --git a/addons/badges/assets/css/front.css b/addons/badges/assets/css/front.css index 6f803e7..a2dbfce 100644 --- a/addons/badges/assets/css/front.css +++ b/addons/badges/assets/css/front.css @@ -1,7 +1,7 @@ .the-badge { display: flex; align-items: center; - justify-content: space-between; + justify-content: space-between; } hr.badge-line { diff --git a/addons/badges/assets/css/index.php b/addons/badges/assets/css/index.php index 1580272..4e6c07c 100644 --- a/addons/badges/assets/css/index.php +++ b/addons/badges/assets/css/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/badges/assets/index.php b/addons/badges/assets/index.php index 1580272..4e6c07c 100644 --- a/addons/badges/assets/index.php +++ b/addons/badges/assets/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/badges/assets/js/front.js b/addons/badges/assets/js/front.js index 29bf974..1d61e0d 100644 --- a/addons/badges/assets/js/front.js +++ b/addons/badges/assets/js/front.js @@ -1,45 +1,33 @@ -jQuery(document).ready( - function () { +jQuery(document).ready(function(){ - //Badges Search Filter - jQuery("#mycerd-badges-search").on( - "keyup", function () { - var value = jQuery(this).val().toLowerCase(); - jQuery(".mycred-badges-list .mycred-badges-list-item").filter( - function () { - jQuery(this).toggle(jQuery(this).text().toLowerCase().indexOf(value) > -1) - } - ); - } - ); + //Badges Search Filter + jQuery("#mycerd-badges-search").on("keyup", function() { + var value = jQuery(this).val().toLowerCase(); + jQuery(".mycred-badges-list .mycred-badges-list-item").filter(function() { + jQuery(this).toggle(jQuery(this).text().toLowerCase().indexOf(value) > -1) + }); + }); - //Show Achieved Badges - jQuery(document).on( - 'click', '.mycred-achieved-badge-btn', function (e) { - e.preventDefault(); - jQuery('.not-earned').hide(); - jQuery('.earned').show(); - } - ); + //Show Achieved Badges + jQuery(document).on( 'click', '.mycred-achieved-badge-btn', function(e){ + e.preventDefault(); + jQuery('.not-earned').hide(); + jQuery('.earned').show(); + }); - //Show Not Achieved Badges - jQuery(document).on( - 'click', '.mycred-not-achieved-badge-btn', function (e) { - e.preventDefault(); - jQuery('.earned').hide(); - jQuery('.not-earned').show(); - } - ); + //Show Not Achieved Badges + jQuery(document).on( 'click', '.mycred-not-achieved-badge-btn', function(e){ + e.preventDefault(); + jQuery('.earned').hide(); + jQuery('.not-earned').show(); + }); - //Clear Filter Button - jQuery(document).on( - 'click', '.mycred-clear-filter-btn', function (e) { - e.preventDefault() - jQuery('.earned').show(); - jQuery('.not-earned').show(); - jQuery('#mycerd-badges-search').val(''); - } - ) - } -); + //Clear Filter Button + jQuery(document).on( 'click', '.mycred-clear-filter-btn', function(e){ + e.preventDefault() + jQuery('.earned').show(); + jQuery('.not-earned').show(); + jQuery('#mycerd-badges-search').val(''); + } ) +}); diff --git a/addons/badges/assets/js/index.php b/addons/badges/assets/js/index.php index 1580272..4e6c07c 100644 --- a/addons/badges/assets/js/index.php +++ b/addons/badges/assets/js/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/badges/includes/index.php b/addons/badges/includes/index.php index 1580272..4e6c07c 100644 --- a/addons/badges/includes/index.php +++ b/addons/badges/includes/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/badges/includes/mycred-badge-functions.php b/addons/badges/includes/mycred-badge-functions.php index 0885004..a3e7502 100644 --- a/addons/badges/includes/mycred-badge-functions.php +++ b/addons/badges/includes/mycred-badge-functions.php @@ -1,818 +1,721 @@ post_id ) - ) { - return $mycred_badge; - } + if ( isset( $mycred_badge ) + && ( $mycred_badge instanceof myCRED_Badge ) + && ( $badge_id === $mycred_badge->post_id ) + ) { + return $mycred_badge; + } - $mycred_badge = new myCRED_Badge($badge_id, $level); + $mycred_badge = new myCRED_Badge( $badge_id, $level ); - do_action('mycred_get_badge'); + do_action( 'mycred_get_badge' ); - return $mycred_badge; + return $mycred_badge; - } + } endif; /** * Get Badge References * Returns an array of references used by badges for quicker checks. - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_get_badge_references') ) : - function mycred_get_badge_references( $point_type = MYCRED_DEFAULT_TYPE_KEY, $force = false ) - { +if ( ! function_exists( 'mycred_get_badge_references' ) ) : + function mycred_get_badge_references( $point_type = MYCRED_DEFAULT_TYPE_KEY, $force = false ) { - $references = mycred_get_option('mycred-badge-refs-' . $point_type); - if (! is_array($references) || empty($references) || $force ) { + $references = mycred_get_option( 'mycred-badge-refs-' . $point_type ); + if ( ! is_array( $references ) || empty( $references ) || $force ) { - global $wpdb; + global $wpdb; - $new_list = array(); + $new_list = array(); - // Old versions - $references = $wpdb->get_results("SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = 'badge_requirements';"); - if (! empty($references) ) { - foreach ( $references as $entry ) { + // Old versions + $references = $wpdb->get_results( "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = 'badge_requirements';" ); + if ( ! empty( $references ) ) { + foreach ( $references as $entry ) { - $requirement = maybe_unserialize($entry->meta_value); - if (! is_array($requirement) || empty($requirement) ) { continue; - } + $requirement = maybe_unserialize( $entry->meta_value ); + if ( ! is_array( $requirement ) || empty( $requirement ) ) continue; - if (! array_key_exists('type', $requirement) || $requirement['type'] != $point_type || $requirement['reference'] == '' ) { continue; - } + if ( ! array_key_exists( 'type', $requirement ) || $requirement['type'] != $point_type || $requirement['reference'] == '' ) continue; - if (! array_key_exists($requirement['reference'], $new_list) ) { - $new_list[ $requirement['reference'] ] = array(); - } + if ( ! array_key_exists( $requirement['reference'], $new_list ) ) + $new_list[ $requirement['reference'] ] = array(); - if (! in_array($entry->post_id, $new_list[ $requirement['reference'] ]) ) { - $new_list[ $requirement['reference'] ][] = $entry->post_id; - } + if ( ! in_array( $entry->post_id, $new_list[ $requirement['reference'] ] ) ) + $new_list[ $requirement['reference'] ][] = $entry->post_id; - } - } + } + } - // New version (post 1.7) - $table = mycred_get_db_column('postmeta'); - $references = $wpdb->get_results("SELECT post_id, meta_value FROM {$table} WHERE meta_key = 'badge_prefs';"); - if (! empty($references) ) { - foreach ( $references as $entry ) { + // New version (post 1.7) + $table = mycred_get_db_column( 'postmeta' ); + $references = $wpdb->get_results( "SELECT post_id, meta_value FROM {$table} WHERE meta_key = 'badge_prefs';" ); + if ( ! empty( $references ) ) { + foreach ( $references as $entry ) { - // Manual badges should be ignored - if (absint(mycred_get_post_meta($entry->post_id, 'manual_badge', true)) === 1 ) { continue; - } + // Manual badges should be ignored + if ( absint( mycred_get_post_meta( $entry->post_id, 'manual_badge', true ) ) === 1 ) continue; - $levels = maybe_unserialize($entry->meta_value); - if (! is_array($levels) || empty($levels) ) { continue; - } + $levels = maybe_unserialize( $entry->meta_value ); + if ( ! is_array( $levels ) || empty( $levels ) ) continue; - foreach ( $levels as $level => $setup ) { + foreach ( $levels as $level => $setup ) { - if ($level > 0 ) { continue; - } + if ( $level > 0 ) continue; - foreach ( $setup['requires'] as $requirement_row => $requirement ) { + foreach ( $setup['requires'] as $requirement_row => $requirement ) { - if ($requirement['type'] != $point_type || $requirement['reference'] == '' ) { continue; - } + if ( $requirement['type'] != $point_type || $requirement['reference'] == '' ) continue; - if (! array_key_exists($requirement['reference'], $new_list) ) { - $new_list[ $requirement['reference'] ] = array(); - } + if ( ! array_key_exists( $requirement['reference'], $new_list ) ) + $new_list[ $requirement['reference'] ] = array(); - if (! in_array($entry->post_id, $new_list[ $requirement['reference'] ]) ) { - $new_list[ $requirement['reference'] ][] = $entry->post_id; - } + if ( ! in_array( $entry->post_id, $new_list[ $requirement['reference'] ] ) ) + $new_list[ $requirement['reference'] ][] = $entry->post_id; - } + } - } + } - } - } + } + } - if (! empty($new_list) ) { - mycred_update_option('mycred-badge-references-' . $point_type, $new_list); - } + if ( ! empty( $new_list ) ) + mycred_update_option( 'mycred-badge-references-' . $point_type, $new_list ); - $references = $new_list; + $references = $new_list; - } + } - return apply_filters('mycred_get_badge_references', $references, $point_type); + return apply_filters( 'mycred_get_badge_references', $references, $point_type ); - } + } endif; /** * Get Badge Requirements * Returns the badge requirements as an array. - * - * @since 1.5 + * @since 1.5 * @version 1.1 */ -if (! function_exists('mycred_get_badge_requirements') ) : - function mycred_get_badge_requirements( $badge_id = null ) - { +if ( ! function_exists( 'mycred_get_badge_requirements' ) ) : + function mycred_get_badge_requirements( $badge_id = NULL ) { - return mycred_get_badge_levels($badge_id); + return mycred_get_badge_levels( $badge_id ); - } + } endif; /** * Get Badge Levels * Returns an array of levels associated with a given badge. - * - * @since 1.7 + * @since 1.7 * @version 1.0.1 */ -if (! function_exists('mycred_get_badge_levels') ) : - function mycred_get_badge_levels( $badge_id ) - { +if ( ! function_exists( 'mycred_get_badge_levels' ) ) : + function mycred_get_badge_levels( $badge_id ) { - $setup = mycred_get_post_meta($badge_id, 'badge_prefs', true); - if (! is_array($setup) || empty($setup) ) { + $setup = mycred_get_post_meta( $badge_id, 'badge_prefs', true ); + if ( ! is_array( $setup ) || empty( $setup ) ) { - // Backwards comp. - $old_setup = mycred_get_post_meta($badge_id, 'badge_requirements', true); + // Backwards comp. + $old_setup = mycred_get_post_meta( $badge_id, 'badge_requirements', true ); - // Convert old setup to new - if (is_array($old_setup) && ! empty($old_setup) ) { + // Convert old setup to new + if ( is_array( $old_setup ) && ! empty( $old_setup ) ) { - $new_setup = array(); - foreach ( $old_setup as $level => $requirements ) { + $new_setup = array(); + foreach ( $old_setup as $level => $requirements ) { - $level_image = mycred_get_post_meta($badge_id, 'level_image' . $level, true); - if ($level_image == '' || $level == 0 ) { - $level_image = mycred_get_post_meta($badge_id, 'main_image', true); - } + $level_image = mycred_get_post_meta( $badge_id, 'level_image' . $level, true ); + if ( $level_image == '' || $level == 0 ) + $level_image = mycred_get_post_meta( $badge_id, 'main_image', true ); - $row = array( - 'image_url' => $level_image, - 'attachment_id' => 0, - 'label' => '', - 'compare' => 'AND', - 'requires' => array(), - 'reward' => array( - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'amount' => 0, - 'log' => '' - ) - ); + $row = array( + 'image_url' => $level_image, + 'attachment_id' => 0, + 'label' => '', + 'compare' => 'AND', + 'requires' => array(), + 'reward' => array( + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'amount' => 0, + 'log' => '' + ) + ); - $row['requires'][] = $requirements; + $row['requires'][] = $requirements; - $new_setup[] = $row; + $new_setup[] = $row; - } + } - if (! empty($new_setup) ) { + if ( ! empty( $new_setup ) ) { - mycred_update_post_meta($badge_id, 'badge_prefs', $new_setup); - mycred_delete_post_meta($badge_id, 'badge_requirements'); + mycred_update_post_meta( $badge_id, 'badge_prefs', $new_setup ); + mycred_delete_post_meta( $badge_id, 'badge_requirements' ); - $setup = $new_setup; + $setup = $new_setup; - } + } - } + } - } + } - if (empty($setup) && ! is_array($setup) ) { - $setup = array(); - } + if ( empty( $setup ) && ! is_array( $setup ) ) + $setup = array(); - if (empty($setup) ) { - $setup[] = array( - 'image_url' => '', - 'attachment_id' => 0, - 'label' => '', - 'compare' => 'AND', - 'requires' => array( - 0 => array( - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'reference' => '', - 'amount' => '', - 'by' => '' - ) - ), - 'reward' => array( - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'amount' => 0, - 'log' => '' - ) - ); - } + if ( empty( $setup ) ) + $setup[] = array( + 'image_url' => '', + 'attachment_id' => 0, + 'label' => '', + 'compare' => 'AND', + 'requires' => array( + 0 => array( + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'reference' => '', + 'amount' => '', + 'by' => '' + ) + ), + 'reward' => array( + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'amount' => 0, + 'log' => '' + ) + ); - return apply_filters('mycred_badge_levels', $setup, $badge_id); + return apply_filters( 'mycred_badge_levels', $setup, $badge_id ); - } + } endif; /** * Display Badge Requirements * Returns the badge requirements as a string in a readable format. - * - * @since 1.5 + * @since 1.5 * @version 1.2.2 */ -if (! function_exists('mycred_display_badge_requirement') ) : - function mycred_display_badge_requirements( $badge_id = null ) - { +if ( ! function_exists( 'mycred_display_badge_requirement' ) ) : + function mycred_display_badge_requirements( $badge_id = NULL ) { - $badge = mycred_get_badge($badge_id); - $levels = mycred_get_badge_levels($badge_id); + $badge = mycred_get_badge( $badge_id ); + $levels = mycred_get_badge_levels( $badge_id ); - if (empty($levels) ) { + if ( empty( $levels ) ) { - $reply = '-'; + $reply = '-'; - } - else { + } + else { - $point_types = mycred_get_types(true); - $references = mycred_get_all_references(); - $req_count = count($levels[0]['requires']); + $point_types = mycred_get_types( true ); + $references = mycred_get_all_references(); + $req_count = count( $levels[0]['requires'] ); - // Get the requirements for the first level - $base_requirements = array(); - foreach ( $levels[0]['requires'] as $requirement_row => $requirement ) { + // Get the requirements for the first level + $base_requirements = array(); + foreach ( $levels[0]['requires'] as $requirement_row => $requirement ) { - if ($requirement['type'] == '' ) { - $requirement['type'] = MYCRED_DEFAULT_TYPE_KEY; - } + if ( $requirement['type'] == '' ) + $requirement['type'] = MYCRED_DEFAULT_TYPE_KEY; - if (! array_key_exists($requirement['type'], $point_types) ) { - continue; - } + if ( ! array_key_exists( $requirement['type'], $point_types ) ) + continue; - if (! array_key_exists($requirement['reference'], $references) ) { - $reference = '-'; - } else { - $reference = $references[ $requirement['reference'] ]; - } + if ( ! array_key_exists( $requirement['reference'], $references ) ) + $reference = '-'; + else + $reference = $references[ $requirement['reference'] ]; - $base_requirements[ $requirement_row ] = array( - 'type' => $requirement['type'], - 'ref' => $reference, - 'amount' => $requirement['amount'], - 'by' => $requirement['by'] - ); + $base_requirements[ $requirement_row ] = array( + 'type' => $requirement['type'], + 'ref' => $reference, + 'amount' => $requirement['amount'], + 'by' => $requirement['by'] + ); - } + } - // Loop through each level - $output = array(); - foreach ( $levels as $level => $setup ) { + // Loop through each level + $output = array(); + foreach ( $levels as $level => $setup ) { - $level_label = ''; + $level_label = ''; - if (! $badge->open_badge ) { - - $level_label = '' . sprintf(__('Level %s', 'mycred'), ( $level + 1 )) . ':'; - if ($levels[ $level ]['label'] != '' ) { - $level_label = '' . $levels[ $level ]['label'] . ':'; - } + if ( ! $badge->open_badge ) { + + $level_label = '' . sprintf( __( 'Level %s', 'mycred' ), ( $level + 1 ) ) . ':'; + if ( $levels[ $level ]['label'] != '' ) + $level_label = '' . $levels[ $level ]['label'] . ':'; - } + } - // Construct requirements to be used in an unorganized list. - $level_req = array(); - foreach ( $setup['requires'] as $requirement_row => $requirement ) { + // Construct requirements to be used in an unorganized list. + $level_req = array(); + foreach ( $setup['requires'] as $requirement_row => $requirement ) { - $level_value = $requirement['amount']; - $requirement = $base_requirements[ $requirement_row ]; + $level_value = $requirement['amount']; + $requirement = $base_requirements[ $requirement_row ]; - $mycred = mycred($requirement['type']); + $mycred = mycred( $requirement['type'] ); - if ($level > 0 ) { - $requirement['amount'] = $level_value; - } + if ( $level > 0 ) + $requirement['amount'] = $level_value; - if ($requirement['by'] == 'count' ) { - $rendered_row = sprintf(esc_html_x('%s for "%s" x %d', '"Points" for "reference" x times', 'mycred'), $mycred->plural(), $requirement['ref'], $requirement['amount']); - } else { - $rendered_row = sprintf(esc_html_x('%s %s for "%s"', '"Gained/Lost" "x points" for "reference"', 'mycred'), ( ( $requirement['amount'] < 0 ) ? esc_html__('Lost', 'mycred') : esc_html__('Gained', 'mycred') ), $mycred->format_creds($requirement['amount']), $requirement['ref']); - } + if ( $requirement['by'] == 'count' ) + $rendered_row = sprintf( _x( '%s for "%s" x %d', '"Points" for "reference" x times', 'mycred' ), $mycred->plural(), $requirement['ref'], $requirement['amount'] ); + else + $rendered_row = sprintf( _x( '%s %s for "%s"', '"Gained/Lost" "x points" for "reference"', 'mycred' ), ( ( $requirement['amount'] < 0 ) ? __( 'Lost', 'mycred' ) : __( 'Gained', 'mycred' ) ), $mycred->format_creds( $requirement['amount'] ), $requirement['ref'] ); - $compare = _x('OR', 'Comparison of badge requirements. A OR B', 'mycred'); - if ($setup['compare'] === 'AND' ) { - $compare = _x('AND', 'Comparison of badge requirements. A AND B', 'mycred'); - } + $compare = _x( 'OR', 'Comparison of badge requirements. A OR B', 'mycred' ); + if ( $setup['compare'] === 'AND' ) + $compare = _x( 'AND', 'Comparison of badge requirements. A AND B', 'mycred' ); - if ($req_count > 1 && $requirement_row+1 < $req_count ) { - $rendered_row .= ' ' . $compare . ''; - } + if ( $req_count > 1 && $requirement_row+1 < $req_count ) + $rendered_row .= ' ' . $compare . ''; - $level_req[] = $rendered_row; + $level_req[] = $rendered_row; - } + } - if (empty($level_req) ) { continue; - } + if ( empty( $level_req ) ) continue; - $output[] = $level_label . ''; + $output[] = $level_label . ''; - } + } - if ((int) mycred_get_post_meta($badge_id, 'manual_badge', true) === 1 ) { - $output[] = '' . esc_html__('This badge is manually awarded.', 'mycred') . ''; - } + if ( (int) mycred_get_post_meta( $badge_id, 'manual_badge', true ) === 1 ) + $output[] = '' . __( 'This badge is manually awarded.', 'mycred' ) . ''; - $reply = implode('', $output); + $reply = implode( '', $output ); - } + } - return apply_filters('mycred_badge_display_requirements', $reply, $badge_id); + return apply_filters( 'mycred_badge_display_requirements', $reply, $badge_id ); - } + } endif; /** * Count Users with Badge * Counts the number of users that has the given badge. Option to get count * of a specific level. - * - * @since 1.5 + * @since 1.5 * @version 1.1 */ -if (! function_exists('mycred_count_users_with_badge') ) : - function mycred_count_users_with_badge( $badge_id = null, $level = null ) - { +if ( ! function_exists( 'mycred_count_users_with_badge' ) ) : + function mycred_count_users_with_badge( $badge_id = NULL, $level = NULL ) { - $badge_id = absint($badge_id); + $badge_id = absint( $badge_id ); - if ($badge_id === 0 ) { return false; - } + if ( $badge_id === 0 ) return false; - // Get the badge object - $badge = mycred_get_badge($badge_id); + // Get the badge object + $badge = mycred_get_badge( $badge_id ); - // Most likely not a badge post ID - if ($badge === false ) { return false; - } + // Most likely not a badge post ID + if ( $badge === false ) return false; - return $badge->get_user_count($level); + return $badge->get_user_count( $level ); - } + } endif; /** * Count Users without Badge * Counts the number of users that does not have a given badge. - * - * @since 1.5 + * @since 1.5 * @version 1.2 */ -if (! function_exists('mycred_count_users_without_badge') ) : - function mycred_count_users_without_badge( $badge_id = null ) - { +if ( ! function_exists( 'mycred_count_users_without_badge' ) ) : + function mycred_count_users_without_badge( $badge_id = NULL ) { - $total = count_users(); - $with_badge = mycred_count_users_with_badge($badge_id); - if ($with_badge === false ) { $with_badge = 0; - } + $total = count_users(); + $with_badge = mycred_count_users_with_badge( $badge_id ); + if ( $with_badge === false ) $with_badge = 0; - $without_badge = $total['total_users'] - $with_badge; + $without_badge = $total['total_users'] - $with_badge; - return apply_filters('mycred_count_users_without_badge', absint($without_badge), $badge_id); + return apply_filters( 'mycred_count_users_without_badge', absint( $without_badge ), $badge_id ); - } + } endif; /** * Reference Has Badge * Checks if a given reference has a badge associated with it. - * - * @since 1.5 + * @since 1.5 * @version 1.4 */ -if (! function_exists('mycred_ref_has_badge') ) : - function mycred_ref_has_badge( $reference = null, $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_ref_has_badge' ) ) : + function mycred_ref_has_badge( $reference = NULL, $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $badge_ids = array(); - if ($reference === null || strlen($reference) == 0 || ! mycred_point_type_exists($point_type) ) { return $badge_ids; - } + $badge_ids = array(); + if ( $reference === NULL || strlen( $reference ) == 0 || ! mycred_point_type_exists( $point_type ) ) return $badge_ids; - $badge_references = mycred_get_badge_references($point_type); - $badge_references = maybe_unserialize($badge_references); + $badge_references = mycred_get_badge_references( $point_type ); + $badge_references = maybe_unserialize( $badge_references ); - if (! empty($badge_references) && array_key_exists($reference, $badge_references) ) { - $badge_ids = $badge_references[ $reference ]; - } + if ( ! empty( $badge_references ) && array_key_exists( $reference, $badge_references ) ) + $badge_ids = $badge_references[ $reference ]; - if (empty($badge_ids) ) { - $badge_ids = false; - } + if ( empty( $badge_ids ) ) + $badge_ids = false; - return apply_filters('mycred_ref_has_badge', $badge_ids, $reference, $badge_references, $point_type); + return apply_filters( 'mycred_ref_has_badge', $badge_ids, $reference, $badge_references, $point_type ); - } + } endif; /** * Badge Level Reached * Checks what level a user has earned for a badge. Returns false if badge was not earned. - * - * @since 1.7 + * @since 1.7 * @version 1.1 */ -if (! function_exists('mycred_badge_level_reached') ) : - function mycred_badge_level_reached( $user_id = null, $badge_id = null ) - { +if ( ! function_exists( 'mycred_badge_level_reached' ) ) : + function mycred_badge_level_reached( $user_id = NULL, $badge_id = NULL ) { - $user_id = absint($user_id); - $badge_id = absint($badge_id); + $user_id = absint( $user_id ); + $badge_id = absint( $badge_id ); - if ($user_id === 0 || $badge_id === 0 ) { return false; - } + if ( $user_id === 0 || $badge_id === 0 ) return false; - // Get the badge object - $badge = mycred_get_badge($badge_id); + // Get the badge object + $badge = mycred_get_badge( $badge_id ); - // Most likely not a badge post ID - if ($badge === false ) { return false; - } + // Most likely not a badge post ID + if ( $badge === false ) return false; - return $badge->query_users_level($user_id); + return $badge->query_users_level( $user_id ); - } + } endif; /** * Check if User Gets Badge * Checks if a given user has earned one or multiple badges. - * - * @since 1.5 + * @since 1.5 * @version 1.4 */ -if (! function_exists('mycred_check_if_user_gets_badge') ) : - function mycred_check_if_user_gets_badge( $user_id = null, $badge_ids = array(), $depreciated = array(), $save = true ) - { +if ( ! function_exists( 'mycred_check_if_user_gets_badge' ) ) : + function mycred_check_if_user_gets_badge( $user_id = NULL, $badge_ids = array(), $depreciated = array(), $save = true ) { - $user_id = absint($user_id); - if ($user_id === 0 ) { return false; - } + $user_id = absint( $user_id ); + if ( $user_id === 0 ) return false; - $earned_badge_ids = array(); - if (! empty($badge_ids) ) { - foreach ( $badge_ids as $badge_id ) { + $earned_badge_ids = array(); + if ( ! empty( $badge_ids ) ) { + foreach ( $badge_ids as $badge_id ) { - $badge = mycred_get_badge($badge_id); - if ($badge === false ) { continue; - } + $badge = mycred_get_badge( $badge_id ); + if ( $badge === false ) continue; - $level_reached = $badge->get_level_reached($user_id); - if ($level_reached !== false ) { + $level_reached = $badge->get_level_reached( $user_id ); + if ( $level_reached !== false ) { - if ($save ) { - $badge->assign($user_id, $level_reached); - } + if ( $save ) + $badge->assign( $user_id, $level_reached ); - $earned_badge_ids[] = $badge_id; + $earned_badge_ids[] = $badge_id; - } + } - } - } + } + } - return $earned_badge_ids; + return $earned_badge_ids; - } + } endif; /** * Assign Badge * Assigns a given badge to all users that fulfill the badges requirements. - * - * @since 1.7 + * @since 1.7 * @version 1.2 */ -if (! function_exists('mycred_assign_badge') ) : - function mycred_assign_badge( $badge_id = null ) - { +if ( ! function_exists( 'mycred_assign_badge' ) ) : + function mycred_assign_badge( $badge_id = NULL ) { - $user_id = absint($user_id); - $badge_id = absint($badge_id); + $user_id = absint( $user_id ); + $badge_id = absint( $badge_id ); - if ($user_id === 0 || $badge_id === 0 ) { return false; - } + if ( $user_id === 0 || $badge_id === 0 ) return false; - // Get the badge object - $badge = mycred_get_badge($badge_id); + // Get the badge object + $badge = mycred_get_badge( $badge_id ); - // Most likely not a badge post ID - if ($badge === false ) { return false; - } + // Most likely not a badge post ID + if ( $badge === false ) return false; - return $badge->assign_all(); + return $badge->assign_all(); - } + } endif; /** * Assign Badge to User - * - * @since 1.7 + * @since 1.7 * @version 1.1 */ -if (! function_exists('mycred_assign_badge_to_user') ) : - function mycred_assign_badge_to_user( $user_id = null, $badge_id = null, $level = 0 ) - { +if ( ! function_exists( 'mycred_assign_badge_to_user' ) ) : + function mycred_assign_badge_to_user( $user_id = NULL, $badge_id = NULL, $level = 0 ) { - $user_id = absint($user_id); - $badge_id = absint($badge_id); - $level = absint($level); + $user_id = absint( $user_id ); + $badge_id = absint( $badge_id ); + $level = absint( $level ); - if ($user_id === 0 || $badge_id === 0 ) { return false; - } + if ( $user_id === 0 || $badge_id === 0 ) return false; - // Get the badge object - $badge = mycred_get_badge($badge_id); + // Get the badge object + $badge = mycred_get_badge( $badge_id ); - // Most likely not a badge post ID - if ($badge === false ) { return false; - } + // Most likely not a badge post ID + if ( $badge === false ) return false; - return $badge->assign($user_id, $level); + return $badge->assign( $user_id, $level ); - } + } endif; /** * User Has Badge * Checks if a user has a particular badge by badge ID. - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_user_has_badge') ) : - function mycred_user_has_badge( $user_id = 0, $badge_id = null, $level_id = 0 ) - { +if ( ! function_exists( 'mycred_user_has_badge' ) ) : + function mycred_user_has_badge( $user_id = 0, $badge_id = NULL, $level_id = 0 ) { - $user_id = absint($user_id); - $badge_id = absint($badge_id); - $level_id = absint($level_id); + $user_id = absint( $user_id ); + $badge_id = absint( $badge_id ); + $level_id = absint( $level_id ); - if ($user_id === 0 || $badge_id === 0 ) { return false; - } + if ( $user_id === 0 || $badge_id === 0 ) return false; - global $mycred_current_account; + global $mycred_current_account; - if (mycred_is_current_account($user_id) && isset($mycred_current_account->badge_ids) && ! empty($mycred_current_account->badge_ids) ) { + if ( mycred_is_current_account( $user_id ) && isset( $mycred_current_account->badge_ids ) && ! empty( $mycred_current_account->badge_ids ) ) { - $has_badge = array_key_exists($badge_id, $mycred_current_account->badge_ids); + $has_badge = array_key_exists( $badge_id, $mycred_current_account->badge_ids ); - } - else { + } + else { - // Get the badge object - $badge = mycred_get_badge($badge_id); + // Get the badge object + $badge = mycred_get_badge( $badge_id ); - // Most likely not a badge post ID - if ($badge !== false ) { - $has_badge = $badge->user_has_badge($user_id, $level_id); - } + // Most likely not a badge post ID + if ( $badge !== false ) + $has_badge = $badge->user_has_badge( $user_id, $level_id ); - } + } - return $has_badge; + return $has_badge; - } + } endif; /** * Get Users Badge Level - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_get_users_badge_level') ) : - function mycred_get_users_badge_level( $user_id = 0, $badge_id = null ) - { +if ( ! function_exists( 'mycred_get_users_badge_level' ) ) : + function mycred_get_users_badge_level( $user_id = 0, $badge_id = NULL ) { - $user_id = absint($user_id); - $badge_id = absint($badge_id); + $user_id = absint( $user_id ); + $badge_id = absint( $badge_id ); - if ($user_id === 0 || $badge_id === 0 ) { return false; - } + if ( $user_id === 0 || $badge_id === 0 ) return false; - global $mycred_current_account; + global $mycred_current_account; - if (mycred_is_current_account($user_id) && isset($mycred_current_account->badges) && ! empty($mycred_current_account->badges) && array_key_exists($badge_id, $mycred_current_account->badges) ) { - return $mycred_current_account->badges[ $badge_id ]->level_id; - } + if ( mycred_is_current_account( $user_id ) && isset( $mycred_current_account->badges ) && ! empty( $mycred_current_account->badges ) && array_key_exists( $badge_id, $mycred_current_account->badges ) ) + return $mycred_current_account->badges[ $badge_id ]->level_id; - // Get the badge object - $badge = mycred_get_badge($badge_id); + // Get the badge object + $badge = mycred_get_badge( $badge_id ); - // Most likely not a badge post ID - if ($badge === false ) { return false; - } + // Most likely not a badge post ID + if ( $badge === false ) return false; - return $badge->get_users_current_level($user_id); + return $badge->get_users_current_level( $user_id ); - } + } endif; /** * Get Users Badges * Returns the badge post IDs that a given user currently holds. - * - * @since 1.5 + * @since 1.5 * @version 1.3 */ -if (! function_exists('mycred_get_users_badges') ) : - function mycred_get_users_badges( $user_id = null, $force = false ) - { +if ( ! function_exists( 'mycred_get_users_badges' ) ) : + function mycred_get_users_badges( $user_id = NULL, $force = false ) { - if ($user_id === null ) { return array(); - } + if ( $user_id === NULL ) return array(); - global $mycred_current_account; + global $mycred_current_account; - if (mycred_is_current_account($user_id) && isset($mycred_current_account->badge_ids) && $force == false ) { - return $mycred_current_account->badge_ids; - } + if ( mycred_is_current_account( $user_id ) && isset( $mycred_current_account->badge_ids ) && $force == false ) + return $mycred_current_account->badge_ids; - $badge_ids = mycred_get_user_meta($user_id, MYCRED_BADGE_KEY . '_ids', '', true); - if (!isset($badge_ids) || $badge_ids == '' || $force ) { + $badge_ids = mycred_get_user_meta( $user_id, MYCRED_BADGE_KEY . '_ids', '', true ); + if ( !isset($badge_ids) || $badge_ids == '' || $force ) { - global $wpdb; + global $wpdb; - $badge_ids = array(); - $query = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->usermeta} WHERE user_id = %d AND meta_key LIKE %s AND meta_key NOT LIKE '%_issued_on' AND meta_key NOT LIKE '%_ids'", $user_id, mycred_get_meta_key(MYCRED_BADGE_KEY) . '%')); + $badge_ids = array(); + $query = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->usermeta} WHERE user_id = %d AND meta_key LIKE %s AND meta_key NOT LIKE '%_issued_on' AND meta_key NOT LIKE '%_ids'", $user_id, mycred_get_meta_key( MYCRED_BADGE_KEY ) . '%' ) ); - if (! empty($query) ) { + if ( ! empty( $query ) ) { - foreach ( $query as $badge ) { + foreach ( $query as $badge ) { - $badge_id = str_replace(MYCRED_BADGE_KEY, '', $badge->meta_key); - if ($badge_id == '' ) { continue; - } - - $badge_id = absint($badge_id); - if (! array_key_exists($badge_id, $badge_ids) ) { - $badge_ids[ $badge_id ] = absint($badge->meta_value); - } + $badge_id = str_replace( MYCRED_BADGE_KEY, '', $badge->meta_key ); + if ( $badge_id == '' ) continue; + + $badge_id = absint( $badge_id ); + if ( ! array_key_exists( $badge_id, $badge_ids ) ) + $badge_ids[ $badge_id ] = absint( $badge->meta_value ); - } + } - mycred_update_user_meta($user_id, MYCRED_BADGE_KEY . '_ids', '', $badge_ids); + mycred_update_user_meta( $user_id, MYCRED_BADGE_KEY . '_ids', '', $badge_ids ); - } + } - } - - $clean_ids = array(); - if (! empty($badge_ids) ) { - foreach ( $badge_ids as $id => $level ) { + } + + $clean_ids = array(); + if ( ! empty( $badge_ids ) ) { + foreach ( $badge_ids as $id => $level ) { - $id = absint($id); - if ($id === 0 || strlen($level) < 1 ) { continue; - } - $clean_ids[ $id ] = absint($level); + $id = absint( $id ); + if ( $id === 0 || strlen( $level ) < 1 ) continue; + $clean_ids[ $id ] = absint( $level ); - } - } + } + } - return apply_filters('mycred_get_users_badges', $clean_ids, $user_id); + return apply_filters( 'mycred_get_users_badges', $clean_ids, $user_id ); - } + } endif; /** * Display Users Badges * Will echo all badge images a given user has earned. - * - * @since 1.5 + * @since 1.5 * @version 1.3.2 */ -if (! function_exists('mycred_display_users_badges') ) : - function mycred_display_users_badges( $user_id = null, $width = MYCRED_BADGE_WIDTH, $height = MYCRED_BADGE_HEIGHT ) - { +if ( ! function_exists( 'mycred_display_users_badges' ) ) : + function mycred_display_users_badges( $user_id = NULL, $width = MYCRED_BADGE_WIDTH, $height = MYCRED_BADGE_HEIGHT ) { - $user_id = absint($user_id); - if ($user_id === 0 ) { return; - } + $user_id = absint( $user_id ); + if ( $user_id === 0 ) return; - $users_badges = mycred_get_users_badges($user_id); + $users_badges = mycred_get_users_badges( $user_id ); - echo '
'; + echo '
'; - do_action('mycred_before_users_badges', $user_id, $users_badges); + do_action( 'mycred_before_users_badges', $user_id, $users_badges ); - if (! empty($users_badges) ) { + if ( ! empty( $users_badges ) ) { - foreach ( $users_badges as $badge_id => $level ) { + foreach ( $users_badges as $badge_id => $level ) { - $badge = mycred_get_badge($badge_id, $level); - if ($badge === false ) { continue; - } + $badge = mycred_get_badge( $badge_id, $level ); + if ( $badge === false ) continue; - $badge->image_width = $width; - $badge->image_height = $height; + $badge->image_width = $width; + $badge->image_height = $height; - $badge_image = ''; + $badge_image = ''; - if ($badge->level_image !== false ) { - $badge_image = $badge->get_image($level); - } else if($badge->main_image !== false ) { - $badge_image = $badge->get_image('main'); - } + if ( $badge->level_image !== false ) + $badge_image = $badge->get_image( $level ); + else if( $badge->main_image !== false ) + $badge_image = $badge->get_image( 'main' ); - if (!empty($badge_image) ) { - echo apply_filters('mycred_the_badge', wp_kses_post( $badge_image ), $badge_id, $badge, $user_id); - } + if ( !empty( $badge_image ) ) + echo wp_kses_post( apply_filters( 'mycred_the_badge', $badge_image, $badge_id, $badge, $user_id ) ); - } + } - } + } - do_action('mycred_after_users_badges', $user_id, $users_badges); + do_action( 'mycred_after_users_badges', $user_id, $users_badges ); - echo '
'; + echo '
'; - } + } endif; /** * Get Badge IDs * Returns all published badge post IDs. - * - * @since 1.5 + * @since 1.5 * @version 1.1 */ -if (! function_exists('mycred_get_badge_ids') ) : - function mycred_get_badge_ids() - { +if ( ! function_exists( 'mycred_get_badge_ids' ) ) : + function mycred_get_badge_ids() { - $badge_ids = wp_cache_get('badge_ids', MYCRED_SLUG); - if ($badge_ids !== false && is_array($badge_ids) ) { return $badge_ids; - } + $badge_ids = wp_cache_get( 'badge_ids', MYCRED_SLUG ); + if ( $badge_ids !== false && is_array( $badge_ids ) ) return $badge_ids; - global $wpdb; + global $wpdb; - $table = mycred_get_db_column('posts'); - $badge_ids = $wpdb->get_col( - $wpdb->prepare( - " + $table = mycred_get_db_column( 'posts' ); + $badge_ids = $wpdb->get_col( $wpdb->prepare( " SELECT ID FROM {$table} WHERE post_type = %s AND post_status = 'publish' - ORDER BY post_date ASC;", MYCRED_BADGE_KEY - ) - ); + ORDER BY post_date ASC;", MYCRED_BADGE_KEY ) ); - wp_cache_set('badge_ids', $badge_ids, MYCRED_SLUG); + wp_cache_set( 'badge_ids', $badge_ids, MYCRED_SLUG ); - return apply_filters('mycred_get_badge_ids', $badge_ids); + return apply_filters( 'mycred_get_badge_ids', $badge_ids ); - } + } endif; /** * Get Badges by Term ID - * - * @since 2.1 + * @since 2.1 * @version 1.0 - * @param $term_id Pass term Id + * @param $term_id Pass term Id * return posts by term Id */ -if(!function_exists('mycred_get_badges_by_term_id') ) : - function mycred_get_badges_by_term_id($term_id ) - { - $badge_args = query_posts( - array( +if( !function_exists( 'mycred_get_badges_by_term_id' ) ) : + function mycred_get_badges_by_term_id($term_id ) { + $badge_args = query_posts(array( 'post_type' => MYCRED_BADGE_KEY, 'showposts' => -1, 'tax_query' => array( @@ -831,18 +734,16 @@ function mycred_get_badges_by_term_id($term_id ) /** * Get Badge/ Level Requirements - * - * @since 2.1 + * @since 2.1 * @version 1.0 - * @param $badge_id Pass Badge ID + * @param $badge_id Pass Badge ID */ -if(!function_exists('mycred_show_badge_requirements') ) : - function mycred_show_badge_requirements( $badge_id ) - { +if( !function_exists( 'mycred_show_badge_requirements' ) ) : + function mycred_show_badge_requirements( $badge_id ) { $data = array(); - $levels = mycred_get_badge_levels($badge_id); - if (empty($levels) ) { + $levels = mycred_get_badge_levels( $badge_id ); + if ( empty( $levels ) ) { $reply = '-'; @@ -857,19 +758,16 @@ function mycred_show_badge_requirements( $badge_id ) $base_requirements = array(); foreach ($levels[0]['requires'] as $requirement_row => $requirement) { - if ($requirement['type'] == '') { + if ($requirement['type'] == '') $requirement['type'] = MYCRED_DEFAULT_TYPE_KEY; - } - if (!array_key_exists($requirement['type'], $point_types)) { + if (!array_key_exists($requirement['type'], $point_types)) continue; - } - if (!array_key_exists($requirement['reference'], $references)) { + if (!array_key_exists($requirement['reference'], $references)) $reference = '-'; - } else { + else $reference = $references[$requirement['reference']]; - } $base_requirements[$requirement_row] = array( 'type' => $requirement['type'], @@ -886,25 +784,22 @@ function mycred_show_badge_requirements( $badge_id ) //collecting images $image = false; - if ($setup['attachment_id'] > 0 ) { + if ( $setup['attachment_id'] > 0 ) { - $_image = wp_get_attachment_url($setup['attachment_id']); - if (strlen($_image) > 5 ) { + $_image = wp_get_attachment_url( $setup['attachment_id'] ); + if ( strlen( $_image ) > 5 ) $output['image'] = $_image; - } } else { - if (strlen($setup['image_url']) > 5 ) { + if ( strlen( $setup['image_url'] ) > 5 ) $output['image'] = $setup['image_url']; - } } $level_label = sprintf(__('Level %s', 'mycred'), ($level + 1)); - if ($levels[$level]['label'] != '') { + if ($levels[$level]['label'] != '') $level_label = $levels[$level]['label']; - } // Construct requirements to be used in an unorganized list. $level_req = array(); @@ -914,44 +809,38 @@ function mycred_show_badge_requirements( $badge_id ) $mycred = mycred($requirement['type']); - if ($level > 0) { + if ($level > 0) $requirement['amount'] = $level_value; - } - if ($requirement['by'] == 'count') { - $rendered_row = sprintf(esc_html_x('%s for "%s" x %d', '"Points" for "reference" x times', 'mycred'), $mycred->plural(), $requirement['ref'], $requirement['amount']); - } else { - $rendered_row = sprintf(esc_html_x('%s %s for "%s"', '"Gained/Lost" "x points" for "reference"', 'mycred'), (($requirement['amount'] < 0) ? __('Lost', 'mycred') : __('Gained', 'mycred')), $mycred->format_creds($requirement['amount']), $requirement['ref']); - } + if ($requirement['by'] == 'count') + $rendered_row = sprintf(_x('%s for "%s" x %d', '"Points" for "reference" x times', 'mycred'), $mycred->plural(), $requirement['ref'], $requirement['amount']); + else + $rendered_row = sprintf(_x('%s %s for "%s"', '"Gained/Lost" "x points" for "reference"', 'mycred'), (($requirement['amount'] < 0) ? __('Lost', 'mycred') : __('Gained', 'mycred')), $mycred->format_creds($requirement['amount']), $requirement['ref']); $compare = _x('OR', 'Comparison of badge requirements. A OR B', 'mycred'); - if ($setup['compare'] === 'AND') { + if ($setup['compare'] === 'AND') $compare = _x('AND', 'Comparison of badge requirements. A AND B', 'mycred'); - } - if ($req_count > 1 && $requirement_row + 1 < $req_count) { + if ($req_count > 1 && $requirement_row + 1 < $req_count) $rendered_row .= ' ' . $compare . ''; - } $level_req[] = $rendered_row; } - if (empty($level_req) ) { continue; - } + if ( empty( $level_req ) ) continue; $output['heading'] = $level_label; $output['requirements'] = $level_req; $output["reward_type"] = $setup["reward"]["type"]; $output["amount"] = $setup["reward"]["amount"]; - array_push($data, $output); + array_push( $data, $output ); } - if ((int) mycred_get_post_meta($badge_id, 'manual_badge', true) === 1 ) { + if ( (int) mycred_get_post_meta( $badge_id, 'manual_badge', true ) === 1 ) $output[] = '' . __('This badge is manually awarded.', 'mycred') . ''; - } return $data; } @@ -961,20 +850,18 @@ function mycred_show_badge_requirements( $badge_id ) /** * Get users have have specific badge - * - * @param $badge_id Pass Badge ID - * @param int $level_id - * @return array Will return Array of User ID's have the specific Badge - * @since 2.1 + * @param $badge_id Pass Badge ID + * @param int $level_id + * @return array Will return Array of User ID's have the specific Badge + * @since 2.1 * @version 1.0 */ -if(!function_exists('mycred_get_users_has_earned_badge') ) : - function mycred_get_users_has_earned_badge( $badge_id, $level_id = 0 ) - { +if( !function_exists( 'mycred_get_users_has_earned_badge' ) ) : + function mycred_get_users_has_earned_badge( $badge_id, $level_id = 0 ) { $users_has_badge = array(); - $badge_id = absint($badge_id); + $badge_id = absint( $badge_id ); $args = array( 'fields' => array( @@ -983,7 +870,7 @@ function mycred_get_users_has_earned_badge( $badge_id, $level_id = 0 ) ) ); - $users = get_users($args); + $users = get_users( $args ); foreach ( $users as $user ) { @@ -992,24 +879,25 @@ function mycred_get_users_has_earned_badge( $badge_id, $level_id = 0 ) $user_id = $user->ID; // Get the badge object - $badge = mycred_get_badge($badge_id); + $badge = mycred_get_badge( $badge_id ); // Most likely not a badge post ID - if ($badge !== false ) { - - $current_level = mycred_get_user_meta($user_id, MYCRED_BADGE_KEY . $badge_id, '', true); + if ( $badge !== false ) { + + $current_level = mycred_get_user_meta( $user_id, MYCRED_BADGE_KEY . $badge_id, '', true ); $current_level = $current_level == '0' ? true : $current_level; - if ($current_level ) { + if ( $current_level ) + { $has_badge = true; - if ((int) $current_level < absint($level_id) ) { + if ( (int) $current_level < absint( $level_id ) ) + { $has_badge = false; } - if ($has_badge ) { + if ( $has_badge ) $users_has_badge[] = $user_id; - } } } } @@ -1020,20 +908,19 @@ function mycred_get_users_has_earned_badge( $badge_id, $level_id = 0 ) /** * Get Badge Types - * - * @since 2.1 + * @since 2.1 * @version 2.1 - * @param $badge_id Pass the Badge id - * @return array Will return all the categories + * @param $badge_id Pass the Badge id + * @return array Will return all the categories */ -if (!function_exists('mycred_get_badge_type') ) : - function mycred_get_badge_type( $badge_id ) - { +if ( !function_exists('mycred_get_badge_type') ) : + function mycred_get_badge_type( $badge_id ) { - $badge_terms = get_the_terms($badge_id, MYCRED_BADGE_CATEGORY, '', ', '); + $badge_terms = get_the_terms( $badge_id, MYCRED_BADGE_CATEGORY, '', ', ' ); - if (is_array($badge_terms) || is_object($badge_terms)) { - $badge_type = join(', ', wp_list_pluck($badge_terms, 'name')); + if (is_array( $badge_terms ) || is_object($badge_terms)) + { + $badge_type = join( ', ', wp_list_pluck($badge_terms, 'name') ); return $badge_type; } @@ -1045,31 +932,27 @@ function mycred_get_badge_type( $badge_id ) /** * Get Badge Level Image Url By Passing setup of Level Requirements Use Function mycred_get_badge_requirements() - * - * @since 2.1 + * @since 2.1 * @version 1.0 - * @param $setup - * @return bool|false|mixed|string + * @param $setup + * @return bool|false|mixed|string */ -if(!function_exists('mycred_get_level_image_url') ) : - function mycred_get_level_image_url( $setup ) - { +if( !function_exists( 'mycred_get_level_image_url' ) ) : + function mycred_get_level_image_url( $setup ) { $image = false; - if ($setup['attachment_id'] > 0 ) { + if ( $setup['attachment_id'] > 0 ) { - $_image = wp_get_attachment_url($setup['attachment_id']); - if (strlen($_image) > 5 ) { + $_image = wp_get_attachment_url( $setup['attachment_id'] ); + if ( strlen( $_image ) > 5 ) return $_image; - } } else { - if (strlen($setup['image_url']) > 5 ) { + if ( strlen( $setup['image_url'] ) > 5 ) return $setup['image_url']; - } } return $image; @@ -1079,36 +962,34 @@ function mycred_get_level_image_url( $setup ) /** * Cretae Evidence page - * - * @since 2.1 + * @since 2.1 * @version 1.0 */ -if (! function_exists('mycred_get_evidence_page_id') ) : - function mycred_get_evidence_page_id() - { +if ( ! function_exists( 'mycred_get_evidence_page_id' ) ) : + function mycred_get_evidence_page_id() { - $evidencePageId = 0; + $evidencePageId = 0; - $badges = mycred_get_addon_settings('badges'); + $badges = mycred_get_addon_settings( 'badges' ); //If Open badge enabled - if (isset($badges['open_badge']) && $badges['open_badge'] == '1' ) { + if ( isset( $badges['open_badge'] ) && $badges['open_badge'] == '1' ) { $canCreatePage = true; - $evidence_page_refrence = mycred_get_option('open_badge_evidence_page', 0); + $evidence_page_refrence = mycred_get_option( 'open_badge_evidence_page', 0 ); - if (! empty($badges['open_badge_evidence_page']) || ! empty($evidence_page_refrence) ) { + if ( ! empty( $badges['open_badge_evidence_page'] ) || ! empty( $evidence_page_refrence ) ) { - $pageId = intval($evidence_page_refrence); + $pageId = intval( $evidence_page_refrence ); - if (! empty($badges['open_badge_evidence_page']) ) { - - $pageId = intval($badges['open_badge_evidence_page']); + if ( ! empty( $badges['open_badge_evidence_page'] ) ) { + + $pageId = intval( $badges['open_badge_evidence_page'] ); - } + } - if (get_post_status($pageId) == 'publish' ) { + if ( get_post_status( $pageId ) == 'publish' ) { $canCreatePage = false; $evidencePageId = $pageId; @@ -1117,7 +998,7 @@ function mycred_get_evidence_page_id() } - if ($canCreatePage ) { + if ( $canCreatePage ) { $postData = array( 'post_content' => '[' . MYCRED_SLUG . '_badge_evidence]', @@ -1128,13 +1009,13 @@ function mycred_get_evidence_page_id() 'post_name' => 'Badge Evidence' ); - $pageId = wp_insert_post($postData); + $pageId = wp_insert_post( $postData ); - $evidencePageId = intval($pageId); + $evidencePageId = intval( $pageId ); - mycred_update_option('open_badge_evidence_page', $evidencePageId); + mycred_update_option( 'open_badge_evidence_page', $evidencePageId ); - mycred_set_badge_evidence_page($evidencePageId); + mycred_set_badge_evidence_page( $evidencePageId ); } @@ -1147,77 +1028,72 @@ function mycred_get_evidence_page_id() /** * Set Evidence page - * - * @since 2.1 + * @since 2.1 * @version 1.0 */ -if (! function_exists('mycred_set_badge_evidence_page') ) : - function mycred_set_badge_evidence_page( $page_id ) - { +if ( ! function_exists( 'mycred_set_badge_evidence_page' ) ) : + function mycred_set_badge_evidence_page( $page_id ) { - $settings = mycred_get_option('mycred_pref_core'); + $settings = mycred_get_option( 'mycred_pref_core' ); - if (isset($settings[ 'badges' ]) ) { + if ( isset( $settings[ 'badges' ] ) ) { - $settings[ 'badges' ][ 'open_badge_evidence_page' ] = intval($page_id); + $settings[ 'badges' ][ 'open_badge_evidence_page' ] = intval( $page_id ); - mycred_update_option('mycred_pref_core', $settings); + mycred_update_option( 'mycred_pref_core', $settings ); - } + } - } + } endif; /** * Get badges list - * - * @since 2.1.1 + * @since 2.1.1 * @version 1.0 */ -if (! function_exists('mycred_get_uncategorized_badge_list') ) : - function mycred_get_uncategorized_badge_list() - { +if ( ! function_exists( 'mycred_get_uncategorized_badge_list' ) ) : + function mycred_get_uncategorized_badge_list() { - $badge_list = ''; + $badge_list = ''; - //Get Badges + //Get Badges $args = array( 'numberposts' => -1, 'post_type' => MYCRED_BADGE_KEY ); - $badges = get_posts($args); + $badges = get_posts( $args ); $user_id = get_current_user_id(); - $categories = get_categories($args); - $category_count = count($categories); + $categories = get_categories( $args ); + $category_count = count( $categories ); //Show Badges foreach ( $badges as $badge ) { - $badge_object = mycred_get_badge($badge->ID); + $badge_object = mycred_get_badge( $badge->ID ); $image_url = $badge_object->main_image_url; - $has_earned = $badge_object->user_has_badge($user_id) ? 'earned' : 'not-earned'; + $has_earned = $badge_object->user_has_badge( $user_id ) ? 'earned' : 'not-earned'; - $category = mycred_get_badge_type($badge->ID); + $category = mycred_get_badge_type( $badge->ID ); - $categories = explode(',', $category); + $categories = explode( ',', $category ); - $badge_list .= '
'; + $badge_list .= '
'; - if ($image_url ) { - $badge_list .= 'Badge Image'; - } + if ( $image_url ) + $badge_list .= 'Badge Image'; $badge_list .= '
'; $badge_list .= '

'.$badge->post_title.'

'; - if($category_count > 0 ) { + if( $category_count > 0 ) { foreach ( $categories as $category ) { - if($category != '' ) { + if( $category != '' ) { $badge_list .= ''.$category.''; @@ -1236,25 +1112,23 @@ function mycred_get_uncategorized_badge_list() //mycred-badges-list-item $badge_list .= '
'; - + } return $badge_list; - } + } endif; /** * Get badges list by categories - * - * @since 2.1.1 + * @since 2.1.1 * @version 1.0 */ -if (! function_exists('mycred_get_categorized_badge_list') ) : - function mycred_get_categorized_badge_list() - { +if ( ! function_exists( 'mycred_get_categorized_badge_list' ) ) : + function mycred_get_categorized_badge_list() { - $user_id = get_current_user_id(); + $user_id = get_current_user_id(); $args = array( 'taxonomy' => MYCRED_BADGE_CATEGORY, @@ -1264,8 +1138,8 @@ function mycred_get_categorized_badge_list() 'hide_empty' => false ); - $categories = get_categories($args); - $category_count = count($categories); + $categories = get_categories( $args ); + $category_count = count( $categories ); $badges_list_tabs = array(); $badges_list_panels = array(); @@ -1275,10 +1149,10 @@ function mycred_get_categorized_badge_list() $category_id = $category->cat_ID; $category_name = $category->cat_name; - $category_badges = mycred_get_badges_by_term_id($category_id); - $badges_count = count($category_badges); + $category_badges = mycred_get_badges_by_term_id( $category_id ); + $badges_count = count( $category_badges ); - if ($badges_count > 0 ) { + if ( $badges_count > 0 ) { $badges_list_tabs[ $category_id ] = '
  • '; $badges_list_tabs[ $category_id ] .= $category_name . '' . $badges_count . ''; @@ -1290,17 +1164,17 @@ function mycred_get_categorized_badge_list() $badge_id = $badge->ID; - $badge_object = mycred_get_badge($badge_id); + $badge_object = mycred_get_badge( $badge_id ); $image_url = $badge_object->main_image_url; - $has_earned = $badge_object->user_has_badge($user_id) ? 'earned' : 'not-earned'; + $has_earned = $badge_object->user_has_badge( $user_id ) ? 'earned' : 'not-earned'; - $badges_list_panels[ $category_id ] .= '
    '; + $badges_list_panels[ $category_id ] .= '
    '; - if ($image_url ) { + if ( $image_url ) { - $badges_list_panels[ $category_id ] .= 'Badge Image'; + $badges_list_panels[ $category_id ] .= 'Badge Image'; } @@ -1319,66 +1193,61 @@ function mycred_get_categorized_badge_list() } return array( - 'tabs' => $badges_list_tabs, - 'panels' => $badges_list_panels, - 'category_count' => $category_count, + 'tabs' => $badges_list_tabs, + 'panels' => $badges_list_panels, + 'category_count' => $category_count, ); - } + } endif; /** * Returns Badge congratulation message. - * - * @since 2.2 + * @since 2.2 * @version 1.0 */ -if (! function_exists('mycred_badge_show_congratulation_msg') ) : - function mycred_badge_show_congratulation_msg( $user_id, $badge, $settings = null ) - { +if ( ! function_exists( 'mycred_badge_show_congratulation_msg' ) ) : + function mycred_badge_show_congratulation_msg( $user_id, $badge, $settings = NULL ) { - $content = ''; + $content = ''; - if (empty($settings) ) { $settings = mycred(); - } + if ( empty( $settings ) ) $settings = mycred(); - if(! empty($settings->core["badges"]["show_congo_text"]) && $badge->user_has_badge($user_id) && ! empty($badge->congratulation_msg) ) { + if( ! empty( $settings->core["badges"]["show_congo_text"] ) && $badge->user_has_badge( $user_id ) && ! empty( $badge->congratulation_msg ) ) { - $content .= '
    ' . $badge->congratulation_msg . '
    '; - - } + $content .= '
    ' . $badge->congratulation_msg . '
    '; + + } - return apply_filters('mycred_badge_show_congratulation_msg', $content, $badge, $settings); + return apply_filters( 'mycred_badge_show_congratulation_msg', $content, $badge, $settings ); - } + } endif; /** * Returns Badge main image with share icons. - * - * @since 2.2 + * @since 2.2 * @version 1.0 */ -if (! function_exists('mycred_badge_show_main_image_with_social_icons') ) : - function mycred_badge_show_main_image_with_social_icons( $user_id, $badge, $mycred = null ) - { +if ( ! function_exists( 'mycred_badge_show_main_image_with_social_icons' ) ) : + function mycred_badge_show_main_image_with_social_icons( $user_id, $badge, $mycred = NULL ) { - $content = ''; + $content = ''; - $image_url = $badge->get_earned_image($user_id); + $image_url = $badge->get_earned_image( $user_id ); - if (! empty($image_url) ) { + if ( ! empty( $image_url ) ) { - $content .= '
    '; + $content .= '
    '; - $content .= 'Badge Image'; + $content .= 'Badge Image'; - if (empty($mycred) ) { $mycred = mycred(); - } + if ( empty( $mycred ) ) $mycred = mycred(); - //If user has earned badge, show user sharing badge option - if($badge->user_has_badge($user_id) - && ! empty($mycred->core["br_social_share"]["enable_open_badge_ss"]) + //If user has earned badge, show user sharing badge option + if( + $badge->user_has_badge( $user_id ) && + ! empty( $mycred->core["br_social_share"]["enable_open_badge_ss"] ) ) { $facebook_url = "http://www.facebook.com/sharer.php?u=".get_permalink()."&p[images][0]=$image_url"; @@ -1386,169 +1255,157 @@ function mycred_badge_show_main_image_with_social_icons( $user_id, $badge, $mycr $linkedin_url = "http://www.linkedin.com/shareArticle?url=".get_permalink().""; $pinterest_url = "https://pinterest.com/pin/create/bookmarklet/?media=$image_url&url=".get_permalink().""; - $content .= mycred_br_get_social_icons($facebook_url, $twitter_url, $linkedin_url, $pinterest_url); + $content .= mycred_br_get_social_icons( $facebook_url, $twitter_url, $linkedin_url, $pinterest_url ); } $content .= '
    '; - - } + + } - return apply_filters('mycred_badge_show_main_image_with_social_icons', $content, $badge, $mycred); + return apply_filters( 'mycred_badge_show_main_image_with_social_icons', $content, $badge, $mycred ); - } + } endif; /** * Returns Badge description. - * - * @since 2.2 + * @since 2.2 * @version 1.0 */ -if (! function_exists('mycred_badge_show_description') ) : - function mycred_badge_show_description( $post, $settings = null ) - { +if ( ! function_exists( 'mycred_badge_show_description' ) ) : + function mycred_badge_show_description( $post, $settings = NULL ) { - $content = ''; + $content = ''; - if (empty($settings) ) { $settings = mycred(); - } + if ( empty( $settings ) ) $settings = mycred(); - if(! empty($settings->core["badges"]["show_level_description"]) && ! empty($post->post_content) ) { + if( ! empty( $settings->core["badges"]["show_level_description"] ) && ! empty( $post->post_content ) ) { - $content .= "

    " . __("Description", "mycred") . "

    "; + $content .= "

    " . __( "Description", "mycred" ) . "

    "; $content .= "

    " . $post->post_content . "

    "; - - } + + } - return apply_filters('mycred_badge_show_description', $content, $post, $settings); + return apply_filters( 'mycred_badge_show_description', $content, $post, $settings ); - } + } endif; /** * Returns Badge levels. - * - * @since 2.2 + * @since 2.2 * @version 1.0 */ -if (! function_exists('mycred_badge_show_levels') ) : - function mycred_badge_show_levels( $user_id, $badge, $settings = null ) - { +if ( ! function_exists( 'mycred_badge_show_levels' ) ) : + function mycred_badge_show_levels( $user_id, $badge, $settings = NULL ) { - $content = ''; + $content = ''; - if (empty($settings) ) { $settings = mycred(); - } + if ( empty( $settings ) ) $settings = mycred(); - if(! empty($settings->core["badges"]["show_levels"]) || $badge->open_badge && ! empty($settings->core["badges"]["show_steps_to_achieve"]) ) { + if( ! empty( $settings->core["badges"]["show_levels"] ) || $badge->open_badge && ! empty( $settings->core["badges"]["show_steps_to_achieve"] ) ) { - if (! $badge->open_badge ) { + if ( ! $badge->open_badge ) $content .= "

    " . __("Levels", "mycred") . "

    "; - } else { + else $content .= "

    " . __("Requirement", "mycred") . "

    "; - } - $levels = mycred_show_badge_requirements($badge->post_id); + $levels = mycred_show_badge_requirements( $badge->post_id ); foreach ( $levels as $id => $level ) { - $level_image_url = $level["image"]; + $level_image_url = $level["image"]; - $heading = $level["heading"]; + $heading = $level["heading"]; - $requirements = $level["requirements"]; + $requirements = $level["requirements"]; - $reward = $level["amount"]; + $reward = $level["amount"]; - $content .= '
    '; + $content .= '
    '; - if (! $badge->open_badge ) { + if ( ! $badge->open_badge ) { - if (! empty($level_image_url) ) { - $content .= ''; - } + if ( ! empty( $level_image_url ) ) + $content .= ''; - $content .= "

    $heading

    "; - } + $content .= "

    $heading

    "; + } - $content .= "
    "; + $content .= "
    "; - if (! empty($settings->core["badges"]["show_steps_to_achieve"]) ) { - $content .= mycred_badge_level_req_check($badge->post_id, $id); - } + if ( ! empty( $settings->core["badges"]["show_steps_to_achieve"] ) ) + $content .= mycred_badge_level_req_check( $badge->post_id, $id ); - if (! empty($settings->core["badges"]["show_level_points"]) && $reward != 0 ) { + if ( ! empty( $settings->core["badges"]["show_level_points"] ) && $reward != 0 ) { - $reward_type = mycred($level['reward_type']); + $reward_type = mycred( $level['reward_type'] ); - $content .= '
    ' . __('Reward:', 'mycred') . ' ' . $reward_type->format_creds($reward) .'
    '; - } + $content .= '
    ' . __('Reward:', 'mycred') . ' ' . $reward_type->format_creds($reward ) .'
    '; + } - $content .= '
    '; - } + $content .= '
    '; + } - $content .= '
    '; - - } + $content .= '
    '; + + } - return apply_filters('mycred_badge_show_levels', $content, $user_id, $badge, $settings); + return apply_filters( 'mycred_badge_show_levels', $content, $user_id, $badge, $settings ); - } + } endif; /** * Returns badge earners. - * - * @since 2.2 + * @since 2.2 * @version 1.0 */ -if (! function_exists('mycred_badge_show_earners') ) : - function mycred_badge_show_earners( $badge, $settings = null ) - { +if ( ! function_exists( 'mycred_badge_show_earners' ) ) : + function mycred_badge_show_earners( $badge, $settings = NULL ) { - $content = ''; + $content = ''; - if (empty($settings) ) { $settings = mycred(); - } + if ( empty( $settings ) ) $settings = mycred(); - if (! empty($settings->core["badges"]["show_earners"]) ) { + if ( ! empty( $settings->core["badges"]["show_earners"] ) ) { - $args = array( - 'meta_query' => array( - array( - 'key' => MYCRED_BADGE_KEY . $badge->post_id, - 'compare' => 'EXISTS' - ) - ) - ); - $users_have_badge = get_users($args); + $args = array( + 'meta_query' => array( + array( + 'key' => MYCRED_BADGE_KEY . $badge->post_id, + 'compare' => 'EXISTS' + ) + ) + ); + $users_have_badge = get_users( $args ); - if (! empty($users_have_badge) ) { - - $content .= '
    '; - $content .= "

    " . __("Earners", "mycred") . "

    "; + if ( ! empty( $users_have_badge ) ) { + + $content .= '
    '; + $content .= "

    " . __("Earners", "mycred") . "

    "; $content .= '
    '; - foreach ( $users_have_badge as $user ) { + foreach ( $users_have_badge as $user ) { - $user_avatar = get_avatar_url($user->ID); + $user_avatar = get_avatar_url( $user->ID ); - $content .= '
    '; - $content .= '
    '; - $content .= "

    $user->display_name

    "; - $content .= '
    '; + $content .= '
    '; + $content .= '
    '; + $content .= "

    $user->display_name

    "; + $content .= '
    '; - } - $content .= '
    '; - $content .= '
    '; + } + $content .= '
    '; $content .= '
    '; + $content .= '
    '; - } - - } + } + + } - return apply_filters('mycred_badge_show_earners', $content, $badge, $settings); + return apply_filters( 'mycred_badge_show_earners', $content, $badge, $settings ); - } -endif; + } +endif; \ No newline at end of file diff --git a/addons/badges/includes/mycred-badge-object.php b/addons/badges/includes/mycred-badge-object.php index 087fdff..3b451c5 100644 --- a/addons/badges/includes/mycred-badge-object.php +++ b/addons/badges/includes/mycred-badge-object.php @@ -1,911 +1,822 @@ post_type) && $object->post_type == MYCRED_BADGE_KEY ) { - $this->post_id = $object->ID; + if ( is_object( $object ) && isset( $object->post_type ) && $object->post_type == MYCRED_BADGE_KEY ) + $this->post_id = $object->ID; - } elseif (is_numeric($object) && mycred_get_post_type($object) == MYCRED_BADGE_KEY ) { - $this->post_id = absint($object); + elseif ( is_numeric( $object ) && mycred_get_post_type( $object ) == MYCRED_BADGE_KEY ) + $this->post_id = absint( $object ); - } else { return false; - } + else return false; - $this->image_width = MYCRED_BADGE_WIDTH; - $this->image_height = MYCRED_BADGE_HEIGHT; + $this->image_width = MYCRED_BADGE_WIDTH; + $this->image_height = MYCRED_BADGE_HEIGHT; - $this->user_meta_key = MYCRED_BADGE_KEY . $this->post_id; + $this->user_meta_key = MYCRED_BADGE_KEY . $this->post_id; - if ($level_id !== null ) { $this->level_id = absint($level_id); - } + if ( $level_id !== NULL ) $this->level_id = absint( $level_id ); - $this->populate($object, $level_id); + $this->populate( $object, $level_id ); - } + } - /** - * Populate - * - * @since 1.0 - * @version 1.0 - */ - protected function populate( $object = null, $level_id = null ) - { + /** + * Populate + * @since 1.0 + * @version 1.0 + */ + protected function populate( $object = NULL, $level_id = NULL ) { - if ($this->post_id === false ) { return; - } + if ( $this->post_id === false ) return; - // Get base badge details - $this->title = ( isset($object->post_title) ) ? $object->post_title : mycred_get_the_title($this->post_id); - $this->earnedby = ( isset($object->earnedby) ) ? $object->earnedby : $this->get_user_count($level_id); - $this->levels = ( isset($object->levels) ) ? $object->levels : mycred_get_badge_levels($this->post_id); + // Get base badge details + $this->title = ( isset( $object->post_title ) ) ? $object->post_title : mycred_get_the_title( $this->post_id ); + $this->earnedby = ( isset( $object->earnedby ) ) ? $object->earnedby : $this->get_user_count( $level_id ); + $this->levels = ( isset( $object->levels ) ) ? $object->levels : mycred_get_badge_levels( $this->post_id ); - if (! empty($this->levels) ) { + if ( ! empty( $this->levels ) ) { - $this->references = array(); - $this->point_types = array(); - $this->compare = $this->levels[0]['compare']; + $this->references = array(); + $this->point_types = array(); + $this->compare = $this->levels[0]['compare']; - if (! empty($this->levels[0]['requires']) ) { - foreach ( $this->levels[0]['requires'] as $requirement_id => $req ) { + if ( ! empty( $this->levels[0]['requires'] ) ) { + foreach ( $this->levels[0]['requires'] as $requirement_id => $req ) { - if ($req['reference'] != '' && ! in_array($req['reference'], $this->references) ) { - $this->references[] = $req['reference']; - } + if ( $req['reference'] != '' && ! in_array( $req['reference'], $this->references ) ) + $this->references[] = $req['reference']; - if ($req['type'] != '' && ! in_array($req['type'], $this->point_types) ) { - $this->point_types[] = $req['type']; - } + if ( $req['type'] != '' && ! in_array( $req['type'], $this->point_types ) ) + $this->point_types[] = $req['type']; - } - } + } + } - } + } - // Indicate manual badge - if (absint(mycred_get_post_meta($this->post_id, 'manual_badge', true)) === 1 ) { - $this->manual = true; - } + // Indicate manual badge + if ( absint( mycred_get_post_meta( $this->post_id, 'manual_badge', true ) ) === 1 ) + $this->manual = true; - // Indicate open badge - if (absint(mycred_get_post_meta($this->post_id, 'open_badge', true)) === 1 ) { + // Indicate open badge + if ( absint( mycred_get_post_meta( $this->post_id, 'open_badge', true ) ) === 1 ) { - $badge_setting = mycred_get_addon_settings('badges'); + $badge_setting = mycred_get_addon_settings( 'badges' ); - if (isset($badge_setting['open_badge']) && $badge_setting['open_badge'] === 1 ) { - - $this->open_badge = true; + if ( isset( $badge_setting['open_badge'] ) && $badge_setting['open_badge'] === 1 ) { + + $this->open_badge = true; - } - - } + } + + } - // If we requested a particular level - if ($level_id !== null ) { - $this->level = $this->get_level($level_id); - } + // If we requested a particular level + if ( $level_id !== NULL ) + $this->level = $this->get_level( $level_id ); - // Get images - $this->main_image = $this->get_image('main'); - $this->main_image_url = $this->get_image_url('main'); - $this->level_image = $this->get_image($level_id); - $this->congratulation_msg = mycred_get_post_meta($this->post_id, 'congratulation_msg', true); - $this->align = mycred_get_post_meta($this->post_id, 'mycred_badge_align', true); - $this->layout = mycred_get_post_meta($this->post_id, 'mycred_layout_check', true); + // Get images + $this->main_image = $this->get_image( 'main' ); + $this->main_image_url = $this->get_image_url( 'main' ); + $this->level_image = $this->get_image( $level_id ); + $this->congratulation_msg = mycred_get_post_meta( $this->post_id, 'congratulation_msg', true ); + $this->align = mycred_get_post_meta( $this->post_id, 'mycred_badge_align', true ); + $this->layout = mycred_get_post_meta( $this->post_id, 'mycred_layout_check', true ); - } + } - /** - * Get User Count - * - * @since 1.0 - * @version 1.0 - */ - public function get_user_count( $level_id = null ) - { + /** + * Get User Count + * @since 1.0 + * @version 1.0 + */ + public function get_user_count( $level_id = NULL ) { - if ($this->post_id === false ) { return 0; - } + if ( $this->post_id === false ) return 0; - $count = mycred_get_post_meta($this->post_id, 'total-users-with-badge', true); - if ($count == '' || $level_id !== null ) { + $count = mycred_get_post_meta( $this->post_id, 'total-users-with-badge', true ); + if ( $count == '' || $level_id !== NULL ) { - global $wpdb; + global $wpdb; - $level_filter = ( $level_id !== null && is_numeric($level_id) ) ? $wpdb->prepare("AND meta_value = %s", $level_id) : ''; + $level_filter = ( $level_id !== NULL && is_numeric( $level_id ) ) ? $wpdb->prepare( "AND meta_value = %s", $level_id ) : ''; - $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT( DISTINCT user_id ) FROM {$wpdb->usermeta} WHERE meta_key = %s {$level_filter};", mycred_get_meta_key($this->user_meta_key))); - if ($count === null ) { $count = 0; - } + $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( DISTINCT user_id ) FROM {$wpdb->usermeta} WHERE meta_key = %s {$level_filter};", mycred_get_meta_key( $this->user_meta_key ) ) ); + if ( $count === NULL ) $count = 0; - if ($level_id === null ) { - mycred_update_post_meta($this->post_id, 'total-users-with-badge', $count, true); - } + if ( $level_id === NULL ) + mycred_update_post_meta( $this->post_id, 'total-users-with-badge', $count, true ); - } + } - return apply_filters('mycred_count_users_with_badge', absint($count), $this->post_id); + return apply_filters( 'mycred_count_users_with_badge', absint( $count ), $this->post_id ); - } + } - /** - * Get Level - * - * @since 1.0 - * @version 1.0 - */ - public function get_level( $level_id = false ) - { + /** + * Get Level + * @since 1.0 + * @version 1.0 + */ + public function get_level( $level_id = false ) { - if ($level_id === false || empty($this->levels) || ! array_key_exists($level_id, $this->levels) ) { return false; - } + if ( $level_id === false || empty( $this->levels ) || ! array_key_exists( $level_id, $this->levels ) ) return false; - return $this->levels[ $level_id ]; + return $this->levels[ $level_id ]; - } + } - /** - * Get Level Requirements - * - * @since 1.0 - * @version 1.0 - */ - public function get_level_requirements( $level_id = false ) - { + /** + * Get Level Requirements + * @since 1.0 + * @version 1.0 + */ + public function get_level_requirements( $level_id = false ) { - if ($level_id === false || empty($this->levels) || ! array_key_exists($level_id, $this->levels) ) { return false; - } + if ( $level_id === false || empty( $this->levels ) || ! array_key_exists( $level_id, $this->levels ) ) return false; - return $this->levels[ $level_id ]['requires']; + return $this->levels[ $level_id ]['requires']; - } + } - /** - * Get Level Reward - * - * @since 1.0 - * @version 1.0 - */ - public function get_level_reward( $level_id = false ) - { + /** + * Get Level Reward + * @since 1.0 + * @version 1.0 + */ + public function get_level_reward( $level_id = false ) { - if ($level_id === false || empty($this->levels) || ! array_key_exists($level_id, $this->levels) ) { return false; - } + if ( $level_id === false || empty( $this->levels ) || ! array_key_exists( $level_id, $this->levels ) ) return false; - return $this->levels[ $level_id ]['reward']; + return $this->levels[ $level_id ]['reward']; - } + } - /** - * User Has Badge - * - * @since 1.0 - * @version 1.0 - */ - public function user_has_badge( $user_id = false, $level_id = 0 ) - { + /** + * User Has Badge + * @since 1.0 + * @version 1.0 + */ + public function user_has_badge( $user_id = false, $level_id = 0 ) { - $has_badge = false; - if ($user_id === false ) { return $has_badge; - } + $has_badge = false; + if ( $user_id === false ) return $has_badge; - $this->user_id = absint($user_id); - $this->current_level = $this->get_users_current_level($user_id); + $this->user_id = absint( $user_id ); + $this->current_level = $this->get_users_current_level( $user_id ); - if ($this->current_level !== false ) { + if ( $this->current_level !== false ) { - $has_badge = true; + $has_badge = true; - if ((int) $this->current_level < absint($level_id) ) { - $has_badge = false; - } + if ( (int) $this->current_level < absint( $level_id ) ) + $has_badge = false; - } + } - return apply_filters('mycred_user_has_badge', $has_badge, $user_id, $this->post_id, $level_id, $this->current_level); + return apply_filters( 'mycred_user_has_badge', $has_badge, $user_id, $this->post_id, $level_id, $this->current_level ); - } + } - /** - * Get Users Current Level - * - * @since 1.0 - * @version 1.0 - */ - public function get_users_current_level( $user_id = false ) - { + /** + * Get Users Current Level + * @since 1.0 + * @version 1.0 + */ + public function get_users_current_level( $user_id = false ) { - if ($user_id === false ) { return $has_badge; - } + if ( $user_id === false ) return $has_badge; - global $mycred_current_account; + global $mycred_current_account; - $user_id = absint($user_id); + $user_id = absint( $user_id ); - if (mycred_is_current_account($user_id) && isset($mycred_current_account->badge_ids) && ! empty($mycred_current_account->badge_ids) && array_key_exists($this->post_id, $mycred_current_account->badge_ids) ) { - return absint($mycred_current_account->badge_ids[ $this->post_id ]); - } + if ( mycred_is_current_account( $user_id ) && isset( $mycred_current_account->badge_ids ) && ! empty( $mycred_current_account->badge_ids ) && array_key_exists( $this->post_id, $mycred_current_account->badge_ids ) ) + return absint( $mycred_current_account->badge_ids[ $this->post_id ] ); - $current_level = mycred_get_user_meta($user_id, $this->user_meta_key, '', true); - $current_level = ( ! empty($current_level) || $current_level === '0' ) ? absint($current_level) : false; + $current_level = mycred_get_user_meta( $user_id, $this->user_meta_key, '', true ); + $current_level = ( ! empty( $current_level ) || $current_level === '0' ) ? absint( $current_level ) : false; - return $current_level; + return $current_level; - } + } - /** - * Get Level Reached - * - * @since 1.0 - * @version 1.0 - */ - public function query_users_level( $user_id = false ) - { + /** + * Get Level Reached + * @since 1.0 + * @version 1.0 + */ + public function query_users_level( $user_id = false ) { - if ($user_id === false || empty($this->levels) ) { return false; - } + if ( $user_id === false || empty( $this->levels ) ) return false; - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - $base_requirements = $this->levels[0]['requires']; - $compare = $this->levels[0]['compare']; - $requirements = count($base_requirements); - $level_reached = false; - $results = array(); + $base_requirements = $this->levels[0]['requires']; + $compare = $this->levels[0]['compare']; + $requirements = count( $base_requirements ); + $level_reached = false; + $results = array(); - // Based on the base requirements, we first get the users log entry results - if (! empty($base_requirements) ) { - foreach ( $base_requirements as $requirement_id => $requirement ) { + // Based on the base requirements, we first get the users log entry results + if ( ! empty( $base_requirements ) ) { + foreach ( $base_requirements as $requirement_id => $requirement ) { - if ($requirement['type'] == '' ) { - $requirement['type'] = MYCRED_DEFAULT_TYPE_KEY; - } + if ( $requirement['type'] == '' ) + $requirement['type'] = MYCRED_DEFAULT_TYPE_KEY; - $mycred = mycred($requirement['type']); - if ($mycred->exclude_user($user_id) ) { continue; - } + $mycred = mycred( $requirement['type'] ); + if ( $mycred->exclude_user( $user_id ) ) continue; - $having = 'COUNT(*)'; - if ($requirement['by'] != 'count' ) { - $having = 'SUM(creds)'; - } + $having = 'COUNT(*)'; + if ( $requirement['by'] != 'count' ) + $having = 'SUM(creds)'; - $query = $wpdb->get_var($wpdb->prepare("SELECT {$having} FROM {$mycred_log_table} WHERE ctype = %s AND ref = %s AND user_id = %d;", $requirement['type'], $requirement['reference'], $user_id)); + $query = $wpdb->get_var( $wpdb->prepare( "SELECT {$having} FROM {$mycred_log_table} WHERE ctype = %s AND ref = %s AND user_id = %d;", $requirement['type'], $requirement['reference'], $user_id ) ); - $query = apply_filters('mycred_badge_requirement', $query, $requirement_id, $requirement, $having, $user_id); + $query = apply_filters( 'mycred_badge_requirement', $query, $requirement_id, $requirement, $having, $user_id ); - if ($query === null ) { $query = 0; - } + if ( $query === NULL ) $query = 0; - $results[ $requirement['reference'] ] = $query; + $results[ $requirement['reference'] ] = $query; - } - } + } + } - // Next we loop through the levels and see compare the previous results to the requirements to determan our level - foreach ( $this->levels as $level_id => $level_setup ) { + // Next we loop through the levels and see compare the previous results to the requirements to determan our level + foreach ( $this->levels as $level_id => $level_setup ) { - $reqs_met = 0; - foreach ( $level_setup['requires'] as $requirement_id => $requirement ) { + $reqs_met = 0; + foreach ( $level_setup['requires'] as $requirement_id => $requirement ) { - if ($results[ $requirement['reference'] ] >= $requirement['amount'] ) { - $reqs_met++; - } + if ( $results[ $requirement['reference'] ] >= $requirement['amount'] ) + $reqs_met++; - } + } - if ($compare === 'AND' && $reqs_met >= $requirements ) { - $level_reached = $level_id; + if ( $compare === 'AND' && $reqs_met >= $requirements ) + $level_reached = $level_id; - } elseif ($compare === 'OR' && $reqs_met > 0 ) { - $level_reached = $level_id; - } + elseif ( $compare === 'OR' && $reqs_met > 0 ) + $level_reached = $level_id; - } + } - do_action('mycred_badge_level_reached', $user_id, $this->post_id, $level_reached); + do_action( 'mycred_badge_level_reached', $user_id, $this->post_id, $level_reached ); - return $level_reached; + return $level_reached; - } + } - /** - * Get Users Next Level ID - * - * @since 1.0 - * @version 1.0 - */ - public function get_users_next_level_id( $user_id = false ) - { + /** + * Get Users Next Level ID + * @since 1.0 + * @version 1.0 + */ + public function get_users_next_level_id( $user_id = false ) { - if (! $this->user_has_badge($user_id) ) { - return 0; - } + if ( ! $this->user_has_badge( $user_id ) ) + return 0; - $max_level = count($this->levels); - if ($this->current_level >= $max_level ) { - return $max_level; - } + $max_level = count( $this->levels ); + if ( $this->current_level >= $max_level ) + return $max_level; - return $this->current_level; + return $this->current_level; - } + } - /** - * Get Users Next Level - * - * @since 1.0 - * @version 1.0 - */ - public function get_users_next_level( $user_id = false ) - { + /** + * Get Users Next Level + * @since 1.0 + * @version 1.0 + */ + public function get_users_next_level( $user_id = false ) { - if (! $this->user_has_badge($user_id) ) { - return false; - } + if ( ! $this->user_has_badge( $user_id ) ) + return false; - $next_level_id = $this->get_users_next_level_id($user_id); + $next_level_id = $this->get_users_next_level_id( $user_id ); - return $this->get_level($next_level_id); + return $this->get_level( $next_level_id ); - } + } - /** - * Assign Badge to User - * - * @since 1.0 - * @since 2.3 Added functions `mycred_update_user_meta`, `mycred_get_user_meta` with `mycred_badge_ids` - * @version 1.0 - */ - public function assign( $user_id = false, $level_id = 0 ) - { + /** + * Assign Badge to User + * @since 1.0 + * @since 2.3 Added functions `mycred_update_user_meta`, `mycred_get_user_meta` with `mycred_badge_ids` + * @version 1.0 + */ + public function assign( $user_id = false, $level_id = 0 ) { - if ($user_id === false || absint($user_id) === 0 ) { return false; - } + if ( $user_id === false || absint( $user_id ) === 0 ) return false; - $previous_level = -1; - $new_level = $level_id; + $previous_level = -1; + $new_level = $level_id; - if ($this->user_has_badge($user_id) ) { + if ( $this->user_has_badge( $user_id ) ) { - // Right now we can not earn the same badge over and over again - // Planing on adding in an option to override this - if ($this->current_level == $level_id ) { return true; - } + // Right now we can not earn the same badge over and over again + // Planing on adding in an option to override this + if ( $this->current_level == $level_id ) return true; - $previous_level = $this->current_level; + $previous_level = $this->current_level; - } + } - else { - $this->user_id = $user_id; - $this->current_level = $new_level; - } + else { + $this->user_id = $user_id; + $this->current_level = $new_level; + } - $execute = apply_filters('mycred_badge_assign', true, $user_id, $new_level, $this); + $execute = apply_filters( 'mycred_badge_assign', true, $user_id, $new_level, $this ); - if ($execute ) { - - $new_level = apply_filters('mycred_badge_user_value', $new_level, $user_id, $this->post_id); + if ( $execute ) { + + $new_level = apply_filters( 'mycred_badge_user_value', $new_level, $user_id, $this->post_id ); - mycred_update_user_meta($user_id, $this->user_meta_key, '', $new_level); - mycred_update_user_meta($user_id, $this->user_meta_key, '_issued_on', time()); - - $badge_ids = mycred_get_user_meta($user_id, 'mycred_badge_ids', '', true); - - if (! empty($badge_ids) && is_array($badge_ids) ) { - $badge_ids[ $this->post_id ] = 0; - } else { - $badge_ids = array( $this->post_id => 0 ); - } - - mycred_update_user_meta($user_id, 'mycred_badge_ids', '', $badge_ids); + mycred_update_user_meta( $user_id, $this->user_meta_key, '', $new_level ); + mycred_update_user_meta( $user_id, $this->user_meta_key, '_issued_on', time() ); + + $badge_ids = mycred_get_user_meta( $user_id, 'mycred_badge_ids', '', true ); + + if ( ! empty( $badge_ids ) && is_array( $badge_ids ) ) + $badge_ids[ $this->post_id ] = 0; + else + $badge_ids = array( $this->post_id => 0 ); + + mycred_update_user_meta( $user_id, 'mycred_badge_ids', '', $badge_ids ); - // Need to update counter with new assignments - if ($new_level == 0 ) { + // Need to update counter with new assignments + if ( $new_level == 0 ) { - $this->earnedby ++; + $this->earnedby ++; - mycred_update_post_meta($this->post_id, 'total-users-with-badge', $this->earnedby); + mycred_update_post_meta( $this->post_id, 'total-users-with-badge', $this->earnedby ); - } + } - $this->payout_reward($previous_level, $new_level); - - do_action('mycred_after_badge_assign', $user_id, $this->post_id, $new_level); + $this->payout_reward( $previous_level, $new_level ); + + do_action( 'mycred_after_badge_assign', $user_id, $this->post_id, $new_level ); - } + } - return true; + return true; - } + } - /** - * Payout Rewards - * - * @since 1.0 - * @version 1.0 - */ - public function payout_reward( $previous_level = -1, $new_level = 0 ) - { + /** + * Payout Rewards + * @since 1.0 + * @version 1.0 + */ + public function payout_reward( $previous_level = -1, $new_level = 0 ) { - // Earning the badge - if ($previous_level < 0 && $new_level == 0 ) { + // Earning the badge + if ( $previous_level < 0 && $new_level == 0 ) { - $reward = $this->get_level_reward($new_level); - if ($reward !== false && ( $reward['log'] == '' || $reward['amount'] == 0 ) ) { return false; - } + $reward = $this->get_level_reward( $new_level ); + if ( $reward !== false && ( $reward['log'] == '' || $reward['amount'] == 0 ) ) return false; - $mycred = mycred($reward['type']); + $mycred = mycred( $reward['type'] ); - // Make sure we only get points once for each level we reach for each badge - if (! $mycred->has_entry('badge_reward', $this->post_id, $this->user_id, 0, $reward['type']) ) { + // Make sure we only get points once for each level we reach for each badge + if ( ! $mycred->has_entry( 'badge_reward', $this->post_id, $this->user_id, 0, $reward['type'] ) ) { - $exec = apply_filters('customize_mycred_badge_condition', true, $this->post_id, $this->user_id, $reward['type']); + $exec = apply_filters( 'customize_mycred_badge_condition', true, $this->post_id, $this->user_id, $reward['type']); - if($exec ) { + if( $exec ) { - $mycred->add_creds( - 'badge_reward', - $this->user_id, - $reward['amount'], - $reward['log'], - $this->post_id, - 0, - $reward['type'] - ); + $mycred->add_creds( + 'badge_reward', + $this->user_id, + $reward['amount'], + $reward['log'], + $this->post_id, + 0, + $reward['type'] + ); - do_action('mycred_badge_rewardes', $this->user_id, $previous_level, $new_level, $reward, $this); + do_action( 'mycred_badge_rewardes', $this->user_id, $previous_level, $new_level, $reward, $this ); - } + } - } + } - } + } - // Earning a new level as well - else { + // Earning a new level as well + else { - // Loop through levels to make sure we do not miss rewards if we jump more than one level - for ( $i = $previous_level; $i <= $new_level; $i++ ) { + // Loop through levels to make sure we do not miss rewards if we jump more than one level + for ( $i = $previous_level; $i <= $new_level; $i++ ) { - $reward = $this->get_level_reward($i); - if ($reward !== false && ( $reward['log'] == '' || $reward['amount'] == 0 ) ) { continue; - } + $reward = $this->get_level_reward( $i ); + if ( $reward !== false && ( $reward['log'] == '' || $reward['amount'] == 0 ) ) continue; - $mycred = mycred($reward['type']); + $mycred = mycred( $reward['type'] ); - // Make sure we only get points once for each level we reach for each badge - if (! $mycred->has_entry('badge_reward', $this->post_id, $this->user_id, $i, $reward['type']) ) { + // Make sure we only get points once for each level we reach for each badge + if ( ! $mycred->has_entry( 'badge_reward', $this->post_id, $this->user_id, $i, $reward['type'] ) ) { - $exec = apply_filters('customize_mycred_badge_condition', true, $this->post_id, $this->user_id, $reward['type']); + $exec = apply_filters( 'customize_mycred_badge_condition', true, $this->post_id, $this->user_id, $reward['type']); - if($exec ) { + if( $exec ) { - $mycred->add_creds( - 'badge_reward', - $this->user_id, - $reward['amount'], - $reward['log'], - $this->post_id, - $i, - $reward['type'] - ); + $mycred->add_creds( + 'badge_reward', + $this->user_id, + $reward['amount'], + $reward['log'], + $this->post_id, + $i, + $reward['type'] + ); - do_action('mycred_badge_rewardes', $this->user_id, $previous_level, $new_level, $reward, $this); + do_action( 'mycred_badge_rewardes', $this->user_id, $previous_level, $new_level, $reward, $this ); - } + } - } + } - } + } - } + } - return true; + return true; - } + } - /** - * Assign Badge to All - * - * @since 1.0 - * @version 1.0 - */ - public function assign_all() - { + /** + * Assign Badge to All + * @since 1.0 + * @version 1.0 + */ + public function assign_all() { - if ($this->post_id === false || empty($this->levels) ) { return false; - } + if ( $this->post_id === false || empty( $this->levels ) ) return false; - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - $results = array(); + $results = array(); - // Need to have some requirements set or we are in trouble - if (! empty($this->levels[0]['requires']) ) { + // Need to have some requirements set or we are in trouble + if ( ! empty( $this->levels[0]['requires'] ) ) { - // Single requirement - if (count($this->levels[0]['requires']) == 1 ) { + // Single requirement + if ( count( $this->levels[0]['requires'] ) == 1 ) { - $requirement = $this->levels[0]['requires'][0]; - $having = ( $requirement['by'] != 'count' ) ? 'SUM( creds )' : 'COUNT( id )'; - $requirement['type'] = ( $requirement['type'] == '' ) ? MYCRED_DEFAULT_TYPE_KEY : $requirement['type']; + $requirement = $this->levels[0]['requires'][0]; + $having = ( $requirement['by'] != 'count' ) ? 'SUM( creds )' : 'COUNT( id )'; + $requirement['type'] = ( $requirement['type'] == '' ) ? MYCRED_DEFAULT_TYPE_KEY : $requirement['type']; - $results = $wpdb->get_results($wpdb->prepare("SELECT DISTINCT user_id, {$having} as total FROM {$mycred_log_table} WHERE ctype = %s AND ref = %s GROUP BY user_id HAVING {$having} >= %f;", $requirement['type'], $requirement['reference'], $requirement['amount'])); + $results = $wpdb->get_results( $wpdb->prepare( "SELECT DISTINCT user_id, {$having} as total FROM {$mycred_log_table} WHERE ctype = %s AND ref = %s GROUP BY user_id HAVING {$having} >= %f;", $requirement['type'], $requirement['reference'], $requirement['amount'] ) ); - // Find the level id for each result based on their total - if (! empty($results) ) { - foreach ( $results as $row ) { + // Find the level id for each result based on their total + if ( ! empty( $results ) ) { + foreach ( $results as $row ) { - $badge_level_id = 0; + $badge_level_id = 0; - foreach ( $this->levels as $level_id => $setup ) { - if ($row->total >= $setup['requires'][0]['amount'] ) { - $badge_level_id = $level_id; - } - } + foreach ( $this->levels as $level_id => $setup ) { + if ( $row->total >= $setup['requires'][0]['amount'] ) + $badge_level_id = $level_id; + } - $row->level_id = $badge_level_id; + $row->level_id = $badge_level_id; - } - } + } + } - } + } - // Multiple requirements - else { + // Multiple requirements + else { - $user_ids = array(); + $user_ids = array(); - $requirements = count($this->levels[0]['requires']); - $compare = $this->levels[0]['compare']; + $requirements = count( $this->levels[0]['requires'] ); + $compare = $this->levels[0]['compare']; - // I feel like there must be a better way of doing this - // If you have a suggestion for how to query all users based on multiple requirements, let me know! - foreach ( $this->levels as $level_id => $level_setup ) { + // I feel like there must be a better way of doing this + // If you have a suggestion for how to query all users based on multiple requirements, let me know! + foreach ( $this->levels as $level_id => $level_setup ) { - $level_user_ids = array(); + $level_user_ids = array(); - // Get all user IDs that fulfill each requirements set - if (! empty($level_setup['requires']) ) { - foreach ( $level_setup['requires'] as $requirement_id => $requirement ) { + // Get all user IDs that fulfill each requirements set + if ( ! empty( $level_setup['requires'] ) ) { + foreach ( $level_setup['requires'] as $requirement_id => $requirement ) { - $having = ( $requirement['by'] != 'count' ) ? 'SUM( creds )' : 'COUNT( id )'; - $requirement['type'] = ( $requirement['type'] == '' ) ? MYCRED_DEFAULT_TYPE_KEY : $requirement['type']; + $having = ( $requirement['by'] != 'count' ) ? 'SUM( creds )' : 'COUNT( id )'; + $requirement['type'] = ( $requirement['type'] == '' ) ? MYCRED_DEFAULT_TYPE_KEY : $requirement['type']; - $level_user_ids[ $requirement_id ] = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT user_id FROM {$mycred_log_table} WHERE ctype = %s AND ref = %s GROUP BY user_id HAVING {$having} >= %f;", $requirement['type'], $requirement['reference'], $requirement['amount'])); + $level_user_ids[ $requirement_id ] = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT user_id FROM {$mycred_log_table} WHERE ctype = %s AND ref = %s GROUP BY user_id HAVING {$having} >= %f;", $requirement['type'], $requirement['reference'], $requirement['amount'] ) ); - } - } + } + } - // OR = get all unique IDs - if ($compare == 'OR' ) { + // OR = get all unique IDs + if ( $compare == 'OR' ) { - $list = array(); - foreach ( $level_user_ids as $requirement_id => $list_of_ids ) { - if (! empty($list_of_ids) ) { - foreach ( $list_of_ids as $uid ) { - if (! in_array($uid, $list) ) { - $list[] = $uid; - } - } - } - } + $list = array(); + foreach ( $level_user_ids as $requirement_id => $list_of_ids ) { + if ( ! empty( $list_of_ids ) ) { + foreach ( $list_of_ids as $uid ) { + if ( ! in_array( $uid, $list ) ) + $list[] = $uid; + } + } + } - } + } - // AND = get IDs that are in all requirements - else { + // AND = get IDs that are in all requirements + else { - $list = $_list = array(); + $list = $_list = array(); - foreach ( $level_user_ids as $requirement_id => $list_of_ids ) { - if (! empty($list_of_ids) ) { - foreach ( $list_of_ids as $uid ) { - if (! array_key_exists($uid, $_list) ) { - $_list[ $uid ] = 1; - } else { - $_list[ $uid ]++; - } - } - } - } + foreach ( $level_user_ids as $requirement_id => $list_of_ids ) { + if ( ! empty( $list_of_ids ) ) { + foreach ( $list_of_ids as $uid ) { + if ( ! array_key_exists( $uid, $_list ) ) + $_list[ $uid ] = 1; + else + $_list[ $uid ]++; + } + } + } - foreach ( $_list as $uid => $count ) { - if ($count >= $requirements ) { - $list[] = $uid; - } - } + foreach ( $_list as $uid => $count ) { + if ( $count >= $requirements ) + $list[] = $uid; + } - } + } - // If no user has reached the first level, no one will have reached higher levels and there is no need to continue - if ($level_id == 0 && empty($list) ) { break; - } + // If no user has reached the first level, no one will have reached higher levels and there is no need to continue + if ( $level_id == 0 && empty( $list ) ) break; - // Create a list where the array key represents the user ID and the array value represents the badge level reached by the user - foreach ( $list as $user_id ) { - $user_ids[ $user_id ] = $level_id; - } + // Create a list where the array key represents the user ID and the array value represents the badge level reached by the user + foreach ( $list as $user_id ) { + $user_ids[ $user_id ] = $level_id; + } - } + } - if (! empty($user_ids) ) { - foreach ( $user_ids as $user_id => $level_reached ) { + if ( ! empty( $user_ids ) ) { + foreach ( $user_ids as $user_id => $level_reached ) { - $row = new StdClass(); - $row->user_id = $user_id; - $row->level_id = $level_reached; + $row = new StdClass(); + $row->user_id = $user_id; + $row->level_id = $level_reached; - $results[] = $row; + $results[] = $row; - } - } + } + } - } - - // Assign results - if (! empty($results) ) { + } + + // Assign results + if ( ! empty( $results ) ) { - // Assign each user - foreach ( $results as $row ) { - mycred_update_user_meta($row->user_id, $this->user_meta_key, '', $row->level_id); - } + // Assign each user + foreach ( $results as $row ) + mycred_update_user_meta( $row->user_id, $this->user_meta_key, '', $row->level_id ); - // Update earned count - $this->earnedby = count($results); + // Update earned count + $this->earnedby = count( $results ); - mycred_update_post_meta($this->post_id, 'total-users-with-badge', $this->earnedby); + mycred_update_post_meta( $this->post_id, 'total-users-with-badge', $this->earnedby ); - //Updating issued_on - mycred_update_user_meta($row->user_id, $this->user_meta_key, '_issued_on', time()); + //Updating issued_on + mycred_update_user_meta( $row->user_id, $this->user_meta_key, '_issued_on', time() ); - } + } - } + } - return count($results); + return count( $results ); - } + } - /** - * Divest Badge from user - * - * @since 1.0 - * @since 2.3 Added functions `mycred_update_user_meta` with `mycred_badge_ids` - * @version 1.0 - */ - public function divest( $user_id = false ) - { + /** + * Divest Badge from user + * @since 1.0 + * @since 2.3 Added functions `mycred_update_user_meta` with `mycred_badge_ids` + * @version 1.0 + */ + public function divest( $user_id = false ) { - if ($user_id === false || absint($user_id) === 0 ) { return false; - } + if ( $user_id === false || absint( $user_id ) === 0 ) return false; - mycred_delete_user_meta($user_id, $this->user_meta_key); - mycred_delete_user_meta($user_id, $this->user_meta_key . '_issued_on'); - $usermeta = mycred_get_user_meta($user_id, 'mycred_badge_ids', '', true); + mycred_delete_user_meta( $user_id, $this->user_meta_key ); + mycred_delete_user_meta( $user_id, $this->user_meta_key . '_issued_on' ); + $usermeta = mycred_get_user_meta( $user_id, 'mycred_badge_ids', '', true ); - if (isset($usermeta[$this->post_id]) ) { - unset($usermeta[$this->post_id]); - } + if ( isset( $usermeta[$this->post_id] ) ) + unset( $usermeta[$this->post_id] ); - $this->earnedby --; - if ($this->earnedby < 0 ) { $this->earnedby = 0; - } + $this->earnedby --; + if ( $this->earnedby < 0 ) $this->earnedby = 0; - mycred_update_post_meta($this->post_id, 'total-users-with-badge', $this->earnedby); - mycred_update_user_meta($user_id, 'mycred_badge_ids', '', $usermeta); + mycred_update_post_meta( $this->post_id, 'total-users-with-badge', $this->earnedby ); + mycred_update_user_meta( $user_id, 'mycred_badge_ids', '', $usermeta ); - return true; + return true; - } + } - /** - * Divest Badge from Everyone - * - * @since 1.0 - * @version 1.0 - */ - public function divest_all() - { + /** + * Divest Badge from Everyone + * @since 1.0 + * @version 1.0 + */ + public function divest_all() { - if ($this->post_id === false ) { return false; - } + if ( $this->post_id === false ) return false; - global $wpdb; + global $wpdb; - // Delete connections - $count = $wpdb->delete( - $wpdb->usermeta, - array( 'meta_key' => mycred_get_meta_key($this->user_meta_key) ), - array( '%s' ) - ); + // Delete connections + $count = $wpdb->delete( + $wpdb->usermeta, + array( 'meta_key' => mycred_get_meta_key( $this->user_meta_key ) ), + array( '%s' ) + ); - $this->earnedby = 0; + $this->earnedby = 0; - mycred_update_post_meta($this->post_id, 'total-users-with-badge', $this->earnedby); + mycred_update_post_meta( $this->post_id, 'total-users-with-badge', $this->earnedby ); - return $count; + return $count; - } + } - /** - * Delete Badge - * - * @since 1.0 - * @version 1.0 - */ - public function delete( $delete_post = false ) - { + /** + * Delete Badge + * @since 1.0 + * @version 1.0 + */ + public function delete( $delete_post = false ) { - if ($this->post_id === false ) { return false; - } + if ( $this->post_id === false ) return false; - $this->divest_all(); + $this->divest_all(); - if (! empty($this->point_types) ) { + if ( ! empty( $this->point_types ) ) { - foreach ( $this->point_types as $point_type ) { - mycred_delete_option('mycred-badge-references-' . $point_type); - } + foreach ( $this->point_types as $point_type ) + mycred_delete_option( 'mycred-badge-references-' . $point_type ); - } + } - if ($delete_post ) { - mycred_delete_post($this->post_id, true); - } + if ( $delete_post ) + mycred_delete_post( $this->post_id, true ); - return true; + return true; - } + } - /** - * Get Badge Image - * - * @since 1.0 - * @version 1.1 - */ - public function get_image( $image = null ) - { + /** + * Get Badge Image + * @since 1.0 + * @version 1.1 + */ + public function get_image( $image = NULL ) { - $image_identification = false; + $image_identification = false; - $level = 'none'; - if ($image != 'main' && is_numeric($image) ) { + $level = 'none'; + if ( $image != 'main' && is_numeric( $image ) ) { - $level = $image; + $level = $image; - } + } - $image_url = $this->get_image_url($image); + $image_url = $this->get_image_url( $image ); - $image_width = ( $this->image_width !== false ) ? ' width="' . esc_attr($this->image_width) . '"' : ''; - $image_height = ( $this->image_height !== false ) ? ' height="' . esc_attr($this->image_height) . '"' : ''; + $image_width = ( $this->image_width !== false ) ? ' width="' . esc_attr( $this->image_width ) . '"' : ''; + $image_height = ( $this->image_height !== false ) ? ' height="' . esc_attr( $this->image_height ) . '"' : ''; - if (! $image_url ) { return false; - } + if ( ! $image_url ) return false; - $html = '' . esc_attr($this->title) . ''; + $html = '' . esc_attr( $this->title ) . ''; - return apply_filters('mycred_badge_image', $html, $image, $this); + return apply_filters( 'mycred_badge_image', $html, $image, $this ); - } + } - public function get_image_url( $image = null ) - { + public function get_image_url( $image = NULL ) { - $image_identification = false; + $image_identification = false; - if ($image === 'main' ) { - $image_identification = mycred_get_post_meta($this->post_id, 'main_image', true); + if ( $image === 'main' ) + $image_identification = mycred_get_post_meta( $this->post_id, 'main_image', true ); - } elseif ($image !== null && is_numeric($image) && isset($this->levels[ $image ]['attachment_id']) ) { + elseif ( $image !== NULL && is_numeric( $image ) && isset( $this->levels[ $image ]['attachment_id'] ) ) { - $image_identification = $this->levels[ $image ]['image_url']; - if ($this->levels[ $image ]['attachment_id'] > 0 ) { - $image_identification = $this->levels[ $image ]['attachment_id']; - } + $image_identification = $this->levels[ $image ]['image_url']; + if ( $this->levels[ $image ]['attachment_id'] > 0 ) { + $image_identification = $this->levels[ $image ]['attachment_id']; + } - } + } - if ($image_identification === false || strlen($image_identification) == 0 ) { return false; - } + if ( $image_identification === false || strlen( $image_identification ) == 0 ) return false; - $image_url = $image_identification; + $image_url = $image_identification; - if (is_numeric($image_identification) && strpos('://', (string) $image_identification) === false ) { - $image_url = mycred_get_attachment_url($image_identification); - } + if ( is_numeric( $image_identification ) && strpos( '://', (string) $image_identification ) === false ) + $image_url = mycred_get_attachment_url( $image_identification ); - return apply_filters('mycred_badge_image_url', $image_url, $image, $this); + return apply_filters( 'mycred_badge_image_url', $image_url, $image, $this ); - } + } - public function get_earned_image( $user_id ) - { + public function get_earned_image( $user_id ) { - $image_url = $this->main_image_url; + $image_url = $this->main_image_url; - if ($this->open_badge && $this->user_has_badge($user_id) ) { + if ( $this->open_badge && $this->user_has_badge( $user_id ) ) { - $wp_upload_dirs = wp_upload_dir(); - $basedir = trailingslashit($wp_upload_dirs[ 'basedir' ]); - $baseurl = trailingslashit($wp_upload_dirs[ 'baseurl' ]); + $wp_upload_dirs = wp_upload_dir(); + $basedir = trailingslashit( $wp_upload_dirs[ 'basedir' ] ); + $baseurl = trailingslashit( $wp_upload_dirs[ 'baseurl' ] ); - $folderName = apply_filters('mycred_open_badge_folder', 'open_badges'); + $folderName = apply_filters( 'mycred_open_badge_folder', 'open_badges' ); - $open_badge_directory = $basedir . $folderName; + $open_badge_directory = $basedir . $folderName; - $open_badge_directory = trailingslashit($open_badge_directory); + $open_badge_directory = trailingslashit( $open_badge_directory ); - $badge_id = $this->post_id; + $badge_id = $this->post_id; - $filename = "badge-{$badge_id}-{$user_id}.png"; - - if (! file_exists($open_badge_directory . $filename) ) { + $filename = "badge-{$badge_id}-{$user_id}.png"; + + if ( ! file_exists( $open_badge_directory . $filename ) ) { - $mycred_Open_Badge = new mycred_Open_Badge(); - $mycred_Open_Badge->bake_users_image($user_id, $badge_id); + $mycred_Open_Badge = new mycred_Open_Badge(); + $mycred_Open_Badge->bake_users_image( $user_id, $badge_id ); - } + } - $image_url = trailingslashit($baseurl . $folderName) . $filename; + $image_url = trailingslashit( $baseurl . $folderName ) . $filename; - } + } - return $image_url; + return $image_url; - } + } - } -endif; + } +endif; \ No newline at end of file diff --git a/addons/badges/includes/mycred-badge-secondary.php b/addons/badges/includes/mycred-badge-secondary.php index ec885d5..4b28fd6 100644 --- a/addons/badges/includes/mycred-badge-secondary.php +++ b/addons/badges/includes/mycred-badge-secondary.php @@ -1,113 +1,103 @@ get_var($wpdb->prepare("SELECT {$having} FROM {$mycred_log_table} WHERE ctype = %s AND ref = %s AND data LIKE %s AND user_id = %d;", $requirement['type'], $requirement['reference'], '%'.$requirement['specific'].'%', $user_id)); - - } - else if($requirement['reference'] == 'gravity_form_submission' && ! empty($requirement['specific']) && $requirement['specific'] != 'Any' ) { - $query = $wpdb->get_var($wpdb->prepare("SELECT {$having} FROM {$mycred_log_table} WHERE ctype = %s AND ref = %s AND ref_id = %d AND user_id = %d;", $requirement['type'], $requirement['reference'], $requirement['specific'], $user_id)); - } - return $query; - } + if( $requirement['reference'] == 'link_click' && ! empty( $requirement['specific'] ) && $requirement['specific'] != 'Any' ) { + + $query = $wpdb->get_var( $wpdb->prepare( "SELECT {$having} FROM {$mycred_log_table} WHERE ctype = %s AND ref = %s AND data LIKE %s AND user_id = %d;", $requirement['type'], $requirement['reference'], '%'.$requirement['specific'].'%', $user_id ) ); + + } + else if( $requirement['reference'] == 'gravity_form_submission' && ! empty( $requirement['specific'] ) && $requirement['specific'] != 'Any' ) { + $query = $wpdb->get_var( $wpdb->prepare( "SELECT {$having} FROM {$mycred_log_table} WHERE ctype = %s AND ref = %s AND ref_id = %d AND user_id = %d;", $requirement['type'], $requirement['reference'], $requirement['specific'], $user_id ) ); + } + return $query; + } - public function badge_specific_template( $data, $requirement_id, $requirement, $badge, $level ) - { + public function badge_specific_template( $data, $requirement_id, $requirement, $badge, $level ) { - if($requirement['reference'] == 'link_click' && ! empty($requirement['specific']) && $requirement['specific'] != 'Any' ) { - - $data = '
    '; - - } - else if($requirement['reference'] == 'gravity_form_submission' && ! empty($requirement['specific']) && $requirement['specific'] != 'Any' ) { - if(class_exists('RGFormsModel') ) { - $gravityforms = RGFormsModel::get_forms(); - $form_list = ''; - foreach ($gravityforms as $form) { - $form_list .= ''; - } - $data = '
    '; - } - } - return $data; + if( $requirement['reference'] == 'link_click' && ! empty( $requirement['specific'] ) && $requirement['specific'] != 'Any' ) { + + $data = '
    '; + + } + else if( $requirement['reference'] == 'gravity_form_submission' && ! empty( $requirement['specific'] ) && $requirement['specific'] != 'Any' ) { + if( class_exists('RGFormsModel') ) { + $gravityforms = RGFormsModel::get_forms(); + $form_list = ''; + foreach ($gravityforms as $form) { + $form_list .= ''; + } + $data = '
    '; + } + } + return $data; - } + } - public function admin_header() - { - $screen = get_current_screen(); - - if ($screen->id == MYCRED_BADGE_KEY ) :?> - - Any'; + foreach ( $gravityforms as $form ) { + $form_list .= ''; + } + $data = '
    '; + echo "var mycred_badge_gravity_form_submission = '" . $data . "';"; + } + ?> + + 'earned', - 'width' => MYCRED_BADGE_WIDTH, - 'height' => MYCRED_BADGE_HEIGHT, - 'user_id' => 'current', - 'title' => '', - 'post_excerpt' => '' - ), $atts, MYCRED_SLUG . '_my_badges' - ) - ); - - if (! is_user_logged_in() && $user_id == 'current' ) { +if ( ! function_exists( 'mycred_render_my_badges' ) ) : + function mycred_render_my_badges( $atts, $content = '' ) { + + extract( shortcode_atts( array( + 'show' => 'earned', + 'width' => MYCRED_BADGE_WIDTH, + 'height' => MYCRED_BADGE_HEIGHT, + 'user_id' => 'current', + 'title' => '', + 'post_excerpt' => '' + ), $atts, MYCRED_SLUG . '_my_badges' ) ); + + if ( ! is_user_logged_in() && $user_id == 'current' ) return $content; - } - $user_id = mycred_get_user_id($user_id); + $user_id = mycred_get_user_id( $user_id ); ob_start(); echo '
    '; // Show only badges that we have earned - if ($show == 'earned' ) { + if ( $show == 'earned' ) { - mycred_display_users_badges($user_id, $width, $height); + mycred_display_users_badges( $user_id, $width, $height ); } // Show all badges highlighting the ones we earned - elseif ($show == 'all' ) { + elseif ( $show == 'all' ) { - $users_badges = mycred_get_users_badges($user_id); + $users_badges = mycred_get_users_badges( $user_id ); $all_badges = mycred_get_badge_ids(); foreach ( $all_badges as $badge_id ) { @@ -54,11 +46,11 @@ function mycred_render_my_badges( $atts, $content = '' ) echo '
    '; // User has not earned badge - if (! array_key_exists($badge_id, $users_badges) ) { + if ( ! array_key_exists( $badge_id, $users_badges ) ) { - $badge = mycred_get_badge($badge_id); + $badge = mycred_get_badge( $badge_id ); - $page_id = get_page($badge_id); + $page_id = get_page( $badge_id); $badge->image_width = $width; @@ -67,69 +59,69 @@ function mycred_render_my_badges( $atts, $content = '' ) $badge_title = $badge->title; $badge_img = $badge->main_image; - - - if ($badge->main_image !== false ) { + if ( $badge->main_image !== false ) { echo '
    ' . wp_kses_post( $badge_img ) . '
    '; - if($title == 'show') { + if( $title == 'show' ) { - echo '
    ' . esc_html( $badge_title ) . ' '.'
    '; + echo '
    ' . esc_html( $badge_title ) . '
    '; - } else { + } + else { - echo ''; + echo ''; } - if($post_excerpt == 'show') { + if( $post_excerpt == 'show' ) { + + echo '
    ' . esc_html( $page_id->post_excerpt ) . '
    '; - echo '
    ' . wp_kses_post( $page_id->post_excerpt ) . ' '.'
    '; + } + else { - } else { - echo ''; + echo ''; + } } } - // User has earned badge else { $level = $users_badges[ $badge_id ]; - $badge = mycred_get_badge($badge_id, $level); + $badge = mycred_get_badge( $badge_id, $level ); $badge->image_width = $width; $badge->image_height = $height; - $badge_page_id = get_page($badge_id); - - + $badge_page_id = get_page( $badge_id); - if ($badge->level_image !== false ) { + if ( $badge->level_image !== false ) { + echo '
    ' . wp_kses_post( $badge->get_image( $level ) ) . '
    '; - echo '
    ' . wp_kses_post( $badge->get_image($level) ) . '
    '; + if( $title == 'show' ) { - if($title == 'show') { - - echo '
    ' . esc_html( $badge->title ) . ' '.'
    '; + echo '
    ' . esc_html( $badge->title ) . '
    '; } - else { - echo ''; + echo ''; } - if($post_excerpt == 'show') { - - echo '
    ' . wp_kses_post( $badge_page_id->post_excerpt ) . ' '.'
    '; + if( $post_excerpt == 'show' ) { + + echo '
    ' . esc_html( $badge_page_id->post_excerpt ) . '
    '; - } else { - echo '';; + } + else { + + echo ''; + } } @@ -138,12 +130,15 @@ function mycred_render_my_badges( $atts, $content = '' ) echo '
    '; - if($title == 'show' || $post_excerpt == 'show') { + if( $title == 'show' || $post_excerpt == 'show' ) { echo '
    '; + } else { + echo ''; + } } @@ -153,7 +148,7 @@ function mycred_render_my_badges( $atts, $content = '' ) $output = ob_get_contents(); ob_end_clean(); - return apply_filters('mycred_my_badges', $output, $user_id); + return apply_filters( 'mycred_my_badges', $output, $user_id ); } endif; @@ -161,55 +156,48 @@ function mycred_render_my_badges( $atts, $content = '' ) /** * Shortcode: mycred_badges * Allows you to show all published badges - * - * @since 1.5 + * @since 1.5 * @version 1.1.1 */ -if (! function_exists('mycred_render_badges') ) : - function mycred_render_badges( $atts, $template = '' ) - { - extract( - shortcode_atts( - array( - 'width' => MYCRED_BADGE_WIDTH, - 'height' => MYCRED_BADGE_HEIGHT - ), $atts, MYCRED_SLUG . '_badges' - ) - ); +if ( ! function_exists( 'mycred_render_badges' ) ) : + function mycred_render_badges( $atts, $template = '' ) { + extract( shortcode_atts( array( + 'width' => MYCRED_BADGE_WIDTH, + 'height' => MYCRED_BADGE_HEIGHT + ), $atts, MYCRED_SLUG . '_badges' ) ); $all_badges = mycred_get_badge_ids(); - if ($template == '' ) { + if ( $template == '' ) $template = '

    %badge_title%

    %requirements%
    %count%
    %default_image% %main_image%
    '; - } $output = '
    '; - if (! empty($all_badges) ) { + if ( ! empty( $all_badges ) ) { foreach ( $all_badges as $badge_id ) { - $badge = mycred_get_badge($badge_id, 0); + $badge = mycred_get_badge( $badge_id, 0 ); $badge->image_width = $width; $badge->image_height = $height; $row = $template; - $row = str_replace('%badge_title%', $badge->title, $row); - $row = str_replace('%requirements%', mycred_display_badge_requirements($badge_id), $row); - $row = str_replace('%count%', $badge->earnedby, $row); - $row = str_replace('%default_image%', $badge->get_image('main'), $row); + $row = str_replace( '%badge_title%', $badge->title, $row ); + $row = str_replace( '%requirements%', mycred_display_badge_requirements( $badge_id ), $row ); + $row = str_replace( '%count%', $badge->earnedby, $row ); + $row = str_replace( '%default_image%', $badge->get_image( 'main' ), $row ); - if(mycred_user_has_badge(get_current_user_id(), $badge_id) ) { + if( mycred_user_has_badge( get_current_user_id(), $badge_id) ) { $user_id = get_current_user_id(); - $badge = mycred_get_badge($badge_id); - $level = $badge->get_users_current_level($user_id); - $row = str_replace('%main_image%', $badge->get_image($level), $row); + $badge = mycred_get_badge( $badge_id ); + $level = $badge->get_users_current_level( $user_id ); + $row = str_replace( '%main_image%', $badge->get_image( $level ), $row ); } else { - $row = str_replace('%main_image%', '', $row); + $row = str_replace( '%main_image%', '', $row ); } - $output .= apply_filters('mycred_badges_badge', $row, $badge); + $output .= apply_filters( 'mycred_badges_badge', $row, $badge ); } @@ -217,30 +205,25 @@ function mycred_render_badges( $atts, $template = '' ) $output .= '
    '; - return apply_filters('mycred_badges', $output); + return apply_filters( 'mycred_badges', $output ); } endif; /** * myCRED Renders Badges List ShortCode - * - * @param string $atts - * @since 2.1 + * @param string $atts + * @since 2.1 * @version 1.0 */ -if(!function_exists('mycred_render_badges_list') ) : - function mycred_render_badges_list( $atts = '' ) - { +if( !function_exists( 'mycred_render_badges_list' ) ) : + function mycred_render_badges_list( $atts = '' ) { - extract( - shortcode_atts( - array( + extract( shortcode_atts( array( 'achievement_tabs' => '1' - ), - $atts, MYCRED_SLUG . '_badges_list' - ) - ); + ), + $atts, MYCRED_SLUG . '_badges_list' + ) ); ob_start();?> @@ -255,32 +238,32 @@ function mycred_render_badges_list( $atts = '' )
    0 ) { ?> + if ( $badges['category_count'] > 0 ) { ?>
      $element ) { + foreach ( $badges['tabs'] as $id => $element ) { - echo wp_kses_post( $element ); + echo wp_kses_post( $element ); - } + } ?>
    $element ) { + foreach ( $badges['panels'] as $id => $element ) { - echo wp_kses_post( $element ); + echo wp_kses_post( $element ); - } + } ?>
    - Evidence not found
    '; - if (isset($_GET['uid']) && isset($_GET['bid']) ) { + if ( isset( $_GET['uid'] ) && isset( $_GET['bid'] ) ) { - $user_id = intval($_GET['uid']); - $badge_id = intval($_GET['bid']); + $user_id = intval( $_GET['uid'] ); + $badge_id = intval( $_GET['bid'] ); - $user_info = get_userdata($user_id); - $badge = mycred_get_badge($badge_id); + $user_info = get_userdata( $user_id ); + $badge = mycred_get_badge( $badge_id ); - if ($user_info && $badge && $badge->open_badge ) { + if ( $user_info && $badge && $badge->open_badge ) { - $issued_on = mycred_get_user_meta($user_id, MYCRED_BADGE_KEY . $badge_id, '_issued_on', true); + $issued_on = mycred_get_user_meta( $user_id, MYCRED_BADGE_KEY . $badge_id, '_issued_on', true ); $content = '
    - +

    ' . $badge->title . '

    Name: '. $user_info->display_name .'

    Email: ' . $user_info->user_email . '

    -

    Issued On: ' . date('Y-m-d\TH:i:sP', $issued_on) . '

    +

    Issued On: ' . date( 'Y-m-d\TH:i:sP', $issued_on ) . '

    Verified

    @@ -375,9 +356,8 @@ function mycred_render_badge_evidence( $atts = '' ) } endif; -add_action('wp_enqueue_scripts', 'enqueue_badge_front_shortcode_scripts'); +add_action( 'wp_enqueue_scripts', 'enqueue_badge_front_shortcode_scripts' ); -function enqueue_badge_front_shortcode_scripts() -{ - wp_enqueue_style('mycred-badge-front-style', plugins_url('assets/css/front.css', myCRED_BADGE), array(), myCRED_BADGE_VERSION, 'all'); -} + function enqueue_badge_front_shortcode_scripts() { + wp_enqueue_style( 'mycred-badge-front-style', plugins_url( 'assets/css/front.css', myCRED_BADGE ), array(), myCRED_BADGE_VERSION , 'all'); + } \ No newline at end of file diff --git a/addons/badges/includes/mycred-open-badge.php b/addons/badges/includes/mycred-open-badge.php index 29559ef..8ac6454 100644 --- a/addons/badges/includes/mycred-open-badge.php +++ b/addons/badges/includes/mycred-open-badge.php @@ -1,318 +1,296 @@ salt = apply_filters('mycred_open_badge_salt', 'MYCREDOPENBADGE'); + $this->salt = apply_filters( 'mycred_open_badge_salt', 'MYCREDOPENBADGE' ); } - public function register_open_badge_routes() - { - - register_rest_route( - 'open-badge', '/assertion/', array( - 'methods' => 'GET', - 'callback' => array( $this, 'get_assertion_data' ), - 'permission_callback' => '__return_true', - ) - ); - - register_rest_route( - 'open-badge', '/info/', array( - 'methods' => 'GET', - 'callback' => array( $this, 'get_badge_info' ), - 'permission_callback' => '__return_true', - ) - ); - - register_rest_route( - 'open-badge', '/issuer/', array( - 'methods' => 'GET', - 'callback' => array( $this, 'get_issuer_data' ), - 'permission_callback' => '__return_true', - ) - ); - - } + public function register_open_badge_routes() { - function bake_users_image( $user_id, $badge_id ) - { + register_rest_route( 'open-badge', '/assertion/', array( + 'methods' => 'GET', + 'callback' => array( $this, 'get_assertion_data' ), + 'permission_callback' => '__return_true', + ) ); - $badge = mycred_get_badge($badge_id); + register_rest_route( 'open-badge', '/info/', array( + 'methods' => 'GET', + 'callback' => array( $this, 'get_badge_info' ), + 'permission_callback' => '__return_true', + ) ); - if (! $badge->open_badge ) { return; - } + register_rest_route( 'open-badge', '/issuer/', array( + 'methods' => 'GET', + 'callback' => array( $this, 'get_issuer_data' ), + 'permission_callback' => '__return_true', + ) ); + + } - $wp_upload_dirs = wp_upload_dir(); - $basedir = trailingslashit($wp_upload_dirs[ 'basedir' ]); - $baseurl = trailingslashit($wp_upload_dirs[ 'baseurl' ]); + function bake_users_image( $user_id, $badge_id ) { - $folderName = apply_filters('mycred_open_badge_folder', 'open_badges'); + $badge = mycred_get_badge( $badge_id ); - $user_badge_directory = $basedir . $folderName; - - if (! file_exists($user_badge_directory) && ! is_dir($user_badge_directory) ) { - mkdir($user_badge_directory); - } - - $user_badge_directory = trailingslashit($user_badge_directory); - - $badge_image = $badge->main_image_url; - - $badge_image_path = str_replace($baseurl, $basedir, $badge_image); + if ( ! $badge->open_badge ) return; - $user_info = get_userdata($user_id); - - $identity = 'sha256$' . hash('sha256', $user_info->user_email . $this->salt); - - $json = $this->get_image_json_data($user_id, $badge_id, $identity, $badge->title, $badge_image); + $wp_upload_dirs = wp_upload_dir(); + $basedir = trailingslashit( $wp_upload_dirs[ 'basedir' ] ); + $baseurl = trailingslashit( $wp_upload_dirs[ 'baseurl' ] ); - $filename = "badge-{$badge_id}-{$user_id}.png"; + $folderName = apply_filters( 'mycred_open_badge_folder', 'open_badges' ); - $this->bake_image($badge_image, $badge_image_path, $json, $filename, $user_badge_directory); + $user_badge_directory = $basedir . $folderName; + + if ( ! file_exists( $user_badge_directory ) && ! is_dir( $user_badge_directory ) ) { + mkdir( $user_badge_directory ); + } + + $user_badge_directory = trailingslashit( $user_badge_directory ); - $user_image_url = trailingslashit($baseurl . $folderName).$user_id; + $badge_image = $badge->main_image_url; + + $badge_image_path = str_replace( $baseurl, $basedir, $badge_image ); - $json['user_image'] = trailingslashit($user_image_url) . $filename; + $user_info = get_userdata( $user_id ); + + $identity = 'sha256$' . hash( 'sha256', $user_info->user_email . $this->salt ); + + $json = $this->get_image_json_data( $user_id, $badge_id, $identity, $badge->title, $badge_image ); - mycred_update_user_meta($user_id, "open-badge-{$badge_id}-{$user_id}", '', $json); + $filename = "badge-{$badge_id}-{$user_id}.png"; - } + $this->bake_image( $badge_image, $badge_image_path, $json, $filename, $user_badge_directory ); - public function get_assertion_data() - { + $user_image_url = trailingslashit( $baseurl . $folderName ).$user_id; - $assertion_data = array(); + $json['user_image'] = trailingslashit( $user_image_url ) . $filename; - if (! empty($_GET['uid']) && ! empty($_GET['bid']) ) { - - $user_id = intval($_GET['uid']); - $badge_id = intval($_GET['bid']); + mycred_update_user_meta( $user_id, "open-badge-{$badge_id}-{$user_id}", '', $json ); - $user_info = get_userdata($user_id); - $badge = mycred_get_badge($badge_id); + } - if ($user_info && $badge ) { + public function get_assertion_data() { - mycred_set_current_account($user_id); + $assertion_data = array(); - if($badge->user_has_badge($user_id) ) { + if ( ! empty( $_GET['uid'] ) && ! empty( $_GET['bid'] ) ) { + + $user_id = intval( $_GET['uid'] ); + $badge_id = intval( $_GET['bid'] ); - $identity_id = 'sha256$' . hash('sha256', $user_info->user_email . $this->salt); - - $issuedOn = mycred_get_user_meta($user_id, MYCRED_BADGE_KEY . $badge_id, '_issued_on', true); - - $assertion_data = array( - '@context' => 'https://w3id.org/openbadges/v2', - 'type' => 'Assertion', - 'id' => $this->get_assertion_url($user_id, $badge_id), - 'recipient' => array( - 'type' => 'email', - 'hashed' => true, - 'salt' => $this->salt, - 'identity' => $identity_id - ), - 'badge' => $this->get_badge_info_url($badge_id), - 'issuedOn' => date('Y-m-d\TH:i:sP', $issuedOn), - 'image' => $badge->main_image_url, - 'verification' => array( - 'type' => 'HostedBadge', - 'verificationProperty' => 'id', - ), - 'evidence' => $this->get_evidence_url($user_id, $badge_id) - ); + $user_info = get_userdata( $user_id ); + $badge = mycred_get_badge( $badge_id ); - } + if ( $user_info && $badge ) { - } + mycred_set_current_account( $user_id ); - } + if( $badge->user_has_badge( $user_id ) ) { - return wp_send_json($assertion_data); + $identity_id = 'sha256$' . hash( 'sha256', $user_info->user_email . $this->salt ); + + $issuedOn = mycred_get_user_meta( $user_id, MYCRED_BADGE_KEY . $badge_id, '_issued_on', true ); + + $assertion_data = array( + '@context' => 'https://w3id.org/openbadges/v2', + 'type' => 'Assertion', + 'id' => $this->get_assertion_url( $user_id, $badge_id ), + 'recipient' => array( + 'type' => 'email', + 'hashed' => true, + 'salt' => $this->salt, + 'identity' => $identity_id + ), + 'badge' => $this->get_badge_info_url( $badge_id ), + 'issuedOn' => date( 'Y-m-d\TH:i:sP', $issuedOn ), + 'image' => $badge->main_image_url, + 'verification' => array( + 'type' => 'HostedBadge', + 'verificationProperty' => 'id', + ), + 'evidence' => $this->get_evidence_url( $user_id, $badge_id ) + ); + + } + + } + + } + + return wp_send_json( $assertion_data ); + + } + + public function get_badge_info() { + + $badge_info = array(); + + if ( ! empty( $_GET['bid'] ) ) { - } + $badge_id = intval( $_GET['bid'] ); - public function get_badge_info() - { + $badge = mycred_get_badge( $badge_id ); + + if( $badge ) { + + $badge_info = array( + '@context' => 'https://w3id.org/openbadges/v2', + 'type' => 'BadgeClass', + 'id' => $this->get_badge_info_url( $badge_id ), + 'name' => $badge->title, + 'image' => $badge->main_image_url, + 'description' => '', + 'criteria' => mycred_get_permalink( $badge_id ), + 'issuer' => $this->get_endpoint_url( 'issuer' ), + 'tags' => array() + ); + + } - $badge_info = array(); + } - if (! empty($_GET['bid']) ) { + return wp_send_json( $badge_info ); + + } - $badge_id = intval($_GET['bid']); + public function get_issuer_data() { - $badge = mycred_get_badge($badge_id); + $blog_title = get_bloginfo( 'name' ); + $admin_email = get_bloginfo( 'admin_email' ); + $blog_url = get_site_url(); - if($badge ) { + $issuer_data = array( + '@context' => 'https://w3id.org/openbadges/v2', + 'type' => 'Issuer', + 'id' => $this->get_endpoint_url( 'issuer' ), + 'name' => $blog_title, + 'url' => $blog_url, + 'email' => $admin_email + ); - $badge_info = array( - '@context' => 'https://w3id.org/openbadges/v2', - 'type' => 'BadgeClass', - 'id' => $this->get_badge_info_url($badge_id), - 'name' => $badge->title, - 'image' => $badge->main_image_url, - 'description' => '', - 'criteria' => mycred_get_permalink($badge_id), - 'issuer' => $this->get_endpoint_url('issuer'), - 'tags' => array() - ); + return wp_send_json( $issuer_data ); - } + } - } + public function get_image_json_data( $user_id, $badge_id, $identity, $badge_title, $badge_image ) { - return wp_send_json($badge_info); - - } + return array( + '@context' => 'https://w3id.org/openbadges/v2', + 'type' => 'Assertion', + 'id' => $this->get_assertion_url( $user_id, $badge_id ), + 'recipient' => array( + 'type' => 'email', + 'hashed' => true, + 'salt' => $this->salt, + 'identity' => $identity + ), + 'badge' => array( + '@context' => 'https://w3id.org/openbadges/v2', + 'type' => 'BadgeClass', + 'id' => $this->get_badge_info_url( $badge_id ), + 'name' => $badge_title, + 'image' => $badge_image, + 'description' => '', + 'criteria' => mycred_get_permalink( $badge_id ), + 'issuer' => $this->get_endpoint_url( 'issuer' ), + 'tags' => [], + ), + 'issuedOn' => date('Y-m-d\TH:i:sP'), + 'image' => $badge_image, + 'verification' => array( + 'type' => 'HostedBadge', + 'verificationProperty' => 'id', + ), + 'evidence' => $this->get_evidence_url( $user_id, $badge_id ) + ); - public function get_issuer_data() - { + } - $blog_title = get_bloginfo('name'); - $admin_email = get_bloginfo('admin_email'); - $blog_url = get_site_url(); + public function bake_image( $badge_image, $badge_image_path, $json, $filename, $user_badge_directory ) { - $issuer_data = array( - '@context' => 'https://w3id.org/openbadges/v2', - 'type' => 'Issuer', - 'id' => $this->get_endpoint_url('issuer'), - 'name' => $blog_title, - 'url' => $blog_url, - 'email' => $admin_email - ); + $png = file_get_contents( $badge_image ); + + if( $png == false ) { + $png = file_get_contents( $badge_image_path, true ); + } - return wp_send_json($issuer_data); + $embed = [ + 'openbadges', + '', + '', + '', + '', + ( string ) json_encode( $json ), + ]; - } + // Glue with null-bytes. + $data = implode( "\0", $embed ); - public function get_image_json_data( $user_id, $badge_id, $identity, $badge_title, $badge_image ) - { - - return array( - '@context' => 'https://w3id.org/openbadges/v2', - 'type' => 'Assertion', - 'id' => $this->get_assertion_url($user_id, $badge_id), - 'recipient' => array( - 'type' => 'email', - 'hashed' => true, - 'salt' => $this->salt, - 'identity' => $identity - ), - 'badge' => array( - '@context' => 'https://w3id.org/openbadges/v2', - 'type' => 'BadgeClass', - 'id' => $this->get_badge_info_url($badge_id), - 'name' => $badge_title, - 'image' => $badge_image, - 'description' => '', - 'criteria' => mycred_get_permalink($badge_id), - 'issuer' => $this->get_endpoint_url('issuer'), - 'tags' => [], - ), - 'issuedOn' => date('Y-m-d\TH:i:sP'), - 'image' => $badge_image, - 'verification' => array( - 'type' => 'HostedBadge', - 'verificationProperty' => 'id', - ), - 'evidence' => $this->get_evidence_url($user_id, $badge_id) - ); + // Make the CRC. + $crc = pack( "N", crc32( 'iTXt' . $data ) ); - } + // Put it all together. + $final = pack( "N", strlen( $data ) ) . 'iTXt' . $data . $crc; - public function bake_image( $badge_image, $badge_image_path, $json, $filename, $user_badge_directory ) - { + // What's the length? + $length = strlen( $png ); - $png = file_get_contents($badge_image); - - if($png == false ) { - $png = file_get_contents($badge_image_path, true); - } - - $embed = [ - 'openbadges', - '', - '', - '', - '', - ( string ) json_encode($json), - ]; - - // Glue with null-bytes. - $data = implode("\0", $embed); - - // Make the CRC. - $crc = pack("N", crc32('iTXt' . $data)); - - // Put it all together. - $final = pack("N", strlen($data)) . 'iTXt' . $data . $crc; - - // What's the length? - $length = strlen($png); - - // Put this all at the end, before IEND. - // We _should_ be removing all other iTXt blobs with keyword openbadges - // before writing this out. - $png = substr($png, 0, $length - 12) . $final . substr($png, $length - 12, 12); - - file_put_contents($user_badge_directory . '/' . $filename, $png); + // Put this all at the end, before IEND. + // We _should_ be removing all other iTXt blobs with keyword openbadges + // before writing this out. + $png = substr( $png, 0, $length - 12 ) . $final . substr( $png, $length - 12, 12 ); + + file_put_contents( $user_badge_directory . '/' . $filename, $png ); - } + } - public function get_endpoint_url( $endpoint ) - { + public function get_endpoint_url( $endpoint ) { - return get_site_url() . '/wp-json/open-badge/' . $endpoint; + return get_site_url() . '/wp-json/open-badge/' . $endpoint; - } + } - public function get_assertion_url( $user_id, $badge_id ) - { + public function get_assertion_url( $user_id, $badge_id ) { - $assertion_url = add_query_arg('uid', $user_id, $this->get_endpoint_url('assertion')); - $assertion_url = add_query_arg('bid', $badge_id, $assertion_url); + $assertion_url = add_query_arg( 'uid', $user_id, $this->get_endpoint_url( 'assertion' ) ); + $assertion_url = add_query_arg( 'bid', $badge_id, $assertion_url ); - return $assertion_url; - } + return $assertion_url; + } - public function get_badge_info_url( $badge_id ) - { + public function get_badge_info_url( $badge_id ) { - $badge_info_url = add_query_arg('bid', $badge_id, $this->get_endpoint_url('info')); + $badge_info_url = add_query_arg( 'bid', $badge_id, $this->get_endpoint_url( 'info' ) ); - return $badge_info_url; + return $badge_info_url; - } + } - public function get_evidence_url( $user_id, $badge_id ) - { + public function get_evidence_url( $user_id, $badge_id ) { - $evidence_page_id = mycred_get_evidence_page_id(); + $evidence_page_id = mycred_get_evidence_page_id(); - $evidence_url = add_query_arg('uid', $user_id, mycred_get_permalink($evidence_page_id)); - $evidence_url = add_query_arg('bid', $badge_id, $evidence_url); + $evidence_url = add_query_arg( 'uid', $user_id, mycred_get_permalink( $evidence_page_id ) ); + $evidence_url = add_query_arg( 'bid', $badge_id, $evidence_url ); - return $evidence_url; + return $evidence_url; - } + } - } -endif; + } +endif; \ No newline at end of file diff --git a/addons/badges/index.php b/addons/badges/index.php index 1580272..4e6c07c 100644 --- a/addons/badges/index.php +++ b/addons/badges/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/badges/myCRED-addon-badges.php b/addons/badges/myCRED-addon-badges.php index ce482a1..86e791e 100644 --- a/addons/badges/myCRED-addon-badges.php +++ b/addons/badges/myCRED-addon-badges.php @@ -502,7 +502,7 @@ public function parent_file( $parent = '' ) { } - elseif ( $pagenow == 'post.php' && isset( $_GET['post'] ) && mycred_get_post_type( sanitize_key( $_GET['post'] ) ) == MYCRED_BADGE_KEY ) { + elseif ( $pagenow == 'post.php' && isset( $_GET['post'] ) && mycred_get_post_type( $_GET['post'] ) == MYCRED_BADGE_KEY ) { return MYCRED_MAIN_SLUG; @@ -534,7 +534,7 @@ public function subparent_file( $subparent = '', $parent = '' ) { } - elseif ( $pagenow == 'post.php' && isset( $_GET['post'] ) && mycred_get_post_type( sanitize_key( $_GET['post'] ) ) == MYCRED_BADGE_KEY ) { + elseif ( $pagenow == 'post.php' && isset( $_GET['post'] ) && mycred_get_post_type( $_GET['post'] ) == MYCRED_BADGE_KEY ) { return 'edit.php?post_type=' . MYCRED_BADGE_KEY; @@ -624,7 +624,7 @@ public function adjust_column_content( $column_name, $badge_id ) { echo '-'; elseif ( $badge->main_image !== false ) - echo wp_kses_post($badge->main_image); + echo wp_kses_post( $badge->main_image ); } @@ -636,7 +636,7 @@ public function adjust_column_content( $column_name, $badge_id ) { if ( $badge->open_badge || $image === false ) echo '-'; else - echo wp_kses_post($image); + echo wp_kses_post( $image ); } @@ -664,7 +664,7 @@ public function adjust_column_content( $column_name, $badge_id ) { $badge = mycred_get_badge_type( $badge_id ); - echo esc_html( $badge == false ? 'No Acheivement Type' : $badge ); + echo $badge == false ? 'No Acheivement Type' : esc_html( $badge ); } @@ -947,7 +947,7 @@ public function publishing_actions() { data : { action : button.attr( 'data-action' ), token : button.attr( 'data-token' ), - badge_id : ID ); ?> + badge_id : ID ); ?> }, dataType : "JSON", url : ajaxurl, @@ -970,7 +970,7 @@ public function publishing_actions() {
    - +
    - +
    @@ -1041,9 +1041,9 @@ public function metabox_open_badge( $post ) { ?>
    - +
    - + - + ' . esc_js( __( 'Add Level', 'mycred' ) ) . ''; - $remove_level = ''; + $remove_level = ''; $level_image = $this->get_level_image( $setup, $level ); $empty_level = 'empty dashicons'; @@ -1275,7 +1275,7 @@ public function metabox_badge_setup( $post ) { $js_level = str_replace( '{{rewards}}', $rewards, $js_level ); - echo $template; + echo $template; $level_counter++; @@ -1474,31 +1474,31 @@ public function after_general_settings( $mycred = NULL ) { $bbpress = ( ( class_exists( 'bbPress' ) ) ? true : false ); ?> -

    +

  • >
  • >
  • >
  • >
  • >
  • diff --git a/addons/badges/templates/mycred-metabox-badge-layout.php b/addons/badges/templates/mycred-metabox-badge-layout.php index ffa2de2..374b0ef 100644 --- a/addons/badges/templates/mycred-metabox-badge-layout.php +++ b/addons/badges/templates/mycred-metabox-badge-layout.php @@ -7,31 +7,31 @@
  • >
  • >
  • >
  • >
  • >
  • diff --git a/addons/banking/abstracts/index.php b/addons/banking/abstracts/index.php index 1580272..4e6c07c 100644 --- a/addons/banking/abstracts/index.php +++ b/addons/banking/abstracts/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/banking/abstracts/mycred-abstract-service.php b/addons/banking/abstracts/mycred-abstract-service.php index 460831e..dc700e7 100644 --- a/addons/banking/abstracts/mycred-abstract-service.php +++ b/addons/banking/abstracts/mycred-abstract-service.php @@ -1,434 +1,373 @@ $value ) { - $this->$key = $value; - } - } - - // Grab myCRED Settings - $this->core = mycred($type); - $this->mycred_type = $type; - - if ($this->mycred_type != MYCRED_DEFAULT_TYPE_KEY ) { - $this->is_main_type = false; - } - - // Prep settings - if (! empty($this->defaults) ) { - $this->prefs = $this->defaults; - } - - if ($service_prefs !== null && array_key_exists($this->id, $service_prefs) ) { - $this->prefs = $service_prefs[ $this->id ]; - } - - $this->prefs = wp_parse_args($this->prefs, $this->defaults); - $this->now = current_time('timestamp', 1); - - } - - /** - * Run - * Must be over-ridden by sub-class! - * - * @since 1.2 - * @version 1.0 - */ - public function run() - { - wp_die('function myCRED_Service::run() must be over-ridden in a sub-class.'); - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.0 - */ - public function preferences() - { - } - - /** - * Sanitise Preference - * - * @since 1.2 - * @version 1.0 - */ - public function sanitise_preferences( $post ) - { - - return $post; - - } - - /** - * Activate - * - * @since 1.5.2 - * @version 1.0 - */ - public function activate() - { - } - - /** - * Deactivate - * - * @since 1.2 - * @version 1.0 - */ - public function deactivate() - { - } - - /** - * Ajax Handler - * - * @since 1.7 - * @version 1.0 - */ - public function ajax_handler() - { - } - - /** - * User Screen - * - * @since 1.7 - * @version 1.0 - */ - public function user_screen( $user ) - { - } - - /** - * Get Field Name - * Returns the field name for the current service - * - * @since 1.2 - * @version 1.1 - */ - public function field_name( $field = '' ) - { - - if (is_array($field) ) { - $array = array(); - foreach ( $field as $parent => $child ) { - if (! is_numeric($parent) ) { - $array[] = $parent; - } - - if (! empty($child) && !is_array($child) ) { - $array[] = $child; - } - } - $field = '[' . implode('][', $array) . ']'; - } - else { - $field = '[' . $field . ']'; - } - - $option_id = 'mycred_pref_bank'; - if (! $this->is_main_type ) { - $option_id = $option_id . '_' . $this->mycred_type; - } - - return $option_id . '[service_prefs][' . $this->id . ']' . $field; - - } - - /** - * Get Field ID - * Returns the field id for the current service - * - * @since 1.2 - * @version 1.1 - */ - public function field_id( $field = '' ) - { - - if (is_array($field) ) { - $array = array(); - foreach ( $field as $parent => $child ) { - if (! is_numeric($parent) ) { - $array[] = str_replace('_', '-', $parent); - } - - if (! empty($child) && !is_array($child) ) { - $array[] = str_replace('_', '-', $child); - } - } - $field = implode('-', $array); - } - else { - $field = str_replace('_', '-', $field); - } - - $option_id = 'mycred_pref_bank'; - if (! $this->is_main_type ) { - $option_id = $option_id . '_' . $this->mycred_type; - } - - $option_id = str_replace('_', '-', $option_id); - return $option_id . '-' . str_replace('_', '-', $this->id) . '-' . $field; - - } - - /** - * Get Days in Year - * - * @since 1.2 - * @version 1.0.2 - */ - public function get_days_in_year() - { - - if (date('L') ) { - $days = 366; - } else { - $days = 365; - } - - return apply_filters('mycred_banking_days_in_year', $days, $this); - - } - - /** - * Is Large Site? - * - * @since 1.7 - * @version 1.0.1 - */ - public function is_large_site() - { - - $is_large = false; - if (is_multisite() && wp_is_large_network() ) { - $is_large = true; - - } else { - - $users = count_users(); - if ($users['total_users'] > 3000 ) { - $is_large = true; - - } else { - - global $wpdb, $mycred_log_table; - - $total = $wpdb->get_var("SELECT COUNT(*) FROM {$mycred_log_table};"); - if ($total !== null && $total > 100000 ) { - $is_large = true; - } - - } - - } - - return $is_large; - - } - - /** - * Get Excluded User IDs - * - * @since 1.7 - * @version 1.0 - */ - public function get_excluded_user_ids() - { - - global $wpdb; - - $exclude_ids = array(); - - if (strlen($this->prefs['exclude_ids']) > 0 ) { - - foreach ( explode(',', $this->prefs['exclude_ids']) as $user_id ) { - $user_id = absint(preg_replace("/[^0-9]/", "", $user_id)); - if ($user_id === 0 ) { continue; - } - $exclude_ids[] = $user_id; - } - - } - - if (! empty($this->prefs['exclude_roles']) ) { - - $args = array(); - $args['role__in'] = $this->prefs['exclude_roles']; - $args['fields'] = 'ID'; - $user_query = new WP_User_Query($args); - $user_ids = $user_query->get_results(); - - if (! empty($user_ids) ) { - foreach ( $user_ids as $user_id ) { - if (in_array($user_id, $exclude_ids) ) { continue; - } - $exclude_ids[] = absint($user_id); - } - } +if ( ! class_exists( 'myCRED_Service' ) ) : + abstract class myCRED_Service { + + // Service ID + public $id; + + // myCRED_Settings Class + public $core; + + // Multipoint types + public $is_main_type = true; + public $mycred_type = MYCRED_DEFAULT_TYPE_KEY; + + // Service Prefs + public $prefs = array(); + public $now = 0; + + /** + * Construct + */ + function __construct( $args = array(), $service_prefs = NULL, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + if ( ! empty( $args ) ) { + foreach ( $args as $key => $value ) { + $this->$key = $value; + } + } + + // Grab myCRED Settings + $this->core = mycred( $type ); + $this->mycred_type = $type; + + if ( $this->mycred_type != MYCRED_DEFAULT_TYPE_KEY ) + $this->is_main_type = false; + + // Prep settings + if ( ! empty( $this->defaults ) ) + $this->prefs = $this->defaults; + + if ( $service_prefs !== NULL && array_key_exists( $this->id, $service_prefs ) ) + $this->prefs = $service_prefs[ $this->id ]; + + $this->prefs = wp_parse_args( $this->prefs, $this->defaults ); + $this->now = current_time( 'timestamp', 1 ); + + } + + /** + * Run + * Must be over-ridden by sub-class! + * @since 1.2 + * @version 1.0 + */ + public function run() { + wp_die( 'function myCRED_Service::run() must be over-ridden in a sub-class.' ); + } + + /** + * Preferences + * @since 0.1 + * @version 1.0 + */ + public function preferences() { } + + /** + * Sanitise Preference + * @since 1.2 + * @version 1.0 + */ + public function sanitise_preferences( $post ) { + + return $post; + + } + + /** + * Activate + * @since 1.5.2 + * @version 1.0 + */ + public function activate() { } + + /** + * Deactivate + * @since 1.2 + * @version 1.0 + */ + public function deactivate() { } + + /** + * Ajax Handler + * @since 1.7 + * @version 1.0 + */ + public function ajax_handler() { } + + /** + * User Screen + * @since 1.7 + * @version 1.0 + */ + public function user_screen( $user ) { } + + /** + * Get Field Name + * Returns the field name for the current service + * @since 1.2 + * @version 1.1 + */ + public function field_name( $field = '' ) { + + if ( is_array( $field ) ) { + $array = array(); + foreach ( $field as $parent => $child ) { + if ( ! is_numeric( $parent ) ) + $array[] = $parent; + + if ( ! empty( $child ) && !is_array( $child ) ) + $array[] = $child; + } + $field = '[' . implode( '][', $array ) . ']'; + } + else { + $field = '[' . $field . ']'; + } + + $option_id = 'mycred_pref_bank'; + if ( ! $this->is_main_type ) + $option_id = $option_id . '_' . $this->mycred_type; + + return $option_id . '[service_prefs][' . $this->id . ']' . $field; + + } + + /** + * Get Field ID + * Returns the field id for the current service + * @since 1.2 + * @version 1.1 + */ + public function field_id( $field = '' ) { + + if ( is_array( $field ) ) { + $array = array(); + foreach ( $field as $parent => $child ) { + if ( ! is_numeric( $parent ) ) + $array[] = str_replace( '_', '-', $parent ); + + if ( ! empty( $child ) && !is_array( $child ) ) + $array[] = str_replace( '_', '-', $child ); + } + $field = implode( '-', $array ); + } + else { + $field = str_replace( '_', '-', $field ); + } + + $option_id = 'mycred_pref_bank'; + if ( ! $this->is_main_type ) + $option_id = $option_id . '_' . $this->mycred_type; + + $option_id = str_replace( '_', '-', $option_id ); + return $option_id . '-' . str_replace( '_', '-', $this->id ) . '-' . $field; + + } + + /** + * Get Days in Year + * @since 1.2 + * @version 1.0.2 + */ + public function get_days_in_year() { + + if ( date( 'L' ) ) + $days = 366; + else + $days = 365; + + return apply_filters( 'mycred_banking_days_in_year', $days, $this ); + + } + + /** + * Is Large Site? + * @since 1.7 + * @version 1.0.1 + */ + public function is_large_site() { + + $is_large = false; + if ( is_multisite() && wp_is_large_network() ) + $is_large = true; - } + else { - if ($this->core->exclude['list'] != '' ) { - - foreach ( explode(',', $this->core->exclude['list']) as $user_id ) { - $user_id = absint(preg_replace("/[^0-9]/", "", $user_id)); - if ($user_id === 0 || in_array($user_id, $exclude_ids) ) { continue; - } - $exclude_ids[] = $user_id; - } - - } - - if ($this->prefs['min_balance'] != '' && $this->core->number($this->prefs['min_balance']) > $this->core->zero() ) { - - $format = '%d'; - if ($this->core->format['decimals'] > 0 ) { - $format = '%f'; - } - - $user_ids = $wpdb->get_col($wpdb->prepare("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value < {$format};", $this->mycred_type, $this->prefs['min_balance'])); - if (! empty($user_ids) ) { - foreach ( $user_ids as $user_id ) { - if (in_array($user_id, $exclude_ids) ) { continue; - } - $exclude_ids[] = absint($user_id); - } - } - - } - - return $exclude_ids; + $users = count_users(); + if ( $users['total_users'] > 3000 ) + $is_large = true; - } - - /** - * Convert Date to GMT Timestamp - * - * @since 1.7 - * @version 1.0 - */ - public function date_to_timestamp( $string = '' ) - { - - return mycred_date_to_gmt_timestamp($string); - - } - - /** - * Convert GMT Timestamp to Date - * - * @since 1.7 - * @version 1.0 - */ - public function timestamp_to_date( $string = '' ) - { - - return mycred_gmt_timestamp_to_local($string); - - } - - /** - * Time Select - * - * @since 1.7 - * @version 1.0 - */ - public function time_select( $name = '', $id = '', $date = null ) - { - - $date = ( ( $date !== false && strlen($date) > 0 ) ? date('H:i', $date) : '' ); - $options = mycred_banking_get_time_options(); - - $element = ''; - - return $element; - - } - - /** - * Timeframe Dropdown - * - * @since 1.2 - * @version 1.0 - */ - public function timeframe_dropdown( $pref_id = '', $use_select = true, $hourly = true ) - { - - $timeframes = mycred_banking_get_timeframes(); - if (! $hourly ) { - unset($timeframes['hourly']); - } - - echo ''; - - } - - } + else { + + global $wpdb, $mycred_log_table; + + $total = $wpdb->get_var( "SELECT COUNT(*) FROM {$mycred_log_table};" ); + if ( $total !== NULL && $total > 100000 ) + $is_large = true; + + } + + } + + return $is_large; + + } + + /** + * Get Excluded User IDs + * @since 1.7 + * @version 1.0 + */ + public function get_excluded_user_ids() { + + global $wpdb; + + $exclude_ids = array(); + + if ( strlen( $this->prefs['exclude_ids'] ) > 0 ) { + + foreach ( explode( ',', $this->prefs['exclude_ids'] ) as $user_id ) { + $user_id = absint( preg_replace( "/[^0-9]/", "", $user_id ) ); + if ( $user_id === 0 ) continue; + $exclude_ids[] = $user_id; + } + + } + + if ( ! empty( $this->prefs['exclude_roles'] ) ) { + + $args = array(); + $args['role__in'] = $this->prefs['exclude_roles']; + $args['fields'] = 'ID'; + $user_query = new WP_User_Query( $args ); + $user_ids = $user_query->get_results(); + + if ( ! empty( $user_ids ) ) { + foreach ( $user_ids as $user_id ) { + if ( in_array( $user_id, $exclude_ids ) ) continue; + $exclude_ids[] = absint( $user_id ); + } + } + + } + + if ( $this->core->exclude['list'] != '' ) { + + foreach ( explode( ',', $this->core->exclude['list'] ) as $user_id ) { + $user_id = absint( preg_replace( "/[^0-9]/", "", $user_id ) ); + if ( $user_id === 0 || in_array( $user_id, $exclude_ids ) ) continue; + $exclude_ids[] = $user_id; + } + + } + + if ( $this->prefs['min_balance'] != '' && $this->core->number( $this->prefs['min_balance'] ) > $this->core->zero() ) { + + $format = '%d'; + if ( $this->core->format['decimals'] > 0 ) + $format = '%f'; + + $user_ids = $wpdb->get_col( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value < {$format};", $this->mycred_type, $this->prefs['min_balance'] ) ); + if ( ! empty( $user_ids ) ) { + foreach ( $user_ids as $user_id ) { + if ( in_array( $user_id, $exclude_ids ) ) continue; + $exclude_ids[] = absint( $user_id ); + } + } + + } + + return $exclude_ids; + + } + + /** + * Convert Date to GMT Timestamp + * @since 1.7 + * @version 1.0 + */ + public function date_to_timestamp( $string = '' ) { + + return mycred_date_to_gmt_timestamp( $string ); + + } + + /** + * Convert GMT Timestamp to Date + * @since 1.7 + * @version 1.0 + */ + public function timestamp_to_date( $string = '' ) { + + return mycred_gmt_timestamp_to_local( $string ); + + } + + /** + * Time Select + * @since 1.7 + * @version 1.0 + */ + public function time_select( $name = '', $id = '', $date = NULL ) { + + $date = ( ( $date !== false && strlen( $date ) > 0 ) ? date( 'H:i', $date ) : '' ); + $options = mycred_banking_get_time_options(); + + $element = ''; + + return $element; + + } + + /** + * Timeframe Dropdown + * @since 1.2 + * @version 1.0 + */ + public function timeframe_dropdown( $pref_id = '', $use_select = true, $hourly = true ) { + + $timeframes = mycred_banking_get_timeframes(); + if ( ! $hourly ) + unset( $timeframes['hourly'] ); + + echo ''; + + } + + } endif; diff --git a/addons/banking/assets/index.php b/addons/banking/assets/index.php index 1580272..4e6c07c 100644 --- a/addons/banking/assets/index.php +++ b/addons/banking/assets/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/banking/assets/js/index.php b/addons/banking/assets/js/index.php index 1580272..4e6c07c 100644 --- a/addons/banking/assets/js/index.php +++ b/addons/banking/assets/js/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/banking/includes/index.php b/addons/banking/includes/index.php index 1580272..4e6c07c 100644 --- a/addons/banking/includes/index.php +++ b/addons/banking/includes/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/banking/includes/mycred-banking-functions.php b/addons/banking/includes/mycred-banking-functions.php index 61b8bd1..14b55e8 100644 --- a/addons/banking/includes/mycred-banking-functions.php +++ b/addons/banking/includes/mycred-banking-functions.php @@ -1,37 +1,32 @@ array(), - 'services' => array(), - 'service_prefs' => array() - ); + $default = array( + 'active' => array(), + 'services' => array(), + 'service_prefs' => array() + ); - $option_id = 'mycred_pref_bank'; - if ($point_type != MYCRED_DEFAULT_TYPE_KEY ) { - $option_id .= '_' . $point_type; - } + $option_id = 'mycred_pref_bank'; + if ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) + $option_id .= '_' . $point_type; - $settings = mycred_get_option($option_id, $default); - $settings = wp_parse_args($settings, $default); + $settings = mycred_get_option( $option_id, $default ); + $settings = wp_parse_args( $settings, $default ); - if ($service !== null && array_key_exists($service, $settings['service_prefs']) ) { - $settings = $settings['service_prefs'][ $service ]; - } + if ( $service !== NULL && array_key_exists( $service, $settings['service_prefs'] ) ) + $settings = $settings['service_prefs'][ $service ]; - return $settings; + return $settings; - } + } endif; diff --git a/addons/banking/index.php b/addons/banking/index.php index 1580272..4e6c07c 100644 --- a/addons/banking/index.php +++ b/addons/banking/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/banking/myCRED-addon-banking.php b/addons/banking/myCRED-addon-banking.php index b75b3cb..b05f74f 100644 --- a/addons/banking/myCRED-addon-banking.php +++ b/addons/banking/myCRED-addon-banking.php @@ -206,7 +206,7 @@ public function admin_page() { update_notice(); ?> -

    +

    settings_name ); ?> @@ -220,13 +220,13 @@ public function admin_page() { foreach ( $installed as $key => $data ) { ?> -

    core->template_tags_general( $data['title'] ); ?>

    +

    core->template_tags_general( $data['title'] ) ); ?>

    - +
    @@ -335,13 +335,13 @@ public function banking_user_screen( $user ) { public function ajax_handler() { // Make sure this is an ajax call for this point type - if ( isset( $_REQUEST['_token'] ) && wp_verify_nonce( $_REQUEST['_token'], 'run-mycred-bank-task' . $this->mycred_type ) ) { + if ( isset( $_REQUEST['_token'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['_token'] ) ), 'run-mycred-bank-task' . $this->mycred_type ) ) { // Make sure ajax call is made by an admin if ( $this->core->user_is_point_admin() ) { // Get the service requesting to use this - $service = sanitize_key( $_POST['service'] ); + $service = ( isset( $_POST['service'] ) ? sanitize_key( wp_unslash( $_POST['service'] ) ) : '' ); $installed = $this->get(); // If there is such a service, load it's ajax handler diff --git a/addons/banking/services/index.php b/addons/banking/services/index.php index 1580272..4e6c07c 100644 --- a/addons/banking/services/index.php +++ b/addons/banking/services/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/banking/services/mycred-service-central.php b/addons/banking/services/mycred-service-central.php index 29c1b42..2c86dce 100644 --- a/addons/banking/services/mycred-service-central.php +++ b/addons/banking/services/mycred-service-central.php @@ -1,213 +1,189 @@ 'central', - 'defaults' => array( - 'bank_id' => '', - 'ignore_manual' => 1 - ) - ), $service_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.5.2 - * @version 1.0 - */ - public function run() - { - - add_filter('mycred_add', array( $this, 'mycred_add' ), 1, 3); - add_action('wp_ajax_get_bank_accounts', array( $this, 'get_bank_accounts' )); - - } - - /** - * Add - * - * @since 1.5.2 - * @version 1.0.1 - */ - public function mycred_add( $reply, $request, $mycred ) - { - - // Make sure we are in the correct point type - if ($this->mycred_type != $mycred->cred_id || $reply === false ) { return $reply; - } - - // Check manual - if (isset($this->prefs['ignore_manual']) && $this->prefs['ignore_manual'] == 0 && $request['ref'] == 'manual' ) { return $reply; - } - - // Instances to ignore - if (in_array($request['ref'], apply_filters('mycred_central_banking_ignore', array( 'interest', 'recurring_payout', 'transfer' ), $this)) ) { return $reply; - } - - extract($request); - - // Make sure that the request is not for our bank account - //if ( $user_id == $this->prefs['bank_id'] ) return $reply; - - // Get the banks balance - $bank_balance = $mycred->get_users_balance($this->prefs['bank_id'], $this->mycred_type); - - // User is to lose points - if ($amount < 0 ) { +if ( ! class_exists( 'myCRED_Banking_Service_Central' ) ) : + class myCRED_Banking_Service_Central extends myCRED_Service { + + /** + * Construct + */ + function __construct( $service_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'central', + 'defaults' => array( + 'bank_id' => '', + 'ignore_manual' => 1 + ) + ), $service_prefs, $type ); + + } + + /** + * Run + * @since 1.5.2 + * @version 1.0 + */ + public function run() { + + add_filter( 'mycred_add', array( $this, 'mycred_add' ), 1, 3 ); + add_action( 'wp_ajax_get_bank_accounts', array( $this, 'get_bank_accounts' ) ); + + } + + /** + * Add + * @since 1.5.2 + * @version 1.0.1 + */ + public function mycred_add( $reply, $request, $mycred ) { + + // Make sure we are in the correct point type + if ( $this->mycred_type != $mycred->cred_id || $reply === false ) return $reply; + + // Check manual + if ( isset( $this->prefs['ignore_manual'] ) && $this->prefs['ignore_manual'] == 0 && $request['ref'] == 'manual' ) return $reply; + + // Instances to ignore + if ( in_array( $request['ref'], apply_filters( 'mycred_central_banking_ignore', array( 'interest', 'recurring_payout', 'transfer' ), $this ) ) ) return $reply; + + extract( $request ); + + // Make sure that the request is not for our bank account + //if ( $user_id == $this->prefs['bank_id'] ) return $reply; + + // Get the banks balance + $bank_balance = $mycred->get_users_balance( $this->prefs['bank_id'], $this->mycred_type ); + + // User is to lose points + if ( $amount < 0 ) { - // Add the points getting deducted to our bank account - $mycred->update_users_balance($this->prefs['bank_id'], abs($amount), $this->mycred_type); + // Add the points getting deducted to our bank account + $mycred->update_users_balance( $this->prefs['bank_id'], abs( $amount ), $this->mycred_type ); - // Log event - $mycred->add_to_log($ref, $this->prefs['bank_id'], abs($amount), $entry, $ref_id, $data, $this->mycred_type); + // Log event + $mycred->add_to_log( $ref, $this->prefs['bank_id'], abs( $amount ), $entry, $ref_id, $data, $this->mycred_type ); - } + } - // User is to gain points - else { + // User is to gain points + else { - // First make sure the bank is not bust - if ($bank_balance <= $mycred->zero() ) { return false; - } + // First make sure the bank is not bust + if ( $bank_balance <= $mycred->zero() ) return false; - // Second we check if the bank is solvent - if ($bank_balance-$amount < $mycred->zero() ) { return false; - } + // Second we check if the bank is solvent + if ( $bank_balance-$amount < $mycred->zero() ) return false; - // If we have come this far, the bank has sufficient funds so lets deduct - $mycred->update_users_balance($this->prefs['bank_id'], 0-$amount, $this->mycred_type); + // If we have come this far, the bank has sufficient funds so lets deduct + $mycred->update_users_balance( $this->prefs['bank_id'], 0-$amount, $this->mycred_type ); - // Log event - $mycred->add_to_log($ref, $this->prefs['bank_id'], 0-$amount, $entry, $ref_id, $data, $this->mycred_type); + // Log event + $mycred->add_to_log( $ref, $this->prefs['bank_id'], 0-$amount, $entry, $ref_id, $data, $this->mycred_type ); - } + } - // Return the result - return $reply; + // Return the result + return $reply; - } + } - /** - * Preference for Central Bank - * - * @since 1.5.2 - * @version 1.1 - */ - public function preferences() - { + /** + * Preference for Central Bank + * @since 1.5.2 + * @version 1.1 + */ + public function preferences() { - $prefs = $this->prefs; + $prefs = $this->prefs; - if (! empty($this->prefs['bank_id']) ) { - $user = get_userdata($this->prefs['bank_id']); - } - ?> + if ( ! empty( $this->prefs['bank_id'] ) ) + $user = get_userdata( $this->prefs['bank_id'] ); +?>
    -
    -
    -
    -
    - - -
    -

    -
    -
    -
    -
    - -
    -
    -
    -
    -
    +
    +
    +
    +
    + + +
    +

    +
    +
    +
    +
    + +
    +
    +
    +
    +
    - '*'. $search_term .'*', - 'search_columns' => array( - 'ID', - 'user_login', - 'user_nicename', - 'user_email', - 'display_name' - ), - 'fields' => array( 'ID', 'display_name', 'user_email' ), - 'number' => 10, - 'offset' => ( intval($page_no) - 1 ) * 10, - 'orderby' => 'display_name' - ) - ); - $users = $users_query->get_results(); - - echo json_encode(array( 'users' => $users, 'more' => ! empty($users) )); - die; - - } - - } -endif; + '*'. $search_term .'*', + 'search_columns' => array( + 'ID', + 'user_login', + 'user_nicename', + 'user_email', + 'display_name' + ), + 'fields' => array( 'ID', 'display_name', 'user_email' ), + 'number' => 10, + 'offset' => ( $page_no - 1 ) * 10, + 'orderby' => 'display_name' + ) ); + $users = $users_query->get_results(); + + echo json_encode( array( 'users' => $users, 'more' => ! empty( $users ) ) ); + die; + + } + + } +endif; \ No newline at end of file diff --git a/addons/buy-creds/abstracts/index.php b/addons/buy-creds/abstracts/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/abstracts/index.php +++ b/addons/buy-creds/abstracts/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/abstracts/mycred-abstract-payment-gateway.php b/addons/buy-creds/abstracts/mycred-abstract-payment-gateway.php index cc14c26..c48423b 100644 --- a/addons/buy-creds/abstracts/mycred-abstract-payment-gateway.php +++ b/addons/buy-creds/abstracts/mycred-abstract-payment-gateway.php @@ -1,2383 +1,2162 @@ now = current_time('timestamp'); - $this->current_user_id = get_current_user_id(); - $this->core = mycred(); - $this->buycred = mycred_get_buycred_settings(); - - // Arguments - if (! empty($args) ) { - foreach ( $args as $key => $value ) { - $this->$key = $value; - } - } - - $gateway_settings = $this->defaults; - if (is_array($gateway_prefs) && array_key_exists($this->id, $gateway_prefs) ) { - $gateway_settings = $gateway_prefs[ $this->id ]; - - } elseif (is_object($gateway_prefs) && array_key_exists($this->id, $gateway_prefs->gateway_prefs) ) { - $gateway_settings = $gateway_prefs->gateway_prefs[ $this->id ]; - } - - $this->prefs = shortcode_atts($this->defaults, $gateway_settings); - - // Sandbox Mode - $this->sandbox_mode = ( isset($this->prefs['sandbox']) ) ? (bool) $this->prefs['sandbox'] : false; - - // Decode Log Entries - add_filter('mycred_prep_template_tags', array( $this, 'decode_log_entries' ), 10, 2); - add_filter('mycred_parse_log_entry_buy_creds_with_' . $this->id, array( $this, 'log_entry' ), 10, 2); - - } - - /** - * Request Validator - * - * @since 1.8 - * @version 1.0 - */ - public function valid_request() - { - - // Step 1 - We need to be logged in to buy - if (! is_user_logged_in() ) { return false; - } - - // Step 2 - We need a valid token to start the request - if (! isset($_REQUEST['token']) || ! wp_verify_nonce($_REQUEST['token'], 'mycred-buy-creds') ) { return false; - } - - $valid = true; - - $this->point_type = $this->get_point_type(); - if ($this->point_type != MYCRED_DEFAULT_TYPE_KEY ) { - $this->core = mycred($this->point_type); - } - - $this->buycred_limit = mycred_get_buycred_sale_setup($this->point_type); - - $this->transaction_id = ( isset($_REQUEST['revisit']) ) ? strtoupper(sanitize_text_field($_REQUEST['revisit'])) : false; - $this->post_id = ( $this->transaction_id !== false ) ? buycred_get_pending_payment_id($this->transaction_id) : false; - $this->buyer_id = $this->current_user_id; - $this->recipient_id = $this->get_recipient_id(); - $this->amount = $this->get_amount(); - $this->cost = $this->get_cost($this->amount, $this->point_type); - $this->currency = ( isset($this->prefs['currency']) ) ? $this->prefs['currency'] : ''; - $this->maximum = -1; - - if ($this->core->exclude_user($this->buyer_id) ) { - $valid = false; - $this->errors[] = __('Buyer is excluded from this point type.', 'mycred'); - } - elseif ($this->core->exclude_user($this->recipient_id) ) { - $valid = false; - $this->errors[] = __('Recipient is excluded from this point type. ', 'mycred'); - } - - elseif ($this->amount === false || $this->amount == 0 ) { - $valid = false; - $this->errors[] = __('An amount value is required.', 'mycred'); - } - - elseif (! empty($this->buycred_limit['max']) && $this->amount > floatval($this->buycred_limit['max']) ) { - $valid = false; - $this->errors[] = apply_filters('buycred_max_amount_error', sprintf(__('The amount must be less than %d.', 'mycred'), $this->buycred_limit['max']), $this->buycred_limit['max'], $this); - } - - elseif ($this->exceeds_limit() ) { - $valid = false; - $this->errors[] = __('You have exceeded the limit.', 'mycred'); - } - - if ($valid ) { - $this->populate_transaction(); - } - - if (! empty($this->errors) ) { - $valid = false; - } - - return apply_filters('mycred_valid_buycred_request', $valid, $this); - - } - - /** - * Populate Transaction - * - * @since 1.8 - * @since 2.3 @filter added `mycred_buycred_populate_transaction` to avoid pending payments log in some cases. - * @version 1.0 - */ - public function populate_transaction() - { - - if(apply_filters('mycred_buycred_populate_transaction', false, $this->id) ) { - return; - } - - // Create a new transaction - $new_transaction = false; - if ($this->transaction_id === false && $this->post_id === false ) { - - $this->post_id = $this->add_pending_payment( - array( - $this->buyer_id, - $this->recipient_id, - $this->amount, - $this->cost, - $this->currency, - $this->point_type - ) - ); - - $this->transaction_id = get_the_title($this->post_id); - - } +if ( ! class_exists( 'myCRED_Payment_Gateway' ) ) : + abstract class myCRED_Payment_Gateway { + + /** + * The Gateways Unique ID + */ + public $id = false; + + /** + * Gateway Label + */ + public $label = ''; + + /** + * Indicates if the gateway is operating in sandbox mode or not + */ + public $sandbox_mode = false; + + /** + * The gateways logo URL + */ + public $gateway_logo_url = ''; + + /** + * Gateways Settings + */ + public $prefs = false; + + /** + * Main Point Type Settings + */ + public $core; + + /** + * buyCRED Add-on Settings + */ + public $buycred = false; + + /** + * The point type being purchased + */ + public $point_type = ''; + + /** + * The point amount being purchased + */ + public $amount = 0; + + /** + * The buyers ID + */ + public $buyer_id = false; + + /** + * The recipients ID + */ + public $recipient_id = false; + + /** + * Indicates if this is a gift or not + */ + public $gifting = false; + + /** + * Indicates if this is a valid purchase request + */ + public $valid_request = false; + + /** + * The current users ID + */ + public $current_user_id = 0; + + /** + * Redirect fields + */ + public $redirect_fields = array(); + + /** + * Redirect URL + */ + public $redirect_to = ''; + + public $errors = array(); + + /** + * Toggle ID + */ + public $toggle_id = ''; + + /** + * Limit Setting + */ + public $buycred_limit = array(); + + protected $response; + protected $request; + protected $status; + + protected $processing_log = NULL; + + /** + * Construct + */ + public function __construct( $args = array(), $gateway_prefs = NULL ) { + + // Make sure gateway prefs is set + if ( $gateway_prefs === NULL ) return; + + // Populate + $this->now = current_time( 'timestamp' ); + $this->current_user_id = get_current_user_id(); + $this->core = mycred(); + $this->buycred = mycred_get_buycred_settings(); + + // Arguments + if ( ! empty( $args ) ) { + foreach ( $args as $key => $value ) { + $this->$key = $value; + } + } + + $gateway_settings = $this->defaults; + if ( is_array( $gateway_prefs ) && array_key_exists( $this->id, $gateway_prefs ) ) + $gateway_settings = $gateway_prefs[ $this->id ]; + + elseif ( is_object( $gateway_prefs ) && array_key_exists( $this->id, $gateway_prefs->gateway_prefs ) ) + $gateway_settings = $gateway_prefs->gateway_prefs[ $this->id ]; + + $this->prefs = shortcode_atts( $this->defaults, $gateway_settings ); + + // Sandbox Mode + $this->sandbox_mode = ( isset( $this->prefs['sandbox'] ) ) ? (bool) $this->prefs['sandbox'] : false; + + // Decode Log Entries + add_filter( 'mycred_prep_template_tags', array( $this, 'decode_log_entries' ), 10, 2 ); + add_filter( 'mycred_parse_log_entry_buy_creds_with_' . $this->id, array( $this, 'log_entry' ), 10, 2 ); + + } + + /** + * Request Validator + * @since 1.8 + * @version 1.0 + */ + public function valid_request() { + + // Step 1 - We need to be logged in to buy + if ( ! is_user_logged_in() ) return false; + + // Step 2 - We need a valid token to start the request + if ( ! isset( $_REQUEST['token'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['token'] ) ), 'mycred-buy-creds' ) ) return false; - // Get existing one - elseif ($this->post_id === false ) { + $valid = true; - $transaction = buycred_get_pending_payment($this->post_id); + $this->point_type = $this->get_point_type(); + if ( $this->point_type != MYCRED_DEFAULT_TYPE_KEY ) + $this->core = mycred( $this->point_type ); - if ($transaction !== false ) { + $this->buycred_limit = mycred_get_buycred_sale_setup( $this->point_type ); - $new_transaction = true; + $this->transaction_id = ( isset( $_REQUEST['revisit'] ) ) ? strtoupper( sanitize_text_field( wp_unslash( $_REQUEST['revisit'] ) ) ) : false; + $this->post_id = ( $this->transaction_id !== false ) ? buycred_get_pending_payment_id( $this->transaction_id ) : false; + $this->buyer_id = $this->current_user_id; + $this->recipient_id = $this->get_recipient_id(); + $this->amount = $this->get_amount(); + $this->cost = $this->get_cost( $this->amount, $this->point_type ); + $this->currency = ( isset( $this->prefs['currency'] ) ) ? $this->prefs['currency'] : ''; + $this->maximum = -1; + + if ( $this->core->exclude_user( $this->buyer_id ) ){ + $valid = false; + $this->errors[] = __( 'Buyer is excluded from this point type.', 'mycred' ); + } + elseif ( $this->core->exclude_user( $this->recipient_id ) ) { + $valid = false; + $this->errors[] = __( 'Recipient is excluded from this point type. ', 'mycred' ); + } - $this->point_type = $transaction->point_type; - $this->amount = $transaction->amount; - $this->cost = $transaction->cost; - $this->currency = $transaction->currency; - $this->buyer_id = $transaction->buyer_id; - $this->recipient_id = $transaction->recipient_id; - $this->transaction_id = $transaction->public_id; - - } - - } - - $this->prep_sale($new_transaction); - - } - - /** - * Prep Sale - * - * @since 1.8 - * @version 1.0 - */ - public function prep_sale( $new_transaction = false ) - { - } - - /** - * Send JSON - * - * @since 1.8 - * @version 1.0 - */ - public function send_json( $content = '' ) - { - - $content = apply_filters('mycred_buycred_send_json', $content, $this); - - wp_send_json($content); - - } - - /** - * Request Exceeds Limit Check - * Checks if a requested amount of points exceeds the "maximum" limit (if used). - * - * @since 1.8 - * @version 1.0 - */ - public function exceeds_limit() - { - - $exceeds = false; - $remaining = mycred_user_can_buycred($this->buyer_id, $this->point_type); - - // A maximum limit is enforced and we have maxed out - if ($remaining === 0 ) { - - $exceeds = true; - $this->maximum = 0; - - } - - // A maximum limit is used so we need to make sure the amount we want to buy is valid - elseif ($remaining !== true ) { - - $this->maximum = $this->core->number($remaining); - - // The amount remaining is lower than our requested amount - if ($remaining > 0 && $remaining < $this->amount ) { - $this->amount = $remaining; - } - - // Make sure the amount does not exceeds our maximum limit, if it does, reject - else { - - $remaining = $this->core->number($remaining - $this->amount); - - if ($remaining < 0 ) { - $exceeds = true; - $this->maximum = 0; - } - else { - - $this->maximum = $remaining; - - } - - } - - } - - return apply_filters('mycred_exceeds_buycred_limit', $exceeds, $remaining, $this); - - } - - /** - * Process Purchase - * - * @since 0.1 - * @version 1.0 - */ - public function process() - { - } - - /** - * Results Handler - * - * @since 0.1 - * @version 1.0 - */ - public function returning() - { - } - - /** - * AJAX Buy Handler - * - * @since 1.8 - * @version 1.0 - */ - public function ajax_buy() - { - } - - /** - * Buy Handler - * - * @since 0.1 - * @version 1.0 - */ - public function buy() - { - } + elseif ( $this->amount === false || $this->amount == 0 ){ + $valid = false; + $this->errors[] = __( 'An amount value is required.', 'mycred' ); + } - /** - * Admin Init Handler - * - * @since 1.7 - * @version 1.0 - */ - public function admin_init() - { - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.0 - */ - public function preferences() - { - - echo '

    This Payment Gateway has no settings

    '; - - } - - /** - * Sanatize Prefs - * - * @since 0.1 - * @version 1.0 - */ - public function sanitise_preferences( $data ) - { - - return $data; - - } - - /** - * Checkout Header - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_header() - { - - $content = ''; - - if ($this->sandbox_mode ) { - $content .= '
    ' . esc_js(esc_attr(__('Test Mode', 'mycred'))) . '
    '; - } - - $content .= '
    '; - - return apply_filters('mycred_buycred_checkout_header', $content, $this); - - } - - /** - * Checkout Footer - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_footer( $button_label = '' ) - { - - if ($button_label == '' ) { - $button_label = __('Continue', 'mycred'); - } - - $content = ''; - if (! empty($this->redirect_fields) ) { - - $fields = apply_filters('mycred_buycred_redirect_fields', $this->redirect_fields, $this); - - if (! empty($fields) ) { - foreach ( $fields as $name => $value ) { $content .= ''; - } - } - - } - - $button = ''; - - // The button - if (! empty($this->toggle_id) ) { - $button = ''; - - } elseif (! empty($this->redirect_to) ) { - $button = ''; - } - - $button = apply_filters('mycred_buycred_checkout_button', $button, $this); - - $content .= '
    '; - - if ($button != '' ) { - $content .= ''; - } - - return apply_filters('mycred_buycred_checkout_footer', $content, $this); - - } - - /** - * Checkout Logo - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_logo( $title = '' ) - { + elseif ( ! empty( $this->buycred_limit['max'] ) && $this->amount > floatval( $this->buycred_limit['max'] ) ){ + $valid = false; + $this->errors[] = apply_filters( 'buycred_max_amount_error', sprintf( __( 'The amount must be less than %d.', 'mycred' ), $this->buycred_limit['max'] ), $this->buycred_limit['max'], $this ); + } - if ($title === '' ) { - if (isset($this->prefs['title']) ) { $title = $this->prefs['title']; - } elseif (isset($this->prefs['label']) ) { $title = $this->prefs['label']; - } - } + elseif ( $this->exceeds_limit() ){ + $valid = false; + $this->errors[] = __( 'You have exceeded the limit.', 'mycred' ); + } - if (isset($this->prefs['logo']) && ! empty($this->prefs['logo']) ) { - $content = ''; + if ( $valid ) + $this->populate_transaction(); - } elseif (isset($this->prefs['logo_url']) && ! empty($this->prefs['logo_url']) ) { - $content = ''; + if ( ! empty( $this->errors ) ) + $valid = false; - } elseif (isset($this->gateway_logo_url) && ! empty($this->gateway_logo_url) ) { - $content = ''; + return apply_filters( 'mycred_valid_buycred_request', $valid, $this ); - } elseif ($title !== false ) { $content = '

    ' . esc_html($title) . '

    '; - } else { - $content = ''; - } + } - return apply_filters('mycred_buycred_checkout_logo', $content, $this); + /** + * Populate Transaction + * @since 1.8 + * @since 2.3 @filter added `mycred_buycred_populate_transaction` to avoid pending payments log in some cases. + * @version 1.0 + */ + public function populate_transaction() { - } + if( apply_filters( 'mycred_buycred_populate_transaction', false, $this->id ) ) + return; - /** - * Checkout: Order - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_order() - { + // Create a new transaction + $new_transaction = false; + if ( $this->transaction_id === false && $this->post_id === false ) { - $table_rows = array(); - $point_type_name = apply_filters('mycred_buycred_checkout_order', $this->core->plural(), $this); - $table_rows[] = '' . esc_html($point_type_name) . '' . $this->amount . ''; - $item_label = apply_filters('mycred_buycred_checkout_order', __('Item', 'mycred'), $this); - $amount_label = apply_filters('mycred_buycred_checkout_order', __('Amount', 'mycred'), $this); - $cost_label = apply_filters('mycred_buycred_checkout_order', __('Cost', 'mycred'), $this); - - if ($this->gifting ) { - $table_rows[] = '' . esc_js(esc_attr($cost_label)) . ': ' . esc_html(get_userdata($this->recipient_id)->display_name) . ''; - } + $this->post_id = $this->add_pending_payment( array( + $this->buyer_id, + $this->recipient_id, + $this->amount, + $this->cost, + $this->currency, + $this->point_type + ) ); - $table_rows[] = '' . esc_js(esc_attr(__('Cost', 'mycred'))) . '' . sprintf('%s %s', apply_filters('mycred_buycred_display_user_amount', $this->cost), $this->prefs['currency']) . ''; + $this->transaction_id = get_the_title( $this->post_id ); - $table_rows = apply_filters('mycred_buycred_order_table_rows', $table_rows, $this); + } - if (! empty($table_rows) ) { - $content = ' + // Get existing one + elseif ( $this->post_id === false ) { + + $transaction = buycred_get_pending_payment( $this->post_id ); + + if ( $transaction !== false ) { + + $new_transaction = true; + + $this->point_type = $transaction->point_type; + $this->amount = $transaction->amount; + $this->cost = $transaction->cost; + $this->currency = $transaction->currency; + $this->buyer_id = $transaction->buyer_id; + $this->recipient_id = $transaction->recipient_id; + $this->transaction_id = $transaction->public_id; + + } + + } + + $this->prep_sale( $new_transaction ); + + } + + /** + * Prep Sale + * @since 1.8 + * @version 1.0 + */ + public function prep_sale( $new_transaction = false ) { } + + /** + * Send JSON + * @since 1.8 + * @version 1.0 + */ + public function send_json( $content = '' ) { + + $content = apply_filters( 'mycred_buycred_send_json', $content, $this ); + + wp_send_json( $content ); + + } + + /** + * Request Exceeds Limit Check + * Checks if a requested amount of points exceeds the "maximum" limit (if used). + * @since 1.8 + * @version 1.0 + */ + public function exceeds_limit() { + + $exceeds = false; + $remaining = mycred_user_can_buycred( $this->buyer_id, $this->point_type ); + + // A maximum limit is enforced and we have maxed out + if ( $remaining === 0 ) { + + $exceeds = true; + $this->maximum = 0; + + } + + // A maximum limit is used so we need to make sure the amount we want to buy is valid + elseif ( $remaining !== true ) { + + $this->maximum = $this->core->number( $remaining ); + + // The amount remaining is lower than our requested amount + if ( $remaining > 0 && $remaining < $this->amount ) + $this->amount = $remaining; + + // Make sure the amount does not exceeds our maximum limit, if it does, reject + else { + + $remaining = $this->core->number( $remaining - $this->amount ); + + if ( $remaining < 0 ) { + $exceeds = true; + $this->maximum = 0; + } + else { + + $this->maximum = $remaining; + + } + + } + + } + + return apply_filters( 'mycred_exceeds_buycred_limit', $exceeds, $remaining, $this ); + + } + + /** + * Process Purchase + * @since 0.1 + * @version 1.0 + */ + public function process() { } + + /** + * Results Handler + * @since 0.1 + * @version 1.0 + */ + public function returning() { } + + /** + * AJAX Buy Handler + * @since 1.8 + * @version 1.0 + */ + public function ajax_buy() { } + + /** + * Buy Handler + * @since 0.1 + * @version 1.0 + */ + public function buy() { } + + /** + * Admin Init Handler + * @since 1.7 + * @version 1.0 + */ + public function admin_init() { } + + /** + * Preferences + * @since 0.1 + * @version 1.0 + */ + public function preferences() { + + echo '

    This Payment Gateway has no settings

    '; + + } + + /** + * Sanatize Prefs + * @since 0.1 + * @version 1.0 + */ + public function sanitise_preferences( $data ) { + + return $data; + + } + + /** + * Checkout Header + * @since 1.8 + * @version 1.0 + */ + public function checkout_header() { + + $content = ''; + + if ( $this->sandbox_mode ) + $content .= '
    ' . esc_js( esc_attr( __( 'Test Mode', 'mycred' ) ) ) . '
    '; + + $content .= '
    '; + + return apply_filters( 'mycred_buycred_checkout_header', $content, $this ); + + } + + /** + * Checkout Footer + * @since 1.8 + * @version 1.0 + */ + public function checkout_footer( $button_label = '' ) { + + if ( $button_label == '' ) + $button_label = __( 'Continue', 'mycred' ); + + $content = ''; + if ( ! empty( $this->redirect_fields ) ) { + + $fields = apply_filters( 'mycred_buycred_redirect_fields', $this->redirect_fields, $this ); + + if ( ! empty( $fields ) ) { + foreach ( $fields as $name => $value ) $content .= ''; + } + + } + + $button = ''; + + // The button + if ( ! empty( $this->toggle_id ) ) + $button = ''; + + elseif ( ! empty( $this->redirect_to ) ) + $button = ''; + + $button = apply_filters( 'mycred_buycred_checkout_button', $button, $this ); + + $content .= '
    '; + + if ( $button != '' ) + $content .= ''; + + return apply_filters( 'mycred_buycred_checkout_footer', $content, $this ); + + } + + /** + * Checkout Logo + * @since 1.8 + * @version 1.0 + */ + public function checkout_logo( $title = '' ) { + + if ( $title === '' ) { + if ( isset( $this->prefs['title'] ) ) $title = $this->prefs['title']; + elseif ( isset( $this->prefs['label'] ) ) $title = $this->prefs['label']; + } + + if ( isset( $this->prefs['logo'] ) && ! empty( $this->prefs['logo'] ) ) + $content = ''; + + elseif ( isset( $this->prefs['logo_url'] ) && ! empty( $this->prefs['logo_url'] ) ) + $content = ''; + + elseif ( isset( $this->gateway_logo_url ) && ! empty( $this->gateway_logo_url ) ) + $content = ''; + + elseif ( $title !== false ) $content = '

    ' . esc_html( $title ) . '

    '; + else { + $content = ''; + } + + return apply_filters( 'mycred_buycred_checkout_logo', $content, $this ); + + } + + /** + * Checkout: Order + * @since 1.8 + * @version 1.0 + */ + public function checkout_order() { + + $table_rows = array(); + $point_type_name = apply_filters( 'mycred_buycred_checkout_order', $this->core->plural(), $this ); + $table_rows[] = '' . esc_html( $point_type_name ) . '' . $this->amount . ''; + $item_label = apply_filters( 'mycred_buycred_checkout_order', __('Item', 'mycred'), $this ); + $amount_label = apply_filters( 'mycred_buycred_checkout_order', __('Amount', 'mycred'), $this ); + $cost_label = apply_filters( 'mycred_buycred_checkout_order', __('Cost', 'mycred'), $this ); + + if ( $this->gifting ) + $table_rows[] = '' . esc_js( esc_attr($cost_label ) ) . ': ' . esc_html( get_userdata( $this->recipient_id )->display_name ) . ''; + + $table_rows[] = '' . esc_js( esc_attr( __( 'Cost', 'mycred' ) ) ) . '' . sprintf( '%s %s', apply_filters( 'mycred_buycred_display_user_amount', $this->cost ), $this->prefs['currency'] ) . ''; + + $table_rows = apply_filters( 'mycred_buycred_order_table_rows', $table_rows, $this ); + + if ( ! empty( $table_rows ) ) + $content = ' - - ' . implode('', $table_rows) . ' + ' . implode( '', $table_rows ) . '
    ' . esc_js(esc_attr($item_label)) . ' - ' . esc_js(esc_attr($amount_label)) . ' + ' . esc_js( esc_attr($item_label ) ) . ' + ' . esc_js( esc_attr($amount_label ) ) . '
    '; - } - - return apply_filters('mycred_buycred_checkout_order', $content, $this); - - } - - /** - * Checkout: Transaction ID - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_transaction_id() - { - - $content = '

    ' . esc_js(esc_attr(__('Transaction ID', 'mycred'))) . '' . esc_attr($this->transaction_id) . '

    '; - - return apply_filters('mycred_buycred_checkout_txtid', $content, $this); - - } - - /** - * Checkout: Cancel - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_cancel() - { - - $content = '
    ' . esc_js(esc_attr(__('cancel purchase', 'mycred'))) . '
    '; - - return apply_filters('mycred_buycred_checkout_cancel', $content, $this); - - } - - /** - * Checkout Page Title - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_page_title() - { - } - - /** - * Checkout Page Body - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_page_body() - { - } - - /** - * Checkout Page Footer - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_page_footer() - { - } - - /** - * Exchange Rate Setup - * - * @since 1.5 - * @version 1.1 - */ - public function exchange_rate_setup( $default = 'USD' ) - { - - if (! isset($this->prefs['exchange']) ) { return; - } - - $content = ''; - $point_types = array( MYCRED_DEFAULT_TYPE_KEY ); - - if (isset($this->buycred['types']) ) { - $point_types = (array) $this->buycred['types']; - } - - foreach ( $point_types as $type_id ) { - - $mycred = mycred($type_id); - - if (! isset($this->prefs['exchange'][ $type_id ]) ) { - $this->prefs['exchange'][ $type_id ] = 1; - } - - $content .= ' + + return apply_filters( 'mycred_buycred_checkout_order', $content, $this ); + + } + + /** + * Checkout: Transaction ID + * @since 1.8 + * @version 1.0 + */ + public function checkout_transaction_id() { + + $content = '

    ' . esc_js( esc_attr( __( 'Transaction ID', 'mycred' ) ) ) . '' . esc_attr( $this->transaction_id ) . '

    '; + + return apply_filters( 'mycred_buycred_checkout_txtid', $content, $this ); + + } + + /** + * Checkout: Cancel + * @since 1.8 + * @version 1.0 + */ + public function checkout_cancel() { + + $content = '
    ' . esc_js( esc_attr( __( 'cancel purchase', 'mycred' ) ) ) . '
    '; + + return apply_filters( 'mycred_buycred_checkout_cancel', $content, $this ); + + } + + /** + * Checkout Page Title + * @since 1.8 + * @version 1.0 + */ + public function checkout_page_title() { } + + /** + * Checkout Page Body + * @since 1.8 + * @version 1.0 + */ + public function checkout_page_body() { } + + /** + * Checkout Page Footer + * @since 1.8 + * @version 1.0 + */ + public function checkout_page_footer() { } + + /** + * Exchange Rate Setup + * @since 1.5 + * @version 1.1 + */ + public function exchange_rate_setup( $default = 'USD' ) { + + if ( ! isset( $this->prefs['exchange'] ) ) return; + + $content = ''; + $point_types = array( MYCRED_DEFAULT_TYPE_KEY ); + + if ( isset( $this->buycred['types'] ) ) + $point_types = (array) $this->buycred['types']; + + foreach ( $point_types as $type_id ) { + + $mycred = mycred( $type_id ); + + if ( ! isset( $this->prefs['exchange'][ $type_id ] ) ) + $this->prefs['exchange'][ $type_id ] = 1; + + $content .= ' - + - + $content .= '
    1 ' . esc_html($mycred->singular()) . '
    1 ' . esc_html( $mycred->singular() ) . '
    =
    '; + '; - if (isset($this->prefs['currency']) ) { - $content .= '' . ( ( $this->prefs['currency'] == '' ) ? __('Select currency', 'mycred') : esc_attr($this->prefs['currency']) ) . ''; + if ( isset( $this->prefs['currency'] ) ) + $content .= '' . ( ( $this->prefs['currency'] == '' ) ? __( 'Select currency', 'mycred' ) : esc_attr( $this->prefs['currency'] ) ) . ''; - } else { - $content .= '' . esc_attr($default) . ''; - } + else + $content .= '' . esc_attr( $default ) . ''; - $content .= '
    '; - } + } + + $allowed_tags = array( + 'table' => array(), + 'tr' => array(), + 'td' => array( 'style' => array() ), + 'div' => array( 'class' => array() ), + 'input' => array( + 'type' => array(), + 'name' => array(), + 'id' => array(), + 'value' => array(), + 'size' => array() + ), + 'span' => array( 'class' => array() ) + ); + + echo wp_kses( apply_filters( 'mycred_buycred_exchange_rate_field', $content, $default, $this ), $allowed_tags ); + + } + + /** + * Add Pending Payment + * @since 1.5 + * @version 1.1.1 + */ + public function add_pending_payment( $data ) { + + $post_id = false; + list ( $to, $from, $amount, $cost, $currency, $point_type ) = $data; + + // Title + if ( isset( $_REQUEST['transaction_id'] ) ) + $post_title = sanitize_title( wp_unslash( $_REQUEST['transaction_id'] ) ); + else + $post_title = strtoupper( wp_generate_password( 6, false, false ) ); + + $check = $this->transaction_exists( $to, $from, $amount, $cost, $currency, $point_type ); + if ( $check !== false ) return $check; + + // Make sure we are not adding more then one pending item + $check = mycred_get_page_by_title( $post_title, ARRAY_A, 'buycred_payment' ); + if ( $check === NULL || ( isset( $check['post_status'] ) && $check['post_status'] == 'trash' ) ) { + + // Generate new id and trash old request + if ( isset( $check['post_status'] ) && $check['post_status'] == 'trash' ) { + buycred_trash_pending_payment( $check['ID'] ); + $post_title = strtoupper( wp_generate_password( 6, false, false ) ); + } + + // Insert post + $post_id = wp_insert_post( array( + 'post_title' => $post_title, + 'post_type' => 'buycred_payment', + 'post_status' => 'publish', + 'post_author' => $from, + 'ping_status' => 'closed', + 'comment_status' => 'open' + ) ); + + // Add meta details if insertion was a success + if ( $post_id !== NULL && ! is_wp_error( $post_id ) ) { + + mycred_add_post_meta( $post_id, 'from', $to, true ); + mycred_add_post_meta( $post_id, 'to', $from, true ); + mycred_add_post_meta( $post_id, 'amount', $amount, true ); + mycred_add_post_meta( $post_id, 'cost', $cost, true ); + mycred_add_post_meta( $post_id, 'currency', $currency, true ); + mycred_add_post_meta( $post_id, 'point_type', $point_type, true); + mycred_add_post_meta( $post_id, 'gateway', $this->id, true ); + + mycred_delete_user_meta( $from, 'buycred_pending_payments' ); + + $mycred = mycred( $point_type ); + + $log_entry = $this->first_comment( sprintf( _x( 'Received new request to purchase %s.', '%s is replaced with the point amount and name.', 'mycred' ), $mycred->format_number( $amount ) . ' ' . $mycred->plural() ) ); + $log_entry = apply_filters( 'mycred_new_buycred_request_comment_' . $this->id, $log_entry, $data ); + + $this->log_call( $post_id, $log_entry ); + + } + + } + else $post_id = $check['ID']; + + return apply_filters( 'mycred_add_pending_payment', $post_id, $data ); + + } + + public function transaction_exists( $to, $from, $amount, $cost, $currency, $point_type ) { + + $post_query = array( + 'post_type' => 'buycred_payment', + 'post_status' => 'publish', + 'posts_per_page' => '-1', + 'orderby' => 'date', + 'order' => 'DESC', + 'fields' => 'ids' + ); + + $meta_query = array(); + + $meta_query[] = array( + 'key' => 'to', + 'value' => $to, + 'compare' => '=', + 'type' => 'NUMERIC' + ); + + $meta_query[] = array( + 'key' => 'from', + 'value' => $from, + 'compare' => '=', + 'type' => 'NUMERIC' + ); + + $meta_query[] = array( + 'key' => 'amount', + 'value' => $amount, + 'compare' => '=', + 'type' => 'NUMERIC' + ); + + $meta_query[] = array( + 'key' => 'cost', + 'value' => $cost, + 'compare' => '=', + 'type' => 'NUMERIC' + ); + + $meta_query[] = array( + 'key' => 'currency', + 'value' => $currency, + 'compare' => '=' + ); + + $meta_query[] = array( + 'key' => 'point_type', + 'value' => $point_type, + 'compare' => '=' + ); + + $meta_query[] = array( + 'key' => 'gateway', + 'value' => $this->id, + 'compare' => '=' + ); + + $post_query['meta_query'] = $meta_query; + + $post_id = false; + $pending = new WP_Query( $post_query ); + if ( ! empty( $pending->posts ) ) { + + $post_id = $pending->posts[0]; + + wp_reset_postdata(); + + } + + return $post_id; + + } + + /** + * First Comment + * Used to allow a gateway to adjust the first comment with pending payments. + * @since 1.7.3 + * @version 1.0 + */ + public function first_comment( $comment ) { + + return $comment; + + } + + /** + * Get Pending Payment + * @since 1.5 + * @version 1.1 + */ + public function get_pending_payment( $post_id = NULL ) { + + $pending_payment = buycred_get_pending_payment( $post_id ); + + return apply_filters( 'mycred_get_pending_payment', $pending_payment, $post_id ); + + } + + /** + * Get Recipient ID + * Returns the numeric ID of the user that is nominated to receive the purchased points. + * @since 1.8 + * @version 1.0 + */ + public function get_recipient_id() { + + $this->gifting = false; + $recipient_id = $this->current_user_id; + + // Gift to a user + if ( $this->buycred['gifting']['members'] == 1 ) { + + if ( isset( $_REQUEST['gift_to'] ) ) { + + $gift_to = absint( $_REQUEST['gift_to'] ); + if ( $gift_to > 0 ) { + $recipient_id = $gift_to; + $this->gifting = true; + } + + } + + } + + // Gifting author + if ( $this->buycred['gifting']['authors'] == 1 ) { + + if ( isset( $_REQEST['post_id'] ) ) { + + $post_id = absint( $_REQEST['post_id'] ); + $post = mycred_get_post( $post_id ); + if ( isset( $post->post_author ) ) { + $recipient_id = absint( $post->post_author ); + $this->gifting = true; + } + + } + + } + + return apply_filters( 'mycred_get_buycred_recipient_id', $recipient_id, $this ); + + } + + public function get_to() { + + return $this->get_recipient_id(); + + } + + /** + * Get Amount + * @since 1.8 + * @version 1.0 + */ + public function get_amount() { + + $settings = mycred_get_buycred_sale_setup( $this->point_type ); + $amount = false; + + // Validate amount ( amount is not zero, higher then minimum required and do not exceed maximum (if set) ) + if ( isset( $_REQUEST['amount'] ) && is_numeric( $_REQUEST['amount'] ) ) { + + $amount = $this->core->number( sanitize_text_field( wp_unslash( $_REQUEST['amount'] ) ) ); + $minimum = $this->core->number( $settings['min'] ); + + // Enforce minimum + if ( $amount < $minimum ) + $amount = $minimum; + + } - echo apply_filters('mycred_buycred_exchange_rate_field', $content, $default, $this); - - } - - /** - * Add Pending Payment - * - * @since 1.5 - * @version 1.1.1 - */ - public function add_pending_payment( $data ) - { - - $post_id = false; - list ( $to, $from, $amount, $cost, $currency, $point_type ) = $data; - - // Title - if (isset($_REQUEST['transaction_id']) ) { - $post_title = sanitize_title($_REQUEST['transaction_id']); - } else { - $post_title = strtoupper(wp_generate_password(6, false, false)); - } - - $check = $this->transaction_exists($to, $from, $amount, $cost, $currency, $point_type); - if ($check !== false ) { return $check; - } - - // Make sure we are not adding more then one pending item - $check = mycred_get_page_by_title($post_title, ARRAY_A, 'buycred_payment'); - if ($check === null || ( isset($check['post_status']) && $check['post_status'] == 'trash' ) ) { - - // Generate new id and trash old request - if (isset($check['post_status']) && $check['post_status'] == 'trash' ) { - buycred_trash_pending_payment($check['ID']); - $post_title = strtoupper(wp_generate_password(6, false, false)); - } - - // Insert post - $post_id = wp_insert_post( - array( - 'post_title' => $post_title, - 'post_type' => 'buycred_payment', - 'post_status' => 'publish', - 'post_author' => $from, - 'ping_status' => 'closed', - 'comment_status' => 'open' - ) - ); - - // Add meta details if insertion was a success - if ($post_id !== null && ! is_wp_error($post_id) ) { - - mycred_add_post_meta($post_id, 'from', $to, true); - mycred_add_post_meta($post_id, 'to', $from, true); - mycred_add_post_meta($post_id, 'amount', $amount, true); - mycred_add_post_meta($post_id, 'cost', $cost, true); - mycred_add_post_meta($post_id, 'currency', $currency, true); - mycred_add_post_meta($post_id, 'point_type', $point_type, true); - mycred_add_post_meta($post_id, 'gateway', $this->id, true); - - mycred_delete_user_meta($from, 'buycred_pending_payments'); - - $mycred = mycred($point_type); - - $log_entry = $this->first_comment(sprintf(_x('Received new request to purchase %s.', '%s is replaced with the point amount and name.', 'mycred'), $mycred->format_number($amount) . ' ' . $mycred->plural())); - $log_entry = apply_filters('mycred_new_buycred_request_comment_' . $this->id, $log_entry, $data); - - $this->log_call($post_id, $log_entry); - - } - - } - else { $post_id = $check['ID']; - } - - return apply_filters('mycred_add_pending_payment', $post_id, $data); - - } - - public function transaction_exists( $to, $from, $amount, $cost, $currency, $point_type ) - { - - $post_query = array( - 'post_type' => 'buycred_payment', - 'post_status' => 'publish', - 'posts_per_page' => '-1', - 'orderby' => 'date', - 'order' => 'DESC', - 'fields' => 'ids' - ); - - $meta_query = array(); - - $meta_query[] = array( - 'key' => 'to', - 'value' => $to, - 'compare' => '=', - 'type' => 'NUMERIC' - ); - - $meta_query[] = array( - 'key' => 'from', - 'value' => $from, - 'compare' => '=', - 'type' => 'NUMERIC' - ); - - $meta_query[] = array( - 'key' => 'amount', - 'value' => $amount, - 'compare' => '=', - 'type' => 'NUMERIC' - ); - - $meta_query[] = array( - 'key' => 'cost', - 'value' => $cost, - 'compare' => '=', - 'type' => 'NUMERIC' - ); - - $meta_query[] = array( - 'key' => 'currency', - 'value' => $currency, - 'compare' => '=' - ); - - $meta_query[] = array( - 'key' => 'point_type', - 'value' => $point_type, - 'compare' => '=' - ); - - $meta_query[] = array( - 'key' => 'gateway', - 'value' => $this->id, - 'compare' => '=' - ); + return apply_filters( 'mycred_get_buycred_amount', $amount, $this ); - $post_query['meta_query'] = $meta_query; + } - $post_id = false; - $pending = new WP_Query($post_query); - if (! empty($pending->posts) ) { + /** + * Get Point Type + * @since 1.5 + * @version 1.2 + */ + public function get_point_type() { - $post_id = $pending->posts[0]; + $point_type = MYCRED_DEFAULT_TYPE_KEY; - wp_reset_postdata(); + if ( isset( $_REQUEST['ctype'] ) ) { - } + $type_id = sanitize_key( $_REQUEST['ctype'] ); + if ( $type_id != '' && mycred_point_type_exists( $type_id ) ) + $point_type = $type_id; - return $post_id; + } - } + return $point_type; - /** - * First Comment - * Used to allow a gateway to adjust the first comment with pending payments. - * - * @since 1.7.3 - * @version 1.0 - */ - public function first_comment( $comment ) - { + } - return $comment; + /** + * Get Cost + * @since 1.3.2 + * @version 1.2 + */ + public function get_cost( $amount = 0, $point_type = MYCRED_DEFAULT_TYPE_KEY, $raw = false, $custom_rate = 0 ) { - } + if( ! empty( $_REQUEST['er_random'] ) ) { + + $custom_rate = mycred_decode_values( $_REQUEST['er_random'] ); + + } - /** - * Get Pending Payment - * - * @since 1.5 - * @version 1.1 - */ - public function get_pending_payment( $post_id = null ) - { + $setup = mycred_get_buycred_sale_setup( $point_type ); - $pending_payment = buycred_get_pending_payment($post_id); + // Apply minimum + if ( $amount < $setup['min'] ) + $amount = $setup['min']; - return apply_filters('mycred_get_pending_payment', $pending_payment, $post_id); + // Calculate cost here so we can use any exchange rate + if ( array_key_exists( $point_type, $this->prefs['exchange'] ) ) { - } + // Check for user override + $override = mycred_get_user_meta( $this->current_user_id, 'mycred_buycred_rates_' . $point_type, '', true ); + if ( isset( $override[ $this->id ] ) && $override[ $this->id ] != '' ) + $rate = $override[ $this->id ]; + else if( $custom_rate !=0 ) + $rate = $custom_rate; + else + $rate = $this->prefs['exchange'][ $point_type ]; - /** - * Get Recipient ID - * Returns the numeric ID of the user that is nominated to receive the purchased points. - * - * @since 1.8 - * @version 1.0 - */ - public function get_recipient_id() - { + if ( isfloat( $rate ) ) + $rate = (float) $rate; + else + $rate = (int) $rate; - $this->gifting = false; - $recipient_id = $this->current_user_id; + $cost = $amount * $rate; - // Gift to a user - if ($this->buycred['gifting']['members'] == 1 ) { + } + else + $cost = $amount; - if (isset($_REQUEST['gift_to']) ) { + // Return a properly formated cost so PayPal is happy + if ( ! $raw ) + $cost = number_format( $cost, 2, '.', '' ); - $gift_to = absint($_REQUEST['gift_to']); - if ($gift_to > 0 ) { - $recipient_id = $gift_to; - $this->gifting = true; - } + return apply_filters( 'mycred_buycred_get_cost', $cost, $amount, $point_type, $this->prefs, $setup ); - } + } - } + /** + * Get Thank You Page + * @since 0.1 + * @version 1.1 + */ + public function get_thankyou() { - // Gifting author - if ($this->buycred['gifting']['authors'] == 1 ) { + $url = home_url( '/' ); - if (isset($_REQEST['post_id']) ) { + // Using a page + if ( $this->buycred['thankyou']['use'] == 'page' ) { - $post_id = absint($_REQEST['post_id']); - $post = mycred_get_post($post_id); - if (isset($post->post_author) ) { - $recipient_id = absint($post->post_author); - $this->gifting = true; - } + if ( ! empty( $this->buycred['thankyou']['page'] ) ) + $url = mycred_get_permalink( $this->buycred['thankyou']['page'] ); - } + } - } + // Using a custom url + elseif ( $this->buycred['thankyou']['use'] == 'custom' ) { - return apply_filters('mycred_get_buycred_recipient_id', $recipient_id, $this); + if ( ! empty( $this->buycred['thankyou']['custom'] ) ) + $url = $this->buycred['thankyou']['custom']; - } - public function get_to() - { + } - return $this->get_recipient_id(); + $profile_url = mycred_get_users_profile_url( $this->buyer_id ); + $url = str_replace( '%profile%', $profile_url, $url ); - } + return apply_filters( 'mycred_buycred_thankyou_url', $url, $this ); - /** - * Get Amount - * - * @since 1.8 - * @version 1.0 - */ - public function get_amount() - { + } - $settings = mycred_get_buycred_sale_setup($this->point_type); - $amount = false; + /** + * Get Entry + * Returns the appropriate log entry template. + * @since 0.1 + * @version 1.1 + */ + public function get_entry( $recipient_id = false, $buyer_id = false ) { - // Validate amount ( amount is not zero, higher then minimum required and do not exceed maximum (if set) ) - if (isset($_REQUEST['amount']) && is_numeric($_REQUEST['amount']) ) { + if ( $recipient_id === false ) $recipient_id = $this->recipient_id; + if ( $buyer_id === false ) $buyer_id = $this->buyer_id; - $amount = $this->core->number($_REQUEST['amount']); - $minimum = $this->core->number($settings['min']); + $log_entry = $this->buycred['log']; - // Enforce minimum - if ($amount < $minimum ) { - $amount = $minimum; - } + // Log entry + if ( $recipient_id != $buyer_id ) { - } + if ( $this->buycred['gifting']['members'] == 1 || $this->buycred['gifting']['authors'] == 1 ) + $log_entry = $this->buycred['gifting']['log']; - return apply_filters('mycred_get_buycred_amount', $amount, $this); + } - } + return $log_entry; - /** - * Get Point Type - * - * @since 1.5 - * @version 1.2 - */ - public function get_point_type() - { + } - $point_type = MYCRED_DEFAULT_TYPE_KEY; + /** + * Get Cancelled Page + * @since 0.1 + * @version 1.4 + */ + public function get_cancelled( $transaction_id = NULL ) { - if (isset($_REQUEST['ctype']) ) { + $url = buycred_get_cancel_transaction_url( $transaction_id ); - $type_id = sanitize_key($_REQUEST['ctype']); - if ($type_id != '' && mycred_point_type_exists($type_id) ) { - $point_type = $type_id; - } + $profile_url = mycred_get_users_profile_url( $this->buyer_id ); + $url = str_replace( '%profile%', $profile_url, $url ); - } + return $url; - return $point_type; + } - } + /** + * Log Gateway Call + * @since 1.5 + * @version 1.2 + */ + public function log_call( $payment_id, $log ) { - /** - * Get Cost - * - * @since 1.3.2 - * @version 1.2 - */ - public function get_cost( $amount = 0, $point_type = MYCRED_DEFAULT_TYPE_KEY, $raw = false, $custom_rate = 0 ) - { + if ( is_array( $log ) ) + $log = implode( '
    ', $log ); - if(isset($_REQUEST['er_random']) && !empty($_REQUEST['er_random'])) { - $custom_rate=mycred_decode_values($_REQUEST['er_random']); - } + buycred_add_pending_comment( $payment_id, $log ); - $setup = mycred_get_buycred_sale_setup($point_type); + } - // Apply minimum - if ($amount < $setup['min'] ) { - $amount = $setup['min']; - } + /** + * Decode Log Entries + * @since 0.1 + * @version 1.0 + */ + public function log_entry( $content, $log_entry ) { - // Calculate cost here so we can use any exchange rate - if (array_key_exists($point_type, $this->prefs['exchange']) ) { + return $this->core->template_tags_user( $content, $log_entry->ref_id ); - // Check for user override - $override = mycred_get_user_meta($this->current_user_id, 'mycred_buycred_rates_' . $point_type, '', true); - if (isset($override[ $this->id ]) && $override[ $this->id ] != '' ) { - $rate = $override[ $this->id ]; - } else if($custom_rate !=0 ) { - $rate = $custom_rate; - } else { - $rate = $this->prefs['exchange'][ $point_type ]; - } + } - if (isfloat($rate) ) { - $rate = (float) $rate; - } else { - $rate = (int) $rate; - } + /** + * Get Log Entry + * @since 1.4 + * @version 1.0.1 + */ + public function get_log_entry( $from = 0, $to = 0 ) { - $cost = $amount * $rate; + $entry = $this->get_entry( $from, $to ); + if ( isset( $this->label ) ) + $entry = str_replace( '%gateway%', $this->label, $entry ); - } - else { - $cost = $amount; - } + if ( $this->sandbox_mode ) $entry = 'TEST ' . $entry; + + return apply_filters( 'mycred_buycred_get_log_entry', $entry, $from, $to, $this ); - // Return a properly formated cost so PayPal is happy - if (! $raw ) { - $cost = number_format($cost, 2, '.', ''); - } + } - return apply_filters('mycred_buycred_get_cost', $cost, $amount, $point_type, $this->prefs, $setup); + /** + * Get Field Name + * Returns the field name for the current gateway + * @since 0.1 + * @version 1.0 + */ + public function field_name( $field = '' ) { - } + if ( is_array( $field ) ) { - /** - * Get Thank You Page - * - * @since 0.1 - * @version 1.1 - */ - public function get_thankyou() - { + $array = array(); + foreach ( $field as $parent => $child ) { + if ( ! is_numeric( $parent ) ) + $array[] = str_replace( '-', '_', $parent ); - $url = home_url('/'); + if ( ! empty( $child ) && ! is_array( $child ) ) + $array[] = str_replace( '-', '_', $child ); + } + $field = '[' . implode( '][', $array ) . ']'; - // Using a page - if ($this->buycred['thankyou']['use'] == 'page' ) { + } + else { - if (! empty($this->buycred['thankyou']['page']) ) { - $url = mycred_get_permalink($this->buycred['thankyou']['page']); - } + $field = '[' . $field . ']'; - } + } - // Using a custom url - elseif ($this->buycred['thankyou']['use'] == 'custom' ) { + return 'mycred_pref_buycreds[gateway_prefs][' . $this->id . ']' . $field; - if (! empty($this->buycred['thankyou']['custom']) ) { - $url = $this->buycred['thankyou']['custom']; - } + } - } + /** + * Get Field ID + * Returns the field id for the current gateway + * @since 0.1 + * @version 1.0 + */ + public function field_id( $field = '' ) { - $profile_url = mycred_get_users_profile_url($this->buyer_id); - $url = str_replace('%profile%', $profile_url, $url); + if ( is_array( $field ) ) { - return apply_filters('mycred_buycred_thankyou_url', $url, $this); + $array = array(); + foreach ( $field as $parent => $child ) { + if ( ! is_numeric( $parent ) ) + $array[] = str_replace( '_', '-', $parent ); - } + if ( ! empty( $child ) && ! is_array( $child ) ) + $array[] = str_replace( '_', '-', $child ); + } + $field = implode( '-', $array ); - /** - * Get Entry - * Returns the appropriate log entry template. - * - * @since 0.1 - * @version 1.1 - */ - public function get_entry( $recipient_id = false, $buyer_id = false ) - { - - if ($recipient_id === false ) { $recipient_id = $this->recipient_id; - } - if ($buyer_id === false ) { $buyer_id = $this->buyer_id; - } - - $log_entry = $this->buycred['log']; + } + else { - // Log entry - if ($recipient_id != $buyer_id ) { - - if ($this->buycred['gifting']['members'] == 1 || $this->buycred['gifting']['authors'] == 1 ) { - $log_entry = $this->buycred['gifting']['log']; - } - - } - - return $log_entry; + $field = str_replace( '_', '-', $field ); - } + } - /** - * Get Cancelled Page - * - * @since 0.1 - * @version 1.4 - */ - public function get_cancelled( $transaction_id = null ) - { + return 'mycred-gateway-prefs-' . str_replace( '_', '-', $this->id ) . '-' . $field; - $url = buycred_get_cancel_transaction_url($transaction_id); + } - $profile_url = mycred_get_users_profile_url($this->buyer_id); - $url = str_replace('%profile%', $profile_url, $url); + /** + * Callback URL + * @since 0.1 + * @version 1.2 + */ + public function callback_url() { - return $url; + $url = add_query_arg( 'mycred_call', $this->id, home_url( '/' ) ); - } + return apply_filters( 'mycred_buycred_callback_url', $url, $this ); - /** - * Log Gateway Call - * - * @since 1.5 - * @version 1.2 - */ - public function log_call( $payment_id, $log ) - { + } - if (is_array($log) ) { - $log = implode('
    ', $log); - } + /** + * Start Log + * @since 1.4 + * @version 1.0 + */ + public function start_log() { - buycred_add_pending_comment($payment_id, $log); + $this->new_log_entry( 'Incoming confirmation call detected' ); + $this->new_log_entry( sprintf( 'Gateway identified itself as "%s"', $this->id ) ); + $this->new_log_entry( 'Verifying caller' ); - } + } - /** - * Decode Log Entries - * - * @since 0.1 - * @version 1.0 - */ - public function log_entry( $content, $log_entry ) - { + /** + * New Log Entry + * @since 0.1 + * @version 1.0 + */ + public function new_log_entry( $entry = '' ) { - return $this->core->template_tags_user($content, $log_entry->ref_id); + if ( ! isset( $this->processing_log[ $this->id ] ) ) + $this->processing_log[ $this->id ] = array(); - } + $this->processing_log[ $this->id ][] = $entry; - /** - * Get Log Entry - * - * @since 1.4 - * @version 1.0.1 - */ - public function get_log_entry( $from = 0, $to = 0 ) - { + } - $entry = $this->get_entry($from, $to); - if (isset($this->label) ) { - $entry = str_replace('%gateway%', $this->label, $entry); - } + /** + * Save Log Entry + * @since 0.1 + * @version 1.0 + */ + public function save_log_entry( $id = '', $outcome = '' ) { - if ($this->sandbox_mode ) { $entry = 'TEST ' . $entry; - } - - return apply_filters('mycred_buycred_get_log_entry', $entry, $from, $to, $this); + update_option( 'mycred_buycred_last_call', array( + 'gateway' => $this->id, + 'date' => time(), + 'outcome' => $outcome, + 'id' => $id, + 'entries' => serialize( $this->processing_log[ $this->id ] ) + ) ); - } + } - /** - * Get Field Name - * Returns the field name for the current gateway - * - * @since 0.1 - * @version 1.0 - */ - public function field_name( $field = '' ) - { + /** + * Payment Page Header + * Pre 1.8 setup. Will be removed as of version 1.9 + * @since 0.1 + * @version 1.2 + */ + public function get_page_header( $site_title = '', $reload = false ) { - if (is_array($field) ) { - - $array = array(); - foreach ( $field as $parent => $child ) { - if (! is_numeric($parent) ) { - $array[] = str_replace('-', '_', $parent); - } + // Set Logo + $logo = ''; + if ( isset( $this->prefs['logo'] ) && ! empty( $this->prefs['logo'] ) ) + $logo = ''; - if (! empty($child) && ! is_array($child) ) { - $array[] = str_replace('-', '_', $child); - } - } - $field = '[' . implode('][', $array) . ']'; - - } - else { - - $field = '[' . $field . ']'; - - } - - return 'mycred_pref_buycreds[gateway_prefs][' . $this->id . ']' . $field; - - } - - /** - * Get Field ID - * Returns the field id for the current gateway - * - * @since 0.1 - * @version 1.0 - */ - public function field_id( $field = '' ) - { - - if (is_array($field) ) { - - $array = array(); - foreach ( $field as $parent => $child ) { - if (! is_numeric($parent) ) { - $array[] = str_replace('_', '-', $parent); - } - - if (! empty($child) && ! is_array($child) ) { - $array[] = str_replace('_', '-', $child); - } - } - $field = implode('-', $array); - - } - else { - - $field = str_replace('_', '-', $field); - - } - - return 'mycred-gateway-prefs-' . str_replace('_', '-', $this->id) . '-' . $field; - - } - - /** - * Callback URL - * - * @since 0.1 - * @version 1.2 - */ - public function callback_url() - { - - $url = add_query_arg('mycred_call', $this->id, home_url('/')); - - return apply_filters('mycred_buycred_callback_url', $url, $this); - - } - - /** - * Start Log - * - * @since 1.4 - * @version 1.0 - */ - public function start_log() - { - - $this->new_log_entry('Incoming confirmation call detected'); - $this->new_log_entry(sprintf('Gateway identified itself as "%s"', $this->id)); - $this->new_log_entry('Verifying caller'); - - } - - /** - * New Log Entry - * - * @since 0.1 - * @version 1.0 - */ - public function new_log_entry( $entry = '' ) - { - - if (! isset($this->processing_log[ $this->id ]) ) { - $this->processing_log[ $this->id ] = array(); - } - - $this->processing_log[ $this->id ][] = $entry; - - } - - /** - * Save Log Entry - * - * @since 0.1 - * @version 1.0 - */ - public function save_log_entry( $id = '', $outcome = '' ) - { - - update_option( - 'mycred_buycred_last_call', array( - 'gateway' => $this->id, - 'date' => time(), - 'outcome' => $outcome, - 'id' => $id, - 'entries' => serialize($this->processing_log[ $this->id ]) - ) - ); - - } - - /** - * Payment Page Header - * Pre 1.8 setup. Will be removed as of version 1.9 - * - * @since 0.1 - * @version 1.2 - */ - public function get_page_header( $site_title = '', $reload = false ) - { - - // Set Logo - $logo = ''; - if (isset($this->prefs['logo']) && ! empty($this->prefs['logo']) ) { - $logo = ''; - - } elseif (isset($this->prefs['logo_url']) && ! empty($this->prefs['logo_url']) ) { - $logo = ''; - - } elseif (isset($this->gateway_logo_url) && ! empty($this->gateway_logo_url) ) { - $logo = ''; - } - - // Set Title - if ($this->sandbox_mode ) { - $title = __('Test Payment', 'mycred'); - - } elseif (isset($this->label) ) { - $title = $this->label; - - } else { - $title = __('Payment', 'mycred'); - } - - if (! isset($this->transaction_id) ) { - $this->transaction_id = ''; - } - - ?> + elseif ( isset( $this->prefs['logo_url'] ) && ! empty( $this->prefs['logo_url'] ) ) + $logo = ''; + + elseif ( isset( $this->gateway_logo_url ) && ! empty( $this->gateway_logo_url ) ) + $logo = ''; + + // Set Title + if ( $this->sandbox_mode ) + $title = __( 'Test Payment', 'mycred' ); + + elseif ( isset( $this->label ) ) + $title = $this->label; + + else + $title = __( 'Payment', 'mycred' ); + + if ( ! isset( $this->transaction_id ) ) + $this->transaction_id = ''; + +?> > - - - - <?php echo $site_title; ?> - - '; - } ?> - - - - - id); ?> + + + + <?php echo $site_title; ?> + + '; ?> + + + + + id ); ?> -
    -
    - -
    -
    -

    -

    -
    -
    - id); - - } - public function purchase_header( $title = '', $reload = false ) - { - $this->get_page_header($title, $reload); - } - - /** - * Payment Page Footer - * - * @since 0.1 - * @version 1.1 - */ - public function get_page_footer() - { - - do_action('mycred_buycred_page_footer', $this->id); - - ?> - - - get_page_footer(); - } - - /** - * Get Buyers Name - * - * @since 1.6 - * @version 1.0 - */ - public function get_buyers_name( $user_id = null ) - { - - if ($user_id === null ) { return ''; - } - - $user = get_userdata($user_id); - if (! isset($user->ID) ) { return $user_id; - } - - if (! empty($user->first_name) && ! empty($user->last_name) ) { - $name = $user->first_name . ' ' . $user->last_name; - - } elseif (class_exists('WooCommerce') ) { - $name = get_user_meta($user_id, 'billing_first_name', true) . ' ' . get_user_meta($user_id, 'billing_last_name', true); - - } else { - $name = $user->display_name; - } - - return $name; - - } - - /** - * Get Debug - * - * @since 1.0 - * @version 1.0 - */ - public function get_debug() - { - - ?> +
    +
    + +
    +
    +

    +

    +
    +
    +id ); + + } + public function purchase_header( $title = '', $reload = false ) { + $this->get_page_header( $title, $reload ); + } + + /** + * Payment Page Footer + * @since 0.1 + * @version 1.1 + */ + public function get_page_footer() { + + do_action( 'mycred_buycred_page_footer', $this->id ); + +?> + + +get_page_footer(); + } + + /** + * Get Buyers Name + * @since 1.6 + * @version 1.0 + */ + public function get_buyers_name( $user_id = NULL ) { + + if ( $user_id === NULL ) return ''; + + $user = get_userdata( $user_id ); + if ( ! isset( $user->ID ) ) return $user_id; + + if ( ! empty( $user->first_name ) && ! empty( $user->last_name ) ) + $name = $user->first_name . ' ' . $user->last_name; + + elseif ( class_exists( 'WooCommerce' ) ) + $name = get_user_meta( $user_id, 'billing_first_name', true ) . ' ' . get_user_meta( $user_id, 'billing_last_name', true ); + + else + $name = $user->display_name; + + return $name; + + } + + /** + * Get Debug + * @since 1.0 + * @version 1.0 + */ + public function get_debug() { + +?>

    - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + +
    status); ?>
    request); ?>
    response); ?>
    status ); ?>
    request ); ?>
    response ); ?>
    - errors) ) { return; - } - - $errors = array(); - foreach ( $this->errors as $form_field => $error_message ) { - $errors[] = $error_message; - } - - ?> -
    ', $errors); ?>
    - id); - - // Logo - if (empty($logo_url) ) { - $logo_url = plugins_url('images/cred-icon32.png', myCRED_THIS); - } - - // Hidden Fields - $hidden_fields = apply_filters("mycred_{$id}_purchase_fields", $hidden_fields, $this); - - ?> +errors ) ) return; + + $errors = array(); + foreach ( $this->errors as $form_field => $error_message ) + $errors[] = $error_message; + +?> +
    ', $errors ); ?>
    +id ); + + // Logo + if ( empty( $logo_url ) ) + $logo_url = plugins_url( 'images/cred-icon32.png', myCRED_THIS ); + + // Hidden Fields + $hidden_fields = apply_filters( "mycred_{$id}_purchase_fields", $hidden_fields, $this ); + +?>
    -
    -
    - $value ) { echo '' . "\n"; - } ?> - Loading - -

    -
    -
    +
    +
    + $value ) echo '' . "\n"; ?> + Loading + +

    +
    +
    - - get_page_redirect($hidden_fields, $location, $custom_html, $sales_data); - } - - /** - * POST to data - * - * @since 0.1 - * @version 1.2 - */ - public function POST_to_data( $unset = false ) - { - - $data = array(); - foreach ( $_POST as $key => $value ) { - $data[ $key ] = stripslashes($value); - } - if ($unset ) { - unset($_POST); - } - - return $data; - - } - - /** - * Transaction ID unique - * Searches the Log for a given transaction. - * - * @returns (bool) true if transaction id is unique or false - * @since 0.1 - * @version 1.0.2 - */ - public function transaction_id_is_unique( $transaction_id = '' ) - { - - if (empty($transaction_id) ) { return false; - } - - global $wpdb, $mycred_log_table; - - // Make sure this is a new transaction - $sql = " + +get_page_redirect( $hidden_fields, $location, $custom_html, $sales_data ); + } + + /** + * POST to data + * @since 0.1 + * @version 1.2 + */ + public function POST_to_data( $unset = false ) { + + $data = array(); + foreach ( $_POST as $key => $value ) { + $data[ $key ] = stripslashes( $value ); + } + if ( $unset ) + unset( $_POST ); + + return $data; + + } + + /** + * Transaction ID unique + * Searches the Log for a given transaction. + * + * @returns (bool) true if transaction id is unique or false + * @since 0.1 + * @version 1.0.2 + */ + public function transaction_id_is_unique( $transaction_id = '' ) { + + if ( empty( $transaction_id ) ) return false; + + global $wpdb, $mycred_log_table; + + // Make sure this is a new transaction + $sql = " SELECT * FROM {$mycred_log_table} WHERE ref = %s AND data LIKE %s AND ctype = %s;"; - $gateway = str_replace('-', '_', $this->id); - $gateway_id = 'buy_creds_with_' . $gateway; - - $check = $wpdb->get_results($wpdb->prepare($sql, $gateway_id, "%:\"" . $transaction_id . "\";%", $this->mycred_type)); - if ($wpdb->num_rows > 0 ) { return false; - } - - return true; - - } - - /** - * Create Unique Transaction ID - * Returns a unique transaction ID that has no been used by buyCRED yet. - * - * @since 1.4 - * @version 1.0.1 - */ - public function create_unique_transaction_id() - { - - global $wpdb, $mycred_log_table; - - do { - - $id = strtoupper(wp_generate_password(12, false, false)); - $query = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$mycred_log_table} WHERE ref LIKE %s AND data LIKE %s;", 'buy_creds_with_%', "%:\"" . $id . "\";%")); - - } while ( ! empty($query) ); - - return $id; - - } - - /** - * Create Token - * Returns a wp nonce - * - * @since 0.1 - * @version 1.0 - */ - public function create_token( $user_id = null ) - { - - return wp_create_nonce('mycred-buy-' . $this->id); - - } - - /** - * Verify Token - * Based on wp_verify_nonce() this function requires the user id used when the token - * was created as by default not logged in users would generate different tokens causing us - * to fail. - * - * @param $user_id (int) required user id - * @param $nonce (string) required nonce to check - * @returns true or false - * @since 0.1 - * @version 1.0.1 - */ - public function verify_token( $user_id, $nonce ) - { - - $uid = absint($user_id); - $i = wp_nonce_tick(); - - if (substr(wp_hash($i . 'mycred-buy-' . $this->id . $uid, 'nonce'), -12, 10) == $nonce ) { - return true; - } - if (substr(wp_hash(( $i - 1 ) . 'mycred-buy-' . $this->id . $uid, 'nonce'), -12, 10) === $nonce ) { - return true; - } - - return false; - - } - - /** - * Encode Sales Data - * - * @since 0.1 - * @version 1.1 - */ - public function encode_sales_data( $data ) - { - - $protect = new myCRED_Protect(); - if ($protect !== false ) { - return $protect->do_encode($data); - } - - return $data; - - } - - /** - * Decode Sales Data - * - * @since 0.1 - * @version 1.1 - */ - public function decode_sales_data( $data ) - { - - $protect = new myCRED_Protect(); - if ($protect !== false ) { - return $protect->do_decode($data); - } - - return $data; - - } - - /** - * Currencies Dropdown - * - * @since 0.1 - * @version 1.0.2 - */ - public function currencies_dropdown( $name = '', $js = '' ) - { - - $currencies = array( - 'USD' => 'US Dollars', - 'AUD' => 'Australian Dollars', - 'CAD' => 'Canadian Dollars', - 'EUR' => 'Euro', - 'GBP' => 'British Pound Sterling', - 'JPY' => 'Japanese Yen', - 'NZD' => 'New Zealand Dollars', - 'CHF' => 'Swiss Francs', - 'HKD' => 'Hong Kong Dollars', - 'SGD' => 'Singapore Dollars', - 'SEK' => 'Swedish Kronor', - 'DKK' => 'Danish Kroner', - 'PLN' => 'Polish Zloty', - 'NOK' => 'Norwegian Kronor', - 'HUF' => 'Hungarian Forint', - 'CZK' => 'Check Koruna', - 'ILS' => 'Israeli Shekel', - 'MXN' => 'Mexican Peso', - 'BRL' => 'Brazilian Real', - 'MYR' => 'Malaysian Ringgits', - 'PHP' => 'Philippine Pesos', - 'RUB' => 'Russian Ruble', - 'TWD' => 'Taiwan New Dollars', - 'THB' => 'Thai Baht' - ); - $currencies = apply_filters('mycred_dropdown_currencies', $currencies, $this->id); - $currencies = apply_filters('mycred_dropdown_currencies_' . $this->id, $currencies); - - if ($js != '' ) { - $js = ' data-update="' . $js . '"'; - } - - echo ''; - - } - - /** - * Item Type Dropdown - * - * @since 0.1 - * @version 1.0 - */ - public function item_types_dropdown( $name = '' ) - { - - $types = array( - 'product' => 'Product', - 'service' => 'Service', - 'donation' => 'Donation' - ); - $types = apply_filters('mycred_dropdown_item_types', $types); - - echo ''; - - } - - /** - * Countries Dropdown Options - * - * @since 0.1 - * @version 1.0 - */ - public function list_option_countries( $selected = '' ) - { - - $countries = array ( - "US" => "UNITED STATES", - "AF" => "AFGHANISTAN", - "AL" => "ALBANIA", - "DZ" => "ALGERIA", - "AS" => "AMERICAN SAMOA", - "AD" => "ANDORRA", - "AO" => "ANGOLA", - "AI" => "ANGUILLA", - "AQ" => "ANTARCTICA", - "AG" => "ANTIGUA AND BARBUDA", - "AR" => "ARGENTINA", - "AM" => "ARMENIA", - "AW" => "ARUBA", - "AU" => "AUSTRALIA", - "AT" => "AUSTRIA", - "AZ" => "AZERBAIJAN", - "BS" => "BAHAMAS", - "BH" => "BAHRAIN", - "BD" => "BANGLADESH", - "BB" => "BARBADOS", - "BY" => "BELARUS", - "BE" => "BELGIUM", - "BZ" => "BELIZE", - "BJ" => "BENIN", - "BM" => "BERMUDA", - "BT" => "BHUTAN", - "BO" => "BOLIVIA", - "BA" => "BOSNIA AND HERZEGOVINA", - "BW" => "BOTSWANA", - "BV" => "BOUVET ISLAND", - "BR" => "BRAZIL", - "IO" => "BRITISH INDIAN OCEAN TERRITORY", - "BN" => "BRUNEI DARUSSALAM", - "BG" => "BULGARIA", - "BF" => "BURKINA FASO", - "BI" => "BURUNDI", - "KH" => "CAMBODIA", - "CM" => "CAMEROON", - "CA" => "CANADA", - "CV" => "CAPE VERDE", - "KY" => "CAYMAN ISLANDS", - "CF" => "CENTRAL AFRICAN REPUBLIC", - "TD" => "CHAD", - "CL" => "CHILE", - "CN" => "CHINA", - "CX" => "CHRISTMAS ISLAND", - "CC" => "COCOS (KEELING) ISLANDS", - "CO" => "COLOMBIA", - "KM" => "COMOROS", - "CG" => "CONGO", - "CD" => "CONGO, THE DEMOCRATIC REPUBLIC OF THE", - "CK" => "COOK ISLANDS", - "CR" => "COSTA RICA", - "CI" => "COTE D'IVOIRE", - "HR" => "CROATIA", - "CU" => "CUBA", - "CY" => "CYPRUS", - "CZ" => "CZECH REPUBLIC", - "DK" => "DENMARK", - "DJ" => "DJIBOUTI", - "DM" => "DOMINICA", - "DO" => "DOMINICAN REPUBLIC", - "EC" => "ECUADOR", - "EG" => "EGYPT", - "SV" => "EL SALVADOR", - "GQ" => "EQUATORIAL GUINEA", - "ER" => "ERITREA", - "EE" => "ESTONIA", - "ET" => "ETHIOPIA", - "FK" => "FALKLAND ISLANDS (MALVINAS)", - "FO" => "FAROE ISLANDS", - "FJ" => "FIJI", - "FI" => "FINLAND", - "FR" => "FRANCE", - "GF" => "FRENCH GUIANA", - "PF" => "FRENCH POLYNESIA", - "TF" => "FRENCH SOUTHERN TERRITORIES", - "GA" => "GABON", - "GM" => "GAMBIA", - "GE" => "GEORGIA", - "DE" => "GERMANY", - "GH" => "GHANA", - "GI" => "GIBRALTAR", - "GR" => "GREECE", - "GL" => "GREENLAND", - "GD" => "GRENADA", - "GP" => "GUADELOUPE", - "GU" => "GUAM", - "GT" => "GUATEMALA", - "GN" => "GUINEA", - "GW" => "GUINEA-BISSAU", - "GY" => "GUYANA", - "HT" => "HAITI", - "HM" => "HEARD ISLAND AND MCDONALD ISLANDS", - "VA" => "HOLY SEE (VATICAN CITY STATE)", - "HN" => "HONDURAS", - "HK" => "HONG KONG", - "HU" => "HUNGARY", - "IS" => "ICELAND", - "IN" => "INDIA", - "ID" => "INDONESIA", - "IR" => "IRAN, ISLAMIC REPUBLIC OF", - "IQ" => "IRAQ", - "IE" => "IRELAND", - "IL" => "ISRAEL", - "IT" => "ITALY", - "JM" => "JAMAICA", - "JP" => "JAPAN", - "JO" => "JORDAN", - "KZ" => "KAZAKHSTAN", - "KE" => "KENYA", - "KI" => "KIRIBATI", - "KP" => "KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF", - "KR" => "KOREA, REPUBLIC OF", - "KW" => "KUWAIT", - "KG" => "KYRGYZSTAN", - "LA" => "LAO PEOPLE'S DEMOCRATIC REPUBLIC", - "LV" => "LATVIA", - "LB" => "LEBANON", - "LS" => "LESOTHO", - "LR" => "LIBERIA", - "LY" => "LIBYAN ARAB JAMAHIRIYA", - "LI" => "LIECHTENSTEIN", - "LT" => "LITHUANIA", - "LU" => "LUXEMBOURG", - "MO" => "MACAO", - "MK" => "MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF", - "MG" => "MADAGASCAR", - "MW" => "MALAWI", - "MY" => "MALAYSIA", - "MV" => "MALDIVES", - "ML" => "MALI", - "MT" => "MALTA", - "MH" => "MARSHALL ISLANDS", - "MQ" => "MARTINIQUE", - "MR" => "MAURITANIA", - "MU" => "MAURITIUS", - "YT" => "MAYOTTE", - "MX" => "MEXICO", - "FM" => "MICRONESIA, FEDERATED STATES OF", - "MD" => "MOLDOVA, REPUBLIC OF", - "MC" => "MONACO", - "MN" => "MONGOLIA", - "MS" => "MONTSERRAT", - "MA" => "MOROCCO", - "MZ" => "MOZAMBIQUE", - "MM" => "MYANMAR", - "NA" => "NAMIBIA", - "NR" => "NAURU", - "NP" => "NEPAL", - "NL" => "NETHERLANDS", - "AN" => "NETHERLANDS ANTILLES", - "NC" => "NEW CALEDONIA", - "NZ" => "NEW ZEALAND", - "NI" => "NICARAGUA", - "NE" => "NIGER", - "NG" => "NIGERIA", - "NU" => "NIUE", - "NF" => "NORFOLK ISLAND", - "MP" => "NORTHERN MARIANA ISLANDS", - "NO" => "NORWAY", - "OM" => "OMAN", - "PK" => "PAKISTAN", - "PW" => "PALAU", - "PS" => "PALESTINIAN TERRITORY, OCCUPIED", - "PA" => "PANAMA", - "PG" => "PAPUA NEW GUINEA", - "PY" => "PARAGUAY", - "PE" => "PERU", - "PH" => "PHILIPPINES", - "PN" => "PITCAIRN", - "PL" => "POLAND", - "PT" => "PORTUGAL", - "PR" => "PUERTO RICO", - "QA" => "QATAR", - "RE" => "REUNION", - "RO" => "ROMANIA", - "RU" => "RUSSIAN FEDERATION", - "RW" => "RWANDA", - "SH" => "SAINT HELENA", - "KN" => "SAINT KITTS AND NEVIS", - "LC" => "SAINT LUCIA", - "PM" => "SAINT PIERRE AND MIQUELON", - "VC" => "SAINT VINCENT AND THE GRENADINES", - "WS" => "SAMOA", - "SM" => "SAN MARINO", - "ST" => "SAO TOME AND PRINCIPE", - "SA" => "SAUDI ARABIA", - "SN" => "SENEGAL", - "CS" => "SERBIA AND MONTENEGRO", - "SC" => "SEYCHELLES", - "SL" => "SIERRA LEONE", - "SG" => "SINGAPORE", - "SK" => "SLOVAKIA", - "SI" => "SLOVENIA", - "SB" => "SOLOMON ISLANDS", - "SO" => "SOMALIA", - "ZA" => "SOUTH AFRICA", - "GS" => "SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS", - "ES" => "SPAIN", - "LK" => "SRI LANKA", - "SD" => "SUDAN", - "SR" => "SURINAME", - "SJ" => "SVALBARD AND JAN MAYEN", - "SZ" => "SWAZILAND", - "SE" => "SWEDEN", - "CH" => "SWITZERLAND", - "SY" => "SYRIAN ARAB REPUBLIC", - "TW" => "TAIWAN, PROVINCE OF CHINA", - "TJ" => "TAJIKISTAN", - "TZ" => "TANZANIA, UNITED REPUBLIC OF", - "TH" => "THAILAND", - "TL" => "TIMOR-LESTE", - "TG" => "TOGO", - "TK" => "TOKELAU", - "TO" => "TONGA", - "TT" => "TRINIDAD AND TOBAGO", - "TN" => "TUNISIA", - "TR" => "TURKEY", - "TM" => "TURKMENISTAN", - "TC" => "TURKS AND CAICOS ISLANDS", - "TV" => "TUVALU", - "UG" => "UGANDA", - "UA" => "UKRAINE", - "AE" => "UNITED ARAB EMIRATES", - "GB" => "UNITED KINGDOM", - "US" => "UNITED STATES", - "UM" => "UNITED STATES MINOR OUTLYING ISLANDS", - "UY" => "URUGUAY", - "UZ" => "UZBEKISTAN", - "VU" => "VANUATU", - "VE" => "VENEZUELA", - "VN" => "VIET NAM", - "VG" => "VIRGIN ISLANDS, BRITISH", - "VI" => "VIRGIN ISLANDS, U.S.", - "WF" => "WALLIS AND FUTUNA", - "EH" => "WESTERN SAHARA", - "YE" => "YEMEN", - "ZM" => "ZAMBIA", - "ZW" => "ZIMBABWE" - ); - $countries = apply_filters('mycred_list_option_countries', $countries); - - foreach ( $countries as $code => $cname ) { - echo ''; - } - - } - - /** - * US States Dropdown Options - * - * @since 0.1 - * @version 1.0 - */ - public function list_option_us_states( $selected = '', $non_us = false ) - { - - $states = array ( - "AL" => "Alabama", - "AK" => "Alaska", - "AZ" => "Arizona", - "AR" => "Arkansas", - "CA" => "California", - "CO" => "Colorado", - "CT" => "Connecticut", - "DC" => "D.C.", - "DE" => "Delaware", - "FL" => "Florida", - "GA" => "Georgia", - "HI" => "Hawaii", - "ID" => "Idaho", - "IL" => "Illinois", - "IN" => "Indiana", - "IA" => "Iowa", - "KS" => "Kansas", - "KY" => "Kentucky", - "LA" => "Louisiana", - "ME" => "Maine", - "MD" => "Maryland", - "MA" => "Massachusetts", - "MI" => "Michigan", - "MN" => "Minnesota", - "MS" => "Mississippi", - "MO" => "Missouri", - "MT" => "Montana", - "NE" => "Nebraska", - "NV" => "Nevada", - "NH" => "New Hampshire", - "NJ" => "New Jersey", - "NM" => "New Mexico", - "NY" => "New York", - "NC" => "North Carolina", - "ND" => "North Dakota", - "OH" => "Ohio", - "OK" => "Oklahoma", - "OR" => "Oregon", - "PA" => "Pennsylvania", - "RI" => "Rhode Island", - "SC" => "South Carolina", - "SD" => "South Dakota", - "TN" => "Tennessee", - "TX" => "Texas", - "UT" => "Utah", - "VT" => "Vermont", - "VA" => "Virginia", - "WA" => "Washington", - "WV" => "West Virginia", - "WI" => "Wisconsin", - "WY" => "Wyoming" - ); - $states = apply_filters('mycred_list_option_us', $states); - - $outside = 'Outside US'; - if ($non_us == 'top' ) { echo ''; - } - foreach ( $states as $code => $cname ) { - echo ''; - } - if ($non_us == 'bottom' ) { echo ''; - } - - } - - /** - * Months Dropdown Options - * - * @since 0.1 - * @version 1.0 - */ - public function list_option_months( $selected = '' ) - { - - $months = array ( - "01" => __('January', 'mycred'), - "02" => __('February', 'mycred'), - "03" => __('March', 'mycred'), - "04" => __('April', 'mycred'), - "05" => __('May', 'mycred'), - "06" => __('June', 'mycred'), - "07" => __('July', 'mycred'), - "08" => __('August', 'mycred'), - "09" => __('September', 'mycred'), - "10" => __('October', 'mycred'), - "11" => __('November', 'mycred'), - "12" => __('December', 'mycred') - ); - - foreach ( $months as $number => $text ) { - echo ''; - } - - } - - /** - * Years Dropdown Options - * - * @since 0.1 - * @version 1.0 - */ - public function list_option_card_years( $selected = '', $number = 16 ) - { - - $now = current_time('timestamp'); - $yy = date('y', $now); - $yyyy = date('Y', $now); - $count = 0; - $options = array(); - - while ( $count <= (int) $number ) { - $count ++; - if ($count > 1 ) { - $yy++; - $yyyy++; - } - $options[ $yy ] = $yyyy; - } - - foreach ( $options as $key => $value ) { - echo ''; - } - - } - - /** - * IPN - Has Required Fields - * - * @since 1.4 - * @version 1.0 - */ - public function IPN_has_required_fields( $required_fields = array(), $method = 'REQUEST' ) - { - - $missing = 0; - foreach ( $required_fields as $field_key ) { - if ($method == 'POST' ) { - if (! isset($_POST[ $field_key ]) ) { - $missing ++; - } - } - elseif ($method == 'GET' ) { - if (! isset($_GET[ $field_key ]) ) { - $missing ++; - } - } - elseif ($method == 'REQUEST' ) { - if (! isset($_REQUEST[ $field_key ]) ) { - $missing ++; - } - } - else { - if (! isset($method[ $field_key ]) ) { - $missing ++; - } - } - } - - if ($missing > 0 ) { - $result = false; - } else { - $result = true; - } - - $result = apply_filters('mycred_buycred_IPN_missing', $result, $required_fields, $this->id); - - return $result; - - } - - /** - * IPN - Is Valid Call - * - * @since 1.4 - * @version 1.0 - */ - public function IPN_is_valid_call() - { - - return false; - - } - - /** - * IPN - Is Valid Sale - * - * @since 1.4 - * @version 1.1 - */ - public function IPN_is_valid_sale( $sales_data_key = '', $cost_key = '', $transactionid_key = '', $method = '' ) - { - - if ($method == 'POST' ) { - $post_id = absint( $_POST[ $sales_data_key ] ); - } elseif ($method == 'GET' ) { - $post_id = absint( $_GET[ $sales_data_key ] ); - } else { - $post_id = absint( $_REQUEST[ $sales_data_key ] ); - } - - $pending_payment = $this->get_pending_payment($post_id); - if ($pending_payment === false ) { return false; - } - - $result = true; - - if ($method == 'POST' ) { - $price = floatval( $_POST[ $cost_key ] ); - } elseif ($method == 'GET' ) { - $price = floatval( $_GET[ $cost_key ] ); - } else { - $price = floatval( $_REQUEST[ $cost_key ] ); - } - - if ($result === true && $pending_payment['cost'] != $price ) { - $result = false; - } - - if ($result === true && isset($this->prefs['currency']) && $this->prefs['currency'] != $pending_payment['currency'] ) { - $result = false; - } - - if ($method == 'POST' ) { - $transaction_id = sanitize_title( $_POST[ $transactionid_key ] ); - } elseif ($method == 'GET' ) { - $transaction_id = sanitize_title( $_GET[ $transactionid_key ] ); - } else { - $transaction_id = sanitize_title( $_REQUEST[ $transactionid_key ] ); - } - - if ($result === true && ! $this->transaction_id_is_unique($transaction_id) ) { - $result = false; - } - - $result = apply_filters('mycred_buycred_valid_sale', $result, $sales_data_key, $cost_key, $transactionid_key, $method, $this); - - if ($result === true ) { - return $decoded_data; - } - - return $result; - - } - - /** - * Complete Payment - * - * @since 1.4 - * @version 1.4 - */ - public function complete_payment( $pending_payment = null, $transaction_id = '' ) - { - - if ($pending_payment === null ) { return false; - } - - $reply = false; - $mycred = mycred($pending_payment->point_type); - - $reference = 'buy_creds_with_' . str_replace(array( ' ', '-' ), '_', $this->id); - $sales_data = array( - 'to' => $pending_payment->recipient_id, - 'from' => $pending_payment->buyer_id, - 'amount' => $pending_payment->amount, - 'cost' => $pending_payment->cost, - 'currency' => $pending_payment->currency, - 'ctype' => $pending_payment->point_type - ); - $data = array( 'ref_type' => 'user', 'txn_id' => $transaction_id, 'sales_data' => implode('|', $sales_data) ); - - if (! $mycred->has_entry($reference, $pending_payment->buyer_id, $pending_payment->recipient_id, $data, $pending_payment->point_type) ) { - - add_filter('mycred_get_email_events', array( $this, 'email_notice' ), 10, 2); - $reply = $mycred->add_creds( - $reference, - $pending_payment->recipient_id, - $pending_payment->amount, - $this->get_log_entry($pending_payment->recipient_id, $pending_payment->buyer_id), - $pending_payment->buyer_id, - $data, - $pending_payment->point_type - ); - remove_filter('mycred_get_email_events', array( $this, 'email_notice' ), 10, 2); - - } - - return apply_filters('mycred_buycred_complete_payment', $reply, $transaction_id, $this); - - } - - /** - * Email Notice Add-on Support - * - * @since 1.5.4 - * @version 1.0 - */ - public function email_notice( $events, $request ) - { - - if (substr($request['ref'], 0, 15) == 'buy_creds_with_' ) { - $events[] = 'buy_creds|positive'; - } - - return $events; - - } - - /** - * Trash Pending Payment - * - * @since 1.5.3 - * @version 1.0.1 - */ - public function trash_pending_payment( $payment_id ) - { - - return buycred_trash_pending_payment($payment_id); - - } - - } + $gateway = str_replace( '-', '_', $this->id ); + $gateway_id = 'buy_creds_with_' . $gateway; + + $check = $wpdb->get_results( $wpdb->prepare( $sql, $gateway_id, "%:\"" . $transaction_id . "\";%", $this->mycred_type ) ); + if ( $wpdb->num_rows > 0 ) return false; + + return true; + + } + + /** + * Create Unique Transaction ID + * Returns a unique transaction ID that has no been used by buyCRED yet. + * @since 1.4 + * @version 1.0.1 + */ + public function create_unique_transaction_id() { + + global $wpdb, $mycred_log_table; + + do { + + $id = strtoupper( wp_generate_password( 12, false, false ) ); + $query = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$mycred_log_table} WHERE ref LIKE %s AND data LIKE %s;", 'buy_creds_with_%', "%:\"" . $id . "\";%" ) ); + + } while ( ! empty( $query ) ); + + return $id; + + } + + /** + * Create Token + * Returns a wp nonce + * @since 0.1 + * @version 1.0 + */ + public function create_token( $user_id = NULL ) { + + return wp_create_nonce( 'mycred-buy-' . $this->id ); + + } + + /** + * Verify Token + * Based on wp_verify_nonce() this function requires the user id used when the token + * was created as by default not logged in users would generate different tokens causing us + * to fail. + * @param $user_id (int) required user id + * @param $nonce (string) required nonce to check + * @returns true or false + * @since 0.1 + * @version 1.0.1 + */ + public function verify_token( $user_id, $nonce ) { + + $uid = absint( $user_id ); + $i = wp_nonce_tick(); + + if ( substr( wp_hash( $i . 'mycred-buy-' . $this->id . $uid, 'nonce' ), -12, 10 ) == $nonce ) + return true; + if ( substr( wp_hash( ( $i - 1 ) . 'mycred-buy-' . $this->id . $uid, 'nonce' ), -12, 10 ) === $nonce ) + return true; + + return false; + + } + + /** + * Encode Sales Data + * @since 0.1 + * @version 1.1 + */ + public function encode_sales_data( $data ) { + + $protect = new myCRED_Protect(); + if ( $protect !== false ) + return $protect->do_encode( $data ); + + return $data; + + } + + /** + * Decode Sales Data + * @since 0.1 + * @version 1.1 + */ + public function decode_sales_data( $data ) { + + $protect = new myCRED_Protect(); + if ( $protect !== false ) + return $protect->do_decode( $data ); + + return $data; + + } + + /** + * Currencies Dropdown + * @since 0.1 + * @version 1.0.2 + */ + public function currencies_dropdown( $name = '', $js = '' ) { + + $currencies = array( + 'USD' => 'US Dollars', + 'AUD' => 'Australian Dollars', + 'CAD' => 'Canadian Dollars', + 'EUR' => 'Euro', + 'GBP' => 'British Pound Sterling', + 'JPY' => 'Japanese Yen', + 'NZD' => 'New Zealand Dollars', + 'CHF' => 'Swiss Francs', + 'HKD' => 'Hong Kong Dollars', + 'SGD' => 'Singapore Dollars', + 'SEK' => 'Swedish Kronor', + 'DKK' => 'Danish Kroner', + 'PLN' => 'Polish Zloty', + 'NOK' => 'Norwegian Kronor', + 'HUF' => 'Hungarian Forint', + 'CZK' => 'Check Koruna', + 'ILS' => 'Israeli Shekel', + 'MXN' => 'Mexican Peso', + 'BRL' => 'Brazilian Real', + 'MYR' => 'Malaysian Ringgits', + 'PHP' => 'Philippine Pesos', + 'RUB' => 'Russian Ruble', + 'TWD' => 'Taiwan New Dollars', + 'THB' => 'Thai Baht' + ); + $currencies = apply_filters( 'mycred_dropdown_currencies', $currencies, $this->id ); + $currencies = apply_filters( 'mycred_dropdown_currencies_' . $this->id, $currencies ); + + if ( $js != '' ) + $js = ' data-update="' . $js . '"'; + + echo ''; + + } + + /** + * Item Type Dropdown + * @since 0.1 + * @version 1.0 + */ + public function item_types_dropdown( $name = '' ) { + + $types = array( + 'product' => 'Product', + 'service' => 'Service', + 'donation' => 'Donation' + ); + $types = apply_filters( 'mycred_dropdown_item_types', $types ); + + echo ''; + + } + + /** + * Countries Dropdown Options + * @since 0.1 + * @version 1.0 + */ + public function list_option_countries( $selected = '' ) { + + $countries = array ( + "US" => "UNITED STATES", + "AF" => "AFGHANISTAN", + "AL" => "ALBANIA", + "DZ" => "ALGERIA", + "AS" => "AMERICAN SAMOA", + "AD" => "ANDORRA", + "AO" => "ANGOLA", + "AI" => "ANGUILLA", + "AQ" => "ANTARCTICA", + "AG" => "ANTIGUA AND BARBUDA", + "AR" => "ARGENTINA", + "AM" => "ARMENIA", + "AW" => "ARUBA", + "AU" => "AUSTRALIA", + "AT" => "AUSTRIA", + "AZ" => "AZERBAIJAN", + "BS" => "BAHAMAS", + "BH" => "BAHRAIN", + "BD" => "BANGLADESH", + "BB" => "BARBADOS", + "BY" => "BELARUS", + "BE" => "BELGIUM", + "BZ" => "BELIZE", + "BJ" => "BENIN", + "BM" => "BERMUDA", + "BT" => "BHUTAN", + "BO" => "BOLIVIA", + "BA" => "BOSNIA AND HERZEGOVINA", + "BW" => "BOTSWANA", + "BV" => "BOUVET ISLAND", + "BR" => "BRAZIL", + "IO" => "BRITISH INDIAN OCEAN TERRITORY", + "BN" => "BRUNEI DARUSSALAM", + "BG" => "BULGARIA", + "BF" => "BURKINA FASO", + "BI" => "BURUNDI", + "KH" => "CAMBODIA", + "CM" => "CAMEROON", + "CA" => "CANADA", + "CV" => "CAPE VERDE", + "KY" => "CAYMAN ISLANDS", + "CF" => "CENTRAL AFRICAN REPUBLIC", + "TD" => "CHAD", + "CL" => "CHILE", + "CN" => "CHINA", + "CX" => "CHRISTMAS ISLAND", + "CC" => "COCOS (KEELING) ISLANDS", + "CO" => "COLOMBIA", + "KM" => "COMOROS", + "CG" => "CONGO", + "CD" => "CONGO, THE DEMOCRATIC REPUBLIC OF THE", + "CK" => "COOK ISLANDS", + "CR" => "COSTA RICA", + "CI" => "COTE D'IVOIRE", + "HR" => "CROATIA", + "CU" => "CUBA", + "CY" => "CYPRUS", + "CZ" => "CZECH REPUBLIC", + "DK" => "DENMARK", + "DJ" => "DJIBOUTI", + "DM" => "DOMINICA", + "DO" => "DOMINICAN REPUBLIC", + "EC" => "ECUADOR", + "EG" => "EGYPT", + "SV" => "EL SALVADOR", + "GQ" => "EQUATORIAL GUINEA", + "ER" => "ERITREA", + "EE" => "ESTONIA", + "ET" => "ETHIOPIA", + "FK" => "FALKLAND ISLANDS (MALVINAS)", + "FO" => "FAROE ISLANDS", + "FJ" => "FIJI", + "FI" => "FINLAND", + "FR" => "FRANCE", + "GF" => "FRENCH GUIANA", + "PF" => "FRENCH POLYNESIA", + "TF" => "FRENCH SOUTHERN TERRITORIES", + "GA" => "GABON", + "GM" => "GAMBIA", + "GE" => "GEORGIA", + "DE" => "GERMANY", + "GH" => "GHANA", + "GI" => "GIBRALTAR", + "GR" => "GREECE", + "GL" => "GREENLAND", + "GD" => "GRENADA", + "GP" => "GUADELOUPE", + "GU" => "GUAM", + "GT" => "GUATEMALA", + "GN" => "GUINEA", + "GW" => "GUINEA-BISSAU", + "GY" => "GUYANA", + "HT" => "HAITI", + "HM" => "HEARD ISLAND AND MCDONALD ISLANDS", + "VA" => "HOLY SEE (VATICAN CITY STATE)", + "HN" => "HONDURAS", + "HK" => "HONG KONG", + "HU" => "HUNGARY", + "IS" => "ICELAND", + "IN" => "INDIA", + "ID" => "INDONESIA", + "IR" => "IRAN, ISLAMIC REPUBLIC OF", + "IQ" => "IRAQ", + "IE" => "IRELAND", + "IL" => "ISRAEL", + "IT" => "ITALY", + "JM" => "JAMAICA", + "JP" => "JAPAN", + "JO" => "JORDAN", + "KZ" => "KAZAKHSTAN", + "KE" => "KENYA", + "KI" => "KIRIBATI", + "KP" => "KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF", + "KR" => "KOREA, REPUBLIC OF", + "KW" => "KUWAIT", + "KG" => "KYRGYZSTAN", + "LA" => "LAO PEOPLE'S DEMOCRATIC REPUBLIC", + "LV" => "LATVIA", + "LB" => "LEBANON", + "LS" => "LESOTHO", + "LR" => "LIBERIA", + "LY" => "LIBYAN ARAB JAMAHIRIYA", + "LI" => "LIECHTENSTEIN", + "LT" => "LITHUANIA", + "LU" => "LUXEMBOURG", + "MO" => "MACAO", + "MK" => "MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF", + "MG" => "MADAGASCAR", + "MW" => "MALAWI", + "MY" => "MALAYSIA", + "MV" => "MALDIVES", + "ML" => "MALI", + "MT" => "MALTA", + "MH" => "MARSHALL ISLANDS", + "MQ" => "MARTINIQUE", + "MR" => "MAURITANIA", + "MU" => "MAURITIUS", + "YT" => "MAYOTTE", + "MX" => "MEXICO", + "FM" => "MICRONESIA, FEDERATED STATES OF", + "MD" => "MOLDOVA, REPUBLIC OF", + "MC" => "MONACO", + "MN" => "MONGOLIA", + "MS" => "MONTSERRAT", + "MA" => "MOROCCO", + "MZ" => "MOZAMBIQUE", + "MM" => "MYANMAR", + "NA" => "NAMIBIA", + "NR" => "NAURU", + "NP" => "NEPAL", + "NL" => "NETHERLANDS", + "AN" => "NETHERLANDS ANTILLES", + "NC" => "NEW CALEDONIA", + "NZ" => "NEW ZEALAND", + "NI" => "NICARAGUA", + "NE" => "NIGER", + "NG" => "NIGERIA", + "NU" => "NIUE", + "NF" => "NORFOLK ISLAND", + "MP" => "NORTHERN MARIANA ISLANDS", + "NO" => "NORWAY", + "OM" => "OMAN", + "PK" => "PAKISTAN", + "PW" => "PALAU", + "PS" => "PALESTINIAN TERRITORY, OCCUPIED", + "PA" => "PANAMA", + "PG" => "PAPUA NEW GUINEA", + "PY" => "PARAGUAY", + "PE" => "PERU", + "PH" => "PHILIPPINES", + "PN" => "PITCAIRN", + "PL" => "POLAND", + "PT" => "PORTUGAL", + "PR" => "PUERTO RICO", + "QA" => "QATAR", + "RE" => "REUNION", + "RO" => "ROMANIA", + "RU" => "RUSSIAN FEDERATION", + "RW" => "RWANDA", + "SH" => "SAINT HELENA", + "KN" => "SAINT KITTS AND NEVIS", + "LC" => "SAINT LUCIA", + "PM" => "SAINT PIERRE AND MIQUELON", + "VC" => "SAINT VINCENT AND THE GRENADINES", + "WS" => "SAMOA", + "SM" => "SAN MARINO", + "ST" => "SAO TOME AND PRINCIPE", + "SA" => "SAUDI ARABIA", + "SN" => "SENEGAL", + "CS" => "SERBIA AND MONTENEGRO", + "SC" => "SEYCHELLES", + "SL" => "SIERRA LEONE", + "SG" => "SINGAPORE", + "SK" => "SLOVAKIA", + "SI" => "SLOVENIA", + "SB" => "SOLOMON ISLANDS", + "SO" => "SOMALIA", + "ZA" => "SOUTH AFRICA", + "GS" => "SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS", + "ES" => "SPAIN", + "LK" => "SRI LANKA", + "SD" => "SUDAN", + "SR" => "SURINAME", + "SJ" => "SVALBARD AND JAN MAYEN", + "SZ" => "SWAZILAND", + "SE" => "SWEDEN", + "CH" => "SWITZERLAND", + "SY" => "SYRIAN ARAB REPUBLIC", + "TW" => "TAIWAN, PROVINCE OF CHINA", + "TJ" => "TAJIKISTAN", + "TZ" => "TANZANIA, UNITED REPUBLIC OF", + "TH" => "THAILAND", + "TL" => "TIMOR-LESTE", + "TG" => "TOGO", + "TK" => "TOKELAU", + "TO" => "TONGA", + "TT" => "TRINIDAD AND TOBAGO", + "TN" => "TUNISIA", + "TR" => "TURKEY", + "TM" => "TURKMENISTAN", + "TC" => "TURKS AND CAICOS ISLANDS", + "TV" => "TUVALU", + "UG" => "UGANDA", + "UA" => "UKRAINE", + "AE" => "UNITED ARAB EMIRATES", + "GB" => "UNITED KINGDOM", + "US" => "UNITED STATES", + "UM" => "UNITED STATES MINOR OUTLYING ISLANDS", + "UY" => "URUGUAY", + "UZ" => "UZBEKISTAN", + "VU" => "VANUATU", + "VE" => "VENEZUELA", + "VN" => "VIET NAM", + "VG" => "VIRGIN ISLANDS, BRITISH", + "VI" => "VIRGIN ISLANDS, U.S.", + "WF" => "WALLIS AND FUTUNA", + "EH" => "WESTERN SAHARA", + "YE" => "YEMEN", + "ZM" => "ZAMBIA", + "ZW" => "ZIMBABWE" + ); + $countries = apply_filters( 'mycred_list_option_countries', $countries ); + + foreach ( $countries as $code => $cname ) { + echo ''; + } + + } + + /** + * US States Dropdown Options + * @since 0.1 + * @version 1.0 + */ + public function list_option_us_states( $selected = '', $non_us = false ) { + + $states = array ( + "AL" => "Alabama", + "AK" => "Alaska", + "AZ" => "Arizona", + "AR" => "Arkansas", + "CA" => "California", + "CO" => "Colorado", + "CT" => "Connecticut", + "DC" => "D.C.", + "DE" => "Delaware", + "FL" => "Florida", + "GA" => "Georgia", + "HI" => "Hawaii", + "ID" => "Idaho", + "IL" => "Illinois", + "IN" => "Indiana", + "IA" => "Iowa", + "KS" => "Kansas", + "KY" => "Kentucky", + "LA" => "Louisiana", + "ME" => "Maine", + "MD" => "Maryland", + "MA" => "Massachusetts", + "MI" => "Michigan", + "MN" => "Minnesota", + "MS" => "Mississippi", + "MO" => "Missouri", + "MT" => "Montana", + "NE" => "Nebraska", + "NV" => "Nevada", + "NH" => "New Hampshire", + "NJ" => "New Jersey", + "NM" => "New Mexico", + "NY" => "New York", + "NC" => "North Carolina", + "ND" => "North Dakota", + "OH" => "Ohio", + "OK" => "Oklahoma", + "OR" => "Oregon", + "PA" => "Pennsylvania", + "RI" => "Rhode Island", + "SC" => "South Carolina", + "SD" => "South Dakota", + "TN" => "Tennessee", + "TX" => "Texas", + "UT" => "Utah", + "VT" => "Vermont", + "VA" => "Virginia", + "WA" => "Washington", + "WV" => "West Virginia", + "WI" => "Wisconsin", + "WY" => "Wyoming" + ); + $states = apply_filters( 'mycred_list_option_us', $states ); + + $outside = 'Outside US'; + if ( $non_us == 'top' ) echo ''; + foreach ( $states as $code => $cname ) { + echo ''; + } + if ( $non_us == 'bottom' ) echo ''; + + } + + /** + * Months Dropdown Options + * @since 0.1 + * @version 1.0 + */ + public function list_option_months( $selected = '' ) { + + $months = array ( + "01" => __( 'January', 'mycred' ), + "02" => __( 'February', 'mycred' ), + "03" => __( 'March', 'mycred' ), + "04" => __( 'April', 'mycred' ), + "05" => __( 'May', 'mycred' ), + "06" => __( 'June', 'mycred' ), + "07" => __( 'July', 'mycred' ), + "08" => __( 'August', 'mycred' ), + "09" => __( 'September', 'mycred' ), + "10" => __( 'October', 'mycred' ), + "11" => __( 'November', 'mycred' ), + "12" => __( 'December', 'mycred' ) + ); + + foreach ( $months as $number => $text ) { + echo ''; + } + + } + + /** + * Years Dropdown Options + * @since 0.1 + * @version 1.0 + */ + public function list_option_card_years( $selected = '', $number = 16 ) { + + $now = current_time( 'timestamp' ); + $yy = date( 'y', $now ); + $yyyy = date( 'Y', $now ); + $count = 0; + $options = array(); + + while ( $count <= (int) $number ) { + $count ++; + if ( $count > 1 ) { + $yy++; + $yyyy++; + } + $options[ $yy ] = $yyyy; + } + + foreach ( $options as $key => $value ) { + echo ''; + } + + } + + /** + * IPN - Has Required Fields + * @since 1.4 + * @version 1.0 + */ + public function IPN_has_required_fields( $required_fields = array(), $method = 'REQUEST' ) { + + $missing = 0; + foreach ( $required_fields as $field_key ) { + if ( $method == 'POST' ) { + if ( ! isset( $_POST[ $field_key ] ) ) + $missing ++; + } + elseif ( $method == 'GET' ) { + if ( ! isset( $_GET[ $field_key ] ) ) + $missing ++; + } + elseif ( $method == 'REQUEST' ) { + if ( ! isset( $_REQUEST[ $field_key ] ) ) + $missing ++; + } + else { + if ( ! isset( $method[ $field_key ] ) ) + $missing ++; + } + } + + if ( $missing > 0 ) + $result = false; + else + $result = true; + + $result = apply_filters( 'mycred_buycred_IPN_missing', $result, $required_fields, $this->id ); + + return $result; + + } + + /** + * IPN - Is Valid Call + * @since 1.4 + * @version 1.0 + */ + public function IPN_is_valid_call() { + + return false; + + } + + /** + * IPN - Is Valid Sale + * @since 1.4 + * @version 1.1 + */ + public function IPN_is_valid_sale( $sales_data_key = '', $cost_key = '', $transactionid_key = '', $method = '' ) { + + if ( $method == 'POST' ) + $post_id = absint( $_POST[ $sales_data_key ] ); + elseif ( $method == 'GET' ) + $post_id = absint( $_GET[ $sales_data_key ] ); + else + $post_id = absint( $_REQUEST[ $sales_data_key ] ); + + $pending_payment = $this->get_pending_payment( $post_id ); + if ( $pending_payment === false ) return false; + + $result = true; + + if ( $method == 'POST' ) + $price = floatval( $_POST[ $cost_key ] ); + elseif ( $method == 'GET' ) + $price = floatval( $_GET[ $cost_key ] ); + else + $price = floatval( $_REQUEST[ $cost_key ] ); + + if ( $result === true && $pending_payment['cost'] != $price ) { + $result = false; + } + + if ( $result === true && isset( $this->prefs['currency'] ) && $this->prefs['currency'] != $pending_payment['currency'] ) { + $result = false; + } + + if ( $method == 'POST' ) + $transaction_id = sanitize_title( $_POST[ $transactionid_key ] ); + elseif ( $method == 'GET' ) + $transaction_id = sanitize_title( $_GET[ $transactionid_key ] ); + else + $transaction_id = sanitize_title( $_REQUEST[ $transactionid_key ] ); + + if ( $result === true && ! $this->transaction_id_is_unique( $transaction_id ) ) { + $result = false; + } + + $result = apply_filters( 'mycred_buycred_valid_sale', $result, $sales_data_key, $cost_key, $transactionid_key, $method, $this ); + + if ( $result === true ) + return $decoded_data; + + return $result; + + } + + /** + * Complete Payment + * @since 1.4 + * @version 1.4 + */ + public function complete_payment( $pending_payment = NULL, $transaction_id = '' ) { + + if ( $pending_payment === NULL ) return false; + + $reply = false; + $mycred = mycred( $pending_payment->point_type ); + + $reference = 'buy_creds_with_' . str_replace( array( ' ', '-' ), '_', $this->id ); + $sales_data = array( + 'to' => $pending_payment->recipient_id, + 'from' => $pending_payment->buyer_id, + 'amount' => $pending_payment->amount, + 'cost' => $pending_payment->cost, + 'currency' => $pending_payment->currency, + 'ctype' => $pending_payment->point_type + ); + $data = array( 'ref_type' => 'user', 'txn_id' => $transaction_id, 'sales_data' => implode( '|', $sales_data ) ); + + if ( ! $mycred->has_entry( $reference, $pending_payment->buyer_id, $pending_payment->recipient_id, $data, $pending_payment->point_type ) ) { + + add_filter( 'mycred_get_email_events', array( $this, 'email_notice' ), 10, 2 ); + $reply = $mycred->add_creds( + $reference, + $pending_payment->recipient_id, + $pending_payment->amount, + $this->get_log_entry( $pending_payment->recipient_id, $pending_payment->buyer_id ), + $pending_payment->buyer_id, + $data, + $pending_payment->point_type + ); + remove_filter( 'mycred_get_email_events', array( $this, 'email_notice' ), 10, 2 ); + + } + + return apply_filters( 'mycred_buycred_complete_payment', $reply, $transaction_id, $this ); + + } + + /** + * Email Notice Add-on Support + * @since 1.5.4 + * @version 1.0 + */ + public function email_notice( $events, $request ) { + + if ( substr( $request['ref'], 0, 15 ) == 'buy_creds_with_' ) + $events[] = 'buy_creds|positive'; + + return $events; + + } + + /** + * Trash Pending Payment + * @since 1.5.3 + * @version 1.0.1 + */ + public function trash_pending_payment( $payment_id ) { + + return buycred_trash_pending_payment( $payment_id ); + + } + + } endif; diff --git a/addons/buy-creds/assets/css/admin-style.css b/addons/buy-creds/assets/css/admin-style.css index d531a58..14585f4 100644 --- a/addons/buy-creds/assets/css/admin-style.css +++ b/addons/buy-creds/assets/css/admin-style.css @@ -1,15 +1,15 @@ .mycred-metabox .widget-content .hook-instance .specific-hook-actions { - margin-bottom: 12px !important; + margin-bottom: 12px !important; } .mycred-metabox .widget-content .hook-instance:last-child .specific-hook-actions { - margin-bottom: 0px !important; + margin-bottom: 0px !important; } .mycred-metabox .widget-content .hook-instance .specific-hook-actions .mycred-add-specific-hook { - display: none; + display: none; } .mycred-metabox .widget-content .hook-instance:last-child .specific-hook-actions .mycred-add-specific-hook { - display: initial; + display: initial; } \ No newline at end of file diff --git a/addons/buy-creds/assets/css/index.php b/addons/buy-creds/assets/css/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/assets/css/index.php +++ b/addons/buy-creds/assets/css/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/assets/images/index.php b/addons/buy-creds/assets/images/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/assets/images/index.php +++ b/addons/buy-creds/assets/images/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/assets/index.php b/addons/buy-creds/assets/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/assets/index.php +++ b/addons/buy-creds/assets/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/assets/js/checkout.js b/addons/buy-creds/assets/js/checkout.js index e70dd07..aedf430 100644 --- a/addons/buy-creds/assets/js/checkout.js +++ b/addons/buy-creds/assets/js/checkout.js @@ -1,237 +1,202 @@ /** * buyCRED Checkout - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -jQuery( - function ($) { - - var buyCREDcheckout = $('#buycred-checkout-wrapper'); - var buyCREDform = $('#buycred-checkout-wrapper #buycred-checkout-form'); - var buyCREDcancel = $('#cancel-checkout-wrapper'); - var activeForm; - - var buycred_send_call = function ( formdata ) { +jQuery(function($){ - $.ajax( - { - type : "POST", - data : formdata, - dataType : "JSON", - url : buyCRED.ajaxurl, - success : function ( response ) { + var buyCREDcheckout = $( '#buycred-checkout-wrapper' ); + var buyCREDform = $( '#buycred-checkout-wrapper #buycred-checkout-form' ); + var buyCREDcancel = $( '#cancel-checkout-wrapper' ); + var activeForm; - console.log(response); + var buycred_send_call = function( formdata ) { - if (typeof response.validationFail === "undefined" ) { - buyCREDform.slideUp( - function () { - buyCREDform.empty().append(response).slideDown(); - } - ); - } - else { - buyCREDform.slideUp( - function () { - buyCREDform.empty().append('
    ' + response.errors[0] + '
    ').slideDown(); - } - ); - buyCREDcancel.addClass('on'); - } + $.ajax({ + type : "POST", + data : formdata, + dataType : "JSON", + url : buyCRED.ajaxurl, + success : function( response ) { - } - } - ); - - }; - - $(document).ready( - function () { - - // Forms rendered by mycred_buy - $('body').on( - 'click', '.mycred-buy-link', function (e) { + console.log(response); - if (buyCRED.checkout == 'popup' ) { + if ( typeof response.validationFail === "undefined" ) { + buyCREDform.slideUp(function(){ + buyCREDform.empty().append( response ).slideDown(); + }); + } + else { + buyCREDform.slideUp(function(){ + buyCREDform.empty().append( '
    ' + response.errors[0] + '
    ' ).slideDown(); + }); + buyCREDcancel.addClass( 'on' ); + } - e.preventDefault(); + } + }); - buyCREDcancel.removeClass('on'); - buyCREDcheckout.addClass('open'); + }; - activeForm = $(this); + $(document).ready(function(){ - var targeturl = $(this).attr('href'); - var formdata = JSON.parse('{"' + decodeURI(targeturl).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}'); - formdata['ajax'] = 1; - formdata['mycred_buy'] = $(this).data('gateway'); - console.log(formdata); - buycred_send_call(formdata); + // Forms rendered by mycred_buy + $( 'body' ).on( 'click', '.mycred-buy-link', function(e){ - } + if ( buyCRED.checkout == 'popup' ) { - } - ); + e.preventDefault(); - // Forms rendered by mycred_buy_form - $('body').on( - 'submit', '.myCRED-buy-form', function (e) { + buyCREDcancel.removeClass( 'on' ); + buyCREDcheckout.addClass( 'open' ); - if (buyCRED.checkout == 'popup' ) { + activeForm = $(this); - e.preventDefault(); + var targeturl = $(this).attr( 'href' ); + var formdata = JSON.parse( '{"' + decodeURI( targeturl ).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}' ); + formdata['ajax'] = 1; + formdata['mycred_buy'] = $(this).data( 'gateway' ); +console.log( formdata ); + buycred_send_call( formdata ); - buyCREDcancel.removeClass('on'); - buyCREDcheckout.addClass('open'); + } - activeForm = $(this); + }); - var formdata = { ajax : 1 }; - var fields = $(this).find('input'); - var selects = $(this).find('select'); + // Forms rendered by mycred_buy_form + $( 'body' ).on( 'submit', '.myCRED-buy-form', function(e){ - fields.each( - function (index, item) { - var element = $(this); - if (element.attr('name') !== undefined ) { - formdata[ element.attr('name') ] = element.val(); - } - } - ); + if ( buyCRED.checkout == 'popup' ) { - selects.each( - function (index, item) { - var element = $(this); - var option = element.find(':selected'); - if (option.val() !== undefined ) { - formdata[ element.attr('name') ] = option.val(); - } - } - ); + e.preventDefault(); - buycred_send_call(formdata); + buyCREDcancel.removeClass( 'on' ); + buyCREDcheckout.addClass( 'open' ); - } + activeForm = $(this); - } - ); + var formdata = { ajax : 1 }; + var fields = $(this).find( 'input' ); + var selects = $(this).find( 'select' ); - $('#buycred-checkout-wrapper').on( - 'click', '.checkout-footer button', function (e) { + fields.each(function(index, item){ + var element = $(this); + if ( element.attr( 'name' ) !== undefined ) { + formdata[ element.attr( 'name' ) ] = element.val(); + } + }); - var buttontype = $(this).data('act'); - var buttonvalue = $(this).data('value'); + selects.each(function(index, item){ + var element = $(this); + var option = element.find( ':selected' ); + if ( option.val() !== undefined ) { + formdata[ element.attr( 'name' ) ] = option.val(); + } + }); - if (buttontype == 'redirect' ) { + buycred_send_call( formdata ); - $(this).attr('disabled', 'disabled').html(buyCRED.redirecting); - - if ($(this).hasClass('bitpay') ) { - window.location = buttonvalue; - } - else - { - buyCREDform.attr('action', buttonvalue); - buyCREDform.submit(); - } + } - } + }); - else if (buttontype == 'toggle' ) { + $( '#buycred-checkout-wrapper' ).on( 'click', '.checkout-footer button', function(e){ - var toggleelement = $('#' + buttonvalue); - toggleelement.prev().slideUp( - function () { - toggleelement.slideDown(); - } - ); + var buttontype = $(this).data( 'act' ); + var buttonvalue = $(this).data( 'value' ); - $(this).parent().slideUp(); - buyCREDcancel.addClass('on'); + if ( buttontype == 'redirect' ) { - } + $(this).attr( 'disabled', 'disabled' ).html( buyCRED.redirecting ); + + if ( $(this).hasClass('bitpay') ) { + window.location = buttonvalue; + } + else + { + buyCREDform.attr( 'action', buttonvalue ); + buyCREDform.submit(); + } - $('#buycred-checkout-wrapper .cancel a').slideUp(); + } - } - ); + else if ( buttontype == 'toggle' ) { - $('#buycred-checkout-page').on( - 'click', '.checkout-footer button', function () { + var toggleelement = $( '#' + buttonvalue ); + toggleelement.prev().slideUp(function(){ + toggleelement.slideDown(); + }); - var pageform = $('#buycred-checkout-page form'); - var buttontype = $(this).data('act'); - var buttonvalue = $(this).data('value'); + $(this).parent().slideUp(); + buyCREDcancel.addClass( 'on' ); - if (buttontype == 'redirect' ) { + } - if ($(this).hasClass('bitpay') ) { - window.location = buttonvalue; - } - else { - pageform.attr('action', buttonvalue); - pageform.submit(); - } + $( '#buycred-checkout-wrapper .cancel a' ).slideUp(); - $(this).attr('disabled', 'disabled').html(buyCRED.redirecting); + }); - } + $( '#buycred-checkout-page' ).on( 'click', '.checkout-footer button', function(){ - else if (buttontype == 'toggle' ) { + var pageform = $( '#buycred-checkout-page form' ); + var buttontype = $(this).data( 'act' ); + var buttonvalue = $(this).data( 'value' ); - var toggleelement = $('#' + buttonvalue); - toggleelement.prev().slideUp( - function () { - toggleelement.slideDown(); - } - ); + if ( buttontype == 'redirect' ) { - $(this).parent().slideUp(); + if ( $(this).hasClass('bitpay') ) { + window.location = buttonvalue; + } + else { + pageform.attr( 'action', buttonvalue ); + pageform.submit(); + } - } + $(this).attr( 'disabled', 'disabled' ).html( buyCRED.redirecting ); - } - ); + } - buyCREDcancel.on( - 'click', function () { + else if ( buttontype == 'toggle' ) { - // Reset the form that was originally submitted - var formfields = activeForm.find('input.form-control'); - formfields.each( - function () { - $(this).val(''); - } - ); + var toggleelement = $( '#' + buttonvalue ); + toggleelement.prev().slideUp(function(){ + toggleelement.slideDown(); + }); - $(this).removeClass('on'); - buyCREDcheckout.removeClass('open'); - buyCREDcancel.removeClass('open'); - buyCREDform.attr('action', '').empty().append('
    '); + $(this).parent().slideUp(); - } - ); + } - $('#buycred-checkout-wrapper').on( - 'click', '.cancel a', function (e) { + }); - $('#buycred-checkout-wrapper form .checkout-footer').slideUp(); + buyCREDcancel.on( 'click', function(){ - } - ); + // Reset the form that was originally submitted + var formfields = activeForm.find( 'input.form-control' ); + formfields.each(function(){ + $(this).val( '' ); + }); - $(document).on( - 'change', '.mycred-change-pointtypes', function () { - - var value = $(this).find('option:selected').text(); - var label = $('.mycred-point-type').html(value); + $(this).removeClass( 'on' ); + buyCREDcheckout.removeClass( 'open' ); + buyCREDcancel.removeClass( 'open' ); + buyCREDform.attr( 'action', '' ).empty().append( '
    ' ); - } - ); + }); - } - ); + $( '#buycred-checkout-wrapper' ).on( 'click', '.cancel a', function(e){ - } -); \ No newline at end of file + $( '#buycred-checkout-wrapper form .checkout-footer' ).slideUp(); + + }); + + $( document ).on( 'change', '.mycred-change-pointtypes', function(){ + + var value = $(this).find('option:selected').text(); + var label = $('.mycred-point-type').html(value); + + }); + + }); + +}); \ No newline at end of file diff --git a/addons/buy-creds/assets/js/index.php b/addons/buy-creds/assets/js/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/assets/js/index.php +++ b/addons/buy-creds/assets/js/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/gateways/Bitpay/Autoloader.php b/addons/buy-creds/gateways/Bitpay/Autoloader.php index 0d3370e..415635b 100644 --- a/addons/buy-creds/gateways/Bitpay/Autoloader.php +++ b/addons/buy-creds/gateways/Bitpay/Autoloader.php @@ -47,7 +47,7 @@ public static function autoload($class) $file = __DIR__.DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $classname).'.php'; if (is_file($file) && is_readable($file)) { - include_once $file; + require_once $file; return true; } diff --git a/addons/buy-creds/gateways/Bitpay/Client/Adapter/CurlAdapter.php b/addons/buy-creds/gateways/Bitpay/Client/Adapter/CurlAdapter.php index b339f27..8d6327c 100644 --- a/addons/buy-creds/gateways/Bitpay/Client/Adapter/CurlAdapter.php +++ b/addons/buy-creds/gateways/Bitpay/Client/Adapter/CurlAdapter.php @@ -77,11 +77,7 @@ public function sendRequest(RequestInterface $request) throw new \Bitpay\Client\ConnectionException($errorMessage); } - /** -* - * - * @var ResponseInterface -*/ + /** @var ResponseInterface */ $response = Response::createFromRawResponse($raw); curl_close($curl); @@ -92,7 +88,7 @@ public function sendRequest(RequestInterface $request) /** * Returns an array of default curl settings to use * - * @param RequestInterface $request + * @param RequestInterface $request * @return array */ private function getCurlDefaultOptions(RequestInterface $request) diff --git a/addons/buy-creds/gateways/Bitpay/Client/Client.php b/addons/buy-creds/gateways/Bitpay/Client/Client.php index e35882a..f82aa12 100644 --- a/addons/buy-creds/gateways/Bitpay/Client/Client.php +++ b/addons/buy-creds/gateways/Bitpay/Client/Client.php @@ -98,7 +98,7 @@ public function setAdapter(AdapterInterface $adapter) } /** - * @param TokenInterface $token + * @param TokenInterface $token * @return ClientInterface */ public function setToken(TokenInterface $token) @@ -197,22 +197,20 @@ public function getCurrencies() throw new \Exception('Error with request: no data returned'); } $currencies = $body['data']; - array_walk( - $currencies, function (&$value, $key) { - $currency = new \Bitpay\Currency(); - $currency - ->setCode($value['code']) - ->setSymbol($value['symbol']) - ->setPrecision($value['precision']) - ->setExchangePctFee($value['exchangePctFee']) - ->setPayoutEnabled($value['payoutEnabled']) - ->setName($value['name']) - ->setPluralName($value['plural']) - ->setAlts($value['alts']) - ->setPayoutFields($value['payoutFields']); - $value = $currency; - } - ); + array_walk($currencies, function (&$value, $key) { + $currency = new \Bitpay\Currency(); + $currency + ->setCode($value['code']) + ->setSymbol($value['symbol']) + ->setPrecision($value['precision']) + ->setExchangePctFee($value['exchangePctFee']) + ->setPayoutEnabled($value['payoutEnabled']) + ->setName($value['name']) + ->setPluralName($value['plural']) + ->setAlts($value['alts']) + ->setPayoutFields($value['payoutFields']); + $value = $currency; + }); return $currencies; } @@ -316,54 +314,48 @@ public function getPayouts($status = null) $payouts = array(); - array_walk( - $body['data'], function ($value, $key) use (&$payouts) { - $payout = new \Bitpay\Payout(); - $payout + array_walk($body['data'], function ($value, $key) use (&$payouts) { + $payout = new \Bitpay\Payout(); + $payout + ->setId($value['id']) + ->setAccountId($value['account']) + ->setCurrency(new \Bitpay\Currency($value['currency'])) + ->setEffectiveDate($value['effectiveDate']) + ->setRequestdate($value['requestDate']) + ->setPricingMethod($value['pricingMethod']) + ->setStatus($value['status']) + ->setAmount($value['amount']) + ->setResponseToken($value['token']) + ->setRate(@$value['rate']) + ->setBtcAmount(@$value['btc']) + ->setReference(@$value['reference']) + ->setNotificationURL(@$value['notificationURL']) + ->setNotificationEmail(@$value['notificationEmail']); + + array_walk($value['instructions'], function ($value, $key) use (&$payout) { + $instruction = new \Bitpay\PayoutInstruction(); + $instruction ->setId($value['id']) - ->setAccountId($value['account']) - ->setCurrency(new \Bitpay\Currency($value['currency'])) - ->setEffectiveDate($value['effectiveDate']) - ->setRequestdate($value['requestDate']) - ->setPricingMethod($value['pricingMethod']) - ->setStatus($value['status']) + ->setLabel($value['label']) + ->setAddress($value['address']) ->setAmount($value['amount']) - ->setResponseToken($value['token']) - ->setRate(@$value['rate']) - ->setBtcAmount(@$value['btc']) - ->setReference(@$value['reference']) - ->setNotificationURL(@$value['notificationURL']) - ->setNotificationEmail(@$value['notificationEmail']); - - array_walk( - $value['instructions'], function ($value, $key) use (&$payout) { - $instruction = new \Bitpay\PayoutInstruction(); - $instruction - ->setId($value['id']) - ->setLabel($value['label']) - ->setAddress($value['address']) - ->setAmount($value['amount']) - ->setStatus($value['status']); - - array_walk( - $value['transactions'], function ($value, $key) use (&$instruction) { - $transaction = new \Bitpay\PayoutTransaction(); - $transaction - ->setTransactionId($value['txid']) - ->setAmount($value['amount']) - ->setDate($value['date']); - - $instruction->addTransaction($transaction); - } - ); - - $payout->addInstruction($instruction); - } - ); - - $payouts[] = $payout; - } - ); + ->setStatus($value['status']); + + array_walk($value['transactions'], function ($value, $key) use (&$instruction) { + $transaction = new \Bitpay\PayoutTransaction(); + $transaction + ->setTransactionId($value['txid']) + ->setAmount($value['amount']) + ->setDate($value['date']); + + $instruction->addTransaction($transaction); + }); + + $payout->addInstruction($instruction); + }); + + $payouts[] = $payout; + }); return $payouts; } @@ -432,32 +424,28 @@ public function getPayout($payoutId) ->setEffectiveDate($data['effectiveDate']) ->setResponseToken($data['token']); - array_walk( - $data['instructions'], function ($value, $key) use (&$payout) { - $instruction = new \Bitpay\PayoutInstruction(); - $instruction - ->setId($value['id']) - ->setLabel($value['label']) - ->setAddress($value['address']) - ->setStatus($value['status']) + array_walk($data['instructions'], function ($value, $key) use (&$payout) { + $instruction = new \Bitpay\PayoutInstruction(); + $instruction + ->setId($value['id']) + ->setLabel($value['label']) + ->setAddress($value['address']) + ->setStatus($value['status']) + ->setAmount($value['amount']) + ->setBtc($value['btc']); + + array_walk($value['transactions'], function ($value, $key) use (&$instruction) { + $transaction = new \Bitpay\PayoutTransaction(); + $transaction + ->setTransactionId($value['txid']) ->setAmount($value['amount']) - ->setBtc($value['btc']); - - array_walk( - $value['transactions'], function ($value, $key) use (&$instruction) { - $transaction = new \Bitpay\PayoutTransaction(); - $transaction - ->setTransactionId($value['txid']) - ->setAmount($value['amount']) - ->setDate($value['date']); + ->setDate($value['date']); - $instruction->addTransaction($transaction); - } - ); + $instruction->addTransaction($transaction); + }); - $payout->addInstruction($instruction); - } - ); + $payout->addInstruction($instruction); + }); return $payout; } @@ -482,18 +470,16 @@ public function getTokens() $tokens = array(); - array_walk( - $body['data'], function ($value, $key) use (&$tokens) { - $key = current(array_keys($value)); - $value = current(array_values($value)); - $token = new \Bitpay\Token(); - $token - ->setFacade($key) - ->setToken($value); + array_walk($body['data'], function ($value, $key) use (&$tokens) { + $key = current(array_keys($value)); + $value = current(array_values($value)); + $token = new \Bitpay\Token(); + $token + ->setFacade($key) + ->setToken($value); - $tokens[$token->getFacade()] = $token; - } - ); + $tokens[$token->getFacade()] = $token; + }); return $tokens; } @@ -613,7 +599,7 @@ public function getInvoice($invoiceId) } /** - * @param RequestInterface $request + * @param RequestInterface $request * @return ResponseInterface */ public function sendRequest(RequestInterface $request) diff --git a/addons/buy-creds/gateways/Bitpay/Client/ClientInterface.php b/addons/buy-creds/gateways/Bitpay/Client/ClientInterface.php index 2f363cd..5c165a2 100644 --- a/addons/buy-creds/gateways/Bitpay/Client/ClientInterface.php +++ b/addons/buy-creds/gateways/Bitpay/Client/ClientInterface.php @@ -42,7 +42,7 @@ interface ClientInterface public function getCurrencies(); /** - * @param InvoiceInterface $invoiceId + * @param InvoiceInterface $invoiceId * @return \Bitpay\Invoice * @throws \Exception */ @@ -50,7 +50,7 @@ public function createInvoice(InvoiceInterface $invoice); //public function getInvoices(); /** - * @param $invoiceId + * @param $invoiceId * @return InvoiceInterface * @throws \Exception */ @@ -65,29 +65,28 @@ public function getInvoice($invoiceId); /** * Create a Payout Request on Bitpay - * - * @param PayoutInterface $payout + * @param PayoutInterface $payout * @return PayoutInterface|mixed * @throws \Exception */ public function createPayout(PayoutInterface $payout); /** - * @param null $status + * @param null $status * @return array * @throws \Exception */ public function getPayouts($status = null); /** - * @param $payoutId + * @param $payoutId * @return \Bitpay\Payout * @throws \Exception */ public function getPayout($payoutId); /** - * @param PayoutInterface + * @param PayoutInterface * @return PayoutInterface|mixed * @throws \Exception */ @@ -100,7 +99,6 @@ public function deletePayout(PayoutInterface $payout); /** * Get an array of tokens indexed by facade - * * @return array * @throws \Exception */ diff --git a/addons/buy-creds/gateways/Bitpay/Client/Response.php b/addons/buy-creds/gateways/Bitpay/Client/Response.php index a7cadf3..cc37858 100644 --- a/addons/buy-creds/gateways/Bitpay/Client/Response.php +++ b/addons/buy-creds/gateways/Bitpay/Client/Response.php @@ -52,7 +52,7 @@ public function __toString() } /** - * @param string $rawResponse + * @param string $rawResponse * @return Response */ public static function createFromRawResponse($rawResponse) diff --git a/addons/buy-creds/gateways/Bitpay/Config/Configuration.php b/addons/buy-creds/gateways/Bitpay/Config/Configuration.php index c26568a..6a6100e 100644 --- a/addons/buy-creds/gateways/Bitpay/Config/Configuration.php +++ b/addons/buy-creds/gateways/Bitpay/Config/Configuration.php @@ -28,33 +28,33 @@ public function getConfigTreeBuilder() $rootNode = $treeBuilder->root('bitpay'); $rootNode ->children() - ->scalarNode('public_key') - ->info('Public Key Filename') - ->defaultValue(getenv('HOME').'/.bitpay/api.pub') - ->end() - ->scalarNode('private_key') - ->info('Private Key Filename') - ->defaultValue(getenv('HOME').'/.bitpay/api.key') - ->end() - ->scalarNode('sin_key') - ->info('Private Key Filename') - ->defaultValue(getenv('HOME').'/.bitpay/api.sin') - ->end() - ->enumNode('network') - ->values(array('livenet', 'testnet')) - ->info('Network') - ->defaultValue('livenet') - ->end() - ->enumNode('adapter') - ->values(array('curl', 'mock')) - ->info('Client Adapter') - ->defaultValue('curl') - ->end() - ->append($this->addKeyStorageNode()) - ->scalarNode('key_storage_password') - ->info('Used to encrypt and decrypt keys when saving to filesystem') - ->defaultNull() - ->end() + ->scalarNode('public_key') + ->info('Public Key Filename') + ->defaultValue(getenv('HOME').'/.bitpay/api.pub') + ->end() + ->scalarNode('private_key') + ->info('Private Key Filename') + ->defaultValue(getenv('HOME').'/.bitpay/api.key') + ->end() + ->scalarNode('sin_key') + ->info('Private Key Filename') + ->defaultValue(getenv('HOME').'/.bitpay/api.sin') + ->end() + ->enumNode('network') + ->values(array('livenet', 'testnet')) + ->info('Network') + ->defaultValue('livenet') + ->end() + ->enumNode('adapter') + ->values(array('curl', 'mock')) + ->info('Client Adapter') + ->defaultValue('curl') + ->end() + ->append($this->addKeyStorageNode()) + ->scalarNode('key_storage_password') + ->info('Used to encrypt and decrypt keys when saving to filesystem') + ->defaultNull() + ->end() ->end(); return $treeBuilder; @@ -76,9 +76,8 @@ protected function addKeyStorageNode() ->info('Class that is used to store your keys') ->defaultValue('Bitpay\Storage\EncryptedFilesystemStorage') ->validate() - ->always() - ->then( - function ($value) { + ->always() + ->then(function ($value) { if (!class_exists($value)) { throw new \Exception( sprintf( @@ -99,8 +98,7 @@ function ($value) { } return $value; - } - ) + }) ->end(); return $node; diff --git a/addons/buy-creds/gateways/Bitpay/Crypto/HashExtension.php b/addons/buy-creds/gateways/Bitpay/Crypto/HashExtension.php index 7dd0fc5..e5a1c48 100644 --- a/addons/buy-creds/gateways/Bitpay/Crypto/HashExtension.php +++ b/addons/buy-creds/gateways/Bitpay/Crypto/HashExtension.php @@ -36,7 +36,7 @@ public function getAlgos() * Copy a hashing context. * (PHP 5 >= 5.3.0) * - * @param resource + * @param resource * @return resource */ final public function copy($context) @@ -77,9 +77,9 @@ public function equals($string1, $string2) * the message digest is returned. * (PHP 5 >= 5.1.2, PECL hash >= 1.1) * - * @param string - * @param string - * @param bool + * @param string + * @param string + * @param bool * @return string */ public function file($algorithm, $filename, $raw_output = false) @@ -92,8 +92,8 @@ public function file($algorithm, $filename, $raw_output = false) * resulting digest. * (PHP 5 >= 5.1.2, PECL hash >= 1.1) * - * @param resource - * @param bool + * @param resource + * @param bool * @return string */ public function finalize($context, $raw_output = false) @@ -110,10 +110,10 @@ public function finalize($context, $raw_output = false) * method and the contents of a given file. * (PHP 5 >= 5.1.2, PECL hash >= 1.1) * - * @param string - * @param string - * @param string - * @param bool + * @param string + * @param string + * @param string + * @param bool * @return string */ public function hmacFile($algorithm, $filename, $key, $raw_output = false) @@ -126,10 +126,10 @@ public function hmacFile($algorithm, $filename, $key, $raw_output = false) * method and the message passed via $data. * (PHP 5 >= 5.1.2, PECL hash >= 1.1) * - * @param string - * @param string - * @param string - * @param bool + * @param string + * @param string + * @param string + * @param bool * @return string */ public function hmac($algo, $data, $key, $raw_output = false) @@ -146,9 +146,9 @@ public function hmac($algo, $data, $key, $raw_output = false) * this is specified, the key *must* be used as well. * (PHP 5 >= 5.1.2, PECL hash >= 1.1) * - * @param string - * @param int - * @param string + * @param string + * @param int + * @param string * @return resource */ public function init($algorithm, $options = 0, $key = null) @@ -166,12 +166,12 @@ public function init($algorithm, $options = 0, $key = null) * randomly with openssl_ramdom_pseudo_bytes(). * (PHP 5 >= 5.5.0) * - * @param string - * @param string - * @param string - * @param int - * @param int - * @param bool + * @param string + * @param string + * @param string + * @param int + * @param int + * @param bool * @return string */ public function pbkdf2($algo, $password, $salt, $iterations, $length = 0, $raw_output = false) @@ -185,9 +185,9 @@ public function pbkdf2($algo, $password, $salt, $iterations, $length = 0, $raw_o * FALSE on failure. * (PHP 5 >= 5.1.2, PECL hash >= 1.1) * - * @param resource - * @param string - * @param resource + * @param resource + * @param string + * @param resource * @return bool */ public function updateFile($hcontext, $filename, $scontext = null) @@ -206,9 +206,9 @@ public function updateFile($hcontext, $filename, $scontext = null) * context from handle. * (PHP 5 >= 5.1.2, PECL hash >= 1.1) * - * @param resource - * @param resource - * @param int + * @param resource + * @param resource + * @param int * @return int */ public function updateStream($context, $handle, $length = -1) @@ -225,8 +225,8 @@ public function updateStream($context, $handle, $length = -1) * The PHP function itself only returns true. * (PHP 5 >= 5.1.2, PECL hash >= 1.1) * - * @param resource - * @param string + * @param resource + * @param string * @return bool */ public function update($context, $data) @@ -245,9 +245,9 @@ public function update($context, $data) * $raw_output param is set to true. * (PHP 5 >= 5.1.2, PECL hash >= 1.1) * - * @param string - * @param string - * @param bool + * @param string + * @param string + * @param bool * @return string */ public function generate($algo, $data, $raw_output = false) diff --git a/addons/buy-creds/gateways/Bitpay/Crypto/McryptExtension.php b/addons/buy-creds/gateways/Bitpay/Crypto/McryptExtension.php index 1c81ea5..9eb4388 100644 --- a/addons/buy-creds/gateways/Bitpay/Crypto/McryptExtension.php +++ b/addons/buy-creds/gateways/Bitpay/Crypto/McryptExtension.php @@ -35,7 +35,7 @@ public function getAlgos() * on failure. If no IV is needed for the cipher type and mode, * a zero is returned. * - * @param string $cipher_type + * @param string $cipher_type * @return int|bool */ public function getIVSize($cipher_type = MCRYPT_TRIPLEDES) @@ -73,7 +73,7 @@ public function getKeySize($cipher_type = MCRYPT_TRIPLEDES) * returns either boolean true/false depending on if the self-test passed * or failed. * - * @param string $cipher_type + * @param string $cipher_type * @return boolean */ public function algoSelfTest($cipher_type = MCRYPT_TRIPLEDES) @@ -82,18 +82,20 @@ public function algoSelfTest($cipher_type = MCRYPT_TRIPLEDES) } /** + * * Encrypts $text based on your $key and $iv. The returned text is * base-64 encoded to make it easier to work with in various scenarios. * Default cipher is MCRYPT_TRIPLEDES but you can substitute depending * on your specific encryption needs. * - * @param string $text - * @param string $key - * @param string $iv - * @param int $bit_check - * @param string $cipher_type + * @param string $text + * @param string $key + * @param string $iv + * @param int $bit_check + * @param string $cipher_type * @return string $text * @throws Exception $e + * */ public function encrypt($text, $key = '', $iv = '', $bit_check = 8, $cipher_type = MCRYPT_TRIPLEDES) { @@ -125,18 +127,20 @@ public function encrypt($text, $key = '', $iv = '', $bit_check = 8, $cipher_type } /** + * * Decrypts $text based on your $key and $iv. Make sure you use the same key * and initialization vector that you used when encrypting the $text. Default * cipher is MCRYPT_TRIPLEDES but you can substitute depending on the cipher * used for encrypting the text - very important. * - * @param string $encrypted_text - * @param string $key - * @param string $iv - * @param int $bit_check - * @param string $cipher_type + * @param string $encrypted_text + * @param string $key + * @param string $iv + * @param int $bit_check + * @param string $cipher_type * @return string $text * @throws Exception $e + * */ public function decrypt($encrypted_text, $key = '', $iv = '', $bit_check = 8, $cipher_type = MCRYPT_TRIPLEDES) { diff --git a/addons/buy-creds/gateways/Bitpay/Crypto/OpenSSLExtension.php b/addons/buy-creds/gateways/Bitpay/Crypto/OpenSSLExtension.php index 08b196c..fcc21b6 100644 --- a/addons/buy-creds/gateways/Bitpay/Crypto/OpenSSLExtension.php +++ b/addons/buy-creds/gateways/Bitpay/Crypto/OpenSSLExtension.php @@ -34,8 +34,8 @@ public function getAlgos() * used for point derivation or for generating signatures. * Only used for assymetric data encryption, as needed. * - * @param int - * @param string + * @param int + * @param string * @return array|boolean array of keys on success, boolean false on failure */ final public function generateKeypair($keybits = 512, $digest_alg = 'sha512') @@ -113,7 +113,7 @@ final public function generateKeypair($keybits = 512, $digest_alg = 'sha512') * Generates a high-quality random number suitable for * use in cryptographic functions and returns hex value. * - * @param int + * @param int * @return string|bool */ final public function randomNumber($bytes = 32) @@ -131,7 +131,7 @@ final public function randomNumber($bytes = 32) * Returns the cipher length on success, or FALSE * on failure. (PHP 5 >= PHP 5.3.3) * - * @param string + * @param string * @return int|bool */ final public function cypherIVLength($cypher = '') @@ -145,9 +145,9 @@ final public function cypherIVLength($cypher = '') * the file named by $outfilename. * (PHP 4 >= 4.2.0, PHP 5) * - * @param resource - * @param string - * @param bool + * @param resource + * @param string + * @param bool * @return bool */ final public function saveCSRtoFile($csr, $outfilename, $notext = true) @@ -165,9 +165,9 @@ final public function saveCSRtoFile($csr, $outfilename, $notext = true) * $out, which is passed by reference. * (PHP 4 >= 4.2.0, PHP 5) * - * @param resource - * @param string - * @param bool + * @param resource + * @param string + * @param bool * @return bool */ final public function saveCSRtoString($csr, $out, $notext = true) @@ -179,21 +179,22 @@ final public function saveCSRtoString($csr, $out, $notext = true) return openssl_csr_export($csr, $out, $notext); } /** - * Encrypts $text based on your $key and $iv. The returned text is - * base-64 encoded to make it easier to work with in various scenarios. - * Default cipher is AES-256-CBC but you can substitute depending - * on your specific encryption needs. - * - * @param string $text - * @param string $key - * @param string $iv - * @param int $bit_check - * @param string $cipher_type - * @return string $text - * @throws Exception $e - */ - public function encrypt($text, $key = '', $iv = '', $bit_check = 8, $cipher_type = 'AES-256-CBC') - { + * + * Encrypts $text based on your $key and $iv. The returned text is + * base-64 encoded to make it easier to work with in various scenarios. + * Default cipher is AES-256-CBC but you can substitute depending + * on your specific encryption needs. + * + * @param string $text + * @param string $key + * @param string $iv + * @param int $bit_check + * @param string $cipher_type + * @return string $text + * @throws Exception $e + * + */ + public function encrypt($text, $key = '', $iv = '', $bit_check = 8, $cipher_type = 'AES-256-CBC') { try { if (function_exists('openssl_pkey_new')) { /* Ensure the key & IV is the same for both encrypt & decrypt. */ @@ -220,21 +221,22 @@ public function encrypt($text, $key = '', $iv = '', $bit_check = 8, $cipher_type } /** + * * Decrypts $text based on your $key and $iv. Make sure you use the same key * and initialization vector that you used when encrypting the $text. Default * cipher is AES-256-CBC but you can substitute depending on the cipher * used for encrypting the text - very important. * - * @param string $encrypted_text - * @param string $key - * @param string $iv - * @param int $bit_check - * @param string $cipher_type + * @param string $encrypted_text + * @param string $key + * @param string $iv + * @param int $bit_check + * @param string $cipher_type * @return string $text * @throws Exception $e + * */ - public function decrypt($encrypted_text, $key = '', $iv = '', $bit_check = 8, $cipher_type = 'AES-256-CBC') - { + public function decrypt($encrypted_text, $key = '', $iv = '', $bit_check = 8, $cipher_type = 'AES-256-CBC') { try { /* Ensure the key & IV is the same for both encrypt & decrypt. */ if (!empty($encrypted_text)) { diff --git a/addons/buy-creds/gateways/Bitpay/Currency.php b/addons/buy-creds/gateways/Bitpay/Currency.php index f542eae..a061ea1 100644 --- a/addons/buy-creds/gateways/Bitpay/Currency.php +++ b/addons/buy-creds/gateways/Bitpay/Currency.php @@ -11,7 +11,7 @@ /** * For the most part this should conform to ISO 4217 * - * @see http://en.wikipedia.org/wiki/ISO_4217 + * @see http://en.wikipedia.org/wiki/ISO_4217 * @package Bitpay */ class Currency implements CurrencyInterface @@ -86,7 +86,7 @@ class Currency implements CurrencyInterface protected $payoutFields; /** - * @param string $code The Currency Code to use, ie USD + * @param string $code The Currency Code to use, ie USD * @throws Exception Throws an exception if the Currency Code is not supported */ public function __construct($code = null) @@ -110,7 +110,7 @@ public function getCode() /** * This will change the $code to all uppercase * - * @param string $code The Currency Code to use, ie USD + * @param string $code The Currency Code to use, ie USD * @throws Exception Throws an exception if the Currency Code is not supported * @return CurrencyInterface */ diff --git a/addons/buy-creds/gateways/Bitpay/DependencyInjection/Loader/ArrayLoader.php b/addons/buy-creds/gateways/Bitpay/DependencyInjection/Loader/ArrayLoader.php index 463ccca..2f2aa06 100644 --- a/addons/buy-creds/gateways/Bitpay/DependencyInjection/Loader/ArrayLoader.php +++ b/addons/buy-creds/gateways/Bitpay/DependencyInjection/Loader/ArrayLoader.php @@ -40,14 +40,12 @@ function ($ext) { $this->container->getExtensions() ) ); - throw new InvalidArgumentException( - sprintf( - 'There is no extension able to load the configuration for "%s". Looked for namespace "%s", found %s', - $namespace, - $namespace, - $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none' - ) - ); + throw new InvalidArgumentException(sprintf( + 'There is no extension able to load the configuration for "%s". Looked for namespace "%s", found %s', + $namespace, + $namespace, + $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none' + )); } } diff --git a/addons/buy-creds/gateways/Bitpay/Invoice.php b/addons/buy-creds/gateways/Bitpay/Invoice.php index 86e68d8..70cff6e 100644 --- a/addons/buy-creds/gateways/Bitpay/Invoice.php +++ b/addons/buy-creds/gateways/Bitpay/Invoice.php @@ -666,7 +666,7 @@ public function setExceptionStatus($exceptionStatus) } /** - * @param void + * @param void * @return */ public function getBtcPaid() @@ -688,7 +688,7 @@ public function setBtcPaid($btcPaid) } /** - * @param void + * @param void * @return Invoice */ public function getRate() @@ -717,7 +717,7 @@ public function getToken() return $this->token; } /** - * @param TokenInterface $token + * @param TokenInterface $token * @return InvoiceInterface */ public function setToken(TokenInterface $token) diff --git a/addons/buy-creds/gateways/Bitpay/InvoiceInterface.php b/addons/buy-creds/gateways/Bitpay/InvoiceInterface.php index b471c5a..0440118 100644 --- a/addons/buy-creds/gateways/Bitpay/InvoiceInterface.php +++ b/addons/buy-creds/gateways/Bitpay/InvoiceInterface.php @@ -246,7 +246,7 @@ public function getOrderId(); * characters. * * @deprecated - * @return string + * @return string */ public function getItemDesc(); @@ -255,7 +255,7 @@ public function getItemDesc(); * length is 100 characters. * * @deprecated - * @return string + * @return string */ public function getItemCode(); @@ -265,7 +265,7 @@ public function getItemCode(); * ● false: Indicates that nothing is to be shipped for this order * * @deprecated - * @return boolean + * @return boolean */ public function isPhysical(); @@ -274,7 +274,7 @@ public function isPhysical(); * if provided. Maximum string length of each field is 100 characters. * * @deprecated - * @return string + * @return string */ public function getBuyerName(); @@ -283,7 +283,7 @@ public function getBuyerName(); * if provided. Maximum string length of each field is 100 characters. * * @deprecated - * @return string + * @return string */ public function getBuyerAddress1(); @@ -292,7 +292,7 @@ public function getBuyerAddress1(); * if provided. Maximum string length of each field is 100 characters. * * @deprecated - * @return string + * @return string */ public function getBuyerAddress2(); @@ -301,7 +301,7 @@ public function getBuyerAddress2(); * if provided. Maximum string length of each field is 100 characters. * * @deprecated - * @return string + * @return string */ public function getBuyerCity(); @@ -310,7 +310,7 @@ public function getBuyerCity(); * if provided. Maximum string length of each field is 100 characters. * * @deprecated - * @return string + * @return string */ public function getBuyerState(); @@ -319,7 +319,7 @@ public function getBuyerState(); * if provided. Maximum string length of each field is 100 characters. * * @deprecated - * @return string + * @return string */ public function getBuyerZip(); @@ -328,7 +328,7 @@ public function getBuyerZip(); * if provided. Maximum string length of each field is 100 characters. * * @deprecated - * @return string + * @return string */ public function getBuyerCountry(); @@ -337,7 +337,7 @@ public function getBuyerCountry(); * if provided. Maximum string length of each field is 100 characters. * * @deprecated - * @return string + * @return string */ public function getBuyerEmail(); @@ -346,7 +346,7 @@ public function getBuyerEmail(); * if provided. Maximum string length of each field is 100 characters. * * @deprecated - * @return string + * @return string */ public function getBuyerPhone(); diff --git a/addons/buy-creds/gateways/Bitpay/Item.php b/addons/buy-creds/gateways/Bitpay/Item.php index 2c6a91c..6837502 100644 --- a/addons/buy-creds/gateways/Bitpay/Item.php +++ b/addons/buy-creds/gateways/Bitpay/Item.php @@ -156,7 +156,7 @@ public function setPhysical($physical) * Checks the new price to include BTC * values with more than 6 decimals. * - * @param string $price The price value to check + * @param string $price The price value to check * @throws \Exception */ protected function checkPriceFormat($price) diff --git a/addons/buy-creds/gateways/Bitpay/Key.php b/addons/buy-creds/gateways/Bitpay/Key.php index 09d1231..dccabd5 100644 --- a/addons/buy-creds/gateways/Bitpay/Key.php +++ b/addons/buy-creds/gateways/Bitpay/Key.php @@ -47,7 +47,7 @@ public function getId() /** * Returns a new instance of self. * - * @param string $id + * @param string $id * @return \Bitpay\KeyInterface */ public static function create($id = null) diff --git a/addons/buy-creds/gateways/Bitpay/Math/BcEngine.php b/addons/buy-creds/gateways/Bitpay/Math/BcEngine.php index 96bbeb8..0939d93 100644 --- a/addons/buy-creds/gateways/Bitpay/Math/BcEngine.php +++ b/addons/buy-creds/gateways/Bitpay/Math/BcEngine.php @@ -58,8 +58,8 @@ public function div($a, $b) * Finds inverse number $inv for $num by modulus $mod, such as: * $inv * $num = 1 (mod $mod) * - * @param string $num - * @param string $mod + * @param string $num + * @param string $mod * @return string * @access public */ diff --git a/addons/buy-creds/gateways/Bitpay/Payout.php b/addons/buy-creds/gateways/Bitpay/Payout.php index 0f6c819..7195d88 100644 --- a/addons/buy-creds/gateways/Bitpay/Payout.php +++ b/addons/buy-creds/gateways/Bitpay/Payout.php @@ -8,7 +8,6 @@ /** * Class Payout - * * @package Bitpay */ class Payout implements PayoutInterface @@ -103,7 +102,7 @@ public function getId() /** * Set the batch ID as assigned from bitpay. * - * @param $id + * @param $id * @return $this */ public function setId($id) @@ -126,7 +125,7 @@ public function getAccountId() /** * Set Account Id - Bitpays account ID for the payout. * - * @param $id + * @param $id * @return $this */ public function setAccountId($id) @@ -148,8 +147,7 @@ public function getAmount() /** * Sets the amount for this payout. - * - * @param $amount + * @param $amount * @return $this */ public function setAmount($amount) @@ -171,8 +169,7 @@ public function getCurrency() /** * Set Currency - * - * @param CurrencyInterface $currency + * @param CurrencyInterface $currency * @return $this */ public function setCurrency(CurrencyInterface $currency) @@ -194,8 +191,7 @@ public function getEffectiveDate() /** * Set Effective date - date payout should be given to employees. - * - * @param $effectiveDate + * @param $effectiveDate * @return $this */ public function setEffectiveDate($effectiveDate) @@ -217,8 +213,7 @@ public function getRate() /** * Set the rate in bitcoin for the payouts of this transaction. - * - * @param $rate + * @param $rate * @return $this */ public function setRate($rate) @@ -240,8 +235,7 @@ public function getBtcAmount() /** * Set the Bitcoin amount for this payout, once set by Bitpay. - * - * @param $amount + * @param $amount * @return $this */ public function setBtcAmount($amount) @@ -284,7 +278,7 @@ public function getInstructions() * Add Instruction of PayoutInstructionInterface type * Increases $this->amount by value. * - * @param PayoutInstructionInterface $instruction + * @param PayoutInstructionInterface $instruction * @return $this */ public function addInstruction(PayoutInstructionInterface $instruction) @@ -300,9 +294,9 @@ public function addInstruction(PayoutInstructionInterface $instruction) * Update Instruction - Supply an index of the instruction to update, * plus the function and single argument, to do something to an instruction. * - * @param $index - * @param $function - * @param $argument + * @param $index + * @param $function + * @param $argument * @return $this */ public function updateInstruction($index, $function, $argument) @@ -324,8 +318,7 @@ public function getStatus() /** * Sets the status for the current payout request - * - * @param $status + * @param $status * @return $this */ public function setStatus($status) @@ -347,8 +340,7 @@ public function getToken() /** * Set the token to authorize this request. - * - * @param TokenInterface $token + * @param TokenInterface $token * @return $this */ public function setToken(TokenInterface $token) @@ -370,7 +362,7 @@ public function getResponseToken() /** * Set Response Token - returned by Bitpay when payout request is created * - * @param $responseToken + * @param $responseToken * @return $this */ public function setResponseToken($responseToken) @@ -391,8 +383,7 @@ public function getPricingMethod() /** * Set the pricing method for this payout request - * - * @param $pricingMethod + * @param $pricingMethod * @return $this */ public function setPricingMethod($pricingMethod) @@ -415,7 +406,7 @@ public function getReference() /** * Set the payroll providers reference for this payout * - * @param $reference + * @param $reference * @return $this */ public function setReference($reference) @@ -438,7 +429,7 @@ public function getNotificationEmail() /** * Set an email address where updates to payout status should be sent. * - * @param $notificationEmail + * @param $notificationEmail * @return $this */ public function setNotificationEmail($notificationEmail) @@ -461,7 +452,7 @@ public function getNotificationUrl() /** * Set a notification url - where updated Payout objects will be sent * - * @param $notificationUrl + * @param $notificationUrl * @return $this */ public function setNotificationUrl($notificationUrl) diff --git a/addons/buy-creds/gateways/Bitpay/PayoutInstruction.php b/addons/buy-creds/gateways/Bitpay/PayoutInstruction.php index bd20a16..973c158 100644 --- a/addons/buy-creds/gateways/Bitpay/PayoutInstruction.php +++ b/addons/buy-creds/gateways/Bitpay/PayoutInstruction.php @@ -8,7 +8,6 @@ /** * Class PayoutInstruction - * * @package Bitpay */ class PayoutInstruction implements PayoutInstructionInterface @@ -75,7 +74,7 @@ public function getId() /** * Set the Bitpay ID for this payout instruction * - * @param $id + * @param $id * @return $this */ public function setId($id) @@ -96,8 +95,7 @@ public function getLabel() /** * Set the employers label for this instruction. - * - * @param $label + * @param $label * @return $this */ public function setLabel($label) @@ -119,8 +117,7 @@ public function getAddress() /** * Set the bitcoin address for this instruction. - * - * @param $address + * @param $address * @return $this */ public function setAddress($address) @@ -142,8 +139,7 @@ public function getAmount() /** * Set the amount for this instruction. - * - * @param $amount + * @param $amount * @return $this */ public function setAmount($amount) @@ -165,8 +161,7 @@ public function getBtc() /** * Set BTC array (available once rates are set) - * - * @param $btc + * @param $btc * @return $this */ public function setBtc($btc) @@ -188,8 +183,7 @@ public function getStatus() /** * Set the status for this instruction - * - * @param $status + * @param $status * @return $this */ public function setStatus($status) @@ -211,8 +205,7 @@ public function getTransactions() /** * Add payout transaction to the - * - * @param PayoutTransactionInterface $transaction + * @param PayoutTransactionInterface $transaction * @return $this */ public function addTransaction(PayoutTransactionInterface $transaction) diff --git a/addons/buy-creds/gateways/Bitpay/PayoutInstructionInterface.php b/addons/buy-creds/gateways/Bitpay/PayoutInstructionInterface.php index fadd736..215c6e1 100644 --- a/addons/buy-creds/gateways/Bitpay/PayoutInstructionInterface.php +++ b/addons/buy-creds/gateways/Bitpay/PayoutInstructionInterface.php @@ -8,7 +8,6 @@ /** * Interface PayoutInstructionInterface - * * @package Bitpay */ interface PayoutInstructionInterface @@ -16,49 +15,42 @@ interface PayoutInstructionInterface /** * Get Bitpay ID for this instruction. - * * @return string */ public function getId(); /** * Get Label for instruction payout. - * * @return string */ public function getLabel(); /** * Get the bitcoin address for the recipient. - * * @return string */ public function getAddress(); /** * Return the amount to pay the recipient. - * * @return string */ public function getAmount(); /** * Get the BTC array (once rates are set) - * * @return array */ public function getBtc(); /** * Return the status of this payout instruction - * * @return string */ public function getStatus(); /** * Return the transactions for this payout - * * @return array */ public function getTransactions(); diff --git a/addons/buy-creds/gateways/Bitpay/PayoutInterface.php b/addons/buy-creds/gateways/Bitpay/PayoutInterface.php index 601a640..9a047c1 100644 --- a/addons/buy-creds/gateways/Bitpay/PayoutInterface.php +++ b/addons/buy-creds/gateways/Bitpay/PayoutInterface.php @@ -8,7 +8,6 @@ /** * Interface PayoutInterface - * * @package Bitpay */ interface PayoutInterface diff --git a/addons/buy-creds/gateways/Bitpay/PayoutTransaction.php b/addons/buy-creds/gateways/Bitpay/PayoutTransaction.php index 5958198..9c13578 100644 --- a/addons/buy-creds/gateways/Bitpay/PayoutTransaction.php +++ b/addons/buy-creds/gateways/Bitpay/PayoutTransaction.php @@ -8,7 +8,6 @@ /** * Class PayoutTransaction - * * @package Bitpay */ class PayoutTransaction implements PayoutTransactionInterface @@ -38,8 +37,7 @@ public function getTransactionId() /** * Set transaction ID for payout. - * - * @param $txid + * @param $txid * @return $this */ public function setTransactionId($txid) @@ -61,8 +59,7 @@ public function getAmount() /** * Set the amount of bitcoin paid in the paout. - * - * @param $amount + * @param $amount * @return $this */ public function setAmount($amount) @@ -84,8 +81,7 @@ public function getDate() /** * Set the date and time of when the payment was sent. - * - * @param $date + * @param $date * @return $this */ public function setDate($date) diff --git a/addons/buy-creds/gateways/Bitpay/PayoutTransactionInterface.php b/addons/buy-creds/gateways/Bitpay/PayoutTransactionInterface.php index ae4841a..b549b04 100644 --- a/addons/buy-creds/gateways/Bitpay/PayoutTransactionInterface.php +++ b/addons/buy-creds/gateways/Bitpay/PayoutTransactionInterface.php @@ -8,28 +8,24 @@ /** * Class PayoutTransaction - * * @package Bitpay */ interface PayoutTransactionInterface { /** * Get bitcoin blockchain transaction ID for the payout transaction. - * * @return mixed */ public function getTransactionID(); /** * The amount of bitcoin paid. - * * @return float */ public function getAmount(); /** * The date and time when the payment was sent. - * * @return string */ public function getDate(); diff --git a/addons/buy-creds/gateways/Bitpay/PrivateKey.php b/addons/buy-creds/gateways/Bitpay/PrivateKey.php index 7b0d2e8..4f70636 100644 --- a/addons/buy-creds/gateways/Bitpay/PrivateKey.php +++ b/addons/buy-creds/gateways/Bitpay/PrivateKey.php @@ -13,7 +13,7 @@ /** * @package Bitcore - * @see https://en.bitcoin.it/wiki/List_of_address_prefixes + * @see https://en.bitcoin.it/wiki/List_of_address_prefixes */ class PrivateKey extends Key { @@ -191,8 +191,8 @@ public function sign($data) * 0x30 + size(all) + 0x02 + size(r) + r + 0x02 + size(s) + s * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf * - * @param string - * @param string + * @param string + * @param string * @return string */ public static function serializeSig($r, $s) @@ -304,7 +304,7 @@ public function pemDecode($pem_data) /** * Encodes keypair data to PEM format. * - * @param array $keypair The keypair info. + * @param array $keypair The keypair info. * @return string The data to decode. */ public function pemEncode($keypair) diff --git a/addons/buy-creds/gateways/Bitpay/SinKey.php b/addons/buy-creds/gateways/Bitpay/SinKey.php index ec3f909..09fce7b 100644 --- a/addons/buy-creds/gateways/Bitpay/SinKey.php +++ b/addons/buy-creds/gateways/Bitpay/SinKey.php @@ -41,7 +41,7 @@ public function __toString() } /** - * @param PublicKey + * @param PublicKey * @return SinKey */ public function setPublicKey(PublicKey $publicKey) diff --git a/addons/buy-creds/gateways/Bitpay/Storage/EncryptedFilesystemStorage.php b/addons/buy-creds/gateways/Bitpay/Storage/EncryptedFilesystemStorage.php index d63ef89..7919595 100644 --- a/addons/buy-creds/gateways/Bitpay/Storage/EncryptedFilesystemStorage.php +++ b/addons/buy-creds/gateways/Bitpay/Storage/EncryptedFilesystemStorage.php @@ -53,15 +53,13 @@ public function persist(\Bitpay\KeyInterface $key) { $path = $key->getId(); $data = serialize($key); - $encoded = bin2hex( - openssl_encrypt( - $data, - self::METHOD, - $this->password, - 1, - self::IV - ) - ); + $encoded = bin2hex(openssl_encrypt( + $data, + self::METHOD, + $this->password, + 1, + self::IV + )); file_put_contents($path, $encoded); } diff --git a/addons/buy-creds/gateways/Bitpay/Storage/MockStorage.php b/addons/buy-creds/gateways/Bitpay/Storage/MockStorage.php index 6a4a553..5cc1d1b 100644 --- a/addons/buy-creds/gateways/Bitpay/Storage/MockStorage.php +++ b/addons/buy-creds/gateways/Bitpay/Storage/MockStorage.php @@ -8,7 +8,7 @@ /** * @codeCoverageIgnore - * @package Bitcore + * @package Bitcore */ class MockStorage implements StorageInterface { diff --git a/addons/buy-creds/gateways/Bitpay/Util/Error.php b/addons/buy-creds/gateways/Bitpay/Util/Error.php index 0b4a932..95b9c5b 100644 --- a/addons/buy-creds/gateways/Bitpay/Util/Error.php +++ b/addons/buy-creds/gateways/Bitpay/Util/Error.php @@ -15,9 +15,9 @@ class Error * and args. * (PHP 4 >= 4.3.0, PHP 5) * - * @param bool - * @param bool - * @param int + * @param bool + * @param bool + * @param int * @return array|void */ final public function backtrace($print = false, $options = false, $limit = 0) @@ -37,7 +37,7 @@ final public function backtrace($print = false, $options = false, $limit = 0) * Returns NULL if there hasn't been an error yet. * (PHP 5 >= 5.2.0) * - * @param void + * @param void * @return array */ final public function last() @@ -69,7 +69,7 @@ final public function log($message, $message_type = 0, $destination = '', $extra * parameter is given. * (PHP 4, PHP 5) * - * @param bool + * @param bool * @return int */ final public function reporting($level = false) @@ -98,32 +98,32 @@ final public function handler($type = 'error', $action = 'restore', $callable_ha $error_types = E_ALL | E_STRICT; } switch (strtolower($type)) { - case 'error': - switch (strtolower($action)) { - case 'restore': - return restore_error_handler(); - break; - case 'set': - return set_error_handler($callable_handler, $error_types); - break; - default: - return false; - } - break; - case 'exception': - switch (strtolower($action)) { - case 'restore': - return restore_exception_handler(); - break; - case 'set': - return set_exception_handler($callable_handler); - break; + case 'error': + switch (strtolower($action)) { + case 'restore': + return restore_error_handler(); + break; + case 'set': + return set_error_handler($callable_handler, $error_types); + break; + default: + return false; + } + break; + case 'exception': + switch (strtolower($action)) { + case 'restore': + return restore_exception_handler(); + break; + case 'set': + return set_exception_handler($callable_handler); + break; + default: + return false; + } + break; default: return false; - } - break; - default: - return false; } } @@ -134,8 +134,8 @@ final public function handler($type = 'error', $action = 'restore', $callable_ha * limited to 1024 bytes. * (PHP 4 >= 4.0.1, PHP 5) * - * @param string - * @param int + * @param string + * @param int * @return bool */ final public function raise($error_msg, $error_type = E_USER_NOTICE) diff --git a/addons/buy-creds/gateways/Bitpay/Util/Fingerprint.php b/addons/buy-creds/gateways/Bitpay/Util/Fingerprint.php index 2635e4f..1453514 100644 --- a/addons/buy-creds/gateways/Bitpay/Util/Fingerprint.php +++ b/addons/buy-creds/gateways/Bitpay/Util/Fingerprint.php @@ -19,7 +19,7 @@ class Fingerprint * takes the hash of that value to use as the env * fingerprint. * - * @param void + * @param void * @return string */ final public static function generate() diff --git a/addons/buy-creds/gateways/Bitpay/Util/Util.php b/addons/buy-creds/gateways/Bitpay/Util/Util.php index 62ffb1b..15241b2 100644 --- a/addons/buy-creds/gateways/Bitpay/Util/Util.php +++ b/addons/buy-creds/gateways/Bitpay/Util/Util.php @@ -219,7 +219,7 @@ public static function doubleAndAdd($hex, PointInterface $point, CurveParameterI * * @see http://php.net/manual/en/function.decbin.php but for large numbers * - * @param string + * @param string * @return string */ public static function decToBin($dec) @@ -252,8 +252,8 @@ public static function decToBin($dec) * xR = s2 - 2xP mod p * yR = -yP + s(xP - xR) mod p * - * @param PointInterface $point - * @param CurveParameterInterface + * @param PointInterface $point + * @param CurveParameterInterface * @return PointInterface */ public static function pointDouble(PointInterface $point, CurveParameterInterface $parameters = null) @@ -305,16 +305,16 @@ public static function pointDouble(PointInterface $point, CurveParameterInterfac } /** - * Point addition method P + Q = R where: - * s = (yP - yQ)/(xP - xQ) mod p - * xR = s2 - xP - xQ mod p - * yR = -yP + s(xP - xR) mod p - * - * @param PointInterface - * @param PointInterface - * - * @return PointInterface - */ + * Point addition method P + Q = R where: + * s = (yP - yQ)/(xP - xQ) mod p + * xR = s2 - xP - xQ mod p + * yR = -yP + s(xP - xR) mod p + * + * @param PointInterface + * @param PointInterface + * + * @return PointInterface + */ public static function pointAdd(PointInterface $P, PointInterface $Q) { if ($P->isInfinity()) { diff --git a/addons/buy-creds/gateways/Bitpay/index.php b/addons/buy-creds/gateways/Bitpay/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/gateways/Bitpay/index.php +++ b/addons/buy-creds/gateways/Bitpay/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/gateways/bank-transfer.php b/addons/buy-creds/gateways/bank-transfer.php index 5f9e614..3cf8e99 100644 --- a/addons/buy-creds/gateways/bank-transfer.php +++ b/addons/buy-creds/gateways/bank-transfer.php @@ -1,265 +1,237 @@ $label ) { - $default_exchange[ $type ] = 1; - } - - parent::__construct( - array( - 'id' => 'bank', - 'label' => 'Bank Transfer', - 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/bank-transfers/', - 'gateway_logo_url' => '', - 'defaults' => array( - 'title' => '', - 'account' => '', - 'logo_url' => '', - 'currency' => 'EUR', - 'exchange' => $default_exchange - ) - ), $gateway_prefs - ); - - } - - /** - * Process Handler - * - * @since 1.0 - * @version 1.0 - */ - public function process() - { - } - - /** - * Results Handler - * - * @since 1.0 - * @version 1.0 - */ - public function returning() - { - - add_filter('mycred_setup_gateways', array( $this, 'relable_gateway' )); - - } - - /** - * Admin Init Handler - * - * @since 1.7 - * @version 1.0 - */ - public function admin_init() - { - - add_filter('mycred_setup_gateways', array( $this, 'relable_gateway' )); - - } - - /** - * Results Handler - * - * @since 1.7.6 - * @version 1.0 - */ - public function relable_gateway( $installed ) - { - - if (! empty($this->prefs['title']) && $this->prefs['title'] != $installed['bank']['title'] ) { - $installed['bank']['title'] = $this->prefs['title']; - } - - return $installed; - - } - - /** - * AJAX Buy Handler - * - * @since 1.8 - * @version 1.0 - */ - public function ajax_buy() - { - - $this->toggle_id = 'buycred-checkout-step2'; - - $content = $this->checkout_header(); - $content .= $this->checkout_logo(); - - $content .= '
    '; - - $content .= $this->checkout_order(); - $content .= $this->checkout_cancel(); - - $content .= '
    '; +if ( ! class_exists( 'myCRED_Bank_Transfer' ) ) : + class myCRED_Bank_Transfer extends myCRED_Payment_Gateway { - $content .= $this->checkout_footer(); + /** + * Construct + */ + public function __construct( $gateway_prefs ) { - // Return a JSON response - $this->send_json($content); + $types = mycred_get_types(); + $default_exchange = array(); + foreach ( $types as $type => $label ) + $default_exchange[ $type ] = 1; - } + parent::__construct( array( + 'id' => 'bank', + 'label' => 'Bank Transfer', + 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/bank-transfers/', + 'gateway_logo_url' => '', + 'defaults' => array( + 'title' => '', + 'account' => '', + 'logo_url' => '', + 'currency' => 'EUR', + 'exchange' => $default_exchange + ) + ), $gateway_prefs ); - /** - * Checkout Page Title - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_page_title() - { + } - echo $this->checkout_logo(); + /** + * Process Handler + * @since 1.0 + * @version 1.0 + */ + public function process() { } - } + /** + * Results Handler + * @since 1.0 + * @version 1.0 + */ + public function returning() { - /** - * Checkout Page Body - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_page_body() - { + add_filter( 'mycred_setup_gateways', array( $this, 'relable_gateway' ) ); - $this->toggle_id = 'buycred-checkout-step2'; + } - echo $this->checkout_header(); - echo $this->checkout_logo(false); + /** + * Admin Init Handler + * @since 1.7 + * @version 1.0 + */ + public function admin_init() { - echo '
    '; + add_filter( 'mycred_setup_gateways', array( $this, 'relable_gateway' ) ); - echo $this->checkout_order(); - echo $this->checkout_cancel(); + } - echo '
    '; + return $installed; - echo $this->checkout_footer(); + } - } + /** + * AJAX Buy Handler + * @since 1.8 + * @version 1.0 + */ + public function ajax_buy() { - /** - * Preferences - * - * @since 1.0 - * @version 1.0 - */ - public function preferences() - { + $this->toggle_id = 'buycred-checkout-step2'; - $prefs = $this->prefs; + $content = $this->checkout_header(); + $content .= $this->checkout_logo(); - ?> + $content .= '
    '; + + $content .= $this->checkout_order(); + $content .= $this->checkout_cancel(); + + $content .= '
    '; + + $content .= $this->checkout_footer(); + + // Return a JSON response + $this->send_json( $content ); + + } + + /** + * Checkout Page Title + * @since 1.8 + * @version 1.0 + */ + public function checkout_page_title() { + + echo $this->checkout_logo(); + + } + + /** + * Checkout Page Body + * @since 1.8 + * @version 1.0 + */ + public function checkout_page_body() { + + $this->toggle_id = 'buycred-checkout-step2'; + + echo $this->checkout_header(); + echo $this->checkout_logo( false ); + + echo '
    '; + + echo $this->checkout_order(); + echo $this->checkout_cancel(); + + echo '
    '; + + echo $this->checkout_footer(); + + } + + /** + * Preferences + * @since 1.0 + * @version 1.0 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -
    -

    -
    - - -
    -
    - - -
    -
    -
    -

    -
    - - -
    -
    - - - exchange_rate_setup(); ?> - -
    -
    +
    +

    +
    + + +
    +
    + + +
    +
    +
    +

    +
    + + +
    +
    + + + exchange_rate_setup(); ?> + +
    +
    -
    -
    - - $this->field_name('account'), 'textarea_rows' => 10 )); ?> -
    -
    +
    +
    + + $this->field_name( 'account' ), 'textarea_rows' => 10 ) ); ?> +
    +
    - $rate ) { - if ($rate != 1 && in_array(substr($rate, 0, 1), array( '.', ',' )) ) { - $data['exchange'][ $type ] = (float) '0' . $rate; - } - } - } - $new_data['exchange'] = $data['exchange']; + // If exchange is less then 1 we must start with a zero + if ( isset( $data['exchange'] ) ) { + foreach ( (array) $data['exchange'] as $type => $rate ) { + if ( $rate != 1 && in_array( substr( $rate, 0, 1 ), array( '.', ',' ) ) ) + $data['exchange'][ $type ] = (float) '0' . $rate; + } + } + $new_data['exchange'] = $data['exchange']; - return $new_data; + return $new_data; - } + } - } + } endif; diff --git a/addons/buy-creds/gateways/bitpay.php b/addons/buy-creds/gateways/bitpay.php index 6e90d59..a6c776c 100644 --- a/addons/buy-creds/gateways/bitpay.php +++ b/addons/buy-creds/gateways/bitpay.php @@ -1,637 +1,606 @@ $label ) { - $default_exchange[ $type ] = 1; - } + /** + * Construct + */ + public function __construct( $gateway_prefs ) { - parent::__construct( - array( - 'id' => 'bitpay', - 'label' => 'Bitpay', - 'gateway_logo_url' => plugins_url('assets/images/bitpay.png', MYCRED_PURCHASE), - 'defaults' => array( - 'sandbox' => 0, - 'api_public' => '', - 'api_secret' => '', - 'api_sign' => '', - 'api_token' => '', - 'api_label' => '', - 'currency' => 'USD', - 'exchange' => $default_exchange, - 'item_name' => 'Purchase of myCRED %plural%', - 'logo_url' => '', - 'speed' => 'high', - 'notifications' => 1 - ) - ), $gateway_prefs - ); - - $this->is_ready = false; - if (isset($this->prefs['api_public']) && ! empty($this->prefs['api_public']) && isset($this->prefs['api_secret']) && ! empty($this->prefs['api_secret']) ) { - $this->is_ready = true; - } + $types = mycred_get_types(); + $default_exchange = array(); + foreach ( $types as $type => $label ) + $default_exchange[ $type ] = 1; - } + parent::__construct( array( + 'id' => 'bitpay', + 'label' => 'Bitpay', + 'gateway_logo_url' => plugins_url( 'assets/images/bitpay.png', MYCRED_PURCHASE ), + 'defaults' => array( + 'sandbox' => 0, + 'api_public' => '', + 'api_secret' => '', + 'api_sign' => '', + 'api_token' => '', + 'api_label' => '', + 'currency' => 'USD', + 'exchange' => $default_exchange, + 'item_name' => 'Purchase of myCRED %plural%', + 'logo_url' => '', + 'speed' => 'high', + 'notifications' => 1 + ) + ), $gateway_prefs ); - /** - * Process - * - * @since 1.4 - * @version 1.2 - */ - public function process() - { + $this->is_ready = false; + if ( isset( $this->prefs['api_public'] ) && ! empty( $this->prefs['api_public'] ) && isset( $this->prefs['api_secret'] ) && ! empty( $this->prefs['api_secret'] ) ) + $this->is_ready = true; - $post = file_get_contents("php://input"); - if (! empty($post) ) { + } - $new_call = array(); - $json = json_decode($post, true); - if (! empty($json) && array_key_exists('id', $json) && array_key_exists('url', $json) ) { + /** + * Process + * @since 1.4 + * @version 1.2 + */ + public function process() { - try { + $post = file_get_contents( "php://input" ); + if ( ! empty( $post ) ) { - $client = new \Bitpay\Client\Client(); - if (false === strpos($json['url'], 'test') ) { - $network = new \Bitpay\Network\Livenet(); - } else { - $network = new \Bitpay\Network\Testnet(); - } + $new_call = array(); + $json = json_decode( $post, true ); + if ( ! empty( $json ) && array_key_exists( 'id', $json ) && array_key_exists( 'url', $json ) ) { - $client->setNetwork($network); - $curlAdapter = new \Bitpay\Client\Adapter\CurlAdapter(); - $client->setAdapter($curlAdapter); + try { - $client->setPrivateKey(buycred_bitpay_decrypt($this->prefs['api_secret'])); - $client->setPublicKey(buycred_bitpay_decrypt($this->prefs['api_public'])); - $client->setToken(buycred_bitpay_decrypt($this->prefs['api_token'])); + $client = new \Bitpay\Client\Client(); + if ( false === strpos( $json['url'], 'test' ) ) + $network = new \Bitpay\Network\Livenet(); + else + $network = new \Bitpay\Network\Testnet(); - $invoice = $client->getInvoice($json['id']); + $client->setNetwork( $network ); + $curlAdapter = new \Bitpay\Client\Adapter\CurlAdapter(); + $client->setAdapter( $curlAdapter ); - } catch ( \Exception $e ) { + $client->setPrivateKey( buycred_bitpay_decrypt( $this->prefs['api_secret'] ) ); + $client->setPublicKey( buycred_bitpay_decrypt( $this->prefs['api_public'] ) ); + $client->setToken( buycred_bitpay_decrypt( $this->prefs['api_token'] ) ); - $new_call[] = $e->getMessage(); + $invoice = $client->getInvoice( $json['id'] ); - } + } catch ( \Exception $e ) { - if (empty($new_call) ) { + $new_call[] = $e->getMessage(); - $transaction_id = $invoice->getOrderId(); - $pending_post_id = buycred_get_pending_payment_id($transaction_id); - $pending_payment = $this->get_pending_payment($pending_post_id); + } - if ($pending_payment !== false ) { + if ( empty( $new_call ) ) { - // If account is credited, delete the post and it's comments. - if ($this->complete_payment($pending_payment, $json['id']) ) { - $this->trash_pending_payment($pending_post_id); - } else { - $new_call[] = __('Failed to credit users account.', 'mycred'); - } + $transaction_id = $invoice->getOrderId(); + $pending_post_id = buycred_get_pending_payment_id( $transaction_id ); + $pending_payment = $this->get_pending_payment( $pending_post_id ); - // Log Call - if (! empty($new_call) ) { - $this->log_call($pending_post_id, $new_call); - } + if ( $pending_payment !== false ) { - } + // If account is credited, delete the post and it's comments. + if ( $this->complete_payment( $pending_payment, $json['id'] ) ) + $this->trash_pending_payment( $pending_post_id ); + else + $new_call[] = __( 'Failed to credit users account.', 'mycred' ); - } + // Log Call + if ( ! empty( $new_call ) ) + $this->log_call( $pending_post_id, $new_call ); - } + } - } + } - } + } - /** - * Returning - * - * @since 1.4 - * @version 1.0 - */ - public function returning() - { - } + } - /** - * Admin Init Handler - * - * @since 1.8 - * @version 1.0 - */ - public function admin_init() - { + } - add_action('wp_ajax_buycred-bitpay-pairing', array( $this, 'ajax_pair' )); + /** + * Returning + * @since 1.4 + * @version 1.0 + */ + public function returning() { } - } + /** + * Admin Init Handler + * @since 1.8 + * @version 1.0 + */ + public function admin_init() { - /** - * AJAX: Pair with bitPay - * - * @since 1.8 - * @version 1.0 - */ - public function ajax_pair() - { + add_action( 'wp_ajax_buycred-bitpay-pairing', array( $this, 'ajax_pair' ) ); - check_ajax_referer('buycred-pair-bitpay', 'token'); + } - $pairing_code = sanitize_text_field($_POST['code']); - $network = sanitize_text_field($_POST['network']); + /** + * AJAX: Pair with bitPay + * @since 1.8 + * @version 1.0 + */ + public function ajax_pair() { - try { + check_ajax_referer( 'buycred-pair-bitpay', 'token' ); - $key = new \Bitpay\PrivateKey(); - $key->generate(); + $pairing_code = sanitize_text_field( $_POST['code'] ); + $network = sanitize_text_field( $_POST['network'] ); - $pub = new \Bitpay\PublicKey(); - $pub->setPrivateKey($key); - $pub->generate(); + try { - $sin = new \Bitpay\SinKey(); - $sin->setPublicKey($pub); - $sin->generate(); + $key = new \Bitpay\PrivateKey(); + $key->generate(); - $client = new \Bitpay\Client\Client(); + $pub = new \Bitpay\PublicKey(); + $pub->setPrivateKey( $key ); + $pub->generate(); - if ($network === 'live' ) { - $client->setNetwork(new \Bitpay\Network\Livenet()); - } else { - $client->setNetwork(new \Bitpay\Network\Testnet()); - } + $sin = new \Bitpay\SinKey(); + $sin->setPublicKey( $pub ); + $sin->generate(); - $curlAdapter = new \Bitpay\Client\Adapter\CurlAdapter(); + $client = new \Bitpay\Client\Client(); - $client->setAdapter($curlAdapter); - $client->setPrivateKey($key); - $client->setPublicKey($pub); + if ( $network === 'live' ) + $client->setNetwork( new \Bitpay\Network\Livenet() ); + else + $client->setNetwork( new \Bitpay\Network\Testnet() ); - } catch ( \Exception $e ) { - wp_send_json_error($e->getMessage()); - } + $curlAdapter = new \Bitpay\Client\Adapter\CurlAdapter(); - $label = preg_replace('/[^a-zA-Z0-9 \-\_\.]/', '', get_bloginfo()); - $label = substr('buyCRED - ' . $label, 0, 59); + $client->setAdapter( $curlAdapter ); + $client->setPrivateKey( $key ); + $client->setPublicKey( $pub ); - try { + } catch ( \Exception $e ) { + wp_send_json_error( $e->getMessage() ); + } - $token = $client->createToken( - array( - 'id' => (string) $sin, - 'pairingCode' => $pairing_code, - 'label' => $label, - ) - ); + $label = preg_replace( '/[^a-zA-Z0-9 \-\_\.]/', '', get_bloginfo() ); + $label = substr( 'buyCRED - ' . $label, 0, 59 ); - } catch ( \Exception $e ) { + try { - wp_send_json_error($e->getMessage()); + $token = $client->createToken( + array( + 'id' => (string) $sin, + 'pairingCode' => $pairing_code, + 'label' => $label, + ) + ); - } + } catch ( \Exception $e ) { - if ($network !== 'live' ) { - $label .= ' (Testnet)'; - } + wp_send_json_error( $e->getMessage() ); - wp_send_json_success( - array( - 'api_secret' => '', - 'api_public' => '', - 'api_sign' => '', - 'api_token' => '', - 'label' => '

    ' . $label . '

    ' - ) - ); + } - } + if ( $network !== 'live' ) + $label .= ' (Testnet)'; - /** - * Prep Sale - * - * @since 1.8 - * @version 1.0 - */ - public function prep_sale( $new_transaction = false ) - { + wp_send_json_success( array( + 'api_secret' => '', + 'api_public' => '', + 'api_sign' => '', + 'api_token' => '', + 'label' => '

    ' . $label . '

    ' + ) ); - // Set currency - $this->currency = ( $this->currency == '' ) ? $this->prefs['currency'] : $this->currency; + } - //Set Cost in raw format - $this->cost = $this->get_cost($this->amount, $this->point_type, true); + /** + * Prep Sale + * @since 1.8 + * @version 1.0 + */ + public function prep_sale( $new_transaction = false ) { - // Item Name - $item_name = str_replace('%number%', $this->amount, $this->prefs['item_name']); - $item_name = $this->core->template_tags_general($item_name); + // Set currency + $this->currency = ( $this->currency == '' ) ? $this->prefs['currency'] : $this->currency; - $user = get_userdata($this->buyer_id); + //Set Cost in raw format + $this->cost = $this->get_cost( $this->amount, $this->point_type, true ); - // Based on the "BitPay for WooCommerce" plugin issued by Bitpay - try { + // Item Name + $item_name = str_replace( '%number%', $this->amount, $this->prefs['item_name'] ); + $item_name = $this->core->template_tags_general( $item_name ); - // Currency - $currency = new \Bitpay\Currency($this->currency); + $user = get_userdata( $this->buyer_id ); - // First, we set the client - $client = new \Bitpay\Client\Client(); + // Based on the "BitPay for WooCommerce" plugin issued by Bitpay + try { - if (! $this->sandbox_mode ) { - $client->setNetwork(new \Bitpay\Network\Livenet()); - } else { - $client->setNetwork(new \Bitpay\Network\Testnet()); - } + // Currency + $currency = new \Bitpay\Currency( $this->currency ); - $curlAdapter = new \Bitpay\Client\Adapter\CurlAdapter(); - $client->setAdapter($curlAdapter); + // First, we set the client + $client = new \Bitpay\Client\Client(); - $client->setPrivateKey(buycred_bitpay_decrypt($this->prefs['api_secret'])); - $client->setPublicKey(buycred_bitpay_decrypt($this->prefs['api_public'])); - $client->setToken(buycred_bitpay_decrypt($this->prefs['api_token'])); + if ( ! $this->sandbox_mode ) + $client->setNetwork( new \Bitpay\Network\Livenet() ); + else + $client->setNetwork( new \Bitpay\Network\Testnet() ); - // Next, we create an invoice object - $invoice = new \Bitpay\Invoice(); - $invoice->setOrderId((string) $this->transaction_id); - $invoice->setCurrency($currency); - $invoice->setFullNotifications(( ( $this->prefs['notifications'] ) ? true : false )); + $curlAdapter = new \Bitpay\Client\Adapter\CurlAdapter(); + $client->setAdapter($curlAdapter); - // Next, we set the invoice item - $item = new \Bitpay\Item(); - $item->setPrice($this->cost); - $item->setDescription($item_name); + $client->setPrivateKey( buycred_bitpay_decrypt( $this->prefs['api_secret'] ) ); + $client->setPublicKey( buycred_bitpay_decrypt( $this->prefs['api_public'] ) ); + $client->setToken( buycred_bitpay_decrypt( $this->prefs['api_token'] ) ); - // This includes setting the buyer - $buyer = new \Bitpay\Buyer(); - $buyer->setEmail($user->user_email); + // Next, we create an invoice object + $invoice = new \Bitpay\Invoice(); + $invoice->setOrderId( (string) $this->transaction_id ); + $invoice->setCurrency( $currency ) ; + $invoice->setFullNotifications( ( ( $this->prefs['notifications'] ) ? true : false ) ); - $invoice->setBuyer($buyer); - $invoice->setItem($item); + // Next, we set the invoice item + $item = new \Bitpay\Item(); + $item->setPrice( $this->cost ); + $item->setDescription( $item_name ); - // Append extras - $invoice->setRedirectUrl($this->get_thankyou()); - $invoice->setNotificationUrl($this->callback_url()); - $invoice->setTransactionSpeed($this->prefs['speed']); + // This includes setting the buyer + $buyer = new \Bitpay\Buyer(); + $buyer->setEmail( $user->user_email ); - // Create an invoice - $invoice = $client->createInvoice($invoice); + $invoice->setBuyer( $buyer ); + $invoice->setItem( $item ); - } catch ( \Exception $e ) { + // Append extras + $invoice->setRedirectUrl( $this->get_thankyou() ); + $invoice->setNotificationUrl( $this->callback_url() ); + $invoice->setTransactionSpeed( $this->prefs['speed'] ); - $this->errors[] = $e->getMessage(); + // Create an invoice + $invoice = $client->createInvoice( $invoice ); - } + } catch ( \Exception $e ) { - if (empty($this->errors) ) { + $this->errors[] = $e->getMessage(); - $this->redirect_to = $invoice->getUrl(); + } - } + if ( empty( $this->errors ) ) { - } + $this->redirect_to = $invoice->getUrl(); - /** - * AJAX Buy Handler - * - * @since 1.8 - * @version 1.0 - */ - public function ajax_buy() - { + } - // Construct the checkout box content - $content = $this->checkout_header(); - $content .= $this->checkout_logo(); - $content .= $this->checkout_order(); - $content .= $this->checkout_cancel(); - $content .= $this->checkout_footer(); + } - // Return a JSON response - $this->send_json($content); + /** + * AJAX Buy Handler + * @since 1.8 + * @version 1.0 + */ + public function ajax_buy() { - } + // Construct the checkout box content + $content = $this->checkout_header(); + $content .= $this->checkout_logo(); + $content .= $this->checkout_order(); + $content .= $this->checkout_cancel(); + $content .= $this->checkout_footer(); - /** - * Checkout Page Body - * This gateway only uses the checkout body. - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_page_body() - { + // Return a JSON response + $this->send_json( $content ); - echo $this->checkout_header(); - echo $this->checkout_logo(false); + } - echo $this->checkout_order(); - echo $this->checkout_cancel(); + /** + * Checkout Page Body + * This gateway only uses the checkout body. + * @since 1.8 + * @version 1.0 + */ + public function checkout_page_body() { - echo $this->checkout_footer(); + echo $this->checkout_header(); + echo $this->checkout_logo( false ); - } + echo $this->checkout_order(); + echo $this->checkout_cancel(); - /** - * Gateway Prefs - * - * @since 1.4 - * @version 1.0 - */ - function preferences() - { + echo $this->checkout_footer(); + + } + + /** + * Gateway Prefs + * @since 1.4 + * @version 1.0 + */ + function preferences() { - $prefs = $this->prefs; + $prefs = $this->prefs; - ?> +?>
    -
    -

    - - is_ready ) : ?> - -
    - -
    - - - -
    - - -
    +
    +

    + + is_ready ) : ?> + +
    + +
    + + + +
    + + +
    - - -
    - -

    - - - - - - -
    + + +
    + +

    + + + + + + +
    - - -
    - - -
    -
    - - -
    -
    -
    -
    - - -
    -
    -
    -
    - - -
    -
    -
    -
    -
    -

    -
    - - - -
    -
    - - - exchange_rate_setup(); ?> - -
    -
    -
    - $rate ) { - if ($rate != 1 && in_array(substr($rate, 0, 1), array( '.', ',' )) ) { - $data['exchange'][ $type ] = (float) '0' . $rate; - } - } - } - $new_data['exchange'] = $data['exchange']; + + +
    + + +
    +
    + + +
    +
    +
    +
    + + +
    +
    +
    +
    + + +
    +
    +
    +
    +
    +

    +
    + + + +
    +
    + + + exchange_rate_setup(); ?> + +
    +
    +
    + $rate ) { + if ( $rate != 1 && in_array( substr( $rate, 0, 1 ), array( '.', ',' ) ) ) + $data['exchange'][ $type ] = (float) '0' . $rate; + } + } + $new_data['exchange'] = $data['exchange']; + + return $new_data; + + } + + } endif; /** * Bitpay Encrypt - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('buycred_bitpay_encrypt') ) : - function buycred_bitpay_encrypt( $data ) - { +if ( ! function_exists( 'buycred_bitpay_encrypt' ) ) : + function buycred_bitpay_encrypt( $data ) { if (false === isset($data) || true === empty($data)) { throw new \Exception('The Bitpay payment plugin was called to encrypt data but no data was passed!'); @@ -640,10 +609,10 @@ function buycred_bitpay_encrypt( $data ) $openssl_ext = new \Bitpay\Crypto\OpenSSLExtension(); $fingerprint = sha1(sha1(__DIR__)); - if (true === isset($fingerprint) - && true === isset($openssl_ext) - && strlen($fingerprint) > 24 - ) { + if (true === isset($fingerprint) && + true === isset($openssl_ext) && + strlen($fingerprint) > 24) + { $fingerprint = substr($fingerprint, 0, 24); if (false === isset($fingerprint) || true === empty($fingerprint)) { @@ -661,18 +630,16 @@ function buycred_bitpay_encrypt( $data ) wp_die('Invalid server fingerprint generated'); } - } + } endif; /** * Bitpay Decrypt - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('buycred_bitpay_decrypt') ) : - function buycred_bitpay_decrypt( $encrypted ) - { +if ( ! function_exists( 'buycred_bitpay_decrypt' ) ) : + function buycred_bitpay_decrypt( $encrypted ) { if (false === isset($encrypted) || true === empty($encrypted)) { throw new \Exception('The Bitpay payment plugin was called to decrypt data but no data was passed!'); @@ -681,10 +648,10 @@ function buycred_bitpay_decrypt( $encrypted ) $fingerprint = sha1(sha1(__DIR__)); - if (true === isset($fingerprint) - && true === isset($openssl_ext) - && strlen($fingerprint) > 24 - ) { + if (true === isset($fingerprint) && + true === isset($openssl_ext) && + strlen($fingerprint) > 24) + { $fingerprint = substr($fingerprint, 0, 24); if (false === isset($fingerprint) || true === empty($fingerprint)) { @@ -709,5 +676,5 @@ function buycred_bitpay_decrypt( $encrypted ) wp_die('Invalid server fingerprint generated'); } - } + } endif; diff --git a/addons/buy-creds/gateways/index.php b/addons/buy-creds/gateways/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/gateways/index.php +++ b/addons/buy-creds/gateways/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/gateways/netbilling.php b/addons/buy-creds/gateways/netbilling.php index 05451d8..9cbc842 100644 --- a/addons/buy-creds/gateways/netbilling.php +++ b/addons/buy-creds/gateways/netbilling.php @@ -1,326 +1,297 @@ $label ) { - $default_exchange[ $type ] = 1; - } - - parent::__construct( - array( - 'id' => 'netbilling', - 'label' => 'NETbilling', - 'gateway_logo_url' => plugins_url('assets/images/netbilling.png', MYCRED_PURCHASE), - 'defaults' => array( - 'sandbox' => 0, - 'account' => '', - 'site_tag' => '', - 'item_name' => 'Purchase of myCRED %plural%', - 'exchange' => $default_exchange, - 'logo_url' => '', - 'cryptokey' => '', - 'currency' => 'USD' - ) - ), $gateway_prefs - ); - - } - - /** - * IPN - Is Valid Call - * Replaces the default check - * - * @since 1.4 - * @version 1.0 - */ - public function IPN_is_valid_call() - { - - $result = true; - - // Accounts Match - $account = explode(':', sanitize_text_field( $_REQUEST['Ecom_Ezic_AccountAndSitetag'] )); - if ($account[0] != $this->prefs['account'] || $account[1] != $this->prefs['site_tag'] ) { - $result = false; - } - - // Crypto Check - $crypto_check = md5($this->prefs['cryptokey'] . sanitize_text_field($_REQUEST['Ecom_Cost_Total']) . sanitize_text_field($_REQUEST['Ecom_Receipt_Description'])); - if ($crypto_check != $_REQUEST['Ecom_Ezic_Security_HashValue_MD5'] ) { - $result = false; - } - - return $result; - - } - - /** - * Process - * - * @since 0.1 - * @version 1.2 - */ - public function process() - { - - // Required fields - if (isset($_REQUEST['Ecom_UserData_salesdata']) && isset($_REQUEST['Ecom_Ezic_Response_TransactionID']) && isset($_REQUEST['Ecom_Cost_Total']) ) { - - // Get Pending Payment - $pending_post_id = sanitize_key($_REQUEST['Ecom_UserData_salesdata']); - $pending_payment = $this->get_pending_payment($pending_post_id); - if ($pending_payment !== false ) { - - // Verify Call with PayPal - if ($this->IPN_is_valid_call() ) { - - $errors = false; - $new_call = array(); - - // Check amount paid - if ($_REQUEST['Ecom_Cost_Total'] != $pending_payment->cost ) { - $new_call[] = sprintf(__('Price mismatch. Expected: %s Received: %s', 'mycred'), $pending_payment->cost, floatval( $_REQUEST['Ecom_Cost_Total'] )); - $errors = true; - } - - // Check status - if ($_REQUEST['Ecom_Ezic_Response_StatusCode'] != 1 ) { - $new_call[] = sprintf(__('Payment not completed. Received: %s', 'mycred'), intval( $_REQUEST['Ecom_Ezic_Response_StatusCode'] )); - $errors = true; - } - - // Credit payment - if ($errors === false ) { - - // If account is credited, delete the post and it's comments. - if ($this->complete_payment($pending_payment, sanitize_title( $_REQUEST['Ecom_Ezic_Response_TransactionID'] )) ) { - $this->trash_pending_payment($pending_post_id); - } else { - $new_call[] = __('Failed to credit users account.', 'mycred'); - } - - } - - // Log Call - if (! empty($new_call) ) { - $this->log_call($pending_post_id, $new_call); - } - - } - - } - - } - - } - - /** - * Returns - * - * @since 0.1 - * @version 1.1 - */ - public function returning() - { - - if (isset($_REQUEST['Ecom_Ezic_AccountAndSitetag']) && isset($_REQUEST['Ecom_UserData_salesdata']) ) { - $this->process(); - } - - } - - /** - * Prep Sale - * - * @since 1.8 - * @version 1.0 - */ - public function prep_sale( $new_transaction = false ) - { - - // Set currency - $this->currency = ( $this->currency == '' ) ? $this->prefs['currency'] : $this->currency; - - // The item name - $item_name = str_replace('%number%', $this->amount, $this->prefs['item_name']); - $item_name = $this->core->template_tags_general($item_name); - - // This gateway redirects, so we need to populate redirect_to - $this->redirect_to = 'https://secure.netbilling.com/gw/native/interactive2.2'; - - // Transaction variables that needs to be submitted - $this->redirect_fields = array( - 'Ecom_Ezic_AccountAndSitetag' => $this->prefs['account'] . ':' . $this->prefs['site_tag'], - 'Ecom_Ezic_Payment_AuthorizationType' => 'SALE', - 'Ecom_Receipt_Description' => $item_name, - 'Ecom_Ezic_Fulfillment_ReturnMethod' => 'POST', - 'Ecom_Cost_Total' => $this->cost, - 'Ecom_UserData_salesdata' => $this->transaction_id, - 'Ecom_Ezic_Fulfillment_ReturnURL' => $this->get_thankyou(), - 'Ecom_Ezic_Fulfillment_GiveUpURL' => $this->get_cancelled($this->transaction_id), - 'Ecom_Ezic_Security_HashValue_MD5' => md5($this->prefs['cryptokey'] . $this->cost . $item_name), - 'Ecom_Ezic_Security_HashFields' => 'Ecom_Cost_Total Ecom_Receipt_Description' - ); - - } - - /** - * AJAX Buy Handler - * - * @since 1.8 - * @version 1.0 - */ - public function ajax_buy() - { - - // Construct the checkout box content - $content = $this->checkout_header(); - $content .= $this->checkout_logo(); - $content .= $this->checkout_order(); - $content .= $this->checkout_cancel(); - $content .= $this->checkout_footer(); - - // Return a JSON response - $this->send_json($content); - - } - - /** - * Checkout Page Body - * This gateway only uses the checkout body. - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_page_body() - { - - echo $this->checkout_header(); - echo $this->checkout_logo(false); - - echo $this->checkout_order(); - echo $this->checkout_cancel(); - - echo $this->checkout_footer(); - - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +if ( ! class_exists( 'myCRED_NETbilling' ) ) : + class myCRED_NETbilling extends myCRED_Payment_Gateway { + + protected $http_code = ''; + + /** + * Construct + */ + public function __construct( $gateway_prefs ) { + + global $netbilling_errors; + + $types = mycred_get_types(); + $default_exchange = array(); + foreach ( $types as $type => $label ) + $default_exchange[ $type ] = 1; + + parent::__construct( array( + 'id' => 'netbilling', + 'label' => 'NETbilling', + 'gateway_logo_url' => plugins_url( 'assets/images/netbilling.png', MYCRED_PURCHASE ), + 'defaults' => array( + 'sandbox' => 0, + 'account' => '', + 'site_tag' => '', + 'item_name' => 'Purchase of myCRED %plural%', + 'exchange' => $default_exchange, + 'logo_url' => '', + 'cryptokey' => '', + 'currency' => 'USD' + ) + ), $gateway_prefs ); + + } + + /** + * IPN - Is Valid Call + * Replaces the default check + * @since 1.4 + * @version 1.0 + */ + public function IPN_is_valid_call() { + + $result = true; + + // Accounts Match + $account = explode( ':', sanitize_text_field( $_REQUEST['Ecom_Ezic_AccountAndSitetag'] ) ); + if ( $account[0] != $this->prefs['account'] || $account[1] != $this->prefs['site_tag'] ) + $result = false; + + // Crypto Check + $crypto_check = md5( $this->prefs['cryptokey'] . sanitize_text_field( $_REQUEST['Ecom_Cost_Total'] ) . sanitize_text_field( $_REQUEST['Ecom_Receipt_Description'] ) ); + if ( $crypto_check != $_REQUEST['Ecom_Ezic_Security_HashValue_MD5'] ) + $result = false; + + return $result; + + } + + /** + * Process + * @since 0.1 + * @version 1.2 + */ + public function process() { + + // Required fields + if ( isset( $_REQUEST['Ecom_UserData_salesdata'] ) && isset( $_REQUEST['Ecom_Ezic_Response_TransactionID'] ) && isset( $_REQUEST['Ecom_Cost_Total'] ) ) { + + // Get Pending Payment + $pending_post_id = sanitize_key( $_REQUEST['Ecom_UserData_salesdata'] ); + $pending_payment = $this->get_pending_payment( $pending_post_id ); + if ( $pending_payment !== false ) { + + // Verify Call with PayPal + if ( $this->IPN_is_valid_call() ) { + + $errors = false; + $new_call = array(); + + // Check amount paid + if ( $_REQUEST['Ecom_Cost_Total'] != $pending_payment->cost ) { + $new_call[] = sprintf( __( 'Price mismatch. Expected: %s Received: %s', 'mycred' ), $pending_payment->cost, $_REQUEST['Ecom_Cost_Total'] ); + $errors = true; + } + + // Check status + if ( $_REQUEST['Ecom_Ezic_Response_StatusCode'] != 1 ) { + $new_call[] = sprintf( __( 'Payment not completed. Received: %s', 'mycred' ), absint( $_REQUEST['Ecom_Ezic_Response_StatusCode'] ) ); + $errors = true; + } + + // Credit payment + if ( $errors === false ) { + + // If account is credited, delete the post and it's comments. + if ( $this->complete_payment( $pending_payment, sanitize_title( $_REQUEST['Ecom_Ezic_Response_TransactionID'] ) ) ) + $this->trash_pending_payment( $pending_post_id ); + else + $new_call[] = __( 'Failed to credit users account.', 'mycred' ); + + } + + // Log Call + if ( ! empty( $new_call ) ) + $this->log_call( $pending_post_id, $new_call ); + + } + + } + + } + + } + + /** + * Returns + * @since 0.1 + * @version 1.1 + */ + public function returning() { + + if ( isset( $_REQUEST['Ecom_Ezic_AccountAndSitetag'] ) && isset( $_REQUEST['Ecom_UserData_salesdata'] ) ) + $this->process(); + + } + + /** + * Prep Sale + * @since 1.8 + * @version 1.0 + */ + public function prep_sale( $new_transaction = false ) { + + // Set currency + $this->currency = ( $this->currency == '' ) ? $this->prefs['currency'] : $this->currency; + + // The item name + $item_name = str_replace( '%number%', $this->amount, $this->prefs['item_name'] ); + $item_name = $this->core->template_tags_general( $item_name ); + + // This gateway redirects, so we need to populate redirect_to + $this->redirect_to = 'https://secure.netbilling.com/gw/native/interactive2.2'; + + // Transaction variables that needs to be submitted + $this->redirect_fields = array( + 'Ecom_Ezic_AccountAndSitetag' => $this->prefs['account'] . ':' . $this->prefs['site_tag'], + 'Ecom_Ezic_Payment_AuthorizationType' => 'SALE', + 'Ecom_Receipt_Description' => $item_name, + 'Ecom_Ezic_Fulfillment_ReturnMethod' => 'POST', + 'Ecom_Cost_Total' => $this->cost, + 'Ecom_UserData_salesdata' => $this->transaction_id, + 'Ecom_Ezic_Fulfillment_ReturnURL' => $this->get_thankyou(), + 'Ecom_Ezic_Fulfillment_GiveUpURL' => $this->get_cancelled( $this->transaction_id ), + 'Ecom_Ezic_Security_HashValue_MD5' => md5( $this->prefs['cryptokey'] . $this->cost . $item_name ), + 'Ecom_Ezic_Security_HashFields' => 'Ecom_Cost_Total Ecom_Receipt_Description' + ); + + } + + /** + * AJAX Buy Handler + * @since 1.8 + * @version 1.0 + */ + public function ajax_buy() { + + // Construct the checkout box content + $content = $this->checkout_header(); + $content .= $this->checkout_logo(); + $content .= $this->checkout_order(); + $content .= $this->checkout_cancel(); + $content .= $this->checkout_footer(); + + // Return a JSON response + $this->send_json( $content ); + + } + + /** + * Checkout Page Body + * This gateway only uses the checkout body. + * @since 1.8 + * @version 1.0 + */ + public function checkout_page_body() { + + echo $this->checkout_header(); + echo $this->checkout_logo( false ); + + echo $this->checkout_order(); + echo $this->checkout_cancel(); + + echo $this->checkout_footer(); + + } + + /** + * Preferences + * @since 0.1 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -
    -

    -
    - - -
    -
    - - -
    -
    - - -

    -
    -
    - - -
    -
    - - -
    -
    -
    -

    -
    - - -
    -
    - - - exchange_rate_setup(); ?> - -
    -
    - - callback_url(); ?> -

    -
    -
    +
    +

    +
    + + +
    +
    + + +
    +
    + + +

    +
    +
    + + +
    +
    + + +
    +
    +
    +

    +
    + + +
    +
    + + + exchange_rate_setup(); ?> + +
    +
    + + callback_url(); ?> +

    +
    +
    - $rate ) { - if ($rate != 1 && in_array(substr($rate, 0, 1), array( '.', ',' )) ) { - $data['exchange'][ $type ] = (float) '0' . $rate; - } - } - } - $new_data['exchange'] = $data['exchange']; - - return $new_data; - - } - - } + $rate ) { + if ( $rate != 1 && in_array( substr( $rate, 0, 1 ), array( '.', ',' ) ) ) + $data['exchange'][ $type ] = (float) '0' . $rate; + } + } + $new_data['exchange'] = $data['exchange']; + + return $new_data; + + } + + } endif; diff --git a/addons/buy-creds/gateways/paypal-standard.php b/addons/buy-creds/gateways/paypal-standard.php index a1309ec..4acbba8 100644 --- a/addons/buy-creds/gateways/paypal-standard.php +++ b/addons/buy-creds/gateways/paypal-standard.php @@ -1,379 +1,349 @@ $label ) { - $default_exchange[ $type ] = 1; - } - - parent::__construct( - array( - 'id' => 'paypal-standard', - 'label' => 'PayPal', - 'gateway_logo_url' => plugins_url('assets/images/paypal.png', MYCRED_PURCHASE), - 'defaults' => array( - 'sandbox' => 0, - 'currency' => '', - 'account' => '', - 'logo_url' => '', - 'item_name' => 'Purchase of myCRED %plural%', - 'exchange' => $default_exchange - ) - ), $gateway_prefs - ); - - } - - /** - * IPN - Is Valid Call - * Replaces the default check - * - * @since 1.4 - * @version 1.0.1 - */ - public function IPN_is_valid_call() - { - - // PayPal Host - $host = 'www.paypal.com'; - if ($this->sandbox_mode ) { - $host = 'www.sandbox.paypal.com'; - } - - $data = $this->POST_to_data(); - - // Prep Respons - $request = 'cmd=_notify-validate'; - $get_magic_quotes_exists = false; - if (function_exists('get_magic_quotes_gpc') ) { - $get_magic_quotes_exists = true; - } - - foreach ( $data as $key => $value ) { - if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1 ) { - $value = urlencode(stripslashes($value)); - } else { - $value = urlencode($value); - } - - $request .= "&$key=$value"; - } - - // Call PayPal - $curl_attempts = apply_filters('mycred_paypal_standard_max_attempts', 3); - $attempt = 1; - $result = ''; - // We will make a x number of curl attempts before finishing with a fsock. - do { - - $call = curl_init("https://$host/cgi-bin/webscr"); - curl_setopt($call, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); - curl_setopt($call, CURLOPT_POST, 1); - curl_setopt($call, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($call, CURLOPT_POSTFIELDS, $request); - curl_setopt($call, CURLOPT_SSL_VERIFYPEER, 1); - curl_setopt($call, CURLOPT_CAINFO, MYCRED_PURCHASE_DIR . '/cacert.pem'); - curl_setopt($call, CURLOPT_SSL_VERIFYHOST, 2); - curl_setopt($call, CURLOPT_FRESH_CONNECT, 1); - curl_setopt($call, CURLOPT_FORBID_REUSE, 1); - curl_setopt($call, CURLOPT_HTTPHEADER, array( 'Connection: Close', 'User-Agent: myCRED' )); - $result = curl_exec($call); - - // End on success - if ($result !== false ) { - curl_close($call); - break; - } - - curl_close($call); - - // Final try - if ($attempt == $curl_attempts ) { - $header = "POST /cgi-bin/webscr HTTP/1.0\r\n"; - $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; - $header .= "Content-Length: " . strlen($request) . "\r\n\r\n"; - $fp = fsockopen('ssl://' . $host, 443, $errno, $errstr, 30); - if ($fp ) { - fputs($fp, $header . $request); - while ( ! feof($fp) ) { - $result = fgets($fp, 1024); - } - fclose($fp); - } - } - $attempt++; - - } while ( $attempt <= $curl_attempts ); - - if (strcmp($result, "VERIFIED") == 0 ) { - return true; - } - - return false; - - } - - /** - * Process Handler - * - * @since 0.1 - * @version 1.3 - */ - public function process() - { - - // Required fields - if (isset($_POST['custom']) && isset($_POST['txn_id']) && isset($_POST['mc_gross']) ) { - - // Get Pending Payment - $pending_post_id = sanitize_key($_POST['custom']); - $pending_payment = $this->get_pending_payment($pending_post_id); - if ($pending_payment !== false ) { - - // Verify Call with PayPal - if ($this->IPN_is_valid_call() ) { - - $errors = false; - $new_call = array(); - - // Check amount paid - if ($_POST['mc_gross'] != $pending_payment->cost ) { - $new_call[] = sprintf(__('Price mismatch. Expected: %s Received: %s', 'mycred'), $pending_payment->cost, $_POST['mc_gross']); - $errors = true; - } - - // Check currency - if ($_POST['mc_currency'] != $pending_payment->currency ) { - $new_call[] = sprintf(__('Currency mismatch. Expected: %s Received: %s', 'mycred'), $pending_payment->currency, $_POST['mc_currency']); - $errors = true; - } - - // Check status - if ($_POST['payment_status'] != 'Completed' ) { - $new_call[] = sprintf(__('Payment not completed. Received: %s', 'mycred'), $_POST['payment_status']); - $errors = true; - } - - // Credit payment - if ($errors === false ) { - - // If account is credited, delete the post and it's comments. - if ($this->complete_payment($pending_payment, $_POST['txn_id']) ) { - $this->trash_pending_payment($pending_post_id); - } else { - $new_call[] = __('Failed to credit users account.', 'mycred'); - } - - } - - // Log Call - if (! empty($new_call) ) { - $this->log_call($pending_post_id, $new_call); - } - - } - - } - - } - - } - - /** - * Results Handler - * - * @since 0.1 - * @version 1.0.1 - */ - public function returning() - { - - if (isset($_REQUEST['tx']) && isset($_REQUEST['st']) && $_REQUEST['st'] == 'Completed' ) { - $this->get_page_header(__('Success', 'mycred'), $this->get_thankyou()); - echo '

    ' . __('Thank you for your purchase', 'mycred') . '

    '; - $this->get_page_footer(); - exit; - } - - } - - /** - * Prep Sale - * - * @since 1.8 - * @version 1.0 - */ - public function prep_sale( $new_transaction = false ) - { - - // Set currency - $this->currency = ( $this->currency == '' ) ? $this->prefs['currency'] : $this->currency; - - // The item name - $item_name = str_replace('%number%', $this->amount, $this->prefs['item_name']); - $item_name = $this->core->template_tags_general($item_name); - - // This gateway redirects, so we need to populate redirect_to - $this->redirect_to = ( $this->sandbox_mode ) ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr'; - - // Transaction variables that needs to be submitted - $this->redirect_fields = array( - 'cmd' => '_xclick', - 'business' => $this->prefs['account'], - 'item_name' => $item_name, - 'quantity' => 1, - 'amount' => $this->cost, - 'currency_code' => $this->currency, - 'no_shipping' => 1, - 'no_note' => 1, - 'custom' => $this->transaction_id, - 'return' => $this->get_thankyou(), - 'notify_url' => $this->callback_url(), - 'rm' => 2, - 'cbt' => sprintf(_x('Return to %s', 'Return label. %s = Website name', 'mycred'), get_bloginfo('name')), - 'cancel_return' => $this->get_cancelled($this->transaction_id) - ); - - } - - /** - * AJAX Buy Handler - * - * @since 1.8 - * @version 1.0 - */ - public function ajax_buy() - { - - // Construct the checkout box content - $content = $this->checkout_header(); - $content .= $this->checkout_logo(); - $content .= $this->checkout_order(); - $content .= $this->checkout_cancel(); - $content .= $this->checkout_footer(); - - // Return a JSON response - $this->send_json($content); - - } - - /** - * Checkout Page Body - * This gateway only uses the checkout body. - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_page_body() - { - - echo $this->checkout_header(); - echo $this->checkout_logo(false); - - echo $this->checkout_order(); - echo $this->checkout_cancel(); - - echo $this->checkout_footer(); - - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.0 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +if ( ! class_exists( 'myCRED_PayPal_Standard' ) ) : + class myCRED_PayPal_Standard extends myCRED_Payment_Gateway { + + /** + * Construct + */ + public function __construct( $gateway_prefs ) { + + $types = mycred_get_types(); + $default_exchange = array(); + foreach ( $types as $type => $label ) + $default_exchange[ $type ] = 1; + + parent::__construct( array( + 'id' => 'paypal-standard', + 'label' => 'PayPal', + 'gateway_logo_url' => plugins_url( 'assets/images/paypal.png', MYCRED_PURCHASE ), + 'defaults' => array( + 'sandbox' => 0, + 'currency' => '', + 'account' => '', + 'logo_url' => '', + 'item_name' => 'Purchase of myCRED %plural%', + 'exchange' => $default_exchange + ) + ), $gateway_prefs ); + + } + + /** + * IPN - Is Valid Call + * Replaces the default check + * @since 1.4 + * @version 1.0.1 + */ + public function IPN_is_valid_call() { + + // PayPal Host + $host = 'www.paypal.com'; + if ( $this->sandbox_mode ) + $host = 'www.sandbox.paypal.com'; + + $data = $this->POST_to_data(); + + // Prep Respons + $request = 'cmd=_notify-validate'; + $get_magic_quotes_exists = false; + if ( function_exists( 'get_magic_quotes_gpc' ) ) + $get_magic_quotes_exists = true; + + foreach ( $data as $key => $value ) { + if ( $get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1 ) + $value = urlencode( stripslashes( $value ) ); + else + $value = urlencode( $value ); + + $request .= "&$key=$value"; + } + + // Call PayPal + $curl_attempts = apply_filters( 'mycred_paypal_standard_max_attempts', 3 ); + $attempt = 1; + $result = ''; + // We will make a x number of curl attempts before finishing with a fsock. + do { + + $call = curl_init( "https://$host/cgi-bin/webscr" ); + curl_setopt( $call, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 ); + curl_setopt( $call, CURLOPT_POST, 1 ); + curl_setopt( $call, CURLOPT_RETURNTRANSFER, 1 ); + curl_setopt( $call, CURLOPT_POSTFIELDS, $request ); + curl_setopt( $call, CURLOPT_SSL_VERIFYPEER, 1 ); + curl_setopt( $call, CURLOPT_CAINFO, MYCRED_PURCHASE_DIR . '/cacert.pem' ); + curl_setopt( $call, CURLOPT_SSL_VERIFYHOST, 2 ); + curl_setopt( $call, CURLOPT_FRESH_CONNECT, 1 ); + curl_setopt( $call, CURLOPT_FORBID_REUSE, 1 ); + curl_setopt( $call, CURLOPT_HTTPHEADER, array( 'Connection: Close', 'User-Agent: myCRED' ) ); + $result = curl_exec( $call ); + + // End on success + if ( $result !== false ) { + curl_close( $call ); + break; + } + + curl_close( $call ); + + // Final try + if ( $attempt == $curl_attempts ) { + $header = "POST /cgi-bin/webscr HTTP/1.0\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . strlen( $request ) . "\r\n\r\n"; + $fp = fsockopen( 'ssl://' . $host, 443, $errno, $errstr, 30 ); + if ( $fp ) { + fputs( $fp, $header . $request ); + while ( ! feof( $fp ) ) { + $result = fgets( $fp, 1024 ); + } + fclose( $fp ); + } + } + $attempt++; + + } while ( $attempt <= $curl_attempts ); + + if ( strcmp( $result, "VERIFIED" ) == 0 ) + return true; + + return false; + + } + + /** + * Process Handler + * @since 0.1 + * @version 1.3 + */ + public function process() { + + // Required fields + if ( isset( $_POST['custom'] ) && isset( $_POST['txn_id'] ) && isset( $_POST['mc_gross'] ) ) { + + // Get Pending Payment + $pending_post_id = sanitize_key( $_POST['custom'] ); + $pending_payment = $this->get_pending_payment( $pending_post_id ); + if ( $pending_payment !== false ) { + + // Verify Call with PayPal + if ( $this->IPN_is_valid_call() ) { + + $errors = false; + $new_call = array(); + + // Check amount paid + if ( $_POST['mc_gross'] != $pending_payment->cost ) { + $new_call[] = sprintf( __( 'Price mismatch. Expected: %s Received: %s', 'mycred' ), $pending_payment->cost, $_POST['mc_gross'] ); + $errors = true; + } + + // Check currency + if ( $_POST['mc_currency'] != $pending_payment->currency ) { + $new_call[] = sprintf( __( 'Currency mismatch. Expected: %s Received: %s', 'mycred' ), $pending_payment->currency, $_POST['mc_currency'] ); + $errors = true; + } + + // Check status + if ( $_POST['payment_status'] != 'Completed' ) { + $new_call[] = sprintf( __( 'Payment not completed. Received: %s', 'mycred' ), $_POST['payment_status'] ); + $errors = true; + } + + // Credit payment + if ( $errors === false ) { + + // If account is credited, delete the post and it's comments. + if ( $this->complete_payment( $pending_payment, $_POST['txn_id'] ) ) + $this->trash_pending_payment( $pending_post_id ); + else + $new_call[] = __( 'Failed to credit users account.', 'mycred' ); + + } + + // Log Call + if ( ! empty( $new_call ) ) + $this->log_call( $pending_post_id, $new_call ); + + } + + } + + } + + } + + /** + * Results Handler + * @since 0.1 + * @version 1.0.1 + */ + public function returning() { + + if ( isset( $_REQUEST['tx'] ) && isset( $_REQUEST['st'] ) && $_REQUEST['st'] == 'Completed' ) { + $this->get_page_header( __( 'Success', 'mycred' ), $this->get_thankyou() ); + echo '

    ' . __( 'Thank you for your purchase', 'mycred' ) . '

    '; + $this->get_page_footer(); + exit; + } + + } + + /** + * Prep Sale + * @since 1.8 + * @version 1.0 + */ + public function prep_sale( $new_transaction = false ) { + + // Set currency + $this->currency = ( $this->currency == '' ) ? $this->prefs['currency'] : $this->currency; + + // The item name + $item_name = str_replace( '%number%', $this->amount, $this->prefs['item_name'] ); + $item_name = $this->core->template_tags_general( $item_name ); + + // This gateway redirects, so we need to populate redirect_to + $this->redirect_to = ( $this->sandbox_mode ) ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr'; + + // Transaction variables that needs to be submitted + $this->redirect_fields = array( + 'cmd' => '_xclick', + 'business' => $this->prefs['account'], + 'item_name' => $item_name, + 'quantity' => 1, + 'amount' => $this->cost, + 'currency_code' => $this->currency, + 'no_shipping' => 1, + 'no_note' => 1, + 'custom' => $this->transaction_id, + 'return' => $this->get_thankyou(), + 'notify_url' => $this->callback_url(), + 'rm' => 2, + 'cbt' => sprintf( _x( 'Return to %s', 'Return label. %s = Website name', 'mycred' ), get_bloginfo( 'name' ) ), + 'cancel_return' => $this->get_cancelled( $this->transaction_id ) + ); + + } + + /** + * AJAX Buy Handler + * @since 1.8 + * @version 1.0 + */ + public function ajax_buy() { + + // Construct the checkout box content + $content = $this->checkout_header(); + $content .= $this->checkout_logo(); + $content .= $this->checkout_order(); + $content .= $this->checkout_cancel(); + $content .= $this->checkout_footer(); + + // Return a JSON response + $this->send_json( $content ); + + } + + /** + * Checkout Page Body + * This gateway only uses the checkout body. + * @since 1.8 + * @version 1.0 + */ + public function checkout_page_body() { + + echo $this->checkout_header(); + echo $this->checkout_logo( false ); + + echo $this->checkout_order(); + echo $this->checkout_cancel(); + + echo $this->checkout_footer(); + + } + + /** + * Preferences + * @since 0.1 + * @version 1.0 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -
    -

    -
    - - -
    -
    - - -
    -
    - - -
    -
    -
    -

    -
    - - - currencies_dropdown('currency', 'mycred-gateway-paypal-standard-currency'); ?> - -
    -
    - - - exchange_rate_setup(); ?> - -
    -
    +
    +

    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    +

    +
    + + + currencies_dropdown( 'currency', 'mycred-gateway-paypal-standard-currency' ); ?> + +
    +
    + + + exchange_rate_setup(); ?> + +
    +
    - $rate ) { - if ($rate != 1 && in_array(substr($rate, 0, 1), array( '.', ',' )) ) { - $data['exchange'][ $type ] = (float) '0' . $rate; - } - } - } - $new_data['exchange'] = $data['exchange']; - - return $new_data; - - } - - } + $rate ) { + if ( $rate != 1 && in_array( substr( $rate, 0, 1 ), array( '.', ',' ) ) ) + $data['exchange'][ $type ] = (float) '0' . $rate; + } + } + $new_data['exchange'] = $data['exchange']; + + return $new_data; + + } + + } endif; diff --git a/addons/buy-creds/gateways/skrill.php b/addons/buy-creds/gateways/skrill.php index 2deb12e..15962a3 100644 --- a/addons/buy-creds/gateways/skrill.php +++ b/addons/buy-creds/gateways/skrill.php @@ -1,414 +1,380 @@ $label ) { - $default_exchange[ $type ] = 1; - } - - parent::__construct( - array( - 'id' => 'skrill', - 'label' => 'Skrill Payment', - 'gateway_logo_url' => plugins_url('assets/images/skrill.png', MYCRED_PURCHASE), - 'defaults' => array( - 'sandbox' => 0, - 'currency' => '', - 'account' => '', - 'word' => '', - 'account_title' => '', - 'account_logo' => '', - 'logo_url' => '', - 'confirmation_note' => '', - 'email_receipt' => 0, - 'item_name' => 'Purchase of myCRED %plural%', - 'exchange' => $default_exchange - ) - ), $gateway_prefs - ); - - } - - /** - * IPN - Is Valid Call - * Replaces the default check - * - * @since 1.4 - * @version 1.1 - */ - public function IPN_is_valid_call() - { - - $result = true; - - $check = sanitize_text_field($_POST['merchant_id']) . sanitize_text_field($_POST['transaction_id']) . strtoupper(md5($this->prefs['word'])) . sanitize_text_field($_POST['mb_amount']) . sanitize_text_field($_POST['mb_currency']) . sanitize_text_field($_POST['status']); - if (strtoupper(md5($check)) !== $_POST['md5sig'] ) { - $result = false; - } - - if ($_POST['pay_to_email'] != trim($this->prefs['account']) ) { - $result = false; - } - - return $result; - - } - - /** - * Process Handler - * - * @since 0.1 - * @version 1.2 - */ - public function process() - { - - // Required fields - if (isset($_POST['sales_data']) && isset($_POST['transaction_id']) && isset($_POST['amount']) ) { - - // Get Pending Payment - $pending_post_id = sanitize_key($_POST['sales_data']); - $pending_payment = $this->get_pending_payment($pending_post_id); - if ($pending_payment !== false ) { - - // Verify Call with PayPal - if ($this->IPN_is_valid_call() ) { - - $errors = false; - $new_call = array(); - - // Check amount paid - if ($_POST['amount'] != $pending_payment->cost ) { - $new_call[] = sprintf(__('Price mismatch. Expected: %s Received: %s', 'mycred'), $pending_payment->cost, $_POST['amount']); - $errors = true; - } - - // Check currency - if ($_POST['currency'] != $pending_payment->currency ) { - $new_call[] = sprintf(__('Currency mismatch. Expected: %s Received: %s', 'mycred'), $pending_payment->currency, $_POST['currency']); - $errors = true; - } - - // Check status - if ($_POST['status'] != '2' ) { - $new_call[] = sprintf(__('Payment not completed. Received: %s', 'mycred'), $_POST['status']); - $errors = true; - } - - // Credit payment - if ($errors === false ) { - - // If account is credited, delete the post and it's comments. - if ($this->complete_payment($pending_payment, $_POST['transaction_id']) ) { - $this->trash_pending_payment($pending_post_id); - } else { - $new_call[] = __('Failed to credit users account.', 'mycred'); - } - - } - - // Log Call - if (! empty($new_call) ) { - $this->log_call($pending_post_id, $new_call); - } - - } - - } - - } - - } - - /** - * Results Handler - * - * @since 0.1 - * @version 1.1 - */ - public function returning() - { - - if (isset($_GET['transaction_id']) && ! empty($_GET['transaction_id']) && isset($_GET['msid']) && ! empty($_GET['msid']) ) { - $this->get_page_header(__('Success', 'mycred'), $this->get_thankyou()); - echo '

    ' . __('Thank you for your purchase', 'mycred') . '

    '; - $this->get_page_footer(); - exit; - } - - } - - /** - * Prep Sale - * - * @since 1.8 - * @version 1.0 - */ - public function prep_sale( $new_transaction = false ) - { - - // Set currency - $this->currency = ( $this->currency == '' ) ? $this->prefs['currency'] : $this->currency; - - // Item Name - $item_name = str_replace('%number%', $this->amount, $this->prefs['item_name']); - $item_name = $this->core->template_tags_general($item_name); - - $this->redirect_to = 'https://www.moneybookers.com/app/payment.pl'; - - $redirect_fields = array( - 'pay_to_email' => $this->prefs['account'], - 'transaction_id' => $this->transaction_id, - 'return_url' => $this->get_thankyou(), - 'cancel_url' => $this->get_cancelled($this->transaction_id), - 'status_url' => $this->callback_url(), - 'return_url_text' => get_bloginfo('name'), - 'hide_login' => 1, - 'merchant_fields' => 'sales_data', - 'sales_data' => $this->post_id, - 'amount' => $this->cost, - 'currency' => $this->prefs['currency'], - 'detail1_description' => __('Item Name', 'mycred'), - 'detail1_text' => $item_name - ); - - // Customize Checkout Page - if (isset($this->prefs['account_title']) && ! empty($this->prefs['account_title']) ) { - $redirect_fields['recipient_description'] = $this->core->template_tags_general($this->prefs['account_title']); - } - - if (isset($this->prefs['account_logo']) && ! empty($this->prefs['account_logo']) ) { - $redirect_fields['logo_url'] = $this->prefs['account_logo']; - } - - if (isset($this->prefs['confirmation_note']) && ! empty($this->prefs['confirmation_note']) ) { - $redirect_fields['confirmation_note'] = $this->core->template_tags_general($this->prefs['confirmation_note']); - } - - // If we want an email receipt for purchases - if (isset($this->prefs['email_receipt']) && ! empty($this->prefs['email_receipt']) ) { - $redirect_fields['status_url2'] = $this->prefs['account']; - } - - // Gifting - if ($this->gifting ) { - - $user = get_userdata($this->recipient_id); - $redirect_fields['detail2_description'] = __('Recipient', 'mycred'); - $redirect_fields['detail2_text'] = $user->display_name; - - } - - $this->redirect_fields = $redirect_fields; - - } - - /** - * AJAX Buy Handler - * - * @since 1.8 - * @version 1.0 - */ - public function ajax_buy() - { - - // Construct the checkout box content - $content = $this->checkout_header(); - $content .= $this->checkout_logo(); - $content .= $this->checkout_order(); - $content .= $this->checkout_cancel(); - $content .= $this->checkout_footer(); - - // Return a JSON response - $this->send_json($content); - - } - - /** - * Checkout Page Body - * This gateway only uses the checkout body. - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_page_body() - { - - echo $this->checkout_header(); - echo $this->checkout_logo(false); - - echo $this->checkout_order(); - echo $this->checkout_cancel(); - - echo $this->checkout_footer(); - - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.0.1 - */ - public function preferences() - { - - add_filter('mycred_dropdown_currencies', array( $this, 'skrill_currencies' )); - $prefs = $this->prefs; - - ?> +if ( ! class_exists( 'myCRED_Skrill' ) ) : + class myCRED_Skrill extends myCRED_Payment_Gateway { + + /** + * Construct + */ + public function __construct( $gateway_prefs ) { + + $types = mycred_get_types(); + $default_exchange = array(); + foreach ( $types as $type => $label ) + $default_exchange[ $type ] = 1; + + parent::__construct( array( + 'id' => 'skrill', + 'label' => 'Skrill Payment', + 'gateway_logo_url' => plugins_url( 'assets/images/skrill.png', MYCRED_PURCHASE ), + 'defaults' => array( + 'sandbox' => 0, + 'currency' => '', + 'account' => '', + 'word' => '', + 'account_title' => '', + 'account_logo' => '', + 'logo_url' => '', + 'confirmation_note' => '', + 'email_receipt' => 0, + 'item_name' => 'Purchase of myCRED %plural%', + 'exchange' => $default_exchange + ) + ), $gateway_prefs ); + + } + + /** + * IPN - Is Valid Call + * Replaces the default check + * @since 1.4 + * @version 1.1 + */ + public function IPN_is_valid_call() { + + $result = true; + + $check = sanitize_text_field( $_POST['merchant_id'] ) . sanitize_text_field( $_POST['transaction_id'] ) . strtoupper( md5( $this->prefs['word'] ) ) . sanitize_text_field( $_POST['mb_amount'] ) . sanitize_text_field( $_POST['mb_currency'] ) . sanitize_text_field( $_POST['status'] ); + if ( strtoupper( md5( $check ) ) !== $_POST['md5sig'] ) + $result = false; + + if ( $_POST['pay_to_email'] != trim( $this->prefs['account'] ) ) + $result = false; + + return $result; + + } + + /** + * Process Handler + * @since 0.1 + * @version 1.2 + */ + public function process() { + + // Required fields + if ( isset( $_POST['sales_data'] ) && isset( $_POST['transaction_id'] ) && isset( $_POST['amount'] ) ) { + + // Get Pending Payment + $pending_post_id = sanitize_key( $_POST['sales_data'] ); + $pending_payment = $this->get_pending_payment( $pending_post_id ); + if ( $pending_payment !== false ) { + + // Verify Call with PayPal + if ( $this->IPN_is_valid_call() ) { + + $errors = false; + $new_call = array(); + + // Check amount paid + if ( $_POST['amount'] != $pending_payment->cost ) { + $new_call[] = sprintf( __( 'Price mismatch. Expected: %s Received: %s', 'mycred' ), $pending_payment->cost, $_POST['amount'] ); + $errors = true; + } + + // Check currency + if ( $_POST['currency'] != $pending_payment->currency ) { + $new_call[] = sprintf( __( 'Currency mismatch. Expected: %s Received: %s', 'mycred' ), $pending_payment->currency, $_POST['currency'] ); + $errors = true; + } + + // Check status + if ( $_POST['status'] != '2' ) { + $new_call[] = sprintf( __( 'Payment not completed. Received: %s', 'mycred' ), $_POST['status'] ); + $errors = true; + } + + // Credit payment + if ( $errors === false ) { + + // If account is credited, delete the post and it's comments. + if ( $this->complete_payment( $pending_payment, $_POST['transaction_id'] ) ) + $this->trash_pending_payment( $pending_post_id ); + else + $new_call[] = __( 'Failed to credit users account.', 'mycred' ); + + } + + // Log Call + if ( ! empty( $new_call ) ) + $this->log_call( $pending_post_id, $new_call ); + + } + + } + + } + + } + + /** + * Results Handler + * @since 0.1 + * @version 1.1 + */ + public function returning() { + + if ( isset( $_GET['transaction_id'] ) && ! empty( $_GET['transaction_id'] ) && isset( $_GET['msid'] ) && ! empty( $_GET['msid'] ) ) { + $this->get_page_header( __( 'Success', 'mycred' ), $this->get_thankyou() ); + echo '

    ' . __( 'Thank you for your purchase', 'mycred' ) . '

    '; + $this->get_page_footer(); + exit; + } + + } + + /** + * Prep Sale + * @since 1.8 + * @version 1.0 + */ + public function prep_sale( $new_transaction = false ) { + + // Set currency + $this->currency = ( $this->currency == '' ) ? $this->prefs['currency'] : $this->currency; + + // Item Name + $item_name = str_replace( '%number%', $this->amount, $this->prefs['item_name'] ); + $item_name = $this->core->template_tags_general( $item_name ); + + $this->redirect_to = 'https://www.moneybookers.com/app/payment.pl'; + + $redirect_fields = array( + 'pay_to_email' => $this->prefs['account'], + 'transaction_id' => $this->transaction_id, + 'return_url' => $this->get_thankyou(), + 'cancel_url' => $this->get_cancelled( $this->transaction_id ), + 'status_url' => $this->callback_url(), + 'return_url_text' => get_bloginfo( 'name' ), + 'hide_login' => 1, + 'merchant_fields' => 'sales_data', + 'sales_data' => $this->post_id, + 'amount' => $this->cost, + 'currency' => $this->prefs['currency'], + 'detail1_description' => __( 'Item Name', 'mycred' ), + 'detail1_text' => $item_name + ); + + // Customize Checkout Page + if ( isset( $this->prefs['account_title'] ) && ! empty( $this->prefs['account_title'] ) ) + $redirect_fields['recipient_description'] = $this->core->template_tags_general( $this->prefs['account_title'] ); + + if ( isset( $this->prefs['account_logo'] ) && ! empty( $this->prefs['account_logo'] ) ) + $redirect_fields['logo_url'] = $this->prefs['account_logo']; + + if ( isset( $this->prefs['confirmation_note'] ) && ! empty( $this->prefs['confirmation_note'] ) ) + $redirect_fields['confirmation_note'] = $this->core->template_tags_general( $this->prefs['confirmation_note'] ); + + // If we want an email receipt for purchases + if ( isset( $this->prefs['email_receipt'] ) && ! empty( $this->prefs['email_receipt'] ) ) + $redirect_fields['status_url2'] = $this->prefs['account']; + + // Gifting + if ( $this->gifting ) { + + $user = get_userdata( $this->recipient_id ); + $redirect_fields['detail2_description'] = __( 'Recipient', 'mycred' ); + $redirect_fields['detail2_text'] = $user->display_name; + + } + + $this->redirect_fields = $redirect_fields; + + } + + /** + * AJAX Buy Handler + * @since 1.8 + * @version 1.0 + */ + public function ajax_buy() { + + // Construct the checkout box content + $content = $this->checkout_header(); + $content .= $this->checkout_logo(); + $content .= $this->checkout_order(); + $content .= $this->checkout_cancel(); + $content .= $this->checkout_footer(); + + // Return a JSON response + $this->send_json( $content ); + + } + + /** + * Checkout Page Body + * This gateway only uses the checkout body. + * @since 1.8 + * @version 1.0 + */ + public function checkout_page_body() { + + echo $this->checkout_header(); + echo $this->checkout_logo( false ); + + echo $this->checkout_order(); + echo $this->checkout_cancel(); + + echo $this->checkout_footer(); + + } + + /** + * Preferences + * @since 0.1 + * @version 1.0.1 + */ + public function preferences() { + + add_filter( 'mycred_dropdown_currencies', array( $this, 'skrill_currencies' ) ); + $prefs = $this->prefs; + +?>
    -
    -

    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - -
    -
    -
    -

    -
    - - - currencies_dropdown('currency', 'mycred-gateway-skrill-currency'); ?> - -
    -
    - - - exchange_rate_setup(); ?> - -
    -
    +
    +

    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    +
    +
    +

    +
    + + + currencies_dropdown( 'currency', 'mycred-gateway-skrill-currency' ); ?> + +
    +
    + + + exchange_rate_setup(); ?> + +
    +
    -

    +

    -
    -
    - -

    - -
    -
    - -

    - -
    -
    +
    +
    + +

    + +
    +
    + +

    + +
    +
    - $rate ) { - if ($rate != 1 && in_array(substr($rate, 0, 1), array( '.', ',' )) ) { - $data['exchange'][ $type ] = (float) '0' . $rate; - } - } - } - $new_data['exchange'] = $data['exchange']; - - return $new_data; - - } - - /** - * Adjust Currencies - * - * @since 1.0.6 - * @version 1.0 - */ - public function skrill_currencies( $currencies ) - { - - $currencies['RON'] = 'Romanian Leu'; - $currencies['TRY'] = 'New Turkish Lira'; - $currencies['RON'] = 'Romanian Leu'; - $currencies['AED'] = 'Utd. Arab Emir. Dirham'; - $currencies['MAD'] = 'Moroccan Dirham'; - $currencies['QAR'] = 'Qatari Rial'; - $currencies['SAR'] = 'Saudi Riyal'; - $currencies['SKK'] = 'Slovakian Koruna'; - $currencies['EEK'] = 'Estonian Kroon'; - $currencies['BGN'] = 'Bulgarian Leva'; - $currencies['ISK'] = 'Iceland Krona'; - $currencies['INR'] = 'Indian Rupee'; - $currencies['LVL'] = 'Latvian Lat'; - $currencies['KRW'] = 'South-Korean Won'; - $currencies['ZAR'] = 'South-African Rand'; - $currencies['HRK'] = 'Croatian Kuna'; - $currencies['LTL'] = 'Lithuanian Litas'; - $currencies['JOD'] = 'Jordanian Dinar'; - $currencies['OMR'] = 'Omani Rial'; - $currencies['RSD'] = 'Serbian Dinar'; - $currencies['TND'] = 'Tunisian Dinar'; - - unset($currencies['MXN']); - unset($currencies['BRL']); - unset($currencies['PHP']); - - return $currencies; - - } - - } + $rate ) { + if ( $rate != 1 && in_array( substr( $rate, 0, 1 ), array( '.', ',' ) ) ) + $data['exchange'][ $type ] = (float) '0' . $rate; + } + } + $new_data['exchange'] = $data['exchange']; + + return $new_data; + + } + + /** + * Adjust Currencies + * @since 1.0.6 + * @version 1.0 + */ + public function skrill_currencies( $currencies ) { + + $currencies['RON'] = 'Romanian Leu'; + $currencies['TRY'] = 'New Turkish Lira'; + $currencies['RON'] = 'Romanian Leu'; + $currencies['AED'] = 'Utd. Arab Emir. Dirham'; + $currencies['MAD'] = 'Moroccan Dirham'; + $currencies['QAR'] = 'Qatari Rial'; + $currencies['SAR'] = 'Saudi Riyal'; + $currencies['SKK'] = 'Slovakian Koruna'; + $currencies['EEK'] = 'Estonian Kroon'; + $currencies['BGN'] = 'Bulgarian Leva'; + $currencies['ISK'] = 'Iceland Krona'; + $currencies['INR'] = 'Indian Rupee'; + $currencies['LVL'] = 'Latvian Lat'; + $currencies['KRW'] = 'South-Korean Won'; + $currencies['ZAR'] = 'South-African Rand'; + $currencies['HRK'] = 'Croatian Kuna'; + $currencies['LTL'] = 'Lithuanian Litas'; + $currencies['JOD'] = 'Jordanian Dinar'; + $currencies['OMR'] = 'Omani Rial'; + $currencies['RSD'] = 'Serbian Dinar'; + $currencies['TND'] = 'Tunisian Dinar'; + + unset( $currencies['MXN'] ); + unset( $currencies['BRL'] ); + unset( $currencies['PHP'] ); + + return $currencies; + + } + + } endif; diff --git a/addons/buy-creds/images/index.php b/addons/buy-creds/images/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/images/index.php +++ b/addons/buy-creds/images/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/includes/buycred-functions.php b/addons/buy-creds/includes/buycred-functions.php index 3381bc9..c40b4c8 100644 --- a/addons/buy-creds/includes/buycred-functions.php +++ b/addons/buy-creds/includes/buycred-functions.php @@ -1,222 +1,205 @@ array( MYCRED_DEFAULT_TYPE_KEY ), - 'checkout' => 'page', - 'log' => '%plural% purchase', - 'login' => __('Please login to purchase %_plural%', 'mycred'), - 'custom_log' => 0, - 'thankyou' => array( - 'use' => 'page', - 'custom' => '', - 'page' => '' - ), - 'cancelled' => array( - 'use' => 'custom', - 'custom' => '', - 'page' => '' - ), - 'gifting' => array( - 'members' => 1, - 'authors' => 1, - 'log' => __('Gift purchase from %display_name%.', 'mycred') - ) - ); - - $settings = mycred_get_addon_settings('buy_creds'); - $settings = wp_parse_args($settings, $defaults); - - return apply_filters('mycred_get_buycred_settings', $settings); - - } +if ( ! function_exists( 'mycred_get_buycred_settings' ) ) : + function mycred_get_buycred_settings() { + + $defaults = array( + 'types' => array( MYCRED_DEFAULT_TYPE_KEY ), + 'checkout' => 'page', + 'log' => '%plural% purchase', + 'login' => __( 'Please login to purchase %_plural%', 'mycred' ), + 'custom_log' => 0, + 'thankyou' => array( + 'use' => 'page', + 'custom' => '', + 'page' => '' + ), + 'cancelled' => array( + 'use' => 'custom', + 'custom' => '', + 'page' => '' + ), + 'gifting' => array( + 'members' => 1, + 'authors' => 1, + 'log' => __( 'Gift purchase from %display_name%.', 'mycred' ) + ) + ); + + $settings = mycred_get_addon_settings( 'buy_creds' ); + $settings = wp_parse_args( $settings, $defaults ); + + return apply_filters( 'mycred_get_buycred_settings', $settings ); + + } endif; /** * Get Gateways - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_get_buycred_gateways') ) : - function mycred_get_buycred_gateways() - { - - $installed = array(); - - // PayPal Standard - $installed['paypal-standard'] = array( - 'title' => 'PayPal Payments Standard', - 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/paypal/', - 'callback' => array( 'myCRED_PayPal_Standard' ), - 'icon' => 'dashicons-admin-generic', - 'sandbox' => true, - 'external' => true, - 'custom_rate' => true - ); - - // BitPay - $installed['bitpay'] = array( - 'title' => 'BitPay (Bitcoins)', - 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/bitpay/', - 'callback' => array( 'myCRED_Bitpay' ), - 'icon' => 'dashicons-admin-generic', - 'sandbox' => true, - 'external' => true, - 'custom_rate' => true - ); - - // NetBilling - $installed['netbilling'] = array( - 'title' => 'NETBilling', - 'callback' => array( 'myCRED_NETbilling' ), - 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/netbilling/', - 'icon' => 'dashicons-admin-generic', - 'sandbox' => true, - 'external' => true, - 'custom_rate' => true - ); - - // Skrill - $installed['skrill'] = array( - 'title' => 'Skrill (Moneybookers)', - 'callback' => array( 'myCRED_Skrill' ), - 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/skrill/', - 'icon' => 'dashicons-admin-generic', - 'sandbox' => true, - 'external' => true, - 'custom_rate' => true - ); - - // Bank Transfers - $installed['bank'] = array( - 'title' => __('Bank Transfer', 'mycred'), - 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/bank-transfers/', - 'callback' => array( 'myCRED_Bank_Transfer' ), - 'icon' => 'dashicons-admin-generic', - 'sandbox' => false, - 'external' => false, - 'custom_rate' => true - ); - - return apply_filters('mycred_setup_gateways', $installed); - - } +if ( ! function_exists( 'mycred_get_buycred_gateways' ) ) : + function mycred_get_buycred_gateways() { + + $installed = array(); + + // PayPal Standard + $installed['paypal-standard'] = array( + 'title' => 'PayPal Payments Standard', + 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/paypal/', + 'callback' => array( 'myCRED_PayPal_Standard' ), + 'icon' => 'dashicons-admin-generic', + 'sandbox' => true, + 'external' => true, + 'custom_rate' => true + ); + + // BitPay + $installed['bitpay'] = array( + 'title' => 'BitPay (Bitcoins)', + 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/bitpay/', + 'callback' => array( 'myCRED_Bitpay' ), + 'icon' => 'dashicons-admin-generic', + 'sandbox' => true, + 'external' => true, + 'custom_rate' => true + ); + + // NetBilling + $installed['netbilling'] = array( + 'title' => 'NETBilling', + 'callback' => array( 'myCRED_NETbilling' ), + 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/netbilling/', + 'icon' => 'dashicons-admin-generic', + 'sandbox' => true, + 'external' => true, + 'custom_rate' => true + ); + + // Skrill + $installed['skrill'] = array( + 'title' => 'Skrill (Moneybookers)', + 'callback' => array( 'myCRED_Skrill' ), + 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/skrill/', + 'icon' => 'dashicons-admin-generic', + 'sandbox' => true, + 'external' => true, + 'custom_rate' => true + ); + + // Bank Transfers + $installed['bank'] = array( + 'title' => __( 'Bank Transfer', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/bank-transfers/', + 'callback' => array( 'myCRED_Bank_Transfer' ), + 'icon' => 'dashicons-admin-generic', + 'sandbox' => false, + 'external' => false, + 'custom_rate' => true + ); + + return apply_filters( 'mycred_setup_gateways', $installed ); + + } endif; /** * Get buyCRED Setup - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_get_requested_gateway_id') ) : - function mycred_get_requested_gateway_id() - { +if ( ! function_exists( 'mycred_get_requested_gateway_id' ) ) : + function mycred_get_requested_gateway_id() { - $gateway_id = false; + $gateway_id = false; - if (isset($_REQUEST['mycred_call']) ) { - $gateway_id = sanitize_key($_REQUEST['mycred_call']); + if ( isset( $_REQUEST['mycred_call'] ) ) + $gateway_id = sanitize_key( $_REQUEST['mycred_call'] ); - } elseif (isset($_REQUEST['mycred_buy']) && is_user_logged_in() ) { - $gateway_id = sanitize_key($_REQUEST['mycred_buy']); - } + elseif ( isset( $_REQUEST['mycred_buy'] ) && is_user_logged_in() ) + $gateway_id = sanitize_key( $_REQUEST['mycred_buy'] ); - return apply_filters('mycred_gateway_id', $gateway_id); + return apply_filters( 'mycred_gateway_id', $gateway_id ); - } + } endif; /** * Get buyCRED Setup - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_get_buycred_sale_setup') ) : - function mycred_get_buycred_sale_setup( $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_get_buycred_sale_setup' ) ) : + function mycred_get_buycred_sale_setup( $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $defaults = array( - 'min' => '', - 'max' => '', - 'time' => '' - ); + $defaults = array( + 'min' => '', + 'max' => '', + 'time' => '' + ); - $saved = mycred_get_option('buycred-setup-' . $point_type, $defaults); - $settings = shortcode_atts($defaults, $saved); + $saved = mycred_get_option( 'buycred-setup-' . $point_type, $defaults ); + $settings = shortcode_atts( $defaults, $saved ); - return apply_filters('mycred_get_buycred_sale_setup', $settings, $point_type); + return apply_filters( 'mycred_get_buycred_sale_setup', $settings, $point_type ); - } + } endif; /** * Get Gateway References - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_get_buycred_gateway_refs') ) : - function mycred_get_buycred_gateway_refs( $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_get_buycred_gateway_refs' ) ) : + function mycred_get_buycred_gateway_refs( $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $references = array( - 'buy_creds_with_paypal_standard', - 'buy_creds_with_skrill', - 'buy_creds_with_netbilling', - 'buy_creds_with_bitpay', - 'buy_creds_with_bank' - ); + $references = array( + 'buy_creds_with_paypal_standard', + 'buy_creds_with_skrill', + 'buy_creds_with_netbilling', + 'buy_creds_with_bitpay', + 'buy_creds_with_bank' + ); - return apply_filters('mycred_buycred_log_refs', $references, $point_type); + return apply_filters( 'mycred_buycred_log_refs', $references, $point_type ); - } + } endif; /** * Purchase Limit Dropdown - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_purchase_limit_dropdown') ) : - function mycred_purchase_limit_dropdown( $name = '', $id = '', $selected = '' ) - { - - $options = apply_filters( - 'mycred_buycred_limit_dropdown', array( - '' => __('No limit', 'mycred'), - 'day' => __('/ Day', 'mycred'), - 'week' => __('/ Week', 'mycred'), - 'month' => __('/ Month', 'mycred') - ) - ); - - $output = ''; - - echo $output; - - } +if ( ! function_exists( 'mycred_purchase_limit_dropdown' ) ) : + function mycred_purchase_limit_dropdown( $name = '', $id = '', $selected = '' ) { + + $options = apply_filters( 'mycred_buycred_limit_dropdown', array( + '' => __( 'No limit', 'mycred' ), + 'day' => __( '/ Day', 'mycred' ), + 'week' => __( '/ Week', 'mycred' ), + 'month' => __( '/ Month', 'mycred' ) + ) ); + + $output = ''; + + echo $output; + + } endif; /** @@ -224,152 +207,131 @@ function mycred_purchase_limit_dropdown( $name = '', $id = '', $selected = '' ) * Returns false if the user is excluded or when using this function with invalid values. * Else returns true if the user can buy as much as they wish else a point value if a max limit is enforced. * Note that this can result in a zero value being returned, if the user has reached their purchase limit but are not excluded. - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_user_can_buycred') ) : - function mycred_user_can_buycred( $user_id = 0, $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_user_can_buycred' ) ) : + function mycred_user_can_buycred( $user_id = 0, $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $can_buy = false; - $total = 0; - $settings = mycred_get_buycred_settings(); - $user_id = absint($user_id); + $can_buy = false; + $total = 0; + $settings = mycred_get_buycred_settings(); + $user_id = absint( $user_id ); - // Need a valid ID, the point type must be enabled for sale - if ($user_id === 0 || ! in_array($point_type, $settings['types']) ) { return $can_buy; - } + // Need a valid ID, the point type must be enabled for sale + if ( $user_id === 0 || ! in_array( $point_type, $settings['types'] ) ) return $can_buy; - $mycred = mycred($point_type); - $setup = mycred_get_buycred_sale_setup($point_type); + $mycred = mycred( $point_type ); + $setup = mycred_get_buycred_sale_setup( $point_type ); - // We need to get the lowest possible value for this point type or the minimum amount we set in our settings - $minimum = $mycred->number(( ( $setup['min'] == '' ) ? $mycred->get_lowest_value() : $setup['min'] )); + // We need to get the lowest possible value for this point type or the minimum amount we set in our settings + $minimum = $mycred->number( ( ( $setup['min'] == '' ) ? $mycred->get_lowest_value() : $setup['min'] ) ); - $can_buy = true; + $can_buy = true; - // Incase we are enforcing a maximum we need to check how much we already purchased this period - // So we can see how much is left on the limit - if (MYCRED_ENABLE_LOGGING && $setup['time'] != '' && $setup['max'] != '' && $setup['max'] > 0 ) { + // Incase we are enforcing a maximum we need to check how much we already purchased this period + // So we can see how much is left on the limit + if ( MYCRED_ENABLE_LOGGING && $setup['time'] != '' && $setup['max'] != '' && $setup['max'] > 0 ) { - $maximum = $mycred->number($setup['max']); + $maximum = $mycred->number( $setup['max'] ); - $total = mycred_get_users_total_purchase($user_id, $point_type, $setup['time']); - $total = $mycred->number($total); + $total = mycred_get_users_total_purchase( $user_id, $point_type, $setup['time'] ); + $total = $mycred->number( $total ); - if ($total < $maximum ) { - $can_buy = $mycred->number($maximum - $total); - } + if ( $total < $maximum ) + $can_buy = $mycred->number( $maximum - $total ); - // Now that we have a "remaining" amount, we need to make sure it is more than the minimum - if ($can_buy < $minimum ) { - $can_buy = 0; - } + // Now that we have a "remaining" amount, we need to make sure it is more than the minimum + if ( $can_buy < $minimum ) + $can_buy = 0; - } + } - return apply_filters('mycred_user_can_buycred', $can_buy, $user_id, $point_type, $total); + return apply_filters( 'mycred_user_can_buycred', $can_buy, $user_id, $point_type, $total ); - } + } endif; /** * Is Gateway Usable * Checks if a gateway (based on it's ID) is "usable" as in it is installed and active. * Note that this will not take into account if sandbox mode is used or not. - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_buycred_gateway_is_usable') ) : - function mycred_buycred_gateway_is_usable( $gateway_id ) - { +if ( ! function_exists( 'mycred_buycred_gateway_is_usable' ) ) : + function mycred_buycred_gateway_is_usable( $gateway_id ) { - global $buycred_instance; + global $buycred_instance; - $usable = false; - if (isset($buycred_instance->active) && array_key_exists($gateway_id, $buycred_instance->active) ) { - $usable = true; - } + $usable = false; + if ( isset( $buycred_instance->active ) && array_key_exists( $gateway_id, $buycred_instance->active ) ) + $usable = true; - return $usable; + return $usable; - } + } endif; /** * Get Users Total Purchase - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_get_users_total_purchase') ) : - function mycred_get_users_total_purchase( $user_id = false, $point_type = MYCRED_DEFAULT_TYPE_KEY, $timeframe = 'all' ) - { +if ( ! function_exists( 'mycred_get_users_total_purchase' ) ) : + function mycred_get_users_total_purchase( $user_id = false, $point_type = MYCRED_DEFAULT_TYPE_KEY, $timeframe = 'all' ) { - $from = 0; - $total = 0; - if (! MYCRED_ENABLE_LOGGING ) { return $total; - } + $from = 0; + $total = 0; + if ( ! MYCRED_ENABLE_LOGGING ) return $total; - $user_id = absint($user_id); - if ($user_id === 0 || ! mycred_point_type_exists($point_type) ) { return $total; - } + $user_id = absint( $user_id ); + if ( $user_id === 0 || ! mycred_point_type_exists( $point_type ) ) return $total; - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - if ($timeframe != 'all' ) { + if ( $timeframe != 'all' ) { - $now = current_time('timestamp'); + $now = current_time( 'timestamp' ); - // By default we assume $timeframe = 'day' - $today = strtotime(date('Y-m-d') . ' midnight', $now); + // By default we assume $timeframe = 'day' + $today = strtotime( date( 'Y-m-d' ) . ' midnight', $now ); - // Per week - if ($timeframe == 'week' ) { + // Per week + if ( $timeframe == 'week' ) { - $weekday = date('w', $now); - $thisweek = strtotime('-' . ( $weekday+1 ) . ' days midnight', $now); - if (get_option('start_of_week') == $weekday ) { - $thisweek = $today; - } + $weekday = date( 'w', $now ); + $thisweek = strtotime( '-' . ( $weekday+1 ) . ' days midnight', $now ); + if ( get_option( 'start_of_week' ) == $weekday ) + $thisweek = $today; - $from = $thisweek; + $from = $thisweek; - } + } - // Per month - elseif ($timeframe == 'month' ) { - $from = strtotime(date('Y-m-01') . ' midnight', $now); - } + // Per month + elseif ( $timeframe == 'month' ) + $from = strtotime( date( 'Y-m-01' ) . ' midnight', $now ); - } + } - // First we need to count the completed purchases - $completed = $wpdb->get_var( - $wpdb->prepare( - " + // First we need to count the completed purchases + $completed = $wpdb->get_var( $wpdb->prepare( " SELECT SUM(creds) FROM {$mycred_log_table} WHERE user_id = %d AND ctype = %s AND ref LIKE %s - AND time > %d", $user_id, $point_type, 'buy_creds_with_%', $from - ) - ); + AND time > %d", $user_id, $point_type, 'buy_creds_with_%', $from ) ); - if ($completed === null ) { $completed = 0; - } + if ( $completed === NULL ) $completed = 0; - // Multisite Master Template support - $posts = mycred_get_db_column('posts'); - $postmeta = mycred_get_db_column('postmeta'); + // Multisite Master Template support + $posts = mycred_get_db_column( 'posts' ); + $postmeta = mycred_get_db_column( 'postmeta' ); - // Next we need to tally up pending payments - $pending = $wpdb->get_var( - $wpdb->prepare( - " + // Next we need to tally up pending payments + $pending = $wpdb->get_var( $wpdb->prepare( " SELECT SUM( a.meta_value ) FROM {$posts} p LEFT JOIN {$postmeta} a @@ -379,480 +341,420 @@ function mycred_get_users_total_purchase( $user_id = false, $point_type = MYCRED WHERE p.post_type = %s AND p.post_status = 'publish' AND p.post_author = %d - AND t.meta_value = %s;", 'buycred_payment', $user_id, $point_type - ) - ); + AND t.meta_value = %s;", 'buycred_payment', $user_id, $point_type ) ); - if ($pending === null ) { $pending = 0; - } + if ( $pending === NULL ) $pending = 0; - $total = $completed + $pending; + $total = $completed + $pending; - return apply_filters('mycred_get_users_total_purchase', $total, $user_id, $point_type, $completed, $total); + return apply_filters( 'mycred_get_users_total_purchase', $total, $user_id, $point_type, $completed, $total ); - } + } endif; /** * Get Pending Payment - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('buycred_get_pending_payment_id') ) : - function buycred_get_pending_payment_id( $payment_id = null ) - { +if ( ! function_exists( 'buycred_get_pending_payment_id' ) ) : + function buycred_get_pending_payment_id( $payment_id = NULL ) { - if ($payment_id === null || $payment_id == '' ) { return false; - } + if ( $payment_id === NULL || $payment_id == '' ) return false; - // In case we are using the transaction ID instead of the post ID. - $post_id = false; - if (! is_numeric($payment_id) ) { + // In case we are using the transaction ID instead of the post ID. + $post_id = false; + if ( ! is_numeric( $payment_id ) ) { - $post = mycred_get_page_by_title(strtoupper($payment_id), OBJECT, 'buycred_payment'); - if ($post === null ) { return false; - } + $post = mycred_get_page_by_title( strtoupper( $payment_id ), OBJECT, 'buycred_payment' ); + if ( $post === NULL ) return false; - $post_id = $post->ID; + $post_id = $post->ID; - } - else { - $post_id = absint($payment_id); - } + } + else { + $post_id = absint( $payment_id ); + } - return $post_id; + return $post_id; - } + } endif; /** * Get Pending Payment - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('buycred_get_pending_payment') ) : - function buycred_get_pending_payment( $payment_id = null ) - { - - // Construct fake pending object ( when no pending payment object exists ) - if (is_array($payment_id) ) { - - $pending_payment = new StdClass(); - $pending_payment->payment_id = false; - $pending_payment->public_id = $payment_id['public_id']; - $pending_payment->point_type = $payment_id['point_type']; - $pending_payment->amount = $payment_id['amount']; - $pending_payment->cost = $payment_id['cost']; - $pending_payment->currency = $payment_id['currency']; - $pending_payment->buyer_id = $payment_id['buyer_id']; - $pending_payment->recipient_id = $payment_id['recipient_id']; - $pending_payment->gateway_id = $payment_id['gateway_id']; - $pending_payment->transaction_id = $payment_id['transaction_id']; - $pending_payment->cancel_url = false; - $pending_payment->pay_now_url = false; - - } - - else { - - $payment_id = buycred_get_pending_payment_id($payment_id); - - if ($payment_id === false ) { return false; - } - - $pending_payment = new StdClass(); - $pending_payment->payment_id = absint($payment_id); - $pending_payment->public_id = get_the_title($payment_id); - $pending_payment->point_type = mycred_get_post_meta($payment_id, 'point_type', true); - $pending_payment->amount = mycred_get_post_meta($payment_id, 'amount', true); - $pending_payment->cost = mycred_get_post_meta($payment_id, 'cost', true); - $pending_payment->currency = mycred_get_post_meta($payment_id, 'currency', true); - $pending_payment->buyer_id = mycred_get_post_meta($payment_id, 'from', true); - $pending_payment->recipient_id = mycred_get_post_meta($payment_id, 'to', true); - $pending_payment->gateway_id = mycred_get_post_meta($payment_id, 'gateway', true); - $pending_payment->transaction_id = $pending_payment->public_id; - - $pending_payment->cancel_url = buycred_get_cancel_transaction_url($pending_payment->public_id); - - $pending_payment->pay_now_url = add_query_arg( - array( - 'mycred_buy' => $pending_payment->gateway_id, - 'amount' => $pending_payment->amount, - 'revisit' => $payment_id, - 'token' => wp_create_nonce('mycred-buy-creds') - ), set_url_scheme(sanitize_url('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'])) - ); - - } - - return apply_filters('buycred_get_pending_payment', $pending_payment, $payment_id); - - } +if ( ! function_exists( 'buycred_get_pending_payment' ) ) : + function buycred_get_pending_payment( $payment_id = NULL ) { + + // Construct fake pending object ( when no pending payment object exists ) + if ( is_array( $payment_id ) ) { + + $pending_payment = new StdClass(); + $pending_payment->payment_id = false; + $pending_payment->public_id = $payment_id['public_id']; + $pending_payment->point_type = $payment_id['point_type']; + $pending_payment->amount = $payment_id['amount']; + $pending_payment->cost = $payment_id['cost']; + $pending_payment->currency = $payment_id['currency']; + $pending_payment->buyer_id = $payment_id['buyer_id']; + $pending_payment->recipient_id = $payment_id['recipient_id']; + $pending_payment->gateway_id = $payment_id['gateway_id']; + $pending_payment->transaction_id = $payment_id['transaction_id']; + $pending_payment->cancel_url = false; + $pending_payment->pay_now_url = false; + + } + + else { + + $payment_id = buycred_get_pending_payment_id( $payment_id ); + + if ( $payment_id === false ) return false; + + $pending_payment = new StdClass(); + $pending_payment->payment_id = absint( $payment_id ); + $pending_payment->public_id = get_the_title( $payment_id ); + $pending_payment->point_type = mycred_get_post_meta( $payment_id, 'point_type', true ); + $pending_payment->amount = mycred_get_post_meta( $payment_id, 'amount', true ); + $pending_payment->cost = mycred_get_post_meta( $payment_id, 'cost', true ); + $pending_payment->currency = mycred_get_post_meta( $payment_id, 'currency', true ); + $pending_payment->buyer_id = mycred_get_post_meta( $payment_id, 'from', true ); + $pending_payment->recipient_id = mycred_get_post_meta( $payment_id, 'to', true ); + $pending_payment->gateway_id = mycred_get_post_meta( $payment_id, 'gateway', true ); + $pending_payment->transaction_id = $pending_payment->public_id; + + $pending_payment->cancel_url = buycred_get_cancel_transaction_url( $pending_payment->public_id ); + + $pending_payment->pay_now_url = add_query_arg( array( + 'mycred_buy' => $pending_payment->gateway_id, + 'amount' => $pending_payment->amount, + 'revisit' => $payment_id, + 'token' => wp_create_nonce( 'mycred-buy-creds' ) + ), set_url_scheme( sanitize_url( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) ); + + } + + return apply_filters( 'buycred_get_pending_payment', $pending_payment, $payment_id ); + + } endif; /** * Add Pending Comment - * - * @since 1.7 + * @since 1.7 * @version 1.1 */ -if (! function_exists('buycred_add_pending_comment') ) : - function buycred_add_pending_comment( $payment_id = null, $comment = null, $time = null ) - { - - if (! MYCRED_BUY_PENDING_COMMENTS ) { return true; - } - - $post_id = buycred_get_pending_payment_id($payment_id); - if ($post_id === false ) { return false; - } - - global $mycred_modules; - - if ($time === null || $time == 'now' ) { - $time = current_time('mysql'); - } - - $author = 'buyCRED'; - $gateway = mycred_get_post_meta($post_id, 'gateway', true); - $gateways = mycred_get_buycred_gateways(); - $author_url = sprintf('buyCRED: %s %s', __('Unknown Gateway', 'mycred'), $gateway); - $author_email = apply_filters('mycred_buycred_comment_email', 'buycred-service@mycred.me'); - - if (array_key_exists($gateway, $gateways) ) { - $author = sprintf('buyCRED: %s %s', $gateways[ $gateway ]['title'], __('Gateway', 'mycred')); - } - - return wp_insert_comment( - array( - 'comment_post_ID' => $post_id, - 'comment_author' => $author, - 'comment_author_email' => $author_email, - 'comment_content' => $comment, - 'comment_type' => 'buycred', - 'comment_author_IP' => sanitize_text_field($_SERVER['REMOTE_ADDR']), - 'comment_date' => $time, - 'comment_approved' => 1, - 'user_id' => 0 - ) - ); - - } +if ( ! function_exists( 'buycred_add_pending_comment' ) ) : + function buycred_add_pending_comment( $payment_id = NULL, $comment = NULL, $time = NULL ) { + + if ( ! MYCRED_BUY_PENDING_COMMENTS ) return true; + + $post_id = buycred_get_pending_payment_id( $payment_id ); + if ( $post_id === false ) return false; + + global $mycred_modules; + + if ( $time === NULL || $time == 'now' ) + $time = current_time( 'mysql' ); + + $author = 'buyCRED'; + $gateway = mycred_get_post_meta( $post_id, 'gateway', true ); + $gateways = mycred_get_buycred_gateways(); + $author_url = sprintf( 'buyCRED: %s %s', __( 'Unknown Gateway', 'mycred' ), $gateway ); + $author_email = apply_filters( 'mycred_buycred_comment_email', 'buycred-service@mycred.me' ); + + if ( array_key_exists( $gateway, $gateways ) ) + $author = sprintf( 'buyCRED: %s %s', $gateways[ $gateway ]['title'], __( 'Gateway', 'mycred' ) ); + + return wp_insert_comment( array( + 'comment_post_ID' => $post_id, + 'comment_author' => $author, + 'comment_author_email' => $author_email, + 'comment_content' => $comment, + 'comment_type' => 'buycred', + 'comment_author_IP' => sanitize_text_field( $_SERVER['REMOTE_ADDR'] ), + 'comment_date' => $time, + 'comment_approved' => 1, + 'user_id' => 0 + ) ); + + } endif; /** * Get Cancel URL - * - * @since 1.7 + * @since 1.7 * @version 1.0.1 */ -if (! function_exists('buycred_get_cancel_transaction_url') ) : - function buycred_get_cancel_transaction_url( $transaction_id = null ) - { +if ( ! function_exists( 'buycred_get_cancel_transaction_url' ) ) : + function buycred_get_cancel_transaction_url( $transaction_id = NULL ) { - $settings = mycred_get_buycred_settings(); - $base = set_url_scheme(sanitize_url('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'])); + $settings = mycred_get_buycred_settings(); + $base = set_url_scheme( sanitize_url( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ); - // Cancel page - if ($settings['cancelled']['use'] == 'page' ) { + // Cancel page + if ( $settings['cancelled']['use'] == 'page' ) { - if (! empty($settings['cancelled']['page']) && $settings['cancelled']['page'] > 0 ) { - $base = mycred_get_permalink($settings['cancelled']['page']); - } + if ( ! empty( $settings['cancelled']['page'] ) && $settings['cancelled']['page'] > 0 ) + $base = mycred_get_permalink( $settings['cancelled']['page'] ); - } + } - // Custom URL - elseif ($settings['cancelled']['use'] != 'page' && $settings['cancelled']['custom'] != '' ) { + // Custom URL + elseif ( $settings['cancelled']['use'] != 'page' && $settings['cancelled']['custom'] != '' ) { - $base = esc_url_raw($settings['cancelled']['custom']); + $base = esc_url_raw( $settings['cancelled']['custom'] ); - } + } - // Override - if (isset($_REQUEST['return_to']) && esc_url_raw($_REQUEST['return_to']) != '' ) { - $base = esc_url_raw($_REQUEST['return_to']); - } + // Override + if ( isset( $_REQUEST['return_to'] ) && esc_url_raw( $_REQUEST['return_to'] ) != '' ) + $base = esc_url_raw( $_REQUEST['return_to'] ); - if ($transaction_id !== null ) { - $url = add_query_arg(array( 'buycred-cancel' => $transaction_id, '_token' => wp_create_nonce('buycred-cancel-pending-payment') ), $base); - } else { - $url = $base; - } + if ( $transaction_id !== NULL ) + $url = add_query_arg( array( 'buycred-cancel' => $transaction_id, '_token' => wp_create_nonce( 'buycred-cancel-pending-payment' ) ), $base ); + else + $url = $base; - return apply_filters('mycred_buycred_cancel_url', $url, $transaction_id, $base); + return apply_filters( 'mycred_buycred_cancel_url', $url, $transaction_id, $base ); - } + } endif; /** * Get Users Pending Payments - * - * @since 1.7 + * @since 1.7 * @version 1.0.2 */ -if (! function_exists('buycred_get_users_pending_payments') ) : - function buycred_get_users_pending_payments( $user_id = null, $point_type = '' ) - { +if ( ! function_exists( 'buycred_get_users_pending_payments' ) ) : + function buycred_get_users_pending_payments( $user_id = NULL, $point_type = '' ) { - $user_id = absint($user_id); - if ($user_id === 0 ) { return false; - } + $user_id = absint( $user_id ); + if ( $user_id === 0 ) return false; - $pending = mycred_get_user_meta($user_id, 'buycred_pending_payments', '', true); - if (! is_array($pending) ) { + $pending = mycred_get_user_meta( $user_id, 'buycred_pending_payments', '', true ); + if ( ! is_array( $pending ) ) { - global $wpdb; + global $wpdb; - $pending = array(); - $table = mycred_get_db_column('posts'); - $saved = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table} posts WHERE posts.post_type = 'buycred_payment' AND posts.post_author = %d AND posts.post_status = 'publish';", $user_id)); + $pending = array(); + $table = mycred_get_db_column( 'posts' ); + $saved = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} posts WHERE posts.post_type = 'buycred_payment' AND posts.post_author = %d AND posts.post_status = 'publish';", $user_id ) ); - if (! empty($saved) ) { + if ( ! empty( $saved ) ) { - foreach ( $saved as $entry ) { + foreach ( $saved as $entry ) { - $point_type = mycred_get_post_meta($entry->ID, 'point_type', true); - if ($point_type == '' ) { $point_type = MYCRED_DEFAULT_TYPE_KEY; - } + $point_type = mycred_get_post_meta( $entry->ID, 'point_type', true ); + if ( $point_type == '' ) $point_type = MYCRED_DEFAULT_TYPE_KEY; - if (! array_key_exists($point_type, $pending) ) { - $pending[ $point_type ] = array(); - } + if ( ! array_key_exists( $point_type, $pending ) ) + $pending[ $point_type ] = array(); - $pending[ $point_type ][] = buycred_get_pending_payment((int) $entry->ID); + $pending[ $point_type ][] = buycred_get_pending_payment( (int) $entry->ID ); - } + } - } + } - else { + else { - if ($point_type == '' ) { - $pending[ MYCRED_DEFAULT_TYPE_KEY ] = array(); - } else { - $pending[ $point_type ] = array(); - } + if ( $point_type == '' ) + $pending[ MYCRED_DEFAULT_TYPE_KEY ] = array(); + else + $pending[ $point_type ] = array(); - } + } - mycred_add_user_meta($user_id, 'buycred_pending_payments', '', $pending, true); + mycred_add_user_meta( $user_id, 'buycred_pending_payments', '', $pending, true ); - } + } - if ($point_type != '' && mycred_point_type_exists($point_type) ) { + if ( $point_type != '' && mycred_point_type_exists( $point_type ) ) { - if (! is_array($pending) || ! array_key_exists($point_type, $pending) ) { - return false; - } + if ( ! is_array( $pending ) || ! array_key_exists( $point_type, $pending ) ) + return false; - return $pending[ $point_type ]; + return $pending[ $point_type ]; - } + } - return $pending; + return $pending; - } + } endif; /** * buyCRED Gateway Constructor - * - * @since 1.7 + * @since 1.7 * @version 1.1 */ -if (! function_exists('buycred_gateway') ) : - function buycred_gateway( $gateway_id = null ) - { +if ( ! function_exists( 'buycred_gateway' ) ) : + function buycred_gateway( $gateway_id = NULL ) { - global $buycred_gateway, $mycred_modules; + global $buycred_gateway, $mycred_modules; - if (isset($buycred_gateway) - && ( $buycred_gateway instanceof myCRED_Payment_Gateway ) - && ( $gateway_id === $buycred_gateway->id ) - ) { - return $buycred_gateway; - } + if ( isset( $buycred_gateway ) + && ( $buycred_gateway instanceof myCRED_Payment_Gateway ) + && ( $gateway_id === $buycred_gateway->id ) + ) { + return $buycred_gateway; + } - $buycred_gateway = false; - $installed = $mycred_modules['solo']['buycred']->get(); - if (array_key_exists($gateway_id, $installed) ) { + $buycred_gateway = false; + $installed = $mycred_modules['solo']['buycred']->get(); + if ( array_key_exists( $gateway_id, $installed ) ) { - $class = $installed[ $gateway_id ]['callback'][0]; + $class = $installed[ $gateway_id ]['callback'][0]; - // Construct Gateway - $buycred_gateway = new $class($mycred_modules['solo']['buycred']->gateway_prefs); + // Construct Gateway + $buycred_gateway = new $class( $mycred_modules['solo']['buycred']->gateway_prefs ); - } + } - return $buycred_gateway; + return $buycred_gateway; - } + } endif; /** * Delete Pending Payment - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('buycred_trash_pending_payment') ) : - function buycred_trash_pending_payment( $payment_id = null ) - { +if ( ! function_exists( 'buycred_trash_pending_payment' ) ) : + function buycred_trash_pending_payment( $payment_id = NULL ) { - $pending_payment = buycred_get_pending_payment($payment_id); - if ($pending_payment === false ) { return false; - } + $pending_payment = buycred_get_pending_payment( $payment_id ); + if ( $pending_payment === false ) return false; - mycred_delete_user_meta($pending_payment->buyer_id, 'buycred_pending_payments'); + mycred_delete_user_meta( $pending_payment->buyer_id, 'buycred_pending_payments' ); - return wp_trash_post($pending_payment->payment_id); + return wp_trash_post( $pending_payment->payment_id ); - } + } endif; /** * Complete Pending Payment - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('buycred_complete_pending_payment') ) : - function buycred_complete_pending_payment( $pending_id ) - { +if ( ! function_exists( 'buycred_complete_pending_payment' ) ) : + function buycred_complete_pending_payment( $pending_id ) { - $pending_payment = buycred_get_pending_payment($pending_id); - if ($pending_payment === false ) { return false; - } + $pending_payment = buycred_get_pending_payment( $pending_id ); + if ( $pending_payment === false ) return false; - $gateway = buycred_gateway($pending_payment->gateway_id); - if ($gateway === false ) { return false; - } + $gateway = buycred_gateway( $pending_payment->gateway_id ); + if ( $gateway === false ) return false; - // Complete Payment - $paid = $gateway->complete_payment($pending_payment, $pending_payment->transaction_id); + // Complete Payment + $paid = $gateway->complete_payment( $pending_payment, $pending_payment->transaction_id ); - if ($paid ) { - return buycred_trash_pending_payment($pending_id); - } + if ( $paid ) + return buycred_trash_pending_payment( $pending_id ); - return $paid; + return $paid; - } + } endif; /** * Checkout Title - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('buycred_checkout_title') ) : - function buycred_checkout_title() - { +if ( ! function_exists( 'buycred_checkout_title' ) ) : + function buycred_checkout_title() { - global $buycred_instance; + global $buycred_instance; - if ($buycred_instance->gateway !== false ) { - $buycred_instance->gateway->checkout_page_title(); - } + if ( $buycred_instance->gateway !== false ) + $buycred_instance->gateway->checkout_page_title(); - } + } endif; /** * Checkout Body - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('buycred_checkout_body') ) : - function buycred_checkout_body() - { +if ( ! function_exists( 'buycred_checkout_body' ) ) : + function buycred_checkout_body() { - global $buycred_instance; + global $buycred_instance; - if ($buycred_instance->gateway !== false ) { - $buycred_instance->gateway->checkout_page_body(); - } + if ( $buycred_instance->gateway !== false ) + $buycred_instance->gateway->checkout_page_body(); - } + } endif; /** * Checkout Logo - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('buycred_checkout_logo') ) : - function buycred_checkout_logo() - { +if ( ! function_exists( 'buycred_checkout_logo' ) ) : + function buycred_checkout_logo() { - global $buycred_instance; + global $buycred_instance; - if ($buycred_instance->gateway !== false ) { - $buycred_instance->gateway->checkout_logo(); - } + if ( $buycred_instance->gateway !== false ) + $buycred_instance->gateway->checkout_logo(); - } + } endif; /** * Checkout Order - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('buycred_checkout_order') ) : - function buycred_checkout_order() - { +if ( ! function_exists( 'buycred_checkout_order' ) ) : + function buycred_checkout_order() { - global $buycred_instance; + global $buycred_instance; - if ($buycred_instance->gateway !== false ) { - $buycred_instance->gateway->checkout_order(); - } + if ( $buycred_instance->gateway !== false ) + $buycred_instance->gateway->checkout_order(); - } + } endif; /** * Checkout Cancel - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('buycred_checkout_cancel') ) : - function buycred_checkout_cancel() - { +if ( ! function_exists( 'buycred_checkout_cancel' ) ) : + function buycred_checkout_cancel() { - global $buycred_instance; + global $buycred_instance; - if ($buycred_instance->gateway !== false ) { - $buycred_instance->gateway->checkout_cancel(); - } + if ( $buycred_instance->gateway !== false ) + $buycred_instance->gateway->checkout_cancel(); - } + } endif; /** * Checkout Footer - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('buycred_checkout_footer') ) : - function buycred_checkout_footer() - { +if ( ! function_exists( 'buycred_checkout_footer' ) ) : + function buycred_checkout_footer() { - global $buycred_instance; + global $buycred_instance; - if ($buycred_instance->gateway !== false ) { - $buycred_instance->gateway->checkout_page_footer(); - } + if ( $buycred_instance->gateway !== false ) + $buycred_instance->gateway->checkout_page_footer(); - } -endif; + } +endif; \ No newline at end of file diff --git a/addons/buy-creds/includes/buycred-reward-hook.php b/addons/buy-creds/includes/buycred-reward-hook.php index 7e29e86..83aa1a1 100644 --- a/addons/buy-creds/includes/buycred-reward-hook.php +++ b/addons/buy-creds/includes/buycred-reward-hook.php @@ -1,235 +1,219 @@ 'buycred_reward', - 'defaults' => array( - 'creds' => array(), - 'log' => array(), - 'min' => array(), - 'max' => array() - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.8 - * @version 1.0 - */ - public function run() - { - - add_filter('mycred_add_finished', array( $this, 'assign_buycred_reward' ), 20, 3); - - } - - /** - * Page Load - * - * @since 1.8 - * @version 1.0 - */ - public function assign_buycred_reward( $result, $request, $mycred ) - { - - extract($request); - - if (! $result || strpos($ref, 'buy_creds_with') === false ) { return $result; - }; - - // Make sure user is not excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - if (! empty($this->prefs['creds']) - && ! empty($this->prefs['log']) - && ! empty($this->prefs['min']) - && ! empty($this->prefs['max']) - ) { - - - $threshold = array(); - - foreach ( $this->prefs['creds'] as $key => $value ) { - - if (floatval($amount) >= floatval($this->prefs['min'][$key]) - && floatval($amount) <= floatval($this->prefs['max'][$key]) - ) { - array_push($threshold, $key); - } - - } - - if (! empty($threshold) ) { - - $hook_index = end($threshold); - - // Execute - $this->core->add_creds( - 'buycred_reward', - $user_id, - $this->prefs['creds'][$hook_index], - $this->prefs['log'][$hook_index], - $ref_id, - $data, - $this->mycred_type - ); - } - - } - - return $result; - - } - - /** - * Preference for Anniversary Hook - * - * @since 1.8 - * @version 1.0 - */ - public function preferences() - { - - $prefs = $this->prefs; - - if (count($prefs['creds']) > 0 ) { - $hooks = $this->buycred_reward_arrange_data($prefs); - $this->buycred_reward_setting($hooks, $this); - } - else { - $default_data = array( - array( - 'creds' => '10', - 'log' => 'Reward for Buying %plural%.', - 'min' => '1', - 'max' => '10' - ) - ); - $this->buycred_reward_setting($default_data, $this); - } - - } - - /** - * Sanitize Preferences - */ - public function sanitise_preferences( $data ) - { - - $new_data = array(); - - foreach ( $data as $data_key => $data_value ) { - foreach ( $data_value as $key => $value) { - if ($data_key == 'creds' ) { - $new_data[$data_key][$key] = ( !empty($value) ) ? floatval($value) : 10; - } - else if ($data_key == 'log' ) { - $new_data[$data_key][$key] = ( !empty($value) ) ? sanitize_text_field($value) : 'Reward for Buying %plural%.'; - } - else if ($data_key == 'min' ) { - $new_data[$data_key][$key] = ( !empty($value) ) ? floatval($value) : 1; - } - else if ($data_key == 'max' ) { - $new_data[$data_key][$key] = ( !empty($value) ) ? floatval($value) : 1; - } - } - } - return $new_data; - } - - public function buycred_reward_arrange_data( $data ) - { - $hook_data = array(); - foreach ( $data['creds'] as $key => $value ) { - $hook_data[$key]['creds'] = $data['creds'][$key]; - $hook_data[$key]['log'] = $data['log'][$key]; - $hook_data[$key]['min'] = $data['min'][$key]; - $hook_data[$key]['max'] = $data['max'][$key]; - } - return $hook_data; - } - - public function buycred_reward_setting( $data ) - { - - foreach ( $data as $hook ):?> -
    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    -
    -
    -
    - - -
    -
    -
    -
    - - -
    -
    -
    -
    -
    -
    - - -
    -
    -
    -
    - 'buycred_reward', + 'defaults' => array( + 'creds' => array(), + 'log' => array(), + 'min' => array(), + 'max' => array() + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.8 + * @version 1.0 + */ + public function run() { + + add_filter( 'mycred_add_finished', array( $this, 'assign_buycred_reward' ), 20, 3 ); + + } + + /** + * Page Load + * @since 1.8 + * @version 1.0 + */ + public function assign_buycred_reward( $result, $request, $mycred ) { + + extract( $request ); + + if ( ! $result || strpos( $ref, 'buy_creds_with' ) === false ) return $result;; + + // Make sure user is not excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + if ( + ! empty( $this->prefs['creds'] ) && + ! empty( $this->prefs['log'] ) && + ! empty( $this->prefs['min'] ) && + ! empty( $this->prefs['max'] ) + ) { + + + $threshold = array(); + + foreach ( $this->prefs['creds'] as $key => $value ) { + + if ( + floatval( $amount ) >= floatval( $this->prefs['min'][$key] ) && + floatval( $amount ) <= floatval( $this->prefs['max'][$key] ) + ) { + array_push( $threshold, $key ); + } + + } + + if ( ! empty( $threshold ) ) { + + $hook_index = end( $threshold ); + + // Execute + $this->core->add_creds( + 'buycred_reward', + $user_id, + $this->prefs['creds'][$hook_index], + $this->prefs['log'][$hook_index], + $ref_id, + $data, + $this->mycred_type + ); + } + + } + + return $result; + + } + + /** + * Preference for Anniversary Hook + * @since 1.8 + * @version 1.0 + */ + public function preferences() { + + $prefs = $this->prefs; + + if ( count( $prefs['creds'] ) > 0 ) { + $hooks = $this->buycred_reward_arrange_data( $prefs ); + $this->buycred_reward_setting( $hooks, $this ); + } + else { + $default_data = array( + array( + 'creds' => '10', + 'log' => 'Reward for Buying %plural%.', + 'min' => '1', + 'max' => '10' + ) + ); + $this->buycred_reward_setting( $default_data, $this ); + } + + } + + /** + * Sanitize Preferences + */ + public function sanitise_preferences( $data ) { + + $new_data = array(); + + foreach ( $data as $data_key => $data_value ) { + foreach ( $data_value as $key => $value) { + if ( $data_key == 'creds' ) { + $new_data[$data_key][$key] = ( !empty( $value ) ) ? floatval( $value ) : 10; + } + else if ( $data_key == 'log' ) { + $new_data[$data_key][$key] = ( !empty( $value ) ) ? sanitize_text_field( $value ) : 'Reward for Buying %plural%.'; + } + else if ( $data_key == 'min' ) { + $new_data[$data_key][$key] = ( !empty( $value ) ) ? floatval( $value ) : 1; + } + else if ( $data_key == 'max' ) { + $new_data[$data_key][$key] = ( !empty( $value ) ) ? floatval( $value ) : 1; + } + } + } + return $new_data; + } + + public function buycred_reward_arrange_data( $data ){ + $hook_data = array(); + foreach ( $data['creds'] as $key => $value ) { + $hook_data[$key]['creds'] = $data['creds'][$key]; + $hook_data[$key]['log'] = $data['log'][$key]; + $hook_data[$key]['min'] = $data['min'][$key]; + $hook_data[$key]['max'] = $data['max'][$key]; + } + return $hook_data; + } + + public function buycred_reward_setting( $data ){ + + foreach ( $data as $hook ):?> +
    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    +
    +
    +
    + + +
    +
    +
    +
    + + +
    +
    +
    +
    +
    +
    + + +
    +
    +
    +
    + __('Reward for Buying %plural%', 'mycred'), - 'description' => __('Adds a myCred hook for buyCred reward.', 'mycred'), - 'callback' => array('myCRED_buyCRED_Reward_Hook') - ); - - return $installed; - } - - - public function register_buycred_reward_refrence( $list ) - { - - $list['buycred_reward'] = __('Reward for buyCRED Purchase', 'mycred'); - return $list; - } - - } +if ( ! class_exists( 'myCRED_buyCRED_Reward' ) ) : + class myCRED_buyCRED_Reward { + + // Instnace + protected static $_instance = NULL; + + /** + * Construct + */ + function __construct() { + + add_action( 'mycred_admin_enqueue', array( $this, 'register_assets' ) ); + add_filter( 'mycred_setup_hooks', array( $this, 'register_buycred_reward_hook' ), 10, 2 ); + add_action( 'mycred_load_hooks', array( $this, 'load_buycred_reward_hook' ) ); + add_filter( 'mycred_all_references', array( $this, 'register_buycred_reward_refrence' ) ); + + } + + /** + * Setup Instance + * @since 1.7 + * @version 1.0 + */ + public static function instance() { + if ( is_null( self::$_instance ) ) { + self::$_instance = new self(); + } + return self::$_instance; + } + + /** + * Register Assets + * @since 1.8 + * @version 1.0 + */ + public function register_assets() { + + wp_enqueue_style( 'buycred-admin-style', plugins_url( 'assets/css/admin-style.css', MYCRED_PURCHASE ), array(), MYCRED_PURCHASE_VERSION, 'all' ); + wp_enqueue_script( 'buycred-admin-script', plugins_url( 'assets/js/admin-script.js', MYCRED_PURCHASE ), array( 'jquery' ), MYCRED_PURCHASE_VERSION, 'all' ); + + } + + public function load_buycred_reward_hook() { + require_once MYCRED_BUYCRED_INCLUDES_DIR . 'buycred-reward-hook.php'; + } + + public function register_buycred_reward_hook( $installed ) { + + $installed['buycred_reward'] = array( + 'title' => __('Reward for Buying %plural%', 'mycred'), + 'description' => __('Adds a myCred hook for buyCred reward.', 'mycred'), + 'callback' => array('myCRED_buyCRED_Reward_Hook') + ); + + return $installed; + } + + + public function register_buycred_reward_refrence( $list ) { + + $list['buycred_reward'] = __('Reward for buyCRED Purchase', 'mycred'); + return $list; + } + + } endif; -function mycred_buycred_reward_init() -{ - return myCRED_buyCRED_Reward::instance(); +function mycred_buycred_reward_init() { + return myCRED_buyCRED_Reward::instance(); } -mycred_buycred_reward_init(); +mycred_buycred_reward_init(); \ No newline at end of file diff --git a/addons/buy-creds/includes/buycred-shortcodes.php b/addons/buy-creds/includes/buycred-shortcodes.php index 11e5c48..0823a95 100644 --- a/addons/buy-creds/includes/buycred-shortcodes.php +++ b/addons/buy-creds/includes/buycred-shortcodes.php @@ -77,7 +77,7 @@ function mycred_render_buy_points( $atts = array(), $button_label = '' ) { if ( empty( $classes ) || ! in_array( 'mycred-buy-link', $classes ) ) $classes[] = 'mycred-buy-link'; - $current_url = set_url_scheme( sanitize_url('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) ); + $current_url = set_url_scheme( sanitize_url( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ); if ( is_ssl() ) $current_url = str_replace( 'http://', 'https://', $current_url ); @@ -222,10 +222,10 @@ function mycred_render_buy_form_points( $atts = array(), $content = '' ) { - +
    diff --git a/addons/buy-creds/includes/index.php b/addons/buy-creds/includes/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/includes/index.php +++ b/addons/buy-creds/includes/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/index.php b/addons/buy-creds/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/index.php +++ b/addons/buy-creds/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/modules/buycred-module-core.php b/addons/buy-creds/modules/buycred-module-core.php index 9ae7254..bbf59fa 100644 --- a/addons/buy-creds/modules/buycred-module-core.php +++ b/addons/buy-creds/modules/buycred-module-core.php @@ -1,358 +1,323 @@ 'gateways', - 'option_id' => 'mycred_pref_buycreds', - 'defaults' => array( - 'installed' => array(), - 'active' => array(), - 'gateway_prefs' => array() - ), - 'labels' => array( - 'menu' => __('buyCred Gateways', 'mycred'), - 'page_title' => __('buyCred Gateways', 'mycred'), - 'page_header' => __('buyCred Gateways', 'mycred') - ), - 'screen_id' => MYCRED_SLUG . '-gateways', - 'accordion' => true, - 'add_to_core' => true, - 'menu_pos' => 70, - 'main_menu' => true - ), $type - ); - - $this->mycred_type = MYCRED_DEFAULT_TYPE_KEY; - - } - - /** - * Load - * - * @version 1.0.2 - */ - public function load() - { - - add_filter('mycred_parse_log_entry', array( $this, 'render_gift_tags' ), 10, 2); - - add_action('mycred_init', array( $this, 'module_init' ), $this->menu_pos); - add_action('wp_loaded', array( $this, 'module_run' )); - - add_action('mycred_register_assets', array( $this, 'register_assets' )); - add_action('mycred_front_enqueue_footer', array( $this, 'enqueue_footer' )); - - add_action('mycred_admin_init', array( $this, 'module_admin_init' ), $this->menu_pos); - add_action('mycred_admin_init', array( $this, 'register_settings' ), $this->menu_pos+1); - add_action('mycred_add_menu', array( $this, 'add_menu' ), $this->menu_pos); - add_action('mycred_add_menu', array( $this, 'add_to_menu' ), $this->menu_pos+1); - - add_action('mycred_after_core_prefs', array( $this, 'after_general_settings' )); - add_filter('mycred_save_core_prefs', array( $this, 'sanitize_extra_settings' ), 90, 3); - - add_action('pre_get_comments', array( $this, 'hide_buycred_transactions' )); - - } - - /** - * Init - * Register shortcodes. - * - * @since 0.1 - * @version 1.4 - */ - public function module_init() - { - - // Add shortcodes first - add_shortcode(MYCRED_SLUG . '_buy', 'mycred_render_buy_points'); - add_shortcode(MYCRED_SLUG . '_buy_form', 'mycred_render_buy_form_points'); - - $this->setup_instance(); - - $this->current_user_id = get_current_user_id(); - - } - - /** - * Register Assets - * - * @since 1.8 - * @version 1.0 - */ - public function register_assets() - { - - wp_register_style('buycred-checkout', plugins_url('assets/css/checkout.css', MYCRED_PURCHASE), array(), MYCRED_PURCHASE_VERSION, 'all'); - wp_register_script('buycred-checkout', plugins_url('assets/js/checkout.js', MYCRED_PURCHASE), array( 'jquery' ), MYCRED_PURCHASE_VERSION, 'all'); - - } - - /** - * Setup Purchase Instance - * - * @since 1.8 - * @version 1.0 - */ - public function setup_instance() - { - - global $buycred_instance; - - $buycred_instance = new StdClass(); - $buycred_instance->settings = mycred_get_buycred_settings(); - $buycred_instance->active = array(); - $buycred_instance->gateway_id = false; - $buycred_instance->checkout = false; - $buycred_instance->cancelled = false; - $buycred_instance->error = false; - $buycred_instance->gateway = false; - - } - - /** - * Get Payment Gateways - * Retreivs all available payment gateways that can be used to buyCRED - * - * @since 0.1 - * @version 1.1.1 - */ - public function get() - { +if ( ! class_exists( 'myCRED_buyCRED_Module' ) ) : + class myCRED_buyCRED_Module extends myCRED_Module { + + public $purchase_log = ''; + + /** + * Construct + */ + function __construct( $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( 'myCRED_BuyCRED_Module', array( + 'module_name' => 'gateways', + 'option_id' => 'mycred_pref_buycreds', + 'defaults' => array( + 'installed' => array(), + 'active' => array(), + 'gateway_prefs' => array() + ), + 'labels' => array( + 'menu' => __( 'buyCred Gateways', 'mycred' ), + 'page_title' => __( 'buyCred Gateways', 'mycred' ), + 'page_header' => __( 'buyCred Gateways', 'mycred' ) + ), + 'screen_id' => MYCRED_SLUG . '-gateways', + 'accordion' => true, + 'add_to_core' => true, + 'menu_pos' => 70, + 'main_menu' => true + ), $type ); + + $this->mycred_type = MYCRED_DEFAULT_TYPE_KEY; + + } + + /** + * Load + * @version 1.0.2 + */ + public function load() { + + add_filter( 'mycred_parse_log_entry', array( $this, 'render_gift_tags' ), 10, 2 ); + + add_action( 'mycred_init', array( $this, 'module_init' ), $this->menu_pos ); + add_action( 'wp_loaded', array( $this, 'module_run' ) ); + + add_action( 'mycred_register_assets', array( $this, 'register_assets' ) ); + add_action( 'mycred_front_enqueue_footer', array( $this, 'enqueue_footer' ) ); + + add_action( 'mycred_admin_init', array( $this, 'module_admin_init' ), $this->menu_pos ); + add_action( 'mycred_admin_init', array( $this, 'register_settings' ), $this->menu_pos+1 ); + add_action( 'mycred_add_menu', array( $this, 'add_menu' ), $this->menu_pos ); + add_action( 'mycred_add_menu', array( $this, 'add_to_menu' ), $this->menu_pos+1 ); - $installed = mycred_get_buycred_gateways(); + add_action( 'mycred_after_core_prefs', array( $this, 'after_general_settings' ) ); + add_filter( 'mycred_save_core_prefs', array( $this, 'sanitize_extra_settings' ), 90, 3 ); + + add_action('pre_get_comments', array( $this, 'hide_buycred_transactions' ) ); + + } + + /** + * Init + * Register shortcodes. + * @since 0.1 + * @version 1.4 + */ + public function module_init() { + + // Add shortcodes first + add_shortcode( MYCRED_SLUG . '_buy', 'mycred_render_buy_points' ); + add_shortcode( MYCRED_SLUG . '_buy_form', 'mycred_render_buy_form_points' ); + + $this->setup_instance(); - // Untill all custom gateways have been updated, make sure all gateways have an external setting - if (! empty($installed) ) { - foreach ( $installed as $id => $settings ) { + $this->current_user_id = get_current_user_id(); + + } + + /** + * Register Assets + * @since 1.8 + * @version 1.0 + */ + public function register_assets() { + + wp_register_style( 'buycred-checkout', plugins_url( 'assets/css/checkout.css', MYCRED_PURCHASE ), array(), MYCRED_PURCHASE_VERSION, 'all' ); + wp_register_script( 'buycred-checkout', plugins_url( 'assets/js/checkout.js', MYCRED_PURCHASE ), array( 'jquery' ), MYCRED_PURCHASE_VERSION, 'all' ); + + } - if (! array_key_exists('external', $settings) ) { - $installed[ $id ]['external'] = true; - } + /** + * Setup Purchase Instance + * @since 1.8 + * @version 1.0 + */ + public function setup_instance() { - if (! array_key_exists('custom_rate', $settings) ) { - $installed[ $id ]['custom_rate'] = false; - } + global $buycred_instance; - } - } + $buycred_instance = new StdClass(); + $buycred_instance->settings = mycred_get_buycred_settings(); + $buycred_instance->active = array(); + $buycred_instance->gateway_id = false; + $buycred_instance->checkout = false; + $buycred_instance->cancelled = false; + $buycred_instance->error = false; + $buycred_instance->gateway = false; - return $installed; + } - } + /** + * Get Payment Gateways + * Retreivs all available payment gateways that can be used to buyCRED + * @since 0.1 + * @version 1.1.1 + */ + public function get() { - /** - * Run - * Runs a gateway if requested. - * - * @since 1.7 - * @version 1.0 - */ - public function module_run() - { + $installed = mycred_get_buycred_gateways(); - global $buycred_instance; + // Untill all custom gateways have been updated, make sure all gateways have an external setting + if ( ! empty( $installed ) ) { + foreach ( $installed as $id => $settings ) { - // Prep - $installed = $this->get(); + if ( ! array_key_exists( 'external', $settings ) ) + $installed[ $id ]['external'] = true; - // Make sure we have installed gateways. - if (empty($installed) ) { return; - } + if ( ! array_key_exists( 'custom_rate', $settings ) ) + $installed[ $id ]['custom_rate'] = false; - // We only want to deal with active gateways - foreach ( $installed as $id => $data ) { - if ($this->is_active($id) ) { - $buycred_instance->active[ $id ] = $data; - } - } + } + } - if (empty($buycred_instance->active) ) { return; - } + return $installed; - /** - * Step 1 - Look for returns - * Runs though all active payment gateways and lets them decide if this is the - * user returning after a remote purchase. Each gateway should know what to look - * for to determen if they are responsible for handling the return. - */ - foreach ( $buycred_instance->active as $id => $data ) { + } - if ($data['external'] === true ) { - $this->call('returning', $buycred_instance->active[ $id ]['callback']); - } + /** + * Run + * Runs a gateway if requested. + * @since 1.7 + * @version 1.0 + */ + public function module_run() { - } + global $buycred_instance; - /** - * Step 2 - Check for gateway calls - * Checks to see if a gateway should be loaded. - */ - $buycred_instance->gateway_id = mycred_get_requested_gateway_id(); - $buycred_instance->checkout = false; - $buycred_instance->is_ajax = ( isset($_REQUEST['ajax']) && $_REQUEST['ajax'] == 1 ) ? true : false; + // Prep + $installed = $this->get(); - do_action('mycred_pre_process_buycred'); + // Make sure we have installed gateways. + if ( empty( $installed ) ) return; - // If we have a valid gateway ID and the gateway is active, lets run that gateway. - if ($buycred_instance->gateway_id !== false && array_key_exists($buycred_instance->gateway_id, $buycred_instance->active) ) { + // We only want to deal with active gateways + foreach ( $installed as $id => $data ) { + if ( $this->is_active( $id ) ) + $buycred_instance->active[ $id ] = $data; + } - // Construct Gateway - $buycred_instance->gateway = buycred_gateway($buycred_instance->gateway_id); + if ( empty( $buycred_instance->active ) ) return; - // Check payment processing - if (isset($_REQUEST['mycred_call']) ) { + /** + * Step 1 - Look for returns + * Runs though all active payment gateways and lets them decide if this is the + * user returning after a remote purchase. Each gateway should know what to look + * for to determen if they are responsible for handling the return. + */ + foreach ( $buycred_instance->active as $id => $data ) { - $buycred_instance->gateway->process(); + if ( $data['external'] === true ) + $this->call( 'returning', $buycred_instance->active[ $id ]['callback'] ); - do_action('mycred_buycred_process', $buycred_instance->gateway_id, $this->gateway_prefs); - do_action("mycred_buycred_process_{$gateway_id}", $this->gateway_prefs); + } - } + /** + * Step 2 - Check for gateway calls + * Checks to see if a gateway should be loaded. + */ + $buycred_instance->gateway_id = mycred_get_requested_gateway_id(); + $buycred_instance->checkout = false; + $buycred_instance->is_ajax = ( isset( $_REQUEST['ajax'] ) && $_REQUEST['ajax'] == 1 ) ? true : false; - add_action('template_redirect', array( $this, 'process_new_request' )); - add_filter('template_include', array( $this, 'checkout_page' ),999); + do_action( 'mycred_pre_process_buycred' ); - } + // If we have a valid gateway ID and the gateway is active, lets run that gateway. + if ( $buycred_instance->gateway_id !== false && array_key_exists( $buycred_instance->gateway_id, $buycred_instance->active ) ) { - } + // Construct Gateway + $buycred_instance->gateway = buycred_gateway( $buycred_instance->gateway_id ); - /** - * Process New Request - * - * @since 1.8 - * @version 1.0 - */ - public function process_new_request() - { + // Check payment processing + if ( isset( $_REQUEST['mycred_call'] ) ) { - global $buycred_instance, $buycred_sale; + $buycred_instance->gateway->process(); - if ($buycred_instance->checkout === false && isset($_REQUEST['mycred_buy']) ) { - $buycred_instance->checkout = true; - } + do_action( 'mycred_buycred_process', $buycred_instance->gateway_id, $this->gateway_prefs ); + do_action( "mycred_buycred_process_{$gateway_id}", $this->gateway_prefs ); - if ($buycred_instance->checkout ) { + } - $buycred_sale = true; + add_action( 'template_redirect', array( $this, 'process_new_request' ) ); + add_filter( 'template_include', array( $this, 'checkout_page' ) ); - if ($buycred_instance->gateway->valid_request() ) { + } - if ($buycred_instance->is_ajax ) { - $buycred_instance->gateway->ajax_buy(); - } + } - do_action('mycred_buycred_buy', $buycred_instance->gateway_id, $this->gateway_prefs); - do_action("mycred_buycred_buy_{$buycred_instance->gateway_id}", $this->gateway_prefs); + /** + * Process New Request + * @since 1.8 + * @version 1.0 + */ + public function process_new_request() { - } - else { + global $buycred_instance, $buycred_sale; - if (! empty($buycred_instance->gateway->errors) ) { - $buycred_instance->checkout = false; + if ( $buycred_instance->checkout === false && isset( $_REQUEST['mycred_buy'] ) ) + $buycred_instance->checkout = true; - if ($buycred_instance->is_ajax ) { - die(json_encode(array( 'validationFail' => true , 'errors' => $buycred_instance->gateway->errors ))); - } else - { - foreach( $buycred_instance->gateway->errors as $error ) - { - global $wp; - echo " + if ( $buycred_instance->checkout ) { + + $buycred_sale = true; + + if ( $buycred_instance->gateway->valid_request() ) { + + if ( $buycred_instance->is_ajax ) + $buycred_instance->gateway->ajax_buy(); + + do_action( 'mycred_buycred_buy', $buycred_instance->gateway_id, $this->gateway_prefs ); + do_action( "mycred_buycred_buy_{$buycred_instance->gateway_id}", $this->gateway_prefs ); + + } + else { + + if ( ! empty( $buycred_instance->gateway->errors ) ) { + $buycred_instance->checkout = false; + + if ( $buycred_instance->is_ajax ) + die( json_encode( array( 'validationFail' => true , 'errors' => $buycred_instance->gateway->errors ) ) ); + else + { + foreach( $buycred_instance->gateway->errors as $error ) + { + global $wp; + echo " "; - } - } - } + } + } + } - } + } - } + } - } + } - /** - * Checkout Page - * - * @since 1.8 - * @version 1.0 - */ - public function checkout_page( $template ) - { + /** + * Checkout Page + * @since 1.8 + * @version 1.0 + */ + public function checkout_page( $template ) { - global $buycred_instance; + global $buycred_instance; - if ($buycred_instance->checkout ) { + if ( $buycred_instance->checkout ) { - return MYCRED_BUYCRED_TEMPLATES_DIR . 'buycred-checkout.php'; - $override = mycred_locate_template('buycred-checkout.php', MYCRED_SLUG, MYCRED_BUYCRED_TEMPLATES_DIR); - if (! $override ) { - $template = $override; - } + return MYCRED_BUYCRED_TEMPLATES_DIR . 'buycred-checkout.php'; + $override = mycred_locate_template( 'buycred-checkout.php', MYCRED_SLUG, MYCRED_BUYCRED_TEMPLATES_DIR ); + if ( ! $override ) + $template = $override; - } + } - return $template; + return $template; - } + } - /** - * Enqueue Footer - * - * @since 1.8 - * @version 1.0 - */ - public function enqueue_footer() - { + /** + * Enqueue Footer + * @since 1.8 + * @version 1.0 + */ + public function enqueue_footer() { - global $buycred_instance, $buycred_sale; + global $buycred_instance, $buycred_sale; - $settings = mycred_get_buycred_settings(); + $settings = mycred_get_buycred_settings(); - if ($buycred_sale ) { + if ( $buycred_sale ) { - wp_enqueue_style('buycred-checkout'); + wp_enqueue_style( 'buycred-checkout' ); - wp_localize_script( - 'buycred-checkout', - 'buyCRED', - apply_filters( - 'mycred_buycred_checkout_js', array( - 'ajaxurl' => get_site_url(), - 'token' => wp_create_nonce('mycred-buy-creds'), - 'checkout' => $settings['checkout'], - 'redirecting' => esc_js(esc_attr__('Redirecting', 'mycred')), - 'error' => 'communications error' - ), $this - ) - ); - wp_enqueue_script('buycred-checkout'); + wp_localize_script( + 'buycred-checkout', + 'buyCRED', + apply_filters( 'mycred_buycred_checkout_js', array( + 'ajaxurl' => get_site_url(), + 'token' => wp_create_nonce( 'mycred-buy-creds' ), + 'checkout' => $settings['checkout'], + 'redirecting' => esc_js( esc_attr__( 'Redirecting', 'mycred' ) ), + 'error' => 'communications error' + ), $this ) + ); + wp_enqueue_script( 'buycred-checkout' ); - if ($settings['checkout'] != 'page' ) { - echo ' + if ( $settings['checkout'] != 'page' ) { + echo '
    X
    @@ -369,1245 +334,1162 @@ public function enqueue_footer()
    '; - } + } - } + } - } + } - /** - * Admin Init - * - * @since 1.5 - * @version 1.1 - */ - public function module_admin_init() - { + /** + * Admin Init + * @since 1.5 + * @version 1.1 + */ + public function module_admin_init() { - add_action('mycred_user_edit_after_balances', array( $this, 'exchange_rates_user_screen' ), 30); + add_action( 'mycred_user_edit_after_balances', array( $this, 'exchange_rates_user_screen' ), 30 ); - add_action('personal_options_update', array( $this, 'save_manual_exchange_rates' ), 30); - add_action('edit_user_profile_update', array( $this, 'save_manual_exchange_rates' ), 30); + add_action( 'personal_options_update', array( $this, 'save_manual_exchange_rates' ), 30 ); + add_action( 'edit_user_profile_update', array( $this, 'save_manual_exchange_rates' ), 30 ); - // Prep - $installed = mycred_get_buycred_gateways(); + // Prep + $installed = mycred_get_buycred_gateways(); - // Make sure we have installed gateways. - if (empty($installed) ) { return; - } + // Make sure we have installed gateways. + if ( empty( $installed ) ) return; - /** - * Admin Init - * Runs though all installed gateways to allow admin inits. - */ - foreach ( $installed as $id => $data ) { - $this->call('admin_init', $installed[ $id ]['callback']); - } + /** + * Admin Init + * Runs though all installed gateways to allow admin inits. + */ + foreach ( $installed as $id => $data ) + $this->call( 'admin_init', $installed[ $id ]['callback'] ); - } + } - /** - * Add to General Settings - * - * @since 0.1 - * @version 1.2 - */ - public function after_general_settings( $mycred = null ) - { + /** + * Add to General Settings + * @since 0.1 + * @version 1.2 + */ + public function after_general_settings( $mycred = NULL ) { - // Reset while on this screen so we can use $this->field_id() and $this->field_name() - $this->module_name = 'buy_creds'; - $this->option_id = ''; + // Reset while on this screen so we can use $this->field_id() and $this->field_name() + $this->module_name = 'buy_creds'; + $this->option_id = ''; - $uses_buddypress = class_exists('BuddyPress'); + $uses_buddypress = class_exists( 'BuddyPress' ); - $settings = mycred_get_buycred_settings(); + $settings = mycred_get_buycred_settings(); - ?> +?>

    buyCRED

    - module_name = 'gateways'; - $this->option_id = 'mycred_pref_buycreds'; + $this->module_name = 'gateways'; + $this->option_id = 'mycred_pref_buycreds'; - } + } - /** - * Save Settings - * - * @since 0.1 - * @version 1.2 - */ - public function sanitize_extra_settings( $new_data, $data, $core ) - { + /** + * Save Settings + * @since 0.1 + * @version 1.2 + */ + public function sanitize_extra_settings( $new_data, $data, $core ) { - $point_types = array(); + $point_types = array(); - if (isset($data['buy_creds']['types']) && ! empty($data['buy_creds']['types']) ) { - foreach ( $data['buy_creds']['types'] as $type_id => $setup ) { + if ( isset( $data['buy_creds']['types'] ) && ! empty( $data['buy_creds']['types'] ) ) { + foreach ( $data['buy_creds']['types'] as $type_id => $setup ) { - $type_id = sanitize_key($type_id); - if (! mycred_point_type_exists($type_id) ) { continue; - } + $type_id = sanitize_key( $type_id ); + if ( ! mycred_point_type_exists( $type_id ) ) continue; - if (isset($setup['enabled']) ) { - $point_types[] = $type_id; - } + if ( isset( $setup['enabled'] ) ) + $point_types[] = $type_id; - $settings = array(); - $settings['min'] = sanitize_text_field($setup['min']); - $settings['max'] = sanitize_text_field($setup['max']); - $settings['time'] = sanitize_key($setup['time']); + $settings = array(); + $settings['min'] = sanitize_text_field( $setup['min'] ); + $settings['max'] = sanitize_text_field( $setup['max'] ); + $settings['time'] = sanitize_key( $setup['time'] ); - $settings = shortcode_atts(mycred_get_buycred_sale_setup($type_id), $settings); + $settings = shortcode_atts( mycred_get_buycred_sale_setup( $type_id ), $settings ); - mycred_update_option('buycred-setup-' . $type_id, $settings); + mycred_update_option( 'buycred-setup-' . $type_id, $settings ); - } - } + } + } - if (empty($point_types) ) { - $point_types[] = MYCRED_DEFAULT_TYPE_KEY; - } + if ( empty( $point_types ) ) + $point_types[] = MYCRED_DEFAULT_TYPE_KEY; - $new_data['buy_creds']['types'] = $point_types; + $new_data['buy_creds']['types'] = $point_types; - $new_data['buy_creds']['checkout'] = sanitize_key($data['buy_creds']['checkout']); - $new_data['buy_creds']['log'] = sanitize_text_field($data['buy_creds']['log']); - $new_data['buy_creds']['login'] = wp_kses_post($data['buy_creds']['login']); + $new_data['buy_creds']['checkout'] = sanitize_key( $data['buy_creds']['checkout'] ); + $new_data['buy_creds']['log'] = sanitize_text_field( $data['buy_creds']['log'] ); + $new_data['buy_creds']['login'] = wp_kses_post( $data['buy_creds']['login'] ); - $new_data['buy_creds']['thankyou']['page'] = absint($data['buy_creds']['thankyou']['page']); - $new_data['buy_creds']['thankyou']['custom'] = sanitize_text_field($data['buy_creds']['thankyou']['custom']); - $new_data['buy_creds']['thankyou']['use'] = ( $new_data['buy_creds']['thankyou']['custom'] != '' ) ? 'custom' : 'page'; + $new_data['buy_creds']['thankyou']['page'] = absint( $data['buy_creds']['thankyou']['page'] ); + $new_data['buy_creds']['thankyou']['custom'] = sanitize_text_field( $data['buy_creds']['thankyou']['custom'] ); + $new_data['buy_creds']['thankyou']['use'] = ( $new_data['buy_creds']['thankyou']['custom'] != '' ) ? 'custom' : 'page'; - $new_data['buy_creds']['cancelled']['page'] = absint($data['buy_creds']['cancelled']['page']); - $new_data['buy_creds']['cancelled']['custom'] = sanitize_text_field($data['buy_creds']['cancelled']['custom']); - $new_data['buy_creds']['cancelled']['use'] = ( $new_data['buy_creds']['cancelled']['custom'] != '' ) ? 'custom' : 'page'; + $new_data['buy_creds']['cancelled']['page'] = absint( $data['buy_creds']['cancelled']['page'] ); + $new_data['buy_creds']['cancelled']['custom'] = sanitize_text_field( $data['buy_creds']['cancelled']['custom'] ); + $new_data['buy_creds']['cancelled']['use'] = ( $new_data['buy_creds']['cancelled']['custom'] != '' ) ? 'custom' : 'page'; - $new_data['buy_creds']['custom_log'] = ( ! isset($data['buy_creds']['custom_log']) ) ? 0 : 1; + $new_data['buy_creds']['custom_log'] = ( ! isset( $data['buy_creds']['custom_log'] ) ) ? 0 : 1; - $new_data['buy_creds']['gifting']['members'] = ( ! isset($data['buy_creds']['gifting']['members']) ) ? 0 : 1; - $new_data['buy_creds']['gifting']['authors'] = ( ! isset($data['buy_creds']['gifting']['authors']) ) ? 0 : 1; - $new_data['buy_creds']['gifting']['log'] = sanitize_text_field($data['buy_creds']['gifting']['log']); + $new_data['buy_creds']['gifting']['members'] = ( ! isset( $data['buy_creds']['gifting']['members'] ) ) ? 0 : 1; + $new_data['buy_creds']['gifting']['authors'] = ( ! isset( $data['buy_creds']['gifting']['authors'] ) ) ? 0 : 1; + $new_data['buy_creds']['gifting']['log'] = sanitize_text_field( $data['buy_creds']['gifting']['log'] ); - delete_option('mycred_buycred_reset'); + delete_option( 'mycred_buycred_reset' ); - return $new_data; + return $new_data; - } + } - /** - * Render Gift Tags - * - * @since 1.4.1 - * @version 1.0 - */ - public function render_gift_tags( $content, $log ) - { + /** + * Render Gift Tags + * @since 1.4.1 + * @version 1.0 + */ + public function render_gift_tags( $content, $log ) { - if (substr($log->ref, 0, 15) != 'buy_creds_with_' ) { return $content; - } - return $this->core->template_tags_user($content, absint($log->ref_id)); + if ( substr( $log->ref, 0, 15 ) != 'buy_creds_with_' ) return $content; + return $this->core->template_tags_user( $content, absint( $log->ref_id ) ); - } + } - /** - * Add Admin Menu Item - * - * @since 0.1 - * @version 1.2 - */ - public function add_to_menu() - { + /** + * Add Admin Menu Item + * @since 0.1 + * @version 1.2 + */ + public function add_to_menu() { - // In case we are using the Master Template feautre on multisites, and this is not the main - // site in the network, bail. - if (mycred_override_settings() && ! mycred_is_main_site() ) { return; - } + // In case we are using the Master Template feautre on multisites, and this is not the main + // site in the network, bail. + if ( mycred_override_settings() && ! mycred_is_main_site() ) return; - // If we selected to insert a purchase log - if (isset($this->core->buy_creds['custom_log']) && $this->core->buy_creds['custom_log'] ) { + // If we selected to insert a purchase log + if ( isset( $this->core->buy_creds['custom_log'] ) && $this->core->buy_creds['custom_log'] ) { - $pages = array(); - $point_types = ( isset($this->core->buy_creds['types']) && ! empty($this->core->buy_creds['types']) ) ? $this->core->buy_creds['types'] : array( MYCRED_DEFAULT_TYPE_KEY ); + $pages = array(); + $point_types = ( isset( $this->core->buy_creds['types'] ) && ! empty( $this->core->buy_creds['types'] ) ) ? $this->core->buy_creds['types'] : array( MYCRED_DEFAULT_TYPE_KEY ); - foreach ( $point_types as $type_id ) { + foreach ( $point_types as $type_id ) { - $mycred = mycred($type_id); - $menu_slug = ( $type_id != MYCRED_DEFAULT_TYPE_KEY ) ? MYCRED_SLUG . '_' . $type_id : MYCRED_SLUG; + $mycred = mycred( $type_id ); + $menu_slug = ( $type_id != MYCRED_DEFAULT_TYPE_KEY ) ? MYCRED_SLUG . '_' . $type_id : MYCRED_SLUG; - $pages[] = add_submenu_page( - $menu_slug, - __('buyCRED Purchase Log', 'mycred'), - __('Purchase Log', 'mycred'), - $mycred->get_point_editor_capability(), - MYCRED_SLUG . '-purchases-' . $type_id, - array( $this, 'purchase_log_page' ) - ); + $pages[] = add_submenu_page( + $menu_slug, + __( 'buyCRED Purchase Log', 'mycred' ), + __( 'Purchase Log', 'mycred' ), + $mycred->get_point_editor_capability(), + MYCRED_SLUG . '-purchases-' . $type_id, + array( $this, 'purchase_log_page' ) + ); - } + } - foreach ( $pages as $page ) { + foreach ( $pages as $page ) { - add_action('admin_print_styles-' . $page, array( $this, 'settings_page_enqueue' )); - add_action('load-' . $page, array( $this, 'screen_options' )); + add_action( 'admin_print_styles-' . $page, array( $this, 'settings_page_enqueue' ) ); + add_action( 'load-' . $page, array( $this, 'screen_options' ) ); - } + } - $this->purchase_log = $pages; + $this->purchase_log = $pages; - } + } - } + } - /** - * Page Header - * - * @since 1.3 - * @version 1.2 - */ - public function settings_header() - { + /** + * Page Header + * @since 1.3 + * @version 1.2 + */ + public function settings_header() { - wp_enqueue_style('mycred-admin'); - wp_enqueue_style('mycred-bootstrap-grid'); - wp_enqueue_style('mycred-forms'); + wp_enqueue_style( 'mycred-admin' ); + wp_enqueue_style( 'mycred-bootstrap-grid' ); + wp_enqueue_style( 'mycred-forms' ); - } + } - /** - * Payment Gateways Page - * - * @since 0.1 - * @since 2.3 Added more gateways in tab `mycred_buycred_more_gateways_tab` - * @version 1.2.2 - */ - public function admin_page() - { + /** + * Payment Gateways Page + * @since 0.1 + * @since 2.3 Added more gateways in tab `mycred_buycred_more_gateways_tab` + * @version 1.2.2 + */ + public function admin_page() { - // Security - if (! $this->core->user_is_point_admin() ) { wp_die('Access Denied'); - } + // Security + if ( ! $this->core->user_is_point_admin() ) wp_die( 'Access Denied' ); - $installed = $this->get(); + $installed = $this->get(); - ?> +?>
    -

    -

    ' . __('Settings Updated', 'mycred') . '

    '; - } - - ?> -
    - - settings_name); ?> - - - -
    - $data ) { - - $has_documentation = ( array_key_exists('documentation', $data) && ! empty($data['documentation']) ) ? esc_url_raw($data['documentation']) : false; - $has_test_mode = ( array_key_exists('sandbox', $data) ) ? (bool) $data['sandbox'] : false; - $sandbox_mode = ( array_key_exists($key, $this->gateway_prefs) && array_key_exists('sandbox', $this->gateway_prefs[ $key ]) && $this->gateway_prefs[ $key ]['sandbox'] === 1 ) ? true : false; - - if (! array_key_exists('icon', $data) ) { - $data['icon'] = 'dashicons-admin-plugins'; - } - - $column_class = 'col-lg-6 col-md-6 col-sm-12 col-xs-12'; - if (! $has_documentation && ! $has_test_mode ) { - $column_class = 'col-lg-12 col-md-12 col-sm-12 col-xs-12'; - } elseif ($has_documentation && $has_test_mode ) { - $column_class = 'col-lg-4 col-md-4 col-sm-12 col-xs-12'; - } - - ?> -

    core->template_tags_general($data['title']); ?>

    - - 'dashicons dashicons-admin-generic static', - 'text' => 'Stripe', - 'additional_text' => 'Paid', - 'url' => 'https://mycred.me/store/buycred-stripe/', - 'status' => 'disabled', - 'plugin' => 'mycred-stripe/mycred-stripe.php' - ); - - $more_gateways_tab[] = array( - 'icon' => 'dashicons dashicons-admin-generic static', - 'text' => 'Coinbase', - 'additional_text' => 'Paid', - 'url' => 'https://mycred.me/store/buycred-coinbase/', - 'status' => 'disabled', - 'plugin' => 'mycred-coinbase/mycred-coinbase.php' - ); - - $more_gateways_tab[] = array( - 'icon' => 'dashicons dashicons-admin-generic static', - 'text' => 'More Gateways', - 'url' => 'https://mycred.me/product-category/buycred-gateways/', - ); - - $more_gateways_tab = apply_filters('mycred_buycred_more_gateways_tab', $more_gateways_tab); - - if(MYCRED_SHOW_PREMIUM_ADDONS ) { - include_once ABSPATH . 'wp-admin/includes/plugin.php'; - - foreach( $more_gateways_tab as $key => $gateway ) - { - - if (isset($gateway['plugin']) && is_plugin_active($gateway['plugin']) ) { - continue; - } - - $disabled_class = ( isset($gateway['status']) && $gateway['status'] == 'disabled' ) ? 'disabled-tab' : ''; - - $content = " +

    +

    ' . __( 'Settings Updated', 'mycred' ) . '

    '; + +?> + + + settings_name ); ?> + + + +
    + $data ) { + + $has_documentation = ( array_key_exists( 'documentation', $data ) && ! empty( $data['documentation'] ) ) ? esc_url_raw( $data['documentation'] ) : false; + $has_test_mode = ( array_key_exists( 'sandbox', $data ) ) ? (bool) $data['sandbox'] : false; + $sandbox_mode = ( array_key_exists( $key, $this->gateway_prefs ) && array_key_exists( 'sandbox', $this->gateway_prefs[ $key ] ) && $this->gateway_prefs[ $key ]['sandbox'] === 1 ) ? true : false; + + if ( ! array_key_exists( 'icon', $data ) ) + $data['icon'] = 'dashicons-admin-plugins'; + + $column_class = 'col-lg-6 col-md-6 col-sm-12 col-xs-12'; + if ( ! $has_documentation && ! $has_test_mode ) + $column_class = 'col-lg-12 col-md-12 col-sm-12 col-xs-12'; + elseif ( $has_documentation && $has_test_mode ) + $column_class = 'col-lg-4 col-md-4 col-sm-12 col-xs-12'; + +?> +

    core->template_tags_general( $data['title'] ); ?>

    + + 'dashicons dashicons-admin-generic static', + 'text' => 'Stripe', + 'additional_text' => 'Paid', + 'url' => 'https://mycred.me/store/buycred-stripe/', + 'status' => 'disabled', + 'plugin' => 'mycred-stripe/mycred-stripe.php' + ); + + $more_gateways_tab[] = array( + 'icon' => 'dashicons dashicons-admin-generic static', + 'text' => 'Coinbase', + 'additional_text' => 'Paid', + 'url' => 'https://mycred.me/store/buycred-coinbase/', + 'status' => 'disabled', + 'plugin' => 'mycred-coinbase/mycred-coinbase.php' + ); + + $more_gateways_tab[] = array( + 'icon' => 'dashicons dashicons-admin-generic static', + 'text' => 'More Gateways', + 'url' => 'https://mycred.me/product-category/buycred-gateways/', + ); + + $more_gateways_tab = apply_filters( 'mycred_buycred_more_gateways_tab', $more_gateways_tab ); + + if( MYCRED_SHOW_PREMIUM_ADDONS ) + { + include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); + + foreach( $more_gateways_tab as $key => $gateway ) + { + + if ( isset( $gateway['plugin'] ) && is_plugin_active( $gateway['plugin'] ) ) + continue; + + $disabled_class = ( isset( $gateway['status'] ) && $gateway['status'] == 'disabled' ) ? 'disabled-tab' : ''; + + $content = "

    {$gateway['text']}"; - if(array_key_exists('additional_text', $gateway) && !empty($gateway['additional_text']) ) { - $content .= "{$gateway['additional_text']}"; - } - - $content .= "

    + if( array_key_exists( 'additional_text', $gateway ) && !empty( $gateway['additional_text'] ) ) + $content .= "{$gateway['additional_text']}"; + + $content .= " "; - echo $content; - } - } - ?> + echo $content; + } + } +?> -
    + - + -

    +

    -
    + - + - get(); + + if ( empty( $installed ) ) return $data; + + foreach ( $installed as $gateway_id => $gateway ) { + + $gateway_id = (string) $gateway_id; + $submitted_data = ( ! empty( $data['gateway_prefs'] ) && array_key_exists( $gateway_id, $data['gateway_prefs'] ) ) ? $data['gateway_prefs'][ $gateway_id ] : false; + + // No need to do anything if we have no data + if ( $submitted_data !== false ) + $data['gateway_prefs'][ $gateway_id ] = $this->call( 'sanitise_preferences', $installed[ $gateway_id ]['callback'], $submitted_data ); + + } + + return $data; + + } + + /** + * Purchase Log Screen Options + * @since 1.4 + * @version 1.1 + */ + public function screen_options() { + + if ( empty( $this->purchase_log ) ) return; + + $meta_key = 'mycred_payments_' . str_replace( MYCRED_SLUG . '-purchases-', '', $_GET['page'] ); + + if ( isset( $_REQUEST['wp_screen_options']['option'] ) && isset( $_REQUEST['wp_screen_options']['value'] ) ) { + + if ( $_REQUEST['wp_screen_options']['option'] == $meta_key ) { + $value = absint( $_REQUEST['wp_screen_options']['value'] ); + mycred_update_user_meta( $this->current_user_id, $meta_key, $value ); + } + + } + + $args = array( + 'label' => __( 'Payments', 'mycred' ), + 'default' => 10, + 'option' => $meta_key + ); + add_screen_option( 'per_page', $args ); + + } + + /** + * Purchase Log + * Render the dedicated admin screen where all point purchases are shown from the myCRED Log. + * This screen is added in for each point type that is set to be for sale. + * @since 1.4 + * @version 1.5 + */ + public function purchase_log_page() { + + $point_type = str_replace( 'mycred-purchases-', '', sanitize_key( $_GET['page'] ) ); + $installed = $this->get(); + + $mycred = $this->core; + if ( $point_type != MYCRED_DEFAULT_TYPE_KEY && mycred_point_type_exists( $point_type ) ) + $mycred = mycred( $point_type ); + + // Security (incase the user has setup different capabilities to manage this particular point type) + if ( ! $mycred->user_is_point_editor() ) wp_die( 'Access Denied' ); + + // Get references + $references = mycred_get_buycred_gateway_refs( $point_type ); - } - - /** - * Sanititze Settings - * - * @since 0.1 - * @version 1.3.1 - */ - public function sanitize_settings( $data ) - { - - $data = apply_filters('mycred_buycred_save_prefs', $data); - $installed = $this->get(); - - if (empty($installed) ) { return $data; - } - - foreach ( $installed as $gateway_id => $gateway ) { - - $gateway_id = (string) $gateway_id; - $submitted_data = ( ! empty($data['gateway_prefs']) && array_key_exists($gateway_id, $data['gateway_prefs']) ) ? $data['gateway_prefs'][ $gateway_id ] : false; - - // No need to do anything if we have no data - if ($submitted_data !== false ) { - $data['gateway_prefs'][ $gateway_id ] = $this->call('sanitise_preferences', $installed[ $gateway_id ]['callback'], $submitted_data); - } - - } - - return $data; - - } - - /** - * Purchase Log Screen Options - * - * @since 1.4 - * @version 1.1 - */ - public function screen_options() - { - - if (empty($this->purchase_log) ) { return; - } - - $meta_key = 'mycred_payments_' . str_replace(MYCRED_SLUG . '-purchases-', '', $_GET['page']); - - if (isset($_REQUEST['wp_screen_options']['option']) && isset($_REQUEST['wp_screen_options']['value']) ) { - - if ($_REQUEST['wp_screen_options']['option'] == $meta_key ) { - $value = absint($_REQUEST['wp_screen_options']['value']); - mycred_update_user_meta($this->current_user_id, $meta_key, $value); - } - - } - - $args = array( - 'label' => __('Payments', 'mycred'), - 'default' => 10, - 'option' => $meta_key - ); - add_screen_option('per_page', $args); - - } - - /** - * Purchase Log - * Render the dedicated admin screen where all point purchases are shown from the myCRED Log. - * This screen is added in for each point type that is set to be for sale. - * - * @since 1.4 - * @version 1.5 - */ - public function purchase_log_page() - { - - $point_type = str_replace('mycred-purchases-', '', sanitize_key( $_GET['page'] ) ); - $installed = $this->get(); - - $mycred = $this->core; - if ($point_type != MYCRED_DEFAULT_TYPE_KEY && mycred_point_type_exists($point_type) ) { - $mycred = mycred($point_type); - } - - // Security (incase the user has setup different capabilities to manage this particular point type) - if (! $mycred->user_is_point_editor() ) { wp_die('Access Denied'); - } - - // Get references - $references = mycred_get_buycred_gateway_refs($point_type); - - $search_args = mycred_get_search_args(); - $filter_url = admin_url('admin.php?page=' . MYCRED_SLUG . '-purchases-' . $point_type); - - $per_page = mycred_get_user_meta($this->current_user_id, 'mycred_payments_' . $point_type, '', true); - if (empty($per_page) || $per_page < 1 ) { $per_page = 10; - } - - // Entries per page - if (! array_key_exists('number', $search_args) ) { - $search_args['number'] = absint($per_page); - } - - $search_args['ctype'] = $point_type; - $search_args['ref'] = array( - 'ids' => $references, - 'compare' => 'IN' - ); - - $log = new myCRED_Query_Log($search_args); - $log->headers = apply_filters( - 'mycred_buycred_log_columns', array( - 'column-gateway' => __('Gateway', 'mycred'), - 'column-username' => __('Buyer', 'mycred'), - 'column-date' => __('Date', 'mycred'), - 'column-amount' => $mycred->plural(), - 'column-payed' => __('Payed', 'mycred'), - 'column-tranid' => __('Transaction ID', 'mycred') - ) - ); - - ?> + $search_args = mycred_get_search_args(); + $filter_url = admin_url( 'admin.php?page=' . MYCRED_SLUG . '-purchases-' . $point_type ); + + $per_page = mycred_get_user_meta( $this->current_user_id, 'mycred_payments_' . $point_type, '', true ); + if ( empty( $per_page ) || $per_page < 1 ) $per_page = 10; + + // Entries per page + if ( ! array_key_exists( 'number', $search_args ) ) + $search_args['number'] = absint( $per_page ); + + $search_args['ctype'] = $point_type; + $search_args['ref'] = array( + 'ids' => $references, + 'compare' => 'IN' + ); + + $log = new myCRED_Query_Log( $search_args ); + $log->headers = apply_filters( 'mycred_buycred_log_columns', array( + 'column-gateway' => __( 'Gateway', 'mycred' ), + 'column-username' => __( 'Buyer', 'mycred' ), + 'column-date' => __( 'Date', 'mycred' ), + 'column-amount' => $mycred->plural(), + 'column-payed' => __( 'Payed', 'mycred' ), + 'column-tranid' => __( 'Transaction ID', 'mycred' ) + ) ); + +?>
    -

    +

    - filter_dates(esc_url($filter_url)); ?> + filter_dates( esc_url( $filter_url ) ); ?> -
    - - + +'; - } + if ( array_key_exists( 's', $search_args ) ) + echo ''; - if (isset($_GET['ref']) ) { - echo ''; - } + if ( isset( $_GET['ref'] ) ) + echo ''; - if (isset($_GET['show']) ) { - echo ''; - } + if ( isset( $_GET['show'] ) ) + echo ''; - if (array_key_exists('order', $search_args) ) { - echo ''; - } + if ( array_key_exists( 'order', $search_args ) ) + echo ''; - if (array_key_exists('paged', $search_args) ) { - echo ''; - } + if ( array_key_exists( 'paged', $search_args ) ) + echo ''; - $log->search(); + $log->search(); - ?> +?> - + -
    +
    - table_nav('top'); ?> + table_nav( 'top' ); ?> -
    - - - - +
    + + +headers as $col_id => $col_title ) { - echo ''; - } + foreach ( $log->headers as $col_id => $col_title ) + echo ''; - ?> - - - - - + + + + +headers as $col_id => $col_title ) { - echo ''; - } + foreach ( $log->headers as $col_id => $col_title ) + echo ''; - ?> - - - - + + + +have_entries() ) { + // If we have results + if ( $log->have_entries() ) { - // Prep - $date_format = get_option('date_format') . ' ' . get_option('time_format'); - $entry_data = ''; - $alt = 0; + // Prep + $date_format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' ); + $entry_data = ''; + $alt = 0; - // Loop results - foreach ( $log->results as $log_entry ) { + // Loop results + foreach ( $log->results as $log_entry ) { - // Highlight alternate rows - $alt = $alt + 1; - $class = ''; - $style = ''; - if ($alt % 2 == 0 ) { $class = ' alt'; - } + // Highlight alternate rows + $alt = $alt + 1; + $class = ''; + $style = ''; + if ( $alt % 2 == 0 ) $class = ' alt'; - // Prep Sales data for use in columns - $sales_data = $this->get_sales_data_from_log_data($log_entry->data); - list ( $buyer_id, $payer_id, $amount, $cost, $currency, $token, $other ) = $sales_data; + // Prep Sales data for use in columns + $sales_data = $this->get_sales_data_from_log_data( $log_entry->data ); + list ( $buyer_id, $payer_id, $amount, $cost, $currency, $token, $other ) = $sales_data; - // Default Currency - if (empty($currency) ) { - $currency = 'USD'; - } + // Default Currency + if ( empty( $currency ) ) + $currency = 'USD'; - $gateway_name = str_replace('buy_creds_with_', '', $log_entry->ref); + $gateway_name = str_replace( 'buy_creds_with_', '', $log_entry->ref ); - // Color rows based on if the transaction was made in Sandbox mode or using a gateway that no longer is used. - if (! array_key_exists(str_replace('_', '-', $gateway_name), $installed) ) { - $style = ' style="color:silver;"'; + // Color rows based on if the transaction was made in Sandbox mode or using a gateway that no longer is used. + if ( ! array_key_exists( str_replace( '_', '-', $gateway_name ), $installed ) ) + $style = ' style="color:silver;"'; - } elseif (! $this->is_active(str_replace('_', '-', $gateway_name)) ) { - $style = ' style="color:gray;"'; + elseif ( ! $this->is_active( str_replace( '_', '-', $gateway_name ) ) ) + $style = ' style="color:gray;"'; - } elseif (substr($log_entry->entry, 0, 4) == 'TEST' ) { - $style = ' style="color:orange;"'; - } + elseif ( substr( $log_entry->entry, 0, 4 ) == 'TEST' ) + $style = ' style="color:orange;"'; - echo ''; + echo ''; - // Run though columns - foreach ( $log->headers as $column_id => $column_name ) { + // Run though columns + foreach ( $log->headers as $column_id => $column_name ) { - echo ''; + echo ''; - } + } - echo ''; + echo ''; - } + } - } + } - // No log entry - else { + // No log entry + else { - echo ''; + echo ''; - } + } - ?> - -
    ' . $col_title . '' . $col_title . '
    ' . $col_title . '' . $col_title . '
    '; + echo ''; - switch ( $column_id ) { + switch ( $column_id ) { - // Used gateway - case 'column-gateway' : + // Used gateway + case 'column-gateway' : - $gateway = str_replace(array( '-', '_' ), ' ', $gateway_name); - echo ucwords($gateway); + $gateway = str_replace( array( '-', '_' ), ' ', $gateway_name ); + echo ucwords( $gateway ); - break; + break; - // Username Column - case 'column-username' : + // Username Column + case 'column-username' : - $user = get_userdata($log_entry->user_id); - if ($user === false ) { - echo 'ID: ' . $log_entry->user_id; - } else { - echo $user->display_name . ' (ID: ' . $log_entry->user_id . ')'; - } + $user = get_userdata( $log_entry->user_id ); + if ( $user === false ) + echo 'ID: ' . $log_entry->user_id; + else + echo $user->display_name . ' (ID: ' . $log_entry->user_id . ')'; - break; + break; - // Date & Time Column - case 'column-date' : + // Date & Time Column + case 'column-date' : - echo date($date_format, $log_entry->time); + echo date( $date_format, $log_entry->time ); - break; + break; - // Amount Column - case 'column-amount' : + // Amount Column + case 'column-amount' : - echo $mycred->format_creds($log_entry->creds); + echo $mycred->format_creds( $log_entry->creds ); - break; + break; - // Amount Paid - case 'column-payed' : + // Amount Paid + case 'column-payed' : - $cost = 'n/a'; - $currency = ''; - $data = maybe_unserialize($log_entry->data); - if (is_array($data) && array_key_exists('sales_data', $data) ) { + $cost = 'n/a'; + $currency = ''; + $data = maybe_unserialize( $log_entry->data ); + if ( is_array( $data ) && array_key_exists( 'sales_data', $data ) ) { - $sales_data = explode('|', $data['sales_data']); - if (count($sales_data) >= 5 ) { - $cost = $sales_data[3]; - $currency = $sales_data[4]; - } + $sales_data = explode( '|', $data['sales_data'] ); + if ( count( $sales_data ) >= 5 ) { + $cost = $sales_data[3]; + $currency = $sales_data[4]; + } - } + } - if ($cost === 'n/a' ) { - echo 'n/a'; + if ( $cost === 'n/a' ) + echo 'n/a'; - } else { + else { - $rendered_cost = apply_filters('mycred_buycred_display_cost', $cost . ' ' . $currency, $sales_data, $log_entry, $gateway_name); - $rendered_cost = apply_filters('mycred_buycred_display_cost_' . $gateway_name, $rendered_cost, $sales_data, $log_entry); + $rendered_cost = apply_filters( 'mycred_buycred_display_cost', $cost . ' ' . $currency, $sales_data, $log_entry, $gateway_name ); + $rendered_cost = apply_filters( 'mycred_buycred_display_cost_' . $gateway_name, $rendered_cost, $sales_data, $log_entry ); - echo $rendered_cost; + echo $rendered_cost; - } + } - break; + break; - // Transaction ID - case 'column-tranid' : + // Transaction ID + case 'column-tranid' : - $transaction_id = $log_entry->time . $log_entry->user_id; - $saved_data = maybe_unserialize($log_entry->data); + $transaction_id = $log_entry->time . $log_entry->user_id; + $saved_data = maybe_unserialize( $log_entry->data ); - if (isset($saved_data['txn_id']) ) { - $transaction_id = $saved_data['txn_id']; + if ( isset( $saved_data['txn_id'] ) ) + $transaction_id = $saved_data['txn_id']; - } elseif (isset($saved_data['transaction_id']) ) { - $transaction_id = $saved_data['transaction_id']; - } + elseif ( isset( $saved_data['transaction_id'] ) ) + $transaction_id = $saved_data['transaction_id']; - echo $transaction_id; + echo $transaction_id; - break; + break; - default : + default : - do_action("mycred_payment_log_{$column_id}", $log_entry); - do_action("mycred_payment_log_{$column_id}_{$type}", $log_entry); + do_action( "mycred_payment_log_{$column_id}", $log_entry ); + do_action( "mycred_payment_log_{$column_id}_{$type}", $log_entry ); - break; + break; - } + } - echo '
    ' . __('No purchases found', 'mycred') . '
    ' . __( 'No purchases found', 'mycred' ) . '
    -
    +?> + + +
    - table_nav('bottom'); ?> + table_nav( 'bottom' ); ?> -
    +
    - + - +
    - core->buy_creds['types']) || empty($this->core->buy_creds['types']) ) { return; - } + // Make sure buyCRED is setup + if ( ! isset( $this->core->buy_creds['types'] ) || empty( $this->core->buy_creds['types'] ) ) return; - // Only visible to admins - if (! mycred_is_admin() ) { return; - } + // Only visible to admins + if ( ! mycred_is_admin() ) return; - $mycred_types = mycred_get_types(true); - $point_types_for_sale = $this->core->buy_creds['types']; - $installed = $this->get(); - $available_options = array(); + $mycred_types = mycred_get_types( true ); + $point_types_for_sale = $this->core->buy_creds['types']; + $installed = $this->get(); + $available_options = array(); - foreach ( $installed as $gateway_id => $prefs ) { + foreach ( $installed as $gateway_id => $prefs ) { - // Gateway is not active or settings have not yet been saved - if (! $this->is_active($gateway_id) || ! array_key_exists($gateway_id, $this->gateway_prefs) || ! $prefs['custom_rate'] ) { continue; - } + // Gateway is not active or settings have not yet been saved + if ( ! $this->is_active( $gateway_id ) || ! array_key_exists( $gateway_id, $this->gateway_prefs ) || ! $prefs['custom_rate'] ) continue; - $gateway_prefs = $this->gateway_prefs[ $gateway_id ]; + $gateway_prefs = $this->gateway_prefs[ $gateway_id ]; - // Need a currency - if (array_key_exists('currency', $gateway_prefs) && $gateway_prefs['currency'] == '' ) { continue; - } + // Need a currency + if ( array_key_exists( 'currency', $gateway_prefs ) && $gateway_prefs['currency'] == '' ) continue; - if (! array_key_exists('currency', $gateway_prefs) ) { - $gateway_prefs['currency'] = 'USD'; - } + if ( ! array_key_exists( 'currency', $gateway_prefs ) ) + $gateway_prefs['currency'] = 'USD'; - $setup = array( 'name' => $prefs['title'], 'currency' => $gateway_prefs['currency'], 'types' => array() ); + $setup = array( 'name' => $prefs['title'], 'currency' => $gateway_prefs['currency'], 'types' => array() ); - foreach ( $mycred_types as $point_type_key => $label ) { + foreach ( $mycred_types as $point_type_key => $label ) { - $row = array( 'name' => $label, 'enabled' => false, 'excluded' => true, 'default' => 0, 'override' => false, 'custom' => '', 'before' => '' ); + $row = array( 'name' => $label, 'enabled' => false, 'excluded' => true, 'default' => 0, 'override' => false, 'custom' => '', 'before' => '' ); - if (in_array($point_type_key, $point_types_for_sale) && array_key_exists($point_type_key, $gateway_prefs['exchange']) ) { + if ( in_array( $point_type_key, $point_types_for_sale ) && array_key_exists( $point_type_key, $gateway_prefs['exchange'] ) ) { - $row['enabled'] = true; + $row['enabled'] = true; - $mycred = mycred($point_type_key); + $mycred = mycred( $point_type_key ); - if (! $mycred->exclude_user($user->ID) ) { + if ( ! $mycred->exclude_user( $user->ID ) ) { - $row['excluded'] = false; - $row['default'] = $gateway_prefs['exchange'][ $point_type_key ]; + $row['excluded'] = false; + $row['default'] = $gateway_prefs['exchange'][ $point_type_key ]; - $row['before'] = $mycred->format_creds(1) . ' = '; + $row['before'] = $mycred->format_creds( 1 ) . ' = '; - $saved_overrides = (array) mycred_get_user_meta($user->ID, 'mycred_buycred_rates_' . $point_type_key, '', true); + $saved_overrides = (array) mycred_get_user_meta( $user->ID, 'mycred_buycred_rates_' . $point_type_key, '', true ); - if (! empty($saved_overrides) && array_key_exists($gateway_id, $saved_overrides) ) { + if ( ! empty( $saved_overrides ) && array_key_exists( $gateway_id, $saved_overrides ) ) { - $row['override'] = true; - $row['custom'] = $saved_overrides[ $gateway_id ]; + $row['override'] = true; + $row['custom'] = $saved_overrides[ $gateway_id ]; - } + } - } + } - } + } - $setup['types'][ $point_type_key ] = $row; + $setup['types'][ $point_type_key ] = $row; - } + } - $available_options[ $gateway_id ] = $setup; + $available_options[ $gateway_id ] = $setup; - } + } - if (empty($available_options) ) { return; - } + if ( empty( $available_options ) ) return; - ?> -

    +?> +

    - $setup ) : - - ?> - - - - - + $setup ) : + +?> + + + + +
    -
    - - $data ) { - - // This point type is not for sale - if (! $data['enabled'] ) { - - ?> -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    -
    - -
    -
    +
    + + $data ) { + + // This point type is not for sale + if ( ! $data['enabled'] ) { + +?> +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    + +
    +

    - $gateway ) { + foreach ( $_POST['mycred_adjust_users_buyrates'] as $ctype => $gateway ) { - $ctype = sanitize_key($ctype); - $mycred = mycred($ctype); + $ctype = sanitize_key( $ctype ); + $mycred = mycred( $ctype ); - if (! $mycred->exclude_user($user_id) ) { + if ( ! $mycred->exclude_user( $user_id ) ) { - $new_rates = array(); - foreach ( (array) $gateway as $gateway_id => $rate ) { + $new_rates = array(); + foreach ( (array) $gateway as $gateway_id => $rate ) { - if ($rate == '' ) { continue; - } + if ( $rate == '' ) continue; - if ($rate != 1 && in_array(substr($rate, 0, 1), array( '.', ',' )) ) { - $rate = (float) '0' . $rate; - } + if ( $rate != 1 && in_array( substr( $rate, 0, 1 ), array( '.', ',' ) ) ) + $rate = (float) '0' . $rate; - $new_rates[ $gateway_id ] = $rate; + $new_rates[ $gateway_id ] = $rate; - } + } - if (! empty($new_rates) ) { - mycred_update_user_meta($user_id, 'mycred_buycred_rates_' . $ctype, '', $new_rates); - } else { - mycred_delete_user_meta($user_id, 'mycred_buycred_rates_' . $ctype); - } + if ( ! empty( $new_rates ) ) + mycred_update_user_meta( $user_id, 'mycred_buycred_rates_' . $ctype, '', $new_rates ); + else + mycred_delete_user_meta( $user_id, 'mycred_buycred_rates_' . $ctype ); - } + } - } + } - } + } - } + } - /** - * Hide Comments - * - * @since 1.8.9 - * @version 1.0 - */ - public function hide_buycred_transactions( $query ) - { + /** + * Hide Comments + * @since 1.8.9 + * @version 1.0 + */ + public function hide_buycred_transactions( $query ) { - $query->query_vars['type__not_in'] = 'buycred'; - - } + $query->query_vars['type__not_in'] = 'buycred'; + + } - } + } endif; /** * Load buyCRED Module - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_load_buycred_core_addon') ) : - function mycred_load_buycred_core_addon( $modules, $point_types ) - { +if ( ! function_exists( 'mycred_load_buycred_core_addon' ) ) : + function mycred_load_buycred_core_addon( $modules, $point_types ) { - $modules['solo']['buycred'] = new myCRED_buyCRED_Module(); - $modules['solo']['buycred']->load(); + $modules['solo']['buycred'] = new myCRED_buyCRED_Module(); + $modules['solo']['buycred']->load(); - return $modules; + return $modules; - } + } endif; -add_filter('mycred_load_modules', 'mycred_load_buycred_core_addon', 30, 2); +add_filter( 'mycred_load_modules', 'mycred_load_buycred_core_addon', 30, 2 ); diff --git a/addons/buy-creds/modules/buycred-module-pending.php b/addons/buy-creds/modules/buycred-module-pending.php index 58376ed..fed1fbe 100644 --- a/addons/buy-creds/modules/buycred-module-pending.php +++ b/addons/buy-creds/modules/buycred-module-pending.php @@ -1,863 +1,786 @@ 'pending_payments', - 'option_id' => '', - 'defaults' => array(), - 'screen_id' => '', - 'accordion' => false, - 'add_to_core' => false, - 'menu_pos' => 75 - ), $type - ); - - } - - /** - * Load - * - * @version 1.0.1 - */ - public function load() - { + /** + * Construct + */ + function __construct( $type = MYCRED_DEFAULT_TYPE_KEY ) { - add_action('mycred_init', array( $this, 'module_init' ), $this->menu_pos); - add_action('mycred_admin_init', array( $this, 'module_admin_init' ), $this->menu_pos); + parent::__construct( 'buyCRED_Pending_Payments', array( + 'module_name' => 'pending_payments', + 'option_id' => '', + 'defaults' => array(), + 'screen_id' => '', + 'accordion' => false, + 'add_to_core' => false, + 'menu_pos' => 75 + ), $type ); - } + } - /** - * Module Init - * - * @since 1.7 - * @version 1.2 - */ - public function module_init() - { + /** + * Load + * @version 1.0.1 + */ + public function load() { - $this->register_pending_payments(); + add_action( 'mycred_init', array( $this, 'module_init' ), $this->menu_pos ); + add_action( 'mycred_admin_init', array( $this, 'module_admin_init' ), $this->menu_pos ); - add_shortcode(MYCRED_SLUG . '_buy_pending', 'mycred_render_pending_purchases'); + } - add_action('mycred_pre_process_buycred', array( $this, 'intercept_cancellations' )); + /** + * Module Init + * @since 1.7 + * @version 1.2 + */ + public function module_init() { - add_action('mycred_add_menu', array( $this, 'add_to_menu' ), $this->menu_pos); - add_action('transition_post_status', array( $this, 'pending_transitions' ), 10, 3); + $this->register_pending_payments(); - } + add_shortcode( MYCRED_SLUG . '_buy_pending', 'mycred_render_pending_purchases' ); - /** - * Intercept Cancellations - * - * @since 1.7 - * @version 1.1 - */ - public function intercept_cancellations() - { - - global $buycred_instance; - - // Intercept payment cancellations - if (isset($_REQUEST['buycred-cancel']) && isset($_REQUEST['_token']) && wp_verify_nonce($_REQUEST['_token'], 'buycred-cancel-pending-payment') ) { - - // Get pending payment object - $pending_payment_id = sanitize_text_field($_REQUEST['buycred-cancel']); - - // Move item to trash - buycred_trash_pending_payment($pending_payment_id); - - // Redirect - wp_safe_redirect(remove_query_arg(array( 'buycred-cancel', '_token' ))); - exit; - - } - - } - - /** - * Pending Transitions - * - * @since 1.8 - * @version 1.0 - */ - public function pending_transitions( $new_status, $old_status, $post ) - { - - if ($post->post_status == MYCRED_BUY_KEY ) { - - mycred_delete_user_meta($post->post_author, 'buycred_pending_payments'); - - } - - } - - /** - * Module Admin Init - * - * @since 1.7 - * @version 1.1 - */ - public function module_admin_init() - { - - add_filter('parent_file', array( $this, 'parent_file' )); - add_filter('submenu_file', array( $this, 'subparent_file' ), 10, 2); - - add_action('admin_notices', array( $this, 'admin_notices' )); - add_filter('post_row_actions', array( $this, 'adjust_row_actions' ), 10, 2); - add_action('admin_head-post.php', array( $this, 'edit_pending_payment_style' )); - add_action('admin_head-edit.php', array( $this, 'pending_payments_style' )); - add_filter('post_updated_messages', array( $this, 'post_updated_messages' )); - - add_filter('manage_' . MYCRED_BUY_KEY . '_posts_columns', array( $this, 'adjust_column_headers' )); - add_action('manage_' . MYCRED_BUY_KEY . '_posts_custom_column', array( $this, 'adjust_column_content' ), 10, 2); - add_filter('bulk_actions-edit-' . MYCRED_BUY_KEY, array( $this, 'bulk_actions' )); - add_action('save_post_' . MYCRED_BUY_KEY, array( $this, 'save_pending_payment' ), 10, 2); - - // Intercept payment completions - if (isset($_GET['credit']) && isset($_GET['token']) && wp_verify_nonce($_GET['token'], 'buycred-payout-pending') ) { - - $pending_id = absint($_GET['credit']); - - if ($this->core->user_is_point_editor() ) { - - $url = remove_query_arg(array( 'credit', 'token' )); - - if (buycred_complete_pending_payment($pending_id) ) { - $url = add_query_arg(array( 'credited' => 1 ), $url); - } - else { - $url = add_query_arg(array( 'credited' => 0 ), $url); - } - - wp_safe_redirect($url); - exit; - - } - - } - - } - - /** - * Register Pending Payments - * - * @since 1.5 - * @version 1.1 - */ - protected function register_pending_payments() - { - - $labels = array( - 'name' => _x('buyCred Pending Payments', 'Post Type General Name', 'mycred'), - 'singular_name' => _x('buyCred Pending Payment', 'Post Type Singular Name', 'mycred'), - 'menu_name' => __('buyCred Pending Payments', 'mycred'), - 'parent_item_colon' => '', - 'all_items' => __('buyCred Pending Payments', 'mycred'), - 'view_item' => '', - 'add_new_item' => '', - 'add_new' => '', - 'edit_item' => __('Edit buyCred Pending Payment', 'mycred'), - 'update_item' => '', - 'search_items' => '', - 'not_found' => __('Not found in Trash', 'mycred'), - 'not_found_in_trash' => __('Not found in Trash', 'mycred'), - ); - $args = array( - 'labels' => $labels, - 'supports' => array( 'title', 'comments' ), - 'hierarchical' => false, - 'public' => false, - 'show_ui' => true, - 'show_in_menu' => false, - 'show_in_nav_menus' => false, - 'show_in_admin_bar' => false, - 'can_export' => true, - 'has_archive' => false, - 'exclude_from_search' => true, - 'publicly_queryable' => false, - 'register_meta_box_cb' => array( $this, 'add_metaboxes' ) - ); - register_post_type(MYCRED_BUY_KEY, apply_filters('mycred_setup_pending_payment', $args)); - - } - - /** - * Adjust Post Updated Messages - * - * @since 1.7 - * @version 1.1 - */ - public function post_updated_messages( $messages ) - { - - $messages[ MYCRED_BUY_KEY ] = array( - 0 => '', - 1 => __('Payment Updated.', 'mycred'), - 2 => __('Payment Updated.', 'mycred'), - 3 => __('Payment Updated.', 'mycred'), - 4 => __('Payment Updated.', 'mycred'), - 5 => __('Payment Updated.', 'mycred'), - 6 => __('Payment Updated.', 'mycred'), - 7 => __('Payment Updated.', 'mycred'), - 8 => __('Payment Updated.', 'mycred'), - 9 => __('Payment Updated.', 'mycred'), - 10 => '' - ); - - return $messages; - - } - - /** - * Add Comment - * - * @since 1.7 - * @version 1.0 - */ - public function add_comment( $post_id, $event = '', $time = null ) - { - - return buycred_add_pending_comment($post_id, $event, $time); - - } - - /** - * Admin Notices - * - * @since 1.7 - * @version 1.1 - */ - public function admin_notices() - { - - if (isset($_GET['post_type']) && $_GET['post_type'] == MYCRED_BUY_KEY && isset($_GET['credited']) ) { - - if ($_GET['credited'] == 1 ) { - echo '

    ' . __('Pending payment successfully credited to account.', 'mycred') . '

    '; - - } elseif ($_GET['credited'] == 0 ) { - echo '

    ' . __('Failed to credit the pending payment to account.', 'mycred') . '

    '; - } - - } - - } - - /** - * Add Admin Menu Item - * - * @since 1.7 - * @version 1.1 - */ - public function add_to_menu() - { - - mycred_add_main_submenu( - __('Pending Payments', 'mycred'), - __('Pending Payments', 'mycred'), - $this->core->get_point_editor_capability(), - 'edit.php?post_type=' . MYCRED_BUY_KEY - ); - - } - - /** - * Parent File - * - * @since 1.7 - * @version 1.0.1 - */ - public function parent_file( $parent = '' ) - { - - global $pagenow; - - if (isset($_GET['post']) && mycred_get_post_type($_GET['post']) == MYCRED_BUY_KEY && isset($_GET['action']) && $_GET['action'] == 'edit' ) { - return MYCRED_MAIN_SLUG; - } - - return $parent; - - } - - /** - * Sub Parent File - * - * @since 1.7.8 - * @version 1.0 - */ - public function subparent_file( $subparent = '', $parent = '' ) - { - - global $pagenow; - - if (( $pagenow == 'edit.php' || $pagenow == 'post-new.php' ) && isset($_GET['post_type']) && $_GET['post_type'] == MYCRED_BUY_KEY ) { - - return 'edit.php?post_type=' . MYCRED_BUY_KEY; - - } + add_action( 'mycred_pre_process_buycred', array( $this, 'intercept_cancellations' ) ); - elseif ($pagenow == 'post.php' && isset($_GET['post']) && mycred_get_post_type($_GET['post']) == MYCRED_BUY_KEY ) { + add_action( 'mycred_add_menu', array( $this, 'add_to_menu' ), $this->menu_pos ); + add_action( 'transition_post_status', array( $this, 'pending_transitions' ), 10, 3 ); - return 'edit.php?post_type=' . MYCRED_BUY_KEY; + } - } + /** + * Intercept Cancellations + * @since 1.7 + * @version 1.1 + */ + public function intercept_cancellations() { - return $subparent; + global $buycred_instance; - } + // Intercept payment cancellations + if ( isset( $_REQUEST['buycred-cancel'] ) && isset( $_REQUEST['_token'] ) && wp_verify_nonce( $_REQUEST['_token'], 'buycred-cancel-pending-payment' ) ) { - /** - * Pending Payment Column Headers - * - * @since 1.5 - * @version 1.0 - */ - public function adjust_column_headers( $columns ) - { + // Get pending payment object + $pending_payment_id = sanitize_text_field( $_REQUEST['buycred-cancel'] ); + + // Move item to trash + buycred_trash_pending_payment( $pending_payment_id ); + + // Redirect + wp_safe_redirect( remove_query_arg( array( 'buycred-cancel', '_token' ) ) ); + exit; + + } + + } + + /** + * Pending Transitions + * @since 1.8 + * @version 1.0 + */ + public function pending_transitions( $new_status, $old_status, $post ) { + + if ( $post->post_status == MYCRED_BUY_KEY ) { + + mycred_delete_user_meta( $post->post_author, 'buycred_pending_payments' ); + + } + + } + + /** + * Module Admin Init + * @since 1.7 + * @version 1.1 + */ + public function module_admin_init() { + + add_filter( 'parent_file', array( $this, 'parent_file' ) ); + add_filter( 'submenu_file', array( $this, 'subparent_file' ), 10, 2 ); + + add_action( 'admin_notices', array( $this, 'admin_notices' ) ); + add_filter( 'post_row_actions', array( $this, 'adjust_row_actions' ), 10, 2 ); + add_action( 'admin_head-post.php', array( $this, 'edit_pending_payment_style' ) ); + add_action( 'admin_head-edit.php', array( $this, 'pending_payments_style' ) ); + add_filter( 'post_updated_messages', array( $this, 'post_updated_messages' ) ); + + add_filter( 'manage_' . MYCRED_BUY_KEY . '_posts_columns', array( $this, 'adjust_column_headers' ) ); + add_action( 'manage_' . MYCRED_BUY_KEY . '_posts_custom_column', array( $this, 'adjust_column_content' ), 10, 2 ); + add_filter( 'bulk_actions-edit-' . MYCRED_BUY_KEY, array( $this, 'bulk_actions' ) ); + add_action( 'save_post_' . MYCRED_BUY_KEY, array( $this, 'save_pending_payment' ), 10, 2 ); + + // Intercept payment completions + if ( isset( $_GET['credit'] ) && isset( $_GET['token'] ) && wp_verify_nonce( $_GET['token'], 'buycred-payout-pending' ) ) { + + $pending_id = absint( $_GET['credit'] ); + + if ( $this->core->user_is_point_editor() ) { + + $url = remove_query_arg( array( 'credit', 'token' ) ); + + if ( buycred_complete_pending_payment( $pending_id ) ) { + $url = add_query_arg( array( 'credited' => 1 ), $url ); + } + else { + $url = add_query_arg( array( 'credited' => 0 ), $url ); + } + + wp_safe_redirect( $url ); + exit; + + } + + } + + } + + /** + * Register Pending Payments + * @since 1.5 + * @version 1.1 + */ + protected function register_pending_payments() { + + $labels = array( + 'name' => _x( 'buyCred Pending Payments', 'Post Type General Name', 'mycred' ), + 'singular_name' => _x( 'buyCred Pending Payment', 'Post Type Singular Name', 'mycred' ), + 'menu_name' => __( 'buyCred Pending Payments', 'mycred' ), + 'parent_item_colon' => '', + 'all_items' => __( 'buyCred Pending Payments', 'mycred' ), + 'view_item' => '', + 'add_new_item' => '', + 'add_new' => '', + 'edit_item' => __( 'Edit buyCred Pending Payment', 'mycred' ), + 'update_item' => '', + 'search_items' => '', + 'not_found' => __( 'Not found in Trash', 'mycred' ), + 'not_found_in_trash' => __( 'Not found in Trash', 'mycred' ), + ); + $args = array( + 'labels' => $labels, + 'supports' => array( 'title', 'comments' ), + 'hierarchical' => false, + 'public' => false, + 'show_ui' => true, + 'show_in_menu' => false, + 'show_in_nav_menus' => false, + 'show_in_admin_bar' => false, + 'can_export' => true, + 'has_archive' => false, + 'exclude_from_search' => true, + 'publicly_queryable' => false, + 'register_meta_box_cb' => array( $this, 'add_metaboxes' ) + ); + register_post_type( MYCRED_BUY_KEY, apply_filters( 'mycred_setup_pending_payment', $args ) ); + + } + + /** + * Adjust Post Updated Messages + * @since 1.7 + * @version 1.1 + */ + public function post_updated_messages( $messages ) { + + $messages[ MYCRED_BUY_KEY ] = array( + 0 => '', + 1 => __( 'Payment Updated.', 'mycred' ), + 2 => __( 'Payment Updated.', 'mycred' ), + 3 => __( 'Payment Updated.', 'mycred' ), + 4 => __( 'Payment Updated.', 'mycred' ), + 5 => __( 'Payment Updated.', 'mycred' ), + 6 => __( 'Payment Updated.', 'mycred' ), + 7 => __( 'Payment Updated.', 'mycred' ), + 8 => __( 'Payment Updated.', 'mycred' ), + 9 => __( 'Payment Updated.', 'mycred' ), + 10 => '' + ); + + return $messages; + + } + + /** + * Add Comment + * @since 1.7 + * @version 1.0 + */ + public function add_comment( $post_id, $event = '', $time = NULL ) { + + return buycred_add_pending_comment( $post_id, $event, $time ); + + } + + /** + * Admin Notices + * @since 1.7 + * @version 1.1 + */ + public function admin_notices() { + + if ( isset( $_GET['post_type'] ) && $_GET['post_type'] == MYCRED_BUY_KEY && isset( $_GET['credited'] ) ) { + + if ( $_GET['credited'] == 1 ) + echo '

    ' . __( 'Pending payment successfully credited to account.', 'mycred' ) . '

    '; + + elseif ( $_GET['credited'] == 0 ) + echo '

    ' . __( 'Failed to credit the pending payment to account.', 'mycred' ) . '

    '; + + } + + } + + /** + * Add Admin Menu Item + * @since 1.7 + * @version 1.1 + */ + public function add_to_menu() { + + mycred_add_main_submenu( + __( 'Pending Payments', 'mycred' ), + __( 'Pending Payments', 'mycred' ), + $this->core->get_point_editor_capability(), + 'edit.php?post_type=' . MYCRED_BUY_KEY + ); + + } + + /** + * Parent File + * @since 1.7 + * @version 1.0.1 + */ + public function parent_file( $parent = '' ) { + + global $pagenow; + + if ( isset( $_GET['post'] ) && mycred_get_post_type( $_GET['post'] ) == MYCRED_BUY_KEY && isset( $_GET['action'] ) && $_GET['action'] == 'edit' ) + return MYCRED_MAIN_SLUG; + + return $parent; - return array( - 'cb' => $columns['cb'], - 'comments' => $columns['comments'], - 'title' => __('Transaction ID', 'mycred'), - 'date' => $columns['date'], - 'author' => __('Buyer', 'mycred'), - 'amount' => __('Amount', 'mycred'), - 'cost' => __('Cost', 'mycred'), - 'gateway' => __('Gateway', 'mycred'), - 'ctype' => __('Type', 'mycred') - ); + } - } + /** + * Sub Parent File + * @since 1.7.8 + * @version 1.0 + */ + public function subparent_file( $subparent = '', $parent = '' ) { - /** - * Pending Payment Column Content - * - * @since 1.5 - * @version 1.0 - */ - public function adjust_column_content( $column_name, $post_id ) - { - - global $mycred_modules; - - switch ( $column_name ) { - case 'author' : - - $from = (int) mycred_get_post_meta($post_id, 'from', true); - $user = get_userdata($from); - - if (isset($user->display_name) ) { - echo '' . $user->display_name . ''; - } else { - echo 'ID: ' . $from; - } - - break; - case 'amount'; + global $pagenow; - $type = mycred_get_post_meta($post_id, 'point_type', true); - $amount = mycred_get_post_meta($post_id, 'amount', true); - $mycred = mycred($type); + if ( ( $pagenow == 'edit.php' || $pagenow == 'post-new.php' ) && isset( $_GET['post_type'] ) && $_GET['post_type'] == MYCRED_BUY_KEY ) { - echo $mycred->format_creds($amount); + return 'edit.php?post_type=' . MYCRED_BUY_KEY; + + } - break; - case 'cost'; + elseif ( $pagenow == 'post.php' && isset( $_GET['post'] ) && mycred_get_post_type( $_GET['post'] ) == MYCRED_BUY_KEY ) { - $cost = mycred_get_post_meta($post_id, 'cost', true); - $currency = mycred_get_post_meta($post_id, 'currency', true); + return 'edit.php?post_type=' . MYCRED_BUY_KEY; - echo $cost . ' ' . $currency; + } - break; - case 'gateway'; + return $subparent; - $gateway = mycred_get_post_meta($post_id, 'gateway', true); - $installed = $mycred_modules['solo']['buycred']->get(); + } - if (isset($installed[ $gateway ]) ) { - echo $installed[ $gateway ]['title']; - } else { - echo $gateway; - } + /** + * Pending Payment Column Headers + * @since 1.5 + * @version 1.0 + */ + public function adjust_column_headers( $columns ) { - break; - case 'ctype'; + return array( + 'cb' => $columns['cb'], + 'comments' => $columns['comments'], + 'title' => __( 'Transaction ID', 'mycred' ), + 'date' => $columns['date'], + 'author' => __( 'Buyer', 'mycred' ), + 'amount' => __( 'Amount', 'mycred' ), + 'cost' => __( 'Cost', 'mycred' ), + 'gateway' => __( 'Gateway', 'mycred' ), + 'ctype' => __( 'Type', 'mycred' ) + ); - $type = mycred_get_post_meta($post_id, 'point_type', true); + } - if (isset($this->point_types[ $type ]) ) { - echo $this->point_types[ $type ]; - } else { - echo $type; - } + /** + * Pending Payment Column Content + * @since 1.5 + * @version 1.0 + */ + public function adjust_column_content( $column_name, $post_id ) { - break; - } + global $mycred_modules; - } + switch ( $column_name ) { + case 'author' : - /** - * Adjust Bulk Actions - * - * @since 1.5 - * @version 1.0 - */ - public function bulk_actions( $actions ) - { - - unset($actions['edit']); - return $actions; - - } - - /** - * Pending Payment Row Actions - * - * @since 1.5 - * @version 1.2 - */ - public function adjust_row_actions( $actions, $post ) - { + $from = (int) mycred_get_post_meta( $post_id, 'from', true ); + $user = get_userdata( $from ); - if ($post->post_type == MYCRED_BUY_KEY && $post->post_status != 'trash' ) { + if ( isset( $user->display_name ) ) + echo '' . $user->display_name . ''; + else + echo 'ID: ' . $from; - unset($actions['inline hide-if-no-js']); + break; + case 'amount'; - // Add option to "Pay Out" now - if ($this->core->user_is_point_editor() ) { - $actions['credit'] = '' . __('Pay Out', 'mycred') . ''; - } + $type = mycred_get_post_meta( $post_id, 'point_type', true ); + $amount = mycred_get_post_meta( $post_id, 'amount', true ); + $mycred = mycred( $type ); - } + echo $mycred->format_creds( $amount ); - return $actions; + break; + case 'cost'; - } + $cost = mycred_get_post_meta( $post_id, 'cost', true ); + $currency = mycred_get_post_meta( $post_id, 'currency', true ); - /** - * Edit Pending Payment Style - * - * @since 1.7 - * @version 1.0.1 - */ - public function edit_pending_payment_style() - { + echo $cost . ' ' . $currency; - global $post_type; + break; + case 'gateway'; - if ($post_type !== MYCRED_BUY_KEY ) { return; - } + $gateway = mycred_get_post_meta( $post_id, 'gateway', true ); + $installed = $mycred_modules['solo']['buycred']->get(); - wp_enqueue_style('mycred-bootstrap-grid'); - wp_enqueue_style('mycred-forms'); + if ( isset( $installed[ $gateway ] ) ) + echo $installed[ $gateway ]['title']; + else + echo $gateway; - add_filter('postbox_classes_buycred_payment_buycred-pending-payment', array( $this, 'metabox_classes' )); - add_filter('postbox_classes_buycred_payment_buycred-pending-comments', array( $this, 'metabox_classes' )); + break; + case 'ctype'; - ?> + $type = mycred_get_post_meta( $post_id, 'point_type', true ); + + if ( isset( $this->point_types[ $type ] ) ) + echo $this->point_types[ $type ]; + else + echo $type; + + break; + } + + } + + /** + * Adjust Bulk Actions + * @since 1.5 + * @version 1.0 + */ + public function bulk_actions( $actions ) { + + unset( $actions['edit'] ); + return $actions; + + } + + /** + * Pending Payment Row Actions + * @since 1.5 + * @version 1.2 + */ + public function adjust_row_actions( $actions, $post ) { + + if ( $post->post_type == MYCRED_BUY_KEY && $post->post_status != 'trash' ) { + + unset( $actions['inline hide-if-no-js'] ); + + // Add option to "Pay Out" now + if ( $this->core->user_is_point_editor() ) + $actions['credit'] = '' . __( 'Pay Out', 'mycred' ) . ''; + + } + + return $actions; + + } + + /** + * Edit Pending Payment Style + * @since 1.7 + * @version 1.0.1 + */ + public function edit_pending_payment_style() { + + global $post_type; + + if ( $post_type !== MYCRED_BUY_KEY ) return; + + wp_enqueue_style( 'mycred-bootstrap-grid' ); + wp_enqueue_style( 'mycred-forms' ); + + add_filter( 'postbox_classes_buycred_payment_buycred-pending-payment', array( $this, 'metabox_classes' ) ); + add_filter( 'postbox_classes_buycred_payment_buycred-pending-comments', array( $this, 'metabox_classes' ) ); + +?> - +?> - $post->post_type, - 'credit' => $post->ID, - 'token' => wp_create_nonce('buycred-payout-pending') - ), admin_url('edit.php') - ); - - $delete_url = get_delete_post_link($post->ID); - - ?> + $post->post_type, + 'credit' => $post->ID, + 'token' => wp_create_nonce( 'buycred-payout-pending' ) + ), admin_url( 'edit.php' ) ); + + $delete_url = get_delete_post_link( $post->ID ); + +?>
    -
    -
    - -
    +
    +
    + +
    -
    +
    -
    -
    +
    +
    -
    +
    -
    -
    -
    +
    +
    +
    -
    - +
    + - + -
    -
    -
    +
    +
    +
    - ID); - $buyer_name = 'ID: ' . $pending_payment->buyer_id; - - $buyer_object = get_userdata($pending_payment->buyer_id); - if (isset($buyer_object->ID) ) { - $buyer_name = $buyer_object->display_name; - if ($buyer_name == '' ) { - $buyer_name = $buyer_object->user_email; - } - } - - if ($pending_payment->recipient_id == $pending_payment->buyer_id ) { - $recipient_name = $buyer_name; - - } else { - $recipient_name = 'ID: ' . $pending_payment->recipient_id; - $recipient_object = get_userdata($pending_payment->recipient_id); - if (isset($recipient_object->ID) ) { - $recipient_name = $recipient_object->display_name; - if ($recipient_name == '' ) { - $recipient_name = $recipient_object->user_email; - } - } - } - - if ($pending_payment->point_type == $this->core->cred_id ) { - $mycred = $this->core; - - } else { - $mycred = mycred($pending_payment->point_type); - } - - ?> +ID ); + $buyer_name = 'ID: ' . $pending_payment->buyer_id; + + $buyer_object = get_userdata( $pending_payment->buyer_id ); + if ( isset( $buyer_object->ID ) ) { + $buyer_name = $buyer_object->display_name; + if ( $buyer_name == '' ) + $buyer_name = $buyer_object->user_email; + } + + if ( $pending_payment->recipient_id == $pending_payment->buyer_id ) + $recipient_name = $buyer_name; + + else { + $recipient_name = 'ID: ' . $pending_payment->recipient_id; + $recipient_object = get_userdata( $pending_payment->recipient_id ); + if ( isset( $recipient_object->ID ) ) { + $recipient_name = $recipient_object->display_name; + if ( $recipient_name == '' ) + $recipient_name = $recipient_object->user_email; + } + } + + if ( $pending_payment->point_type == $this->core->cred_id ) + $mycred = $this->core; + + else + $mycred = mycred( $pending_payment->point_type ); + +?>
    -
    -
    -
    - -

    -
    -
    -
    -
    - -

    -
    -
    -
    -
    -
    -
    - - core->buy_creds['types']) == 1 ) { - - ?> -

    plural()); ?>

    - - - - -
    -
    -
    -
    - - -
    -
    -
    -
    - - -
    -
    -
    -
    - - -
    -
    -
    -
    - - -
    -
    -
    +
    +
    +
    + +

    +
    +
    +
    +
    + +

    +
    +
    +
    +
    +
    +
    + +core->buy_creds['types'] ) == 1 ) { + +?> +

    plural() ); ?>

    + + + + +
    +
    +
    +
    + + +
    +
    +
    +
    + + +
    +
    +
    +
    + + +
    +
    +
    +
    + + +
    +
    +
    - $post->ID )); + $comments = get_comments( array( 'post_id' => $post->ID ) ); - echo ''; - } + } - /** - * Save Pending Payment - * - * @since 1.7 - * @version 1.0 - */ - public function save_pending_payment( $post_id, $post ) - { + /** + * Save Pending Payment + * @since 1.7 + * @version 1.0 + */ + public function save_pending_payment( $post_id, $post ) { - if (! $this->core->user_is_point_editor() || ! isset($_POST['buycred_pending_payment']) ) { return; - } + if ( ! $this->core->user_is_point_editor() || ! isset( $_POST['buycred_pending_payment'] ) ) return; - $pending_payment = $_POST['buycred_pending_payment']; - $changed = false; + $pending_payment = $_POST['buycred_pending_payment']; + $changed = false; - foreach ( $pending_payment as $meta_key => $meta_value ) { + foreach ( $pending_payment as $meta_key => $meta_value ) { - $new_value = sanitize_text_field($meta_value); - $old_value = mycred_get_post_meta($post_id, $meta_key, true); - if ($new_value != $old_value ) { - mycred_update_post_meta($post_id, $meta_key, $new_value); - $changed = true; - } + $new_value = sanitize_text_field( $meta_value ); + $old_value = mycred_get_post_meta( $post_id, $meta_key, true ); + if ( $new_value != $old_value ) { + mycred_update_post_meta( $post_id, $meta_key, $new_value ); + $changed = true; + } - } + } - if ($changed ) { - $user = wp_get_current_user(); - $this->add_comment($post_id, sprintf(__('Pending payment updated by %s', 'mycred'), $user->user_login)); - } + if ( $changed ) { + $user = wp_get_current_user(); + $this->add_comment( $post_id, sprintf( __( 'Pending payment updated by %s', 'mycred' ), $user->user_login ) ); + } - } + } - } + } endif; /** * Load buyCRED Pending Module - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_load_buycred_pending_addon') ) : - function mycred_load_buycred_pending_addon( $modules, $point_types ) - { +if ( ! function_exists( 'mycred_load_buycred_pending_addon' ) ) : + function mycred_load_buycred_pending_addon( $modules, $point_types ) { - $modules['solo']['buycred-pending'] = new buyCRED_Pending_Payments(); - $modules['solo']['buycred-pending']->load(); + $modules['solo']['buycred-pending'] = new buyCRED_Pending_Payments(); + $modules['solo']['buycred-pending']->load(); - return $modules; + return $modules; - } + } endif; -add_filter('mycred_load_modules', 'mycred_load_buycred_pending_addon', 40, 2); +add_filter( 'mycred_load_modules', 'mycred_load_buycred_pending_addon', 40, 2 ); diff --git a/addons/buy-creds/modules/index.php b/addons/buy-creds/modules/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/modules/index.php +++ b/addons/buy-creds/modules/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/buy-creds/myCRED-addon-buy-creds.php b/addons/buy-creds/myCRED-addon-buy-creds.php index 067367c..3b04ac5 100644 --- a/addons/buy-creds/myCRED-addon-buy-creds.php +++ b/addons/buy-creds/myCRED-addon-buy-creds.php @@ -4,25 +4,22 @@ * Addon URI: http://codex.mycred.me/chapter-iii/buycred/ * Version: 1.6 */ -if (! defined('myCRED_VERSION') ) { exit; -} - -define('MYCRED_PURCHASE', __FILE__); -define('MYCRED_PURCHASE_VERSION', '1.6'); -define('MYCRED_PURCHASE_DIR', myCRED_ADDONS_DIR . 'buy-creds/'); -define('MYCRED_BUYCRED_ABSTRACT_DIR', MYCRED_PURCHASE_DIR . 'abstracts/'); -define('MYCRED_BUYCRED_GATEWAYS_DIR', MYCRED_PURCHASE_DIR . 'gateways/'); -define('MYCRED_BUYCRED_MODULES_DIR', MYCRED_PURCHASE_DIR . 'modules/'); -define('MYCRED_BUYCRED_INCLUDES_DIR', MYCRED_PURCHASE_DIR . 'includes/'); -define('MYCRED_BUYCRED_TEMPLATES_DIR', MYCRED_PURCHASE_DIR . 'templates/'); - -if (! defined('MYCRED_BUY_PENDING_COMMENTS') ) { - define('MYCRED_BUY_PENDING_COMMENTS', true); -} - -if (! defined('MYCRED_BUY_KEY') ) { - define('MYCRED_BUY_KEY', 'buycred_payment'); -} +if ( ! defined( 'myCRED_VERSION' ) ) exit; + +define( 'MYCRED_PURCHASE', __FILE__ ); +define( 'MYCRED_PURCHASE_VERSION', '1.6' ); +define( 'MYCRED_PURCHASE_DIR', myCRED_ADDONS_DIR . 'buy-creds/' ); +define( 'MYCRED_BUYCRED_ABSTRACT_DIR', MYCRED_PURCHASE_DIR . 'abstracts/' ); +define( 'MYCRED_BUYCRED_GATEWAYS_DIR', MYCRED_PURCHASE_DIR . 'gateways/' ); +define( 'MYCRED_BUYCRED_MODULES_DIR', MYCRED_PURCHASE_DIR . 'modules/' ); +define( 'MYCRED_BUYCRED_INCLUDES_DIR', MYCRED_PURCHASE_DIR . 'includes/' ); +define( 'MYCRED_BUYCRED_TEMPLATES_DIR', MYCRED_PURCHASE_DIR . 'templates/' ); + +if ( ! defined( 'MYCRED_BUY_PENDING_COMMENTS' ) ) + define( 'MYCRED_BUY_PENDING_COMMENTS', true ); + +if ( ! defined( 'MYCRED_BUY_KEY' ) ) + define( 'MYCRED_BUY_KEY', 'buycred_payment' ); /** * Load Dependencies @@ -35,8 +32,7 @@ /** * Load Built-in Gateways - * - * @since 1.4 + * @since 1.4 * @version 1.0 */ require_once MYCRED_BUYCRED_GATEWAYS_DIR . 'paypal-standard.php'; @@ -45,12 +41,11 @@ require_once MYCRED_BUYCRED_GATEWAYS_DIR . 'skrill.php'; require_once MYCRED_BUYCRED_GATEWAYS_DIR . 'bank-transfer.php'; -do_action('mycred_buycred_load_gateways'); +do_action( 'mycred_buycred_load_gateways' ); /** * Load Modules - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ require_once MYCRED_BUYCRED_MODULES_DIR . 'buycred-module-core.php'; diff --git a/addons/buy-creds/templates/buycred-checkout.php b/addons/buy-creds/templates/buycred-checkout.php index 4e3b447..376cd61 100644 --- a/addons/buy-creds/templates/buycred-checkout.php +++ b/addons/buy-creds/templates/buycred-checkout.php @@ -1,25 +1,25 @@
    -
    +
    - + -
    -
    +
    +
    -
    + - + -
    + -
    - + +
    - + \ No newline at end of file diff --git a/addons/buy-creds/templates/index.php b/addons/buy-creds/templates/index.php index 1580272..4e6c07c 100644 --- a/addons/buy-creds/templates/index.php +++ b/addons/buy-creds/templates/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/cash-creds/abstracts/cashcred-abstract-payment-gateway.php b/addons/cash-creds/abstracts/cashcred-abstract-payment-gateway.php index 3a8a289..6064b45 100644 --- a/addons/cash-creds/abstracts/cashcred-abstract-payment-gateway.php +++ b/addons/cash-creds/abstracts/cashcred-abstract-payment-gateway.php @@ -1,772 +1,707 @@ current_user_id = get_current_user_id(); - $this->core = mycred(); - - // Arguments - if (! empty($args) ) { - foreach ( $args as $key => $value ) { - $this->$key = $value; - } - } - - $gateway_settings = $this->defaults; - if (is_array($gateway_prefs) && array_key_exists($this->id, $gateway_prefs) ) { - $gateway_settings = $gateway_prefs[ $this->id ]; - - } elseif (is_object($gateway_prefs) && array_key_exists($this->id, $gateway_prefs->gateway_prefs) ) { - $gateway_settings = $gateway_prefs->gateway_prefs[ $this->id ]; - } - - $this->prefs = shortcode_atts($this->defaults, $gateway_settings); - - // Sandbox Mode - $this->sandbox_mode = ( isset($this->prefs['sandbox']) ) ? (bool) $this->prefs['sandbox'] : false; - - } - - /** - * Process Purchase - * - * @since 0.1 - * @version 1.0 - */ - public function process($post = false) - { - } - - /** - * Results Handler - * - * @since 0.1 - * @version 1.0 - */ - public function returning() - { - } - - /** - * Admin Init Handler - * - * @since 1.7 - * @version 1.0 - */ - public function admin_init() - { - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.0 - */ - public function preferences() - { - - echo '

    This Payment Gateway has no settings

    '; - - } - - /** - * Sanatize Prefs - * - * @since 0.1 - * @version 1.0 - */ - public function sanitise_preferences( $data ) - { - - return $data; - - } - - /** - * Exchange Rate Setup - * - * @since 1.5 - * @version 1.1 - */ - public function exchange_rate_setup( $default = 'USD' ) - { - - if (! isset($this->prefs['exchange']) ) { return; - } - - $content = ''; - $point_types = mycred_get_types(); +if ( ! class_exists( 'myCRED_Cash_Payment_Gateway' ) ) : + abstract class myCRED_Cash_Payment_Gateway { + + /** + * The Gateways Unique ID + */ + public $id = false; + + /** + * Gateway Label + */ + public $label = ''; + + /** + * Indicates if the gateway is operating in sandbox mode or not + */ + public $sandbox_mode = false; + + /** + * Gateways Settings + */ + public $prefs = false; + + /** + * Main Point Type Settings + */ + public $core; + + /** + * The current users ID + */ + public $current_user_id = 0; + + protected $errors = array(); + + /** + * Construct + */ + public function __construct( $args = array(), $gateway_prefs = NULL ) { + + // Make sure gateway prefs is set + if ( $gateway_prefs === NULL ) return; + + // Populate + $this->current_user_id = get_current_user_id(); + $this->core = mycred(); + + // Arguments + if ( ! empty( $args ) ) { + foreach ( $args as $key => $value ) { + $this->$key = $value; + } + } + + $gateway_settings = $this->defaults; + if ( is_array( $gateway_prefs ) && array_key_exists( $this->id, $gateway_prefs ) ) + $gateway_settings = $gateway_prefs[ $this->id ]; + + elseif ( is_object( $gateway_prefs ) && array_key_exists( $this->id, $gateway_prefs->gateway_prefs ) ) + $gateway_settings = $gateway_prefs->gateway_prefs[ $this->id ]; + + $this->prefs = shortcode_atts( $this->defaults, $gateway_settings ); + + // Sandbox Mode + $this->sandbox_mode = ( isset( $this->prefs['sandbox'] ) ) ? (bool) $this->prefs['sandbox'] : false; + + } + + /** + * Process Purchase + * @since 0.1 + * @version 1.0 + */ + public function process($post = false) { } + + /** + * Results Handler + * @since 0.1 + * @version 1.0 + */ + public function returning() { } + + /** + * Admin Init Handler + * @since 1.7 + * @version 1.0 + */ + public function admin_init() { } + + /** + * Preferences + * @since 0.1 + * @version 1.0 + */ + public function preferences() { + + echo '

    This Payment Gateway has no settings

    '; + + } + + /** + * Sanatize Prefs + * @since 0.1 + * @version 1.0 + */ + public function sanitise_preferences( $data ) { + + return $data; + + } + + /** + * Exchange Rate Setup + * @since 1.5 + * @version 1.1 + */ + public function exchange_rate_setup( $default = 'USD' ) { + + if ( ! isset( $this->prefs['exchange'] ) ) return; + + $content = ''; + $point_types = mycred_get_types(); - foreach ( $point_types as $type_id => $label ) { + foreach ( $point_types as $type_id => $label ) { - $mycred = mycred($type_id); + $mycred = mycred( $type_id ); - if (! isset($this->prefs['exchange'][ $type_id ]) ) { - $this->prefs['exchange'][ $type_id ] = 1; - } + if ( ! isset( $this->prefs['exchange'][ $type_id ] ) ) + $this->prefs['exchange'][ $type_id ] = 1; - $content .= ' + $content .= ' - + - + $content .= '
    1 ' . esc_html($mycred->singular()) . '
    1 ' . esc_html( $mycred->singular() ) . '
    =
    '; + '; - if (isset($this->prefs['currency']) ) { - $content .= '' . ( ( $this->prefs['currency'] == '' ) ? __('Select currency', 'mycred') : esc_attr($this->prefs['currency']) ) . ''; + if ( isset( $this->prefs['currency'] ) ) + $content .= '' . ( ( $this->prefs['currency'] == '' ) ? __( 'Select currency', 'mycred' ) : esc_attr( $this->prefs['currency'] ) ) . ''; - } else { - $content .= '' . esc_attr($default) . ''; - } + else + $content .= '' . esc_attr( $default ) . ''; - $content .= '
    '; - } + } - echo apply_filters('mycred_cashcred_exchange_rate_field', $content, $default, $this); + echo apply_filters( 'mycred_cashcred_exchange_rate_field', $content, $default, $this ); - } + } - /** - * Get Field Name - * Returns the field name for the current gateway - * - * @since 0.1 - * @version 1.0 - */ - public function field_name( $field = '' ) - { - - if (is_array($field) ) { - - $array = array(); - foreach ( $field as $parent => $child ) { - if (! is_numeric($parent) ) { - $array[] = str_replace('-', '_', $parent); - } - - if (! empty($child) && ! is_array($child) ) { - $array[] = str_replace('-', '_', $child); - } - } - $field = '[' . implode('][', $array) . ']'; - - } - else { - - $field = '[' . $field . ']'; - - } - - return 'mycred_pref_cashcreds[gateway_prefs][' . $this->id . ']' . $field; - - } - - /** - * Get Field ID - * Returns the field id for the current gateway - * - * @since 0.1 - * @version 1.0 - */ - public function field_id( $field = '' ) - { - - if (is_array($field) ) { - - $array = array(); - foreach ( $field as $parent => $child ) { - if (! is_numeric($parent) ) { - $array[] = str_replace('_', '-', $parent); - } - - if (! empty($child) && ! is_array($child) ) { - $array[] = str_replace('_', '-', $child); - } - } - $field = implode('-', $array); - - } - else { - - $field = str_replace('_', '-', $field); - - } - - return 'mycred-gateway-prefs-' . str_replace('_', '-', $this->id) . '-' . $field; - - } - - /** - * Get Errors - * - * @since 1.0 - * @version 1.0 - */ - public function get_errors() - { - - if (empty($this->errors) ) { return; - } - - $errors = array(); - foreach ( $this->errors as $form_field => $error_message ) { - $errors[] = $error_message; - } - - ?> -
    ', $errors); ?>
    - 'Australian dollar', - 'BRL' => 'Brazilian real', - 'CAD' => 'Canadian dollar', - 'CNY' => 'Chinese Renmenbi', - 'CZK' => 'Czech koruna', - 'DKK' => 'Danish krone', - 'EUR' => 'Euro', - 'HKD' => 'Hong Kong dollar', - 'HUF' => 'Hungarian forint', - 'INR' => 'Indian rupee', - 'ILS' => 'Israeli new shekel', - 'JPY' => 'Japanese yen', - 'MYR' => 'Malaysian ringgit', - 'MXN' => 'Mexican peso', - 'TWD' => 'New Taiwan dollar', - 'NZD' => 'New Zealand dollar', - 'NOK' => 'Norwegian krone', - 'PHP' => 'Philippine peso', - 'PLN' => 'Polish złoty', - 'GBP' => 'Pound sterling', - 'RUB' => 'Russian ruble', - 'SGD' => 'Singapore dollar', - 'SEK' => 'Swedish krona', - 'CHF' => 'Swiss franc', - 'THB' => 'Thai baht', - 'USD' => 'United States dollar' + /** + * Get Field Name + * Returns the field name for the current gateway + * @since 0.1 + * @version 1.0 + */ + public function field_name( $field = '' ) { + + if ( is_array( $field ) ) { + + $array = array(); + foreach ( $field as $parent => $child ) { + if ( ! is_numeric( $parent ) ) + $array[] = str_replace( '-', '_', $parent ); + + if ( ! empty( $child ) && ! is_array( $child ) ) + $array[] = str_replace( '-', '_', $child ); + } + $field = '[' . implode( '][', $array ) . ']'; + + } + else { + + $field = '[' . $field . ']'; + + } + + return 'mycred_pref_cashcreds[gateway_prefs][' . $this->id . ']' . $field; + + } + + /** + * Get Field ID + * Returns the field id for the current gateway + * @since 0.1 + * @version 1.0 + */ + public function field_id( $field = '' ) { + + if ( is_array( $field ) ) { + + $array = array(); + foreach ( $field as $parent => $child ) { + if ( ! is_numeric( $parent ) ) + $array[] = str_replace( '_', '-', $parent ); + + if ( ! empty( $child ) && ! is_array( $child ) ) + $array[] = str_replace( '_', '-', $child ); + } + $field = implode( '-', $array ); + + } + else { + + $field = str_replace( '_', '-', $field ); + + } + + return 'mycred-gateway-prefs-' . str_replace( '_', '-', $this->id ) . '-' . $field; + + } + + /** + * Get Errors + * @since 1.0 + * @version 1.0 + */ + public function get_errors() { + + if ( empty( $this->errors ) ) return; + + $errors = array(); + foreach ( $this->errors as $form_field => $error_message ) + $errors[] = $error_message; + +?> +
    ', $errors ); ?>
    + 'Australian dollar', + 'BRL' => 'Brazilian real', + 'CAD' => 'Canadian dollar', + 'CNY' => 'Chinese Renmenbi', + 'CZK' => 'Czech koruna', + 'DKK' => 'Danish krone', + 'EUR' => 'Euro', + 'HKD' => 'Hong Kong dollar', + 'HUF' => 'Hungarian forint', + 'INR' => 'Indian rupee', + 'ILS' => 'Israeli new shekel', + 'JPY' => 'Japanese yen', + 'MYR' => 'Malaysian ringgit', + 'MXN' => 'Mexican peso', + 'TWD' => 'New Taiwan dollar', + 'NZD' => 'New Zealand dollar', + 'NOK' => 'Norwegian krone', + 'PHP' => 'Philippine peso', + 'PLN' => 'Polish złoty', + 'GBP' => 'Pound sterling', + 'RUB' => 'Russian ruble', + 'SGD' => 'Singapore dollar', + 'SEK' => 'Swedish krona', + 'CHF' => 'Swiss franc', + 'THB' => 'Thai baht', + 'USD' => 'United States dollar' ]; - $currencies = apply_filters('mycred_dropdown_currencies', $currencies, $this->id); - $currencies = apply_filters('mycred_dropdown_currencies_' . $this->id, $currencies); - - if ($js != '' ) { - $js = ' data-update="' . $js . '"'; - } - - echo ''; - - } - - /** - * Item Type Dropdown - * - * @since 0.1 - * @version 1.0 - */ - public function item_types_dropdown( $name = '' ) - { - - $types = array( - 'product' => 'Product', - 'service' => 'Service', - 'donation' => 'Donation' - ); - $types = apply_filters('mycred_dropdown_item_types', $types); - - echo ''; - - } - - /** - * Countries Dropdown Options - * - * @since 0.1 - * @version 1.0 - */ - public function list_option_countries( $selected = '' ) - { - - $countries = array ( - "US" => "UNITED STATES", - "AF" => "AFGHANISTAN", - "AL" => "ALBANIA", - "DZ" => "ALGERIA", - "AS" => "AMERICAN SAMOA", - "AD" => "ANDORRA", - "AO" => "ANGOLA", - "AI" => "ANGUILLA", - "AQ" => "ANTARCTICA", - "AG" => "ANTIGUA AND BARBUDA", - "AR" => "ARGENTINA", - "AM" => "ARMENIA", - "AW" => "ARUBA", - "AU" => "AUSTRALIA", - "AT" => "AUSTRIA", - "AZ" => "AZERBAIJAN", - "BS" => "BAHAMAS", - "BH" => "BAHRAIN", - "BD" => "BANGLADESH", - "BB" => "BARBADOS", - "BY" => "BELARUS", - "BE" => "BELGIUM", - "BZ" => "BELIZE", - "BJ" => "BENIN", - "BM" => "BERMUDA", - "BT" => "BHUTAN", - "BO" => "BOLIVIA", - "BA" => "BOSNIA AND HERZEGOVINA", - "BW" => "BOTSWANA", - "BV" => "BOUVET ISLAND", - "BR" => "BRAZIL", - "IO" => "BRITISH INDIAN OCEAN TERRITORY", - "BN" => "BRUNEI DARUSSALAM", - "BG" => "BULGARIA", - "BF" => "BURKINA FASO", - "BI" => "BURUNDI", - "KH" => "CAMBODIA", - "CM" => "CAMEROON", - "CA" => "CANADA", - "CV" => "CAPE VERDE", - "KY" => "CAYMAN ISLANDS", - "CF" => "CENTRAL AFRICAN REPUBLIC", - "TD" => "CHAD", - "CL" => "CHILE", - "CN" => "CHINA", - "CX" => "CHRISTMAS ISLAND", - "CC" => "COCOS (KEELING) ISLANDS", - "CO" => "COLOMBIA", - "KM" => "COMOROS", - "CG" => "CONGO", - "CD" => "CONGO, THE DEMOCRATIC REPUBLIC OF THE", - "CK" => "COOK ISLANDS", - "CR" => "COSTA RICA", - "CI" => "COTE D'IVOIRE", - "HR" => "CROATIA", - "CU" => "CUBA", - "CY" => "CYPRUS", - "CZ" => "CZECH REPUBLIC", - "DK" => "DENMARK", - "DJ" => "DJIBOUTI", - "DM" => "DOMINICA", - "DO" => "DOMINICAN REPUBLIC", - "EC" => "ECUADOR", - "EG" => "EGYPT", - "SV" => "EL SALVADOR", - "GQ" => "EQUATORIAL GUINEA", - "ER" => "ERITREA", - "EE" => "ESTONIA", - "ET" => "ETHIOPIA", - "FK" => "FALKLAND ISLANDS (MALVINAS)", - "FO" => "FAROE ISLANDS", - "FJ" => "FIJI", - "FI" => "FINLAND", - "FR" => "FRANCE", - "GF" => "FRENCH GUIANA", - "PF" => "FRENCH POLYNESIA", - "TF" => "FRENCH SOUTHERN TERRITORIES", - "GA" => "GABON", - "GM" => "GAMBIA", - "GE" => "GEORGIA", - "DE" => "GERMANY", - "GH" => "GHANA", - "GI" => "GIBRALTAR", - "GR" => "GREECE", - "GL" => "GREENLAND", - "GD" => "GRENADA", - "GP" => "GUADELOUPE", - "GU" => "GUAM", - "GT" => "GUATEMALA", - "GN" => "GUINEA", - "GW" => "GUINEA-BISSAU", - "GY" => "GUYANA", - "HT" => "HAITI", - "HM" => "HEARD ISLAND AND MCDONALD ISLANDS", - "VA" => "HOLY SEE (VATICAN CITY STATE)", - "HN" => "HONDURAS", - "HK" => "HONG KONG", - "HU" => "HUNGARY", - "IS" => "ICELAND", - "IN" => "INDIA", - "ID" => "INDONESIA", - "IR" => "IRAN, ISLAMIC REPUBLIC OF", - "IQ" => "IRAQ", - "IE" => "IRELAND", - "IL" => "ISRAEL", - "IT" => "ITALY", - "JM" => "JAMAICA", - "JP" => "JAPAN", - "JO" => "JORDAN", - "KZ" => "KAZAKHSTAN", - "KE" => "KENYA", - "KI" => "KIRIBATI", - "KP" => "KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF", - "KR" => "KOREA, REPUBLIC OF", - "KW" => "KUWAIT", - "KG" => "KYRGYZSTAN", - "LA" => "LAO PEOPLE'S DEMOCRATIC REPUBLIC", - "LV" => "LATVIA", - "LB" => "LEBANON", - "LS" => "LESOTHO", - "LR" => "LIBERIA", - "LY" => "LIBYAN ARAB JAMAHIRIYA", - "LI" => "LIECHTENSTEIN", - "LT" => "LITHUANIA", - "LU" => "LUXEMBOURG", - "MO" => "MACAO", - "MK" => "MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF", - "MG" => "MADAGASCAR", - "MW" => "MALAWI", - "MY" => "MALAYSIA", - "MV" => "MALDIVES", - "ML" => "MALI", - "MT" => "MALTA", - "MH" => "MARSHALL ISLANDS", - "MQ" => "MARTINIQUE", - "MR" => "MAURITANIA", - "MU" => "MAURITIUS", - "YT" => "MAYOTTE", - "MX" => "MEXICO", - "FM" => "MICRONESIA, FEDERATED STATES OF", - "MD" => "MOLDOVA, REPUBLIC OF", - "MC" => "MONACO", - "MN" => "MONGOLIA", - "MS" => "MONTSERRAT", - "MA" => "MOROCCO", - "MZ" => "MOZAMBIQUE", - "MM" => "MYANMAR", - "NA" => "NAMIBIA", - "NR" => "NAURU", - "NP" => "NEPAL", - "NL" => "NETHERLANDS", - "AN" => "NETHERLANDS ANTILLES", - "NC" => "NEW CALEDONIA", - "NZ" => "NEW ZEALAND", - "NI" => "NICARAGUA", - "NE" => "NIGER", - "NG" => "NIGERIA", - "NU" => "NIUE", - "NF" => "NORFOLK ISLAND", - "MP" => "NORTHERN MARIANA ISLANDS", - "NO" => "NORWAY", - "OM" => "OMAN", - "PK" => "PAKISTAN", - "PW" => "PALAU", - "PS" => "PALESTINIAN TERRITORY, OCCUPIED", - "PA" => "PANAMA", - "PG" => "PAPUA NEW GUINEA", - "PY" => "PARAGUAY", - "PE" => "PERU", - "PH" => "PHILIPPINES", - "PN" => "PITCAIRN", - "PL" => "POLAND", - "PT" => "PORTUGAL", - "PR" => "PUERTO RICO", - "QA" => "QATAR", - "RE" => "REUNION", - "RO" => "ROMANIA", - "RU" => "RUSSIAN FEDERATION", - "RW" => "RWANDA", - "SH" => "SAINT HELENA", - "KN" => "SAINT KITTS AND NEVIS", - "LC" => "SAINT LUCIA", - "PM" => "SAINT PIERRE AND MIQUELON", - "VC" => "SAINT VINCENT AND THE GRENADINES", - "WS" => "SAMOA", - "SM" => "SAN MARINO", - "ST" => "SAO TOME AND PRINCIPE", - "SA" => "SAUDI ARABIA", - "SN" => "SENEGAL", - "CS" => "SERBIA AND MONTENEGRO", - "SC" => "SEYCHELLES", - "SL" => "SIERRA LEONE", - "SG" => "SINGAPORE", - "SK" => "SLOVAKIA", - "SI" => "SLOVENIA", - "SB" => "SOLOMON ISLANDS", - "SO" => "SOMALIA", - "ZA" => "SOUTH AFRICA", - "GS" => "SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS", - "ES" => "SPAIN", - "LK" => "SRI LANKA", - "SD" => "SUDAN", - "SR" => "SURINAME", - "SJ" => "SVALBARD AND JAN MAYEN", - "SZ" => "SWAZILAND", - "SE" => "SWEDEN", - "CH" => "SWITZERLAND", - "SY" => "SYRIAN ARAB REPUBLIC", - "TW" => "TAIWAN, PROVINCE OF CHINA", - "TJ" => "TAJIKISTAN", - "TZ" => "TANZANIA, UNITED REPUBLIC OF", - "TH" => "THAILAND", - "TL" => "TIMOR-LESTE", - "TG" => "TOGO", - "TK" => "TOKELAU", - "TO" => "TONGA", - "TT" => "TRINIDAD AND TOBAGO", - "TN" => "TUNISIA", - "TR" => "TURKEY", - "TM" => "TURKMENISTAN", - "TC" => "TURKS AND CAICOS ISLANDS", - "TV" => "TUVALU", - "UG" => "UGANDA", - "UA" => "UKRAINE", - "AE" => "UNITED ARAB EMIRATES", - "GB" => "UNITED KINGDOM", - "US" => "UNITED STATES", - "UM" => "UNITED STATES MINOR OUTLYING ISLANDS", - "UY" => "URUGUAY", - "UZ" => "UZBEKISTAN", - "VU" => "VANUATU", - "VE" => "VENEZUELA", - "VN" => "VIET NAM", - "VG" => "VIRGIN ISLANDS, BRITISH", - "VI" => "VIRGIN ISLANDS, U.S.", - "WF" => "WALLIS AND FUTUNA", - "EH" => "WESTERN SAHARA", - "YE" => "YEMEN", - "ZM" => "ZAMBIA", - "ZW" => "ZIMBABWE" - ); - $countries = apply_filters('mycred_list_option_countries', $countries); - - foreach ( $countries as $code => $cname ) { - echo ''; - } - - } - - /** - * US States Dropdown Options - * - * @since 0.1 - * @version 1.0 - */ - public function list_option_us_states( $selected = '', $non_us = false ) - { - - $states = array ( - "AL" => "Alabama", - "AK" => "Alaska", - "AZ" => "Arizona", - "AR" => "Arkansas", - "CA" => "California", - "CO" => "Colorado", - "CT" => "Connecticut", - "DC" => "D.C.", - "DE" => "Delaware", - "FL" => "Florida", - "GA" => "Georgia", - "HI" => "Hawaii", - "ID" => "Idaho", - "IL" => "Illinois", - "IN" => "Indiana", - "IA" => "Iowa", - "KS" => "Kansas", - "KY" => "Kentucky", - "LA" => "Louisiana", - "ME" => "Maine", - "MD" => "Maryland", - "MA" => "Massachusetts", - "MI" => "Michigan", - "MN" => "Minnesota", - "MS" => "Mississippi", - "MO" => "Missouri", - "MT" => "Montana", - "NE" => "Nebraska", - "NV" => "Nevada", - "NH" => "New Hampshire", - "NJ" => "New Jersey", - "NM" => "New Mexico", - "NY" => "New York", - "NC" => "North Carolina", - "ND" => "North Dakota", - "OH" => "Ohio", - "OK" => "Oklahoma", - "OR" => "Oregon", - "PA" => "Pennsylvania", - "RI" => "Rhode Island", - "SC" => "South Carolina", - "SD" => "South Dakota", - "TN" => "Tennessee", - "TX" => "Texas", - "UT" => "Utah", - "VT" => "Vermont", - "VA" => "Virginia", - "WA" => "Washington", - "WV" => "West Virginia", - "WI" => "Wisconsin", - "WY" => "Wyoming" - ); - $states = apply_filters('mycred_list_option_us', $states); - - $outside = 'Outside US'; - if ($non_us == 'top' ) { echo ''; - } - foreach ( $states as $code => $cname ) { - echo ''; - } - if ($non_us == 'bottom' ) { echo ''; - } - - } - - /** - * Months Dropdown Options - * - * @since 0.1 - * @version 1.0 - */ - public function list_option_months( $selected = '' ) - { - - $months = array ( - "01" => __('January', 'mycred'), - "02" => __('February', 'mycred'), - "03" => __('March', 'mycred'), - "04" => __('April', 'mycred'), - "05" => __('May', 'mycred'), - "06" => __('June', 'mycred'), - "07" => __('July', 'mycred'), - "08" => __('August', 'mycred'), - "09" => __('September', 'mycred'), - "10" => __('October', 'mycred'), - "11" => __('November', 'mycred'), - "12" => __('December', 'mycred') - ); - - foreach ( $months as $number => $text ) { - echo ''; - } - - } - - /** - * Years Dropdown Options - * - * @since 0.1 - * @version 1.0 - */ - public function list_option_card_years( $selected = '', $number = 16 ) - { - - $now = current_time('timestamp'); - $yy = date('y', $now); - $yyyy = date('Y', $now); - $count = 0; - $options = array(); - - while ( $count <= (int) $number ) { - $count ++; - if ($count > 1 ) { - $yy++; - $yyyy++; - } - $options[ $yy ] = $yyyy; - } - - foreach ( $options as $key => $value ) { - echo ''; - } - - } - - } + $currencies = apply_filters( 'mycred_dropdown_currencies', $currencies, $this->id ); + $currencies = apply_filters( 'mycred_dropdown_currencies_' . $this->id, $currencies ); + + if ( $js != '' ) + $js = ' data-update="' . $js . '"'; + + echo ''; + + } + + /** + * Item Type Dropdown + * @since 0.1 + * @version 1.0 + */ + public function item_types_dropdown( $name = '' ) { + + $types = array( + 'product' => 'Product', + 'service' => 'Service', + 'donation' => 'Donation' + ); + $types = apply_filters( 'mycred_dropdown_item_types', $types ); + + echo ''; + + } + + /** + * Countries Dropdown Options + * @since 0.1 + * @version 1.0 + */ + public function list_option_countries( $selected = '' ) { + + $countries = array ( + "US" => "UNITED STATES", + "AF" => "AFGHANISTAN", + "AL" => "ALBANIA", + "DZ" => "ALGERIA", + "AS" => "AMERICAN SAMOA", + "AD" => "ANDORRA", + "AO" => "ANGOLA", + "AI" => "ANGUILLA", + "AQ" => "ANTARCTICA", + "AG" => "ANTIGUA AND BARBUDA", + "AR" => "ARGENTINA", + "AM" => "ARMENIA", + "AW" => "ARUBA", + "AU" => "AUSTRALIA", + "AT" => "AUSTRIA", + "AZ" => "AZERBAIJAN", + "BS" => "BAHAMAS", + "BH" => "BAHRAIN", + "BD" => "BANGLADESH", + "BB" => "BARBADOS", + "BY" => "BELARUS", + "BE" => "BELGIUM", + "BZ" => "BELIZE", + "BJ" => "BENIN", + "BM" => "BERMUDA", + "BT" => "BHUTAN", + "BO" => "BOLIVIA", + "BA" => "BOSNIA AND HERZEGOVINA", + "BW" => "BOTSWANA", + "BV" => "BOUVET ISLAND", + "BR" => "BRAZIL", + "IO" => "BRITISH INDIAN OCEAN TERRITORY", + "BN" => "BRUNEI DARUSSALAM", + "BG" => "BULGARIA", + "BF" => "BURKINA FASO", + "BI" => "BURUNDI", + "KH" => "CAMBODIA", + "CM" => "CAMEROON", + "CA" => "CANADA", + "CV" => "CAPE VERDE", + "KY" => "CAYMAN ISLANDS", + "CF" => "CENTRAL AFRICAN REPUBLIC", + "TD" => "CHAD", + "CL" => "CHILE", + "CN" => "CHINA", + "CX" => "CHRISTMAS ISLAND", + "CC" => "COCOS (KEELING) ISLANDS", + "CO" => "COLOMBIA", + "KM" => "COMOROS", + "CG" => "CONGO", + "CD" => "CONGO, THE DEMOCRATIC REPUBLIC OF THE", + "CK" => "COOK ISLANDS", + "CR" => "COSTA RICA", + "CI" => "COTE D'IVOIRE", + "HR" => "CROATIA", + "CU" => "CUBA", + "CY" => "CYPRUS", + "CZ" => "CZECH REPUBLIC", + "DK" => "DENMARK", + "DJ" => "DJIBOUTI", + "DM" => "DOMINICA", + "DO" => "DOMINICAN REPUBLIC", + "EC" => "ECUADOR", + "EG" => "EGYPT", + "SV" => "EL SALVADOR", + "GQ" => "EQUATORIAL GUINEA", + "ER" => "ERITREA", + "EE" => "ESTONIA", + "ET" => "ETHIOPIA", + "FK" => "FALKLAND ISLANDS (MALVINAS)", + "FO" => "FAROE ISLANDS", + "FJ" => "FIJI", + "FI" => "FINLAND", + "FR" => "FRANCE", + "GF" => "FRENCH GUIANA", + "PF" => "FRENCH POLYNESIA", + "TF" => "FRENCH SOUTHERN TERRITORIES", + "GA" => "GABON", + "GM" => "GAMBIA", + "GE" => "GEORGIA", + "DE" => "GERMANY", + "GH" => "GHANA", + "GI" => "GIBRALTAR", + "GR" => "GREECE", + "GL" => "GREENLAND", + "GD" => "GRENADA", + "GP" => "GUADELOUPE", + "GU" => "GUAM", + "GT" => "GUATEMALA", + "GN" => "GUINEA", + "GW" => "GUINEA-BISSAU", + "GY" => "GUYANA", + "HT" => "HAITI", + "HM" => "HEARD ISLAND AND MCDONALD ISLANDS", + "VA" => "HOLY SEE (VATICAN CITY STATE)", + "HN" => "HONDURAS", + "HK" => "HONG KONG", + "HU" => "HUNGARY", + "IS" => "ICELAND", + "IN" => "INDIA", + "ID" => "INDONESIA", + "IR" => "IRAN, ISLAMIC REPUBLIC OF", + "IQ" => "IRAQ", + "IE" => "IRELAND", + "IL" => "ISRAEL", + "IT" => "ITALY", + "JM" => "JAMAICA", + "JP" => "JAPAN", + "JO" => "JORDAN", + "KZ" => "KAZAKHSTAN", + "KE" => "KENYA", + "KI" => "KIRIBATI", + "KP" => "KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF", + "KR" => "KOREA, REPUBLIC OF", + "KW" => "KUWAIT", + "KG" => "KYRGYZSTAN", + "LA" => "LAO PEOPLE'S DEMOCRATIC REPUBLIC", + "LV" => "LATVIA", + "LB" => "LEBANON", + "LS" => "LESOTHO", + "LR" => "LIBERIA", + "LY" => "LIBYAN ARAB JAMAHIRIYA", + "LI" => "LIECHTENSTEIN", + "LT" => "LITHUANIA", + "LU" => "LUXEMBOURG", + "MO" => "MACAO", + "MK" => "MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF", + "MG" => "MADAGASCAR", + "MW" => "MALAWI", + "MY" => "MALAYSIA", + "MV" => "MALDIVES", + "ML" => "MALI", + "MT" => "MALTA", + "MH" => "MARSHALL ISLANDS", + "MQ" => "MARTINIQUE", + "MR" => "MAURITANIA", + "MU" => "MAURITIUS", + "YT" => "MAYOTTE", + "MX" => "MEXICO", + "FM" => "MICRONESIA, FEDERATED STATES OF", + "MD" => "MOLDOVA, REPUBLIC OF", + "MC" => "MONACO", + "MN" => "MONGOLIA", + "MS" => "MONTSERRAT", + "MA" => "MOROCCO", + "MZ" => "MOZAMBIQUE", + "MM" => "MYANMAR", + "NA" => "NAMIBIA", + "NR" => "NAURU", + "NP" => "NEPAL", + "NL" => "NETHERLANDS", + "AN" => "NETHERLANDS ANTILLES", + "NC" => "NEW CALEDONIA", + "NZ" => "NEW ZEALAND", + "NI" => "NICARAGUA", + "NE" => "NIGER", + "NG" => "NIGERIA", + "NU" => "NIUE", + "NF" => "NORFOLK ISLAND", + "MP" => "NORTHERN MARIANA ISLANDS", + "NO" => "NORWAY", + "OM" => "OMAN", + "PK" => "PAKISTAN", + "PW" => "PALAU", + "PS" => "PALESTINIAN TERRITORY, OCCUPIED", + "PA" => "PANAMA", + "PG" => "PAPUA NEW GUINEA", + "PY" => "PARAGUAY", + "PE" => "PERU", + "PH" => "PHILIPPINES", + "PN" => "PITCAIRN", + "PL" => "POLAND", + "PT" => "PORTUGAL", + "PR" => "PUERTO RICO", + "QA" => "QATAR", + "RE" => "REUNION", + "RO" => "ROMANIA", + "RU" => "RUSSIAN FEDERATION", + "RW" => "RWANDA", + "SH" => "SAINT HELENA", + "KN" => "SAINT KITTS AND NEVIS", + "LC" => "SAINT LUCIA", + "PM" => "SAINT PIERRE AND MIQUELON", + "VC" => "SAINT VINCENT AND THE GRENADINES", + "WS" => "SAMOA", + "SM" => "SAN MARINO", + "ST" => "SAO TOME AND PRINCIPE", + "SA" => "SAUDI ARABIA", + "SN" => "SENEGAL", + "CS" => "SERBIA AND MONTENEGRO", + "SC" => "SEYCHELLES", + "SL" => "SIERRA LEONE", + "SG" => "SINGAPORE", + "SK" => "SLOVAKIA", + "SI" => "SLOVENIA", + "SB" => "SOLOMON ISLANDS", + "SO" => "SOMALIA", + "ZA" => "SOUTH AFRICA", + "GS" => "SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS", + "ES" => "SPAIN", + "LK" => "SRI LANKA", + "SD" => "SUDAN", + "SR" => "SURINAME", + "SJ" => "SVALBARD AND JAN MAYEN", + "SZ" => "SWAZILAND", + "SE" => "SWEDEN", + "CH" => "SWITZERLAND", + "SY" => "SYRIAN ARAB REPUBLIC", + "TW" => "TAIWAN, PROVINCE OF CHINA", + "TJ" => "TAJIKISTAN", + "TZ" => "TANZANIA, UNITED REPUBLIC OF", + "TH" => "THAILAND", + "TL" => "TIMOR-LESTE", + "TG" => "TOGO", + "TK" => "TOKELAU", + "TO" => "TONGA", + "TT" => "TRINIDAD AND TOBAGO", + "TN" => "TUNISIA", + "TR" => "TURKEY", + "TM" => "TURKMENISTAN", + "TC" => "TURKS AND CAICOS ISLANDS", + "TV" => "TUVALU", + "UG" => "UGANDA", + "UA" => "UKRAINE", + "AE" => "UNITED ARAB EMIRATES", + "GB" => "UNITED KINGDOM", + "US" => "UNITED STATES", + "UM" => "UNITED STATES MINOR OUTLYING ISLANDS", + "UY" => "URUGUAY", + "UZ" => "UZBEKISTAN", + "VU" => "VANUATU", + "VE" => "VENEZUELA", + "VN" => "VIET NAM", + "VG" => "VIRGIN ISLANDS, BRITISH", + "VI" => "VIRGIN ISLANDS, U.S.", + "WF" => "WALLIS AND FUTUNA", + "EH" => "WESTERN SAHARA", + "YE" => "YEMEN", + "ZM" => "ZAMBIA", + "ZW" => "ZIMBABWE" + ); + $countries = apply_filters( 'mycred_list_option_countries', $countries ); + + foreach ( $countries as $code => $cname ) { + echo ''; + } + + } + + /** + * US States Dropdown Options + * @since 0.1 + * @version 1.0 + */ + public function list_option_us_states( $selected = '', $non_us = false ) { + + $states = array ( + "AL" => "Alabama", + "AK" => "Alaska", + "AZ" => "Arizona", + "AR" => "Arkansas", + "CA" => "California", + "CO" => "Colorado", + "CT" => "Connecticut", + "DC" => "D.C.", + "DE" => "Delaware", + "FL" => "Florida", + "GA" => "Georgia", + "HI" => "Hawaii", + "ID" => "Idaho", + "IL" => "Illinois", + "IN" => "Indiana", + "IA" => "Iowa", + "KS" => "Kansas", + "KY" => "Kentucky", + "LA" => "Louisiana", + "ME" => "Maine", + "MD" => "Maryland", + "MA" => "Massachusetts", + "MI" => "Michigan", + "MN" => "Minnesota", + "MS" => "Mississippi", + "MO" => "Missouri", + "MT" => "Montana", + "NE" => "Nebraska", + "NV" => "Nevada", + "NH" => "New Hampshire", + "NJ" => "New Jersey", + "NM" => "New Mexico", + "NY" => "New York", + "NC" => "North Carolina", + "ND" => "North Dakota", + "OH" => "Ohio", + "OK" => "Oklahoma", + "OR" => "Oregon", + "PA" => "Pennsylvania", + "RI" => "Rhode Island", + "SC" => "South Carolina", + "SD" => "South Dakota", + "TN" => "Tennessee", + "TX" => "Texas", + "UT" => "Utah", + "VT" => "Vermont", + "VA" => "Virginia", + "WA" => "Washington", + "WV" => "West Virginia", + "WI" => "Wisconsin", + "WY" => "Wyoming" + ); + $states = apply_filters( 'mycred_list_option_us', $states ); + + $outside = 'Outside US'; + if ( $non_us == 'top' ) echo ''; + foreach ( $states as $code => $cname ) { + echo ''; + } + if ( $non_us == 'bottom' ) echo ''; + + } + + /** + * Months Dropdown Options + * @since 0.1 + * @version 1.0 + */ + public function list_option_months( $selected = '' ) { + + $months = array ( + "01" => __( 'January', 'mycred' ), + "02" => __( 'February', 'mycred' ), + "03" => __( 'March', 'mycred' ), + "04" => __( 'April', 'mycred' ), + "05" => __( 'May', 'mycred' ), + "06" => __( 'June', 'mycred' ), + "07" => __( 'July', 'mycred' ), + "08" => __( 'August', 'mycred' ), + "09" => __( 'September', 'mycred' ), + "10" => __( 'October', 'mycred' ), + "11" => __( 'November', 'mycred' ), + "12" => __( 'December', 'mycred' ) + ); + + foreach ( $months as $number => $text ) { + echo ''; + } + + } + + /** + * Years Dropdown Options + * @since 0.1 + * @version 1.0 + */ + public function list_option_card_years( $selected = '', $number = 16 ) { + + $now = current_time( 'timestamp' ); + $yy = date( 'y', $now ); + $yyyy = date( 'Y', $now ); + $count = 0; + $options = array(); + + while ( $count <= (int) $number ) { + $count ++; + if ( $count > 1 ) { + $yy++; + $yyyy++; + } + $options[ $yy ] = $yyyy; + } + + foreach ( $options as $key => $value ) { + echo ''; + } + + } + + } endif; diff --git a/addons/cash-creds/abstracts/index.php b/addons/cash-creds/abstracts/index.php index 1580272..4e6c07c 100644 --- a/addons/cash-creds/abstracts/index.php +++ b/addons/cash-creds/abstracts/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/cash-creds/assets/css/admin-style.css b/addons/cash-creds/assets/css/admin-style.css index 8bafce9..5b2498d 100644 --- a/addons/cash-creds/assets/css/admin-style.css +++ b/addons/cash-creds/assets/css/admin-style.css @@ -1,88 +1,88 @@ .type-cashcred_withdrawal .cashcred_Approved{ - background-color: #008505; - padding: 5px; - border: 1px solid #008906; - color: white; - border-radius: 5px; + background-color: #008505; + padding: 5px; + border: 1px solid #008906; + color: white; + border-radius: 5px; } .type-cashcred_withdrawal .cashcred_Pending{ - background-color: #f6cb4a; - padding: 5px; - border: 1px solid #cc9900; - color: white; - border-radius: 5px; + background-color: #f6cb4a; + padding: 5px; + border: 1px solid #cc9900; + color: white; + border-radius: 5px; } .type-cashcred_withdrawal .cashcred_Cancelled{ - background-color: #bd2419; - padding: 5px; - border: 1px solid #a70b00; - color: white; - border-radius: 5px; + background-color: #bd2419; + padding: 5px; + border: 1px solid #a70b00; + color: white; + border-radius: 5px; } .cashcred_bages { - margin-top: 10px; + margin-top: 10px; } .history li { - padding: 6px; - background-color: #f7f7f7; - border: 1px solid #c9c9c9; - border-radius: 10px; - -webkit-box-shadow: 0px 1px 1px 0px rgba(0,0,0,0.35); - -moz-box-shadow: 0px 1px 1px 0px rgba(0,0,0,0.35); - box-shadow: 0px 1px 1px 0px rgba(0,0,0,0.35); + padding: 6px; + background-color: #f7f7f7; + border: 1px solid #c9c9c9; + border-radius: 10px; + -webkit-box-shadow: 0px 1px 1px 0px rgba(0,0,0,0.35); + -moz-box-shadow: 0px 1px 1px 0px rgba(0,0,0,0.35); + box-shadow: 0px 1px 1px 0px rgba(0,0,0,0.35); } #cashcred-comments .history li time { - font-weight: 600; + font-weight: 600; } .readonly_fields[readonly]{ - opacity: 0.6; + opacity: 0.6; } #cashcred-comments .history p { - border-top: 1px solid silver; - margin-top: 5px; - background-color: #e7e7e7; - padding: 7px; - border-radius: 6px; + border-top: 1px solid silver; + margin-top: 5px; + background-color: #e7e7e7; + padding: 7px; + border-radius: 6px; } #cashcred-developer-log pre { - white-space: pre-wrap; - white-space: -moz-pre-wrap; - white-space: -pre-wrap; - white-space: -o-pre-wrap; - word-wrap: break-word; - background-color: #e6e6e6; - padding: 10px; - border: solid 1px #c8c8c8; - border-radius: 5px; + white-space: pre-wrap; + white-space: -moz-pre-wrap; + white-space: -pre-wrap; + white-space: -o-pre-wrap; + word-wrap: break-word; + background-color: #e6e6e6; + padding: 10px; + border: solid 1px #c8c8c8; + border-radius: 5px; } #payment_gateway_detail input.form-control { - width: 100%; + width: 100%; } #payment_gateway_detail .inside{ padding: 4px;} .cashcred_panel { - background-color: #e6e6e6; - padding: 10px; - border: 1px solid #c9c9c9; - margin-bottom: 5px; + background-color: #e6e6e6; + padding: 10px; + border: 1px solid #c9c9c9; + margin-bottom: 5px; } #cashcred_withdrawal_request .row select ,#cashcred_withdrawal_request .row input{ - width: 100%; + width: 100%; } #cashcred-payment-status .spinner { - display:none; + display:none; } #cashcred-payment-status .spinner.is-active { - display:block; - float: left; - position: absolute; - left: 10px; + display:block; + float: left; + position: absolute; + left: 10px; } #payment_response{ display:none; diff --git a/addons/cash-creds/assets/css/index.php b/addons/cash-creds/assets/css/index.php index 1580272..4e6c07c 100644 --- a/addons/cash-creds/assets/css/index.php +++ b/addons/cash-creds/assets/css/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/cash-creds/assets/css/withdraw.css b/addons/cash-creds/assets/css/withdraw.css index 907c9f2..5f9a35a 100644 --- a/addons/cash-creds/assets/css/withdraw.css +++ b/addons/cash-creds/assets/css/withdraw.css @@ -1,17 +1,17 @@ #cashcred { - width: 100%; + width: 100%; } #cashcred * { - box-sizing: border-box; + box-sizing: border-box; } #cashcred ul.cashcred-nav-tabs li { - display: inline-block; - padding: 10px; - position: relative; - border: 1px solid #e9e9e9; - margin-right: 5px; + display: inline-block; + padding: 10px; + position: relative; + border: 1px solid #e9e9e9; + margin-right: 5px; margin-bottom: 5px; } @@ -27,12 +27,12 @@ } #cashcred #cashcred_tab_content .cashcred-tab { - border: 1px solid #e9e9e9; - padding: 5px; - width: 100%; - margin-top: 5px; - padding-right: 10px; - padding-left: 10px; + border: 1px solid #e9e9e9; + padding: 5px; + width: 100%; + margin-top: 5px; + padding-right: 10px; + padding-left: 10px; } #cashcred .form-group label { @@ -53,8 +53,8 @@ } #cashcred input[type=submit] { - margin-top: 10px; - margin-bottom: 5px; + margin-top: 10px; + margin-bottom: 5px; } #cashcred input[type=submit]:hover { @@ -62,35 +62,35 @@ } #cashcred select { - cursor: pointer; + cursor: pointer; } #cashcred_total{ - text-align: right; - margin-top: 15px; - margin-bottom: 15px; - border-bottom: 3px double #cccccc; - border-top: 3px double #cccccc; - padding: 10px; - min-width: 140px; - float: right; + text-align: right; + margin-top: 15px; + margin-bottom: 15px; + border-bottom: 3px double #cccccc; + border-top: 3px double #cccccc; + padding: 10px; + min-width: 140px; + float: right; } div#submit_button, .amount_label{ - float: left; + float: left; } .cashcred-tab{ - display:none; + display:none; } .cashcred-min { - font-style: italic; + font-style: italic; } .cashcred_gateway_notice { - display: none; - color: red; + display: none; + color: red; font-size: smaller; } diff --git a/addons/cash-creds/assets/images/index.php b/addons/cash-creds/assets/images/index.php index 1580272..4e6c07c 100644 --- a/addons/cash-creds/assets/images/index.php +++ b/addons/cash-creds/assets/images/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/cash-creds/assets/index.php b/addons/cash-creds/assets/index.php index 1580272..4e6c07c 100644 --- a/addons/cash-creds/assets/index.php +++ b/addons/cash-creds/assets/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/cash-creds/assets/js/index.php b/addons/cash-creds/assets/js/index.php index 1580272..4e6c07c 100644 --- a/addons/cash-creds/assets/js/index.php +++ b/addons/cash-creds/assets/js/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/cash-creds/assets/js/withdraw.js b/addons/cash-creds/assets/js/withdraw.js index 849cf11..1318c3e 100644 --- a/addons/cash-creds/assets/js/withdraw.js +++ b/addons/cash-creds/assets/js/withdraw.js @@ -1,212 +1,189 @@ /** * CashCred Withdraw - * - * @since 2.0 + * @since 2.0 * @version 1.0 */ -jQuery( - function ($) { - - $(document).ready( - function () { - - - - if ($("#cashcred_pay_method").length ) { - exchange_calculation(); - display_cashcred_gateway_notice(); - } - - $("#cashcred_point_type").change( - function () { - exchange_calculation(); - } - ); - - $("#cashcred_pay_method").change( - function () { - exchange_calculation(); - display_cashcred_gateway_notice(); - } - ); - - $('.mycred-cashcred-form').on( - 'keyup change', '#withdraw_points', function ( e ) { +jQuery(function($){ + + $(document).ready(function() { + + + + if ( $( "#cashcred_pay_method" ).length ) { + exchange_calculation(); + display_cashcred_gateway_notice(); + } + + $( "#cashcred_point_type" ).change(function() { + exchange_calculation(); + }); + + $( "#cashcred_pay_method" ).change(function() { + exchange_calculation(); + display_cashcred_gateway_notice(); + }); + + $( '.mycred-cashcred-form' ).on( 'keyup change', '#withdraw_points', function( e ){ - exchange_calculation(); - - } - ); - - - $('body').on( - 'submit', '.mycred-cashcred-form', function ( e ) { - - - - withdraw_points = $("#withdraw_points").val(); - if(parseFloat(withdraw_points) <= 0 ) { - e.preventDefault(); - } - } - ); - - $('.cashcred-nav-tabs li').click( - function () { - var id = $(this).attr('id'); - $('.cashcred-nav-tabs li').removeClass('active'); - $('.cashcred-tab').hide(); - $(this).addClass('active'); - $('#'+ id + 'c').show(); - } - ); - - $('.cashcred-tab').hide(); - $('#tab1c').show(); - - var elementType = $('#cashcred_save_settings').prop('nodeName'); - - if (elementType != 'INPUT' ) { - first_tab_active = $("#cashcred_save_settings option:first").val(); - $('.cashcred_panel').hide(); - $('#panel_'+first_tab_active).show(); - } - - $("select#cashcred_save_settings").change( - function () { - id = $(this).val(); - $('.cashcred_panel').hide(); - $('#panel_'+id).show(); - } - ); - - } - ); - - function exchange_calculation() - { - - cashcred_point_type = $("#cashcred_point_type").val(); - cashcred_pay_method = $("#cashcred_pay_method").val(); - withdraw_points = $("#withdraw_points").val(); - cashcred_fee = cashcred_fee_setting(cashcred_point_type, withdraw_points); - currency_code = cashcred.exchange[cashcred_pay_method].currency; - conversion_rate = cashcred.exchange[cashcred_pay_method].point_type[cashcred_point_type]; - - if ( typeof conversion_rate === 'undefined' ) { - conversion_rate = 1; - } - - min = cashcred.exchange[cashcred_pay_method].min; - max = cashcred.exchange[cashcred_pay_method].max - - amount = withdraw_points * conversion_rate; - - $("#withdraw_points").attr({"max" : max , "min" : min }); - - $('.cashcred-min span').html(min); - - $("#cashcred_currency_symbol").html(currency_code); - $("#cashcred_total_amount").html(amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')); - - } - - function display_cashcred_gateway_notice() - { - - if (cashcred.gateway_notices[ $('#cashcred_pay_method').val() ] ) { - - $('.cashcred_gateway_notice').show(); - - } - else { - - $('.cashcred_gateway_notice').hide(); - - } - - } - - function cashcred_fee_setting( point_type, withdraw_points ) - { - - if (cashcred_data.cashcred_setting.use == 1 ) { - var fee = 0; - var ctype = cashcred_data.cashcred_setting.types[point_type]; - var by = cashcred_data.cashcred_setting.types[point_type].by; - var fee_amount = cashcred_data.cashcred_setting.types[point_type].amount; - var max_cap = cashcred_data.cashcred_setting.types[point_type].max_cap; - var min_cap = cashcred_data.cashcred_setting.types[point_type].min_cap; - var presentation = cashcred_data.cashcred_setting.types[point_type].presentation; - - //formats - decimals = cashcred_data.format[point_type].decimals; - decimal_sep = cashcred_data.format[point_type].separators.decimal; - thousand_sep = cashcred_data.format[point_type].separators.thousand; - if(withdraw_points > 0 ) { - fee = fee_amount; - if(by == 'percent' ) { - fee = ( ( fee_amount / 100 ) * withdraw_points ); - fee_amount = fee_amount + '%'; - } - - if(min_cap != 0 ) { - fee = ( parseInt(fee) + parseInt(min_cap) ); - } - - - if (max_cap != 0 && fee > max_cap ) { - fee = max_cap; - } - - presentation = presentation.replace("%fee%", fee_amount); - presentation = presentation.replace("%min%", min_cap); - presentation = presentation.replace("%max%", max_cap); - presentation = presentation.replace("%total%", mycred_number_format(fee, decimals, decimal_sep, thousand_sep)); - - $('.cashcred-fee').show(); - $('.cashcred-fee span').html(presentation); - } - - } - else { - - $('.cashcred-fee').hide(); - - } - } - - function mycred_number_format( number, decimals, dec_point, thousands_sep ) - { - - // Strip all characters but numerical ones. - number = (number + '').replace(/[^0-9+\-Ee.]/g, ''); - var n = !isFinite(+number) ? 0 : +number, - prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), - sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, - dec = (typeof dec_point === 'undefined') ? '.' : dec_point, - s = '', - toFixedFix = function (n, prec) { - var k = Math.pow(10, prec); - return '' + Math.round(n * k) / k; - }; - - // Fix for IE parseFloat(0.55).toFixed(0) = 0; - s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.'); - if (s[0].length > 3) { - s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep); - } - if ((s[1] || '').length < prec) { - s[1] = s[1] || ''; - s[1] += new Array(prec - s[1].length + 1).join('0'); - } - - return s.join(dec); - } - - - } -); + exchange_calculation(); + + }); + + + $( 'body' ).on( 'submit', '.mycred-cashcred-form', function( e ){ + + + + withdraw_points = $( "#withdraw_points" ).val(); + if( parseFloat( withdraw_points ) <= 0 ) { + e.preventDefault(); + } + }); + + $('.cashcred-nav-tabs li').click( function(){ + var id = $(this).attr('id'); + $('.cashcred-nav-tabs li').removeClass('active'); + $('.cashcred-tab').hide(); + $(this).addClass('active'); + $('#'+ id + 'c').show(); + }); + + $('.cashcred-tab').hide(); + $('#tab1c').show(); + + var elementType = $('#cashcred_save_settings').prop('nodeName'); + + if ( elementType != 'INPUT' ) { + first_tab_active = $("#cashcred_save_settings option:first").val(); + $('.cashcred_panel').hide(); + $('#panel_'+first_tab_active).show(); + } + + $("select#cashcred_save_settings").change( function(){ + id = $(this).val(); + $('.cashcred_panel').hide(); + $('#panel_'+id).show(); + }); + + }); + + function exchange_calculation(){ + + cashcred_point_type = $( "#cashcred_point_type" ).val(); + cashcred_pay_method = $( "#cashcred_pay_method" ).val(); + withdraw_points = $( "#withdraw_points" ).val(); + cashcred_fee = cashcred_fee_setting( cashcred_point_type, withdraw_points ); + currency_code = cashcred.exchange[cashcred_pay_method].currency; + conversion_rate = cashcred.exchange[cashcred_pay_method].point_type[cashcred_point_type]; + + if ( typeof conversion_rate === 'undefined' ) { + conversion_rate = 1; + } + + min = cashcred.exchange[cashcred_pay_method].min; + max = cashcred.exchange[cashcred_pay_method].max + + amount = withdraw_points * conversion_rate; + + $( "#withdraw_points" ).attr({"max" : max , "min" : min }); + + $( '.cashcred-min span' ).html( min ); + + $( "#cashcred_currency_symbol" ).html(currency_code); + $( "#cashcred_total_amount" ).html(amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')); + + } + + function display_cashcred_gateway_notice() { + + if ( cashcred.gateway_notices[ $('#cashcred_pay_method').val() ] ) { + + $('.cashcred_gateway_notice').show(); + + } + else { + + $('.cashcred_gateway_notice').hide(); + + } + + } + + function cashcred_fee_setting( point_type, withdraw_points ) { + + if ( cashcred_data.cashcred_setting.use == 1 ) { + var fee = 0; + var ctype = cashcred_data.cashcred_setting.types[point_type]; + var by = cashcred_data.cashcred_setting.types[point_type].by; + var fee_amount = cashcred_data.cashcred_setting.types[point_type].amount; + var max_cap = cashcred_data.cashcred_setting.types[point_type].max_cap; + var min_cap = cashcred_data.cashcred_setting.types[point_type].min_cap; + var presentation = cashcred_data.cashcred_setting.types[point_type].presentation; + + //formats + decimals = cashcred_data.format[point_type].decimals; + decimal_sep = cashcred_data.format[point_type].separators.decimal; + thousand_sep = cashcred_data.format[point_type].separators.thousand; + if( withdraw_points > 0 ) { + fee = fee_amount; + if( by == 'percent' ){ + fee = ( ( fee_amount / 100 ) * withdraw_points ); + fee_amount = fee_amount + '%'; + } + + if( min_cap != 0 ) + fee = ( parseInt(fee) + parseInt(min_cap) ); + + + if ( max_cap != 0 && fee > max_cap ) + fee = max_cap; + + presentation = presentation.replace( "%fee%", fee_amount ); + presentation = presentation.replace( "%min%", min_cap ); + presentation = presentation.replace( "%max%", max_cap ); + presentation = presentation.replace( "%total%", mycred_number_format( fee, decimals, decimal_sep, thousand_sep ) ); + + $('.cashcred-fee').show(); + $( '.cashcred-fee span' ).html( presentation ); + } + + } + else { + + $('.cashcred-fee').hide(); + + } + } + + function mycred_number_format ( number, decimals, dec_point, thousands_sep ) { + + // Strip all characters but numerical ones. + number = (number + '').replace(/[^0-9+\-Ee.]/g, ''); + var n = !isFinite(+number) ? 0 : +number, + prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), + sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, + dec = (typeof dec_point === 'undefined') ? '.' : dec_point, + s = '', + toFixedFix = function (n, prec) { + var k = Math.pow(10, prec); + return '' + Math.round(n * k) / k; + }; + + // Fix for IE parseFloat(0.55).toFixed(0) = 0; + s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.'); + if (s[0].length > 3) { + s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep); + } + if ((s[1] || '').length < prec) { + s[1] = s[1] || ''; + s[1] += new Array(prec - s[1].length + 1).join('0'); + } + + return s.join(dec) ; + } + + +}); diff --git a/addons/cash-creds/gateways/bank-transfer.php b/addons/cash-creds/gateways/bank-transfer.php index cee9d88..bba9f0e 100644 --- a/addons/cash-creds/gateways/bank-transfer.php +++ b/addons/cash-creds/gateways/bank-transfer.php @@ -1,330 +1,306 @@ $label ) { $default_exchange[ $type ] = 1; - } - - parent::__construct( - array( - 'id' => 'bank', - 'label' => 'Bank Transfer', - 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/bank-transfers/', - 'gateway_logo_url' => '', - 'defaults' => array( - 'enable_additional_notes' => '', - 'additional_notes' => '', - 'minimum_amount' => '', - 'maximum_amount' => '', - 'currency' => 'EUR', - 'exchange' => $default_exchange - ) - ), $gateway_prefs - ); - - } - - /** - * Process Handler - * - * @since 1.0 - * @version 1.0 - */ - public function process( $post = false ) - { - - $time = current_time('mysql'); - - update_post_meta($post, 'cashcred_payment_transfer_date', $time); - - return array ( - 'status' => true , - 'message' => 'Amount transfer successfully to your bank account', - 'date' => $time - ); +if ( ! class_exists( 'myCRED_cashcred_Bank_Transfer' ) ) : + class myCRED_cashcred_Bank_Transfer extends myCRED_Cash_Payment_Gateway { + + /** + * Construct + */ + public function __construct( $gateway_prefs ) { + + $types = mycred_get_types(); + + $default_exchange = array(); + + foreach ( $types as $type => $label ) $default_exchange[ $type ] = 1; + + parent::__construct( array( + 'id' => 'bank', + 'label' => 'Bank Transfer', + 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/bank-transfers/', + 'gateway_logo_url' => '', + 'defaults' => array( + 'enable_additional_notes' => '', + 'additional_notes' => '', + 'minimum_amount' => '', + 'maximum_amount' => '', + 'currency' => 'EUR', + 'exchange' => $default_exchange + ) + ), $gateway_prefs ); + + } + + /** + * Process Handler + * @since 1.0 + * @version 1.0 + */ + public function process( $post = false ) { + + $time = current_time( 'mysql' ); + + update_post_meta( $post, 'cashcred_payment_transfer_date', $time ); + + return array ( + 'status' => true , + 'message' => 'Amount transfer successfully to your bank account', + 'date' => $time + ); - } - - /** - * Results Handler - * - * @since 1.0 - * @version 1.0 - */ - public function returning() - { - - add_filter('mycred_setup_gateways', array( $this, 'relable_gateway' )); - - } - - /** - * Admin Init Handler - * - * @since 1.7 - * @version 1.0 - */ - public function admin_init() - { - - add_filter('mycred_setup_gateways', array( $this, 'relable_gateway' )); - - } - - /** - * Results Handler - * - * @since 1.7.6 - * @version 1.0 - */ - public function relable_gateway( $installed ) - { - - if (! empty($this->prefs['title']) && $this->prefs['title'] != $installed['bank']['title'] ) { - $installed['bank']['title'] = $this->prefs['title']; - } - - return $installed; - - } - - - /** - * Preferences - * - * @since 1.0 - * @version 1.0 - */ - public function preferences() - { - - $prefs = $this->prefs; - ?> + } + + /** + * Results Handler + * @since 1.0 + * @version 1.0 + */ + public function returning() { + + add_filter( 'mycred_setup_gateways', array( $this, 'relable_gateway' ) ); + + } + + /** + * Admin Init Handler + * @since 1.7 + * @version 1.0 + */ + public function admin_init() { + + add_filter( 'mycred_setup_gateways', array( $this, 'relable_gateway' ) ); + + } + + /** + * Results Handler + * @since 1.7.6 + * @version 1.0 + */ + public function relable_gateway( $installed ) { + + if ( ! empty( $this->prefs['title'] ) && $this->prefs['title'] != $installed['bank']['title'] ) + $installed['bank']['title'] = $this->prefs['title']; + + return $installed; + + } + + + /** + * Preferences + * @since 1.0 + * @version 1.0 + */ + public function preferences() { + + $prefs = $this->prefs; +?>
    -
    -

    - -
    - - -
    - -
    - - -
    - -
    - -
    - -
    -
    -

    - -
    - - -
    - -
    - - - exchange_rate_setup(); ?> - -
    - -
    +
    +

    + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    +
    +

    + +
    + + +
    + +
    + + + exchange_rate_setup(); ?> + +
    + +
    -
    -
    - - $this->field_name('additional_notes'), 'textarea_rows' => 10 )); ?> -
    -
    +
    +
    + + $this->field_name( 'additional_notes' ), 'textarea_rows' => 10 ) ); ?> +
    +
    - form_fields(); - - $bank_form = new CashCred_Gateway_Fields($data, $fields); - - ?> -
    - -

    - - -
    -

    -
    - - - generate_form(); ?> - -
    - - array( - 'type' => 'text', - 'lable' => 'Account name', - 'classes' => 'form-control', - 'placeholder' => 'Account name', - ), - 'ac_number' => array( - 'type' => 'text', - 'lable' => 'Account number', - 'classes' => 'form-control', - 'placeholder' => 'Account number', - ), - 'ac_code' => array( - 'type' => 'text', - 'lable' => 'Sort code', - 'classes' => 'form-control', - 'placeholder' => 'Sort code', - ), - 'ba_name' => array( - 'type' => 'text', - 'lable' => 'Bank name', - 'classes' => 'form-control', - 'placeholder' => 'Bank name', - ), - 'ro_number' => array( - 'type' => 'text', - 'lable' => 'Routing number', - 'classes' => 'form-control', - 'placeholder' => 'Routing number', - ), - 'ib_name' => array( - 'type' => 'text', - 'lable' => 'IBAN', - 'classes' => 'form-control', - 'placeholder' => 'IBAN', - ), - 'sw_code' => array( - 'type' => 'text', - 'lable' => 'Swift code', - 'classes' => 'form-control', - 'placeholder' => 'Swift code', - ) - ); - - return apply_filters('mycred_cashcred_bank_transfer_fields', $gateway_fields); - - } - - - /** - * Sanatize Prefs - * - * @since 1.0 - * @version 1.0 - */ - public function sanitise_preferences( $data ) - { - - $new_data = array(); - - $new_data['additional_notes'] = sanitize_text_field($data['additional_notes']); - - if(isset($data['enable_additional_notes']) ) { - - $new_data['enable_additional_notes'] = sanitize_text_field($data['enable_additional_notes']); - - } - $new_data['minimum_amount'] = sanitize_text_field($data['minimum_amount']); - $new_data['maximum_amount'] = sanitize_text_field($data['maximum_amount']); - $new_data['additional_notes'] = wp_kses_post($data['additional_notes']); - $new_data['currency'] = sanitize_text_field($data['currency']); - - // If exchange is less then 1 we must start with a zero - if (isset($data['exchange']) ) { - foreach ( (array) $data['exchange'] as $type => $rate ) { - if ($rate != 1 && in_array(substr($rate, 0, 1), array( '.', ',' )) ) { - $data['exchange'][ $type ] = (float) '0' . $rate; - } - } - } - $new_data['exchange'] = $data['exchange']; - - return $new_data; - - } - - } +form_fields(); + + $bank_form = new CashCred_Gateway_Fields( $data, $fields ); + + ?> +
    + +

    + + +
    +

    +
    + + + generate_form(); ?> + +
    + + array( + 'type' => 'text', + 'lable' => 'Account name', + 'classes' => 'form-control', + 'placeholder' => 'Account name', + ), + 'ac_number' => array( + 'type' => 'text', + 'lable' => 'Account number', + 'classes' => 'form-control', + 'placeholder' => 'Account number', + ), + 'ac_code' => array( + 'type' => 'text', + 'lable' => 'Sort code', + 'classes' => 'form-control', + 'placeholder' => 'Sort code', + ), + 'ba_name' => array( + 'type' => 'text', + 'lable' => 'Bank name', + 'classes' => 'form-control', + 'placeholder' => 'Bank name', + ), + 'ro_number' => array( + 'type' => 'text', + 'lable' => 'Routing number', + 'classes' => 'form-control', + 'placeholder' => 'Routing number', + ), + 'ib_name' => array( + 'type' => 'text', + 'lable' => 'IBAN', + 'classes' => 'form-control', + 'placeholder' => 'IBAN', + ), + 'sw_code' => array( + 'type' => 'text', + 'lable' => 'Swift code', + 'classes' => 'form-control', + 'placeholder' => 'Swift code', + ) + ); + + return apply_filters( 'mycred_cashcred_bank_transfer_fields', $gateway_fields ); + + } + + + /** + * Sanatize Prefs + * @since 1.0 + * @version 1.0 + */ + public function sanitise_preferences( $data ) { + + $new_data = array(); + + $new_data['additional_notes'] = sanitize_text_field( $data['additional_notes'] ); + + if( isset( $data['enable_additional_notes'] ) ) { + + $new_data['enable_additional_notes'] = sanitize_text_field( $data['enable_additional_notes'] ); + + } + $new_data['minimum_amount'] = sanitize_text_field( $data['minimum_amount'] ); + $new_data['maximum_amount'] = sanitize_text_field( $data['maximum_amount'] ); + $new_data['additional_notes'] = wp_kses_post( $data['additional_notes'] ); + $new_data['currency'] = sanitize_text_field( $data['currency'] ); + + // If exchange is less then 1 we must start with a zero + if ( isset( $data['exchange'] ) ) { + foreach ( (array) $data['exchange'] as $type => $rate ) { + if ( $rate != 1 && in_array( substr( $rate, 0, 1 ), array( '.', ',' ) ) ) + $data['exchange'][ $type ] = (float) '0' . $rate; + } + } + $new_data['exchange'] = $data['exchange']; + + return $new_data; + + } + + } endif; diff --git a/addons/cash-creds/gateways/index.php b/addons/cash-creds/gateways/index.php index 1580272..4e6c07c 100644 --- a/addons/cash-creds/gateways/index.php +++ b/addons/cash-creds/gateways/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/cash-creds/includes/cashcred-functions.php b/addons/cash-creds/includes/cashcred-functions.php index dca152b..90f4e42 100644 --- a/addons/cash-creds/includes/cashcred-functions.php +++ b/addons/cash-creds/includes/cashcred-functions.php @@ -1,641 +1,587 @@ __('Bank Transfer', 'mycred'), - 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/bank-transfers/', - 'callback' => array( 'myCRED_cashcred_Bank_Transfer' ), - 'icon' => 'dashicons-admin-generic', - 'sandbox' => false, - 'external' => false, - 'custom_rate' => true - ); + // Bank Transfers + $installed['bank'] = array( + 'title' => __( 'Bank Transfer', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/chapter-iii/buycred/payment-gateways/bank-transfers/', + 'callback' => array( 'myCRED_cashcred_Bank_Transfer' ), + 'icon' => 'dashicons-admin-generic', + 'sandbox' => false, + 'external' => false, + 'custom_rate' => true + ); - return apply_filters('mycred_cashcred_setup_gateways', $installed); + return apply_filters( 'mycred_cashcred_setup_gateways', $installed ); - } + } endif; /** * Get buyCRED Setup - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('cashcred_get_requested_gateway_id') ) : - function cashcred_get_requested_gateway_id() - { +if ( ! function_exists( 'cashcred_get_requested_gateway_id' ) ) : + function cashcred_get_requested_gateway_id() { - $gateway_id = false; - - if (isset($_REQUEST['cashcred_pay_method']) && is_user_logged_in() ) { - $gateway_id = trim($_REQUEST['cashcred_pay_method']); - } + $gateway_id = false; + + if ( isset( $_REQUEST['cashcred_pay_method'] ) && is_user_logged_in() ) + $gateway_id = trim( $_REQUEST['cashcred_pay_method'] ); - return apply_filters('mycred_gateway_id', $gateway_id); + return apply_filters( 'mycred_gateway_id', $gateway_id ); - } + } endif; -if (! function_exists('cashcred_register_fields') ) : - function cashcred_register_fields($type,$name) - { - - return 'cashcred_user_settings['.$type.']['.$name.']'; +if ( ! function_exists( 'cashcred_register_fields' ) ) : + function cashcred_register_fields($type,$name) { + + return 'cashcred_user_settings['.$type.']['.$name.']'; - } + } endif; -if (! function_exists('cashcred_get_user_payment_details') ) : - function cashcred_get_user_payment_details() - { +if ( ! function_exists( 'cashcred_get_user_payment_details' ) ) : + function cashcred_get_user_payment_details() { - $user_id = get_current_user_id(); + $user_id = get_current_user_id(); - if (is_admin() ) { - $post_id = get_the_ID(); - $user_id = check_site_get_post_meta($post_id, 'from', true); - } - return mycred_get_user_meta($user_id, 'cashcred_user_settings', '', true); + if ( is_admin() ) { + $post_id = get_the_ID(); + $user_id = check_site_get_post_meta( $post_id, 'from', true ); + } + return mycred_get_user_meta( $user_id, 'cashcred_user_settings', '', true ); - } + } endif; /** * Display Messages - * - * @since 1.9 + * @since 1.9 * @version 1.0 * * $type = error, success */ -if (! function_exists('cashcred_display_message') ) : - function cashcred_display_message() - { - - $cashcred_notice = mycred_get_user_meta(get_current_user_id(), 'cashcred_notice', '', true); - - if(! empty($cashcred_notice) ) {?> -

    - -

    - +

    + +

    + active) ) { $gateways_list; - } + if ( empty( $cashcred_instance->active ) ) $gateways_list; - if (empty($gateways) ) { + if ( empty( $gateways ) ) { - $gateways_list = $cashcred_instance->active; - - } - else { + $gateways_list = $cashcred_instance->active; + + } + else { - $gateways = explode(',', $gateways); + $gateways = explode( ',', $gateways ); - foreach ( $gateways as $gateway_id ) { + foreach ( $gateways as $gateway_id ) { - if (array_key_exists($gateway_id, $cashcred_instance->active) ) { - $gateways_list[ $gateway_id ] = $cashcred_instance->active[ $gateway_id ]; - } + if ( array_key_exists( $gateway_id, $cashcred_instance->active ) ) + $gateways_list[ $gateway_id ] = $cashcred_instance->active[ $gateway_id ]; - } + } - } + } - return $gateways_list; + return $gateways_list; - } + } endif; /** * Return list of usable Point Types for the given user. * If a $types empty return all point types. - * - * @since 1.9 + * @since 1.9 * @version 1.0 */ -if (! function_exists('cashcred_get_point_types') ) : - function cashcred_get_point_types( $types, $user_id ) - { +if ( ! function_exists( 'cashcred_get_point_types' ) ) : + function cashcred_get_point_types( $types, $user_id ) { - global $mycred_types; + global $mycred_types; - $point_types = array(); + $point_types = array(); - $available_types = array_keys($mycred_types); + $available_types = array_keys( $mycred_types ); - if (! empty($types) ) { - - $types = explode(',', $types); - $available_types = array_intersect($available_types, $types); + if ( ! empty( $types ) ) { + + $types = explode( ',', $types ); + $available_types = array_intersect( $available_types, $types ); - } + } - foreach ( $available_types as $type_id ) { - - $mycred = mycred($type_id); - - if (! $mycred->exclude_user($user_id) ) { - - $point_types[ $type_id ] = $mycred; + foreach ( $available_types as $type_id ) { + + $mycred = mycred( $type_id ); + + if ( ! $mycred->exclude_user( $user_id ) ) { + + $point_types[ $type_id ] = $mycred; - } + } - } + } - return $point_types; + return $point_types; - } + } endif; /** * Return list of Point Types Which user have balance. * If a $types empty return all point types. - * - * @since 1.9 + * @since 1.9 * @version 1.0 */ -if (! function_exists('cashcred_is_user_have_balances') ) : - function cashcred_is_user_have_balances( $point_types, $user_id ) - { +if ( ! function_exists( 'cashcred_is_user_have_balances' ) ) : + function cashcred_is_user_have_balances( $point_types, $user_id ) { - $usable_point_types = array(); + $usable_point_types = array(); - foreach ( $point_types as $point_type ) { - if ($point_type->get_users_balance($user_id) > 0 ) { - $usable_point_types[ $point_type->cred_id ] = $point_type; - } - } + foreach ( $point_types as $point_type ) { + if ( $point_type->get_users_balance( $user_id ) > 0 ) { + $usable_point_types[ $point_type->cred_id ] = $point_type; + } + } - return $usable_point_types; + return $usable_point_types; - } + } endif; /** * Get Withdraw requests. * $status | Pending, Approved, Cancelled - * - * @since 1.9 + * @since 1.9 * @version 1.0 */ -if (! function_exists('cashcred_get_withdraw_requests') ) : - function cashcred_get_withdraw_requests( $status = 'Pending' ) - { - - $meta_query = array( - array( - 'key' => 'status', - 'value' => $status, - 'compare' => '=' - ), - array( - 'key' => 'from', - 'value' => get_current_user_id(), - 'compare' => '=' - ) - ); - - if ($status == 'Pending' ) { - array_push( - $meta_query, - array( - 'key' => 'points', - 'value' => '', - 'compare' => '!=' - ) - ); - } - - $args = array( - 'post_type' => 'cashcred_withdrawal', - 'post_status' => 'publish' , - 'posts_per_page' => -1, - 'paged' => get_query_var('paged'), - 'meta_query' => $meta_query - ); - - return get_posts($args); - - } +if ( ! function_exists( 'cashcred_get_withdraw_requests' ) ) : + function cashcred_get_withdraw_requests( $status = 'Pending' ) { + + $meta_query = array( + array( + 'key' => 'status', + 'value' => $status, + 'compare' => '=' + ), + array( + 'key' => 'from', + 'value' => get_current_user_id(), + 'compare' => '=' + ) + ); + + if ( $status == 'Pending' ) { + array_push( + $meta_query, + array( + 'key' => 'points', + 'value' => '', + 'compare' => '!=' + ) + ); + } + + $args = array( + 'post_type' => 'cashcred_withdrawal', + 'post_status' => 'publish' , + 'posts_per_page' => -1, + 'paged' => get_query_var('paged'), + 'meta_query' => $meta_query + ); + + return get_posts( $args ); + + } endif; /** * Get Pending Payment - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('cashcred_get_pending_payment_id') ) : - function cashcred_get_pending_payment_id( $payment_id = null ) - { +if ( ! function_exists( 'cashcred_get_pending_payment_id' ) ) : + function cashcred_get_pending_payment_id( $payment_id = NULL ) { - if ($payment_id === null || $payment_id == '' ) { return false; - } + if ( $payment_id === NULL || $payment_id == '' ) return false; - // In case we are using the transaction ID instead of the post ID. - $post_id = false; - if (! is_numeric($payment_id) ) { + // In case we are using the transaction ID instead of the post ID. + $post_id = false; + if ( ! is_numeric( $payment_id ) ) { - $post = mycred_get_page_by_title(strtoupper($payment_id), OBJECT, 'buycred_payment'); - if ($post === null ) { return false; - } + $post = mycred_get_page_by_title( strtoupper( $payment_id ), OBJECT, 'buycred_payment' ); + if ( $post === NULL ) return false; - $post_id = $post->ID; + $post_id = $post->ID; - } - else { - $post_id = absint($payment_id); - } + } + else { + $post_id = absint( $payment_id ); + } - return $post_id; + return $post_id; - } + } endif; /** * Get Pending Payment - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('cashcred_get_payment_settings') ) : - function cashcred_get_payment_settings( $payment_id = null ) - { - - // Construct fake pending object ( when no pending payment object exists ) - if (is_array($payment_id) ) { - - $pending_payment = new StdClass(); - $pending_payment->payment_id = false; - $pending_payment->public_id = $payment_id['public_id']; - $pending_payment->point_type = $payment_id['point_type']; - $pending_payment->points = $payment_id['points']; - $pending_payment->cost = $payment_id['cost']; - $pending_payment->currency = $payment_id['currency']; - $pending_payment->gateway_id = $payment_id['gateway_id']; - $pending_payment->transaction_id = $payment_id['transaction_id']; - - } - - else { - - $payment_id = cashcred_get_pending_payment_id($payment_id); - - if ($payment_id === false ) { return false; - } - - $pending_payment = new StdClass(); - $pending_payment->payment_id = absint($payment_id); - $pending_payment->public_id = get_the_title($payment_id); - $pending_payment->point_type = check_site_get_post_meta($payment_id, 'point_type', true); - $pending_payment->points = check_site_get_post_meta($payment_id, 'points', true); - $pending_payment->cost = check_site_get_post_meta($payment_id, 'cost', true); - $pending_payment->currency = check_site_get_post_meta($payment_id, 'currency', true); - $pending_payment->gateway_id = check_site_get_post_meta($payment_id, 'gateway', true); - $pending_payment->transaction_id = $pending_payment->public_id; - - } - - return apply_filters('cashcred_get_payment_settings', $pending_payment, $payment_id); +if ( ! function_exists( 'cashcred_get_payment_settings' ) ) : + function cashcred_get_payment_settings( $payment_id = NULL ) { + + // Construct fake pending object ( when no pending payment object exists ) + if ( is_array( $payment_id ) ) { - } + $pending_payment = new StdClass(); + $pending_payment->payment_id = false; + $pending_payment->public_id = $payment_id['public_id']; + $pending_payment->point_type = $payment_id['point_type']; + $pending_payment->points = $payment_id['points']; + $pending_payment->cost = $payment_id['cost']; + $pending_payment->currency = $payment_id['currency']; + $pending_payment->gateway_id = $payment_id['gateway_id']; + $pending_payment->transaction_id = $payment_id['transaction_id']; + + } + + else { + + $payment_id = cashcred_get_pending_payment_id( $payment_id ); + + if ( $payment_id === false ) return false; + + $pending_payment = new StdClass(); + $pending_payment->payment_id = absint( $payment_id ); + $pending_payment->public_id = get_the_title( $payment_id ); + $pending_payment->point_type = check_site_get_post_meta( $payment_id, 'point_type', true ); + $pending_payment->points = check_site_get_post_meta( $payment_id, 'points', true ); + $pending_payment->cost = check_site_get_post_meta( $payment_id, 'cost', true ); + $pending_payment->currency = check_site_get_post_meta( $payment_id, 'currency', true ); + $pending_payment->gateway_id = check_site_get_post_meta( $payment_id, 'gateway', true ); + $pending_payment->transaction_id = $pending_payment->public_id; + + } + + return apply_filters( 'cashcred_get_payment_settings', $pending_payment, $payment_id ); + + } endif; /** * Add Pending Comment - * - * @since 1.7 + * @since 1.7 * @version 1.1 */ -if (! function_exists('cashcred_add_comment') ) : - function cashcred_add_comment( $payment_id = null, $comment = null, $time = null ) - { - - if (! MYCRED_CASHCRED_PENDING_COMMENTS ) { return true; - } - - $post_id = cashcred_get_pending_payment_id($payment_id); - if ($post_id === false ) { return false; - } - - global $mycred_modules; - - if ($time === null || $time == 'now' ) { - $time = current_time('mysql'); - } - - $author = 'cashcred'; - $gateway = mycred_get_post_meta($post_id, 'gateway', true); - $gateways = mycred_get_cashcred_gateways(); - $author_url = sprintf('buyCRED: %s %s', __('Unknown Gateway', 'mycred'), $gateway); - $author_email = apply_filters('mycred_buycred_comment_email', 'buycred-service@mycred.me'); - - if (array_key_exists($gateway, $gateways) ) { - $author = sprintf('buyCRED: %s %s', $gateways[ $gateway ]['title'], __('Gateway', 'mycred')); - } - - return wp_insert_comment( - array( - 'comment_post_ID' => $post_id, - 'comment_author' => $author, - 'comment_author_email' => $author_email, - 'comment_content' => $comment, - 'comment_type' => 'cashcred', - 'comment_author_IP' => sanitize_text_field($_SERVER['REMOTE_ADDR']), - 'comment_date' => $time, - 'comment_approved' => 1, - 'user_id' => 0 - ) - ); +if ( ! function_exists( 'cashcred_add_comment' ) ) : + function cashcred_add_comment( $payment_id = NULL, $comment = NULL, $time = null ) { - } + if ( ! MYCRED_CASHCRED_PENDING_COMMENTS ) return true; + + $post_id = cashcred_get_pending_payment_id( $payment_id ); + if ( $post_id === false ) return false; + + global $mycred_modules; + + if ( $time === null || $time == 'now' ) + $time = current_time( 'mysql' ); + + $author = 'cashcred'; + $gateway = mycred_get_post_meta( $post_id, 'gateway', true ); + $gateways = mycred_get_cashcred_gateways(); + $author_url = sprintf( 'buyCRED: %s %s', __( 'Unknown Gateway', 'mycred' ), $gateway ); + $author_email = apply_filters( 'mycred_buycred_comment_email', 'buycred-service@mycred.me' ); + + if ( array_key_exists( $gateway, $gateways ) ) + $author = sprintf( 'buyCRED: %s %s', $gateways[ $gateway ]['title'], __( 'Gateway', 'mycred' ) ); + + return wp_insert_comment( array( + 'comment_post_ID' => $post_id, + 'comment_author' => $author, + 'comment_author_email' => $author_email, + 'comment_content' => $comment, + 'comment_type' => 'cashcred', + 'comment_author_IP' => $_SERVER['REMOTE_ADDR'], + 'comment_date' => $time, + 'comment_approved' => 1, + 'user_id' => 0 + ) ); + + } endif; /** * buyCRED Gateway Constructor - * - * @since 1.7 + * @since 1.7 * @version 1.1 */ -if (! function_exists('cashcred_gateway') ) : - function cashcred_gateway( $gateway_id = null ) - { +if ( ! function_exists( 'cashcred_gateway' ) ) : + function cashcred_gateway( $gateway_id = NULL ) { - global $cashcred_gateway, $mycred_modules; - - if (isset($cashcred_gateway) - && ( $cashcred_gateway instanceof myCRED_Cash_Payment_Gateway ) - && ( $gateway_id === $cashcred_gateway->id ) - ) { - return $cashcred_gateway; - } + global $cashcred_gateway, $mycred_modules; + + if ( isset( $cashcred_gateway ) + && ( $cashcred_gateway instanceof myCRED_Cash_Payment_Gateway ) + && ( $gateway_id === $cashcred_gateway->id ) + ) { + return $cashcred_gateway; + } - $cashcred_gateway = false; - $installed = $mycred_modules['solo']['cashcred']->get(); - if (array_key_exists($gateway_id, $installed) ) { + $cashcred_gateway = false; + $installed = $mycred_modules['solo']['cashcred']->get(); + if ( array_key_exists( $gateway_id, $installed ) ) { - $class = $installed[ $gateway_id ]['callback'][0]; + $class = $installed[ $gateway_id ]['callback'][0]; - // Construct Gateway - $cashcred_gateway = new $class($mycred_modules['solo']['cashcred']->gateway_prefs); + // Construct Gateway + $cashcred_gateway = new $class( $mycred_modules['solo']['cashcred']->gateway_prefs ); - } + } - return $cashcred_gateway; + return $cashcred_gateway; - } + } endif; /** * CashCred_Gateway_Fields class - * - * @since 2.0 + * @since 2.0 * @version 1.0 */ -if (! class_exists('CashCred_Gateway_Fields') ) : - class CashCred_Gateway_Fields - { +if ( ! class_exists( 'CashCred_Gateway_Fields' ) ) : + class CashCred_Gateway_Fields { - public $gateway_name; + public $gateway_name; - private $gateway_fields; + private $gateway_fields; - /** - * Construct - * - * @since 2.0 - * @version 1.0 - */ - public function __construct( $name, $fields ) - { + /** + * Construct + * @since 2.0 + * @version 1.0 + */ + public function __construct( $name, $fields ) { - $this->gateway_name = $name; - $this->gateway_fields = $fields; + $this->gateway_name = $name; + $this->gateway_fields = $fields; - $this->populate(); + $this->populate(); - } + } - private function populate() - { + private function populate() { - $user_payment_details = cashcred_get_user_payment_details(); + $user_payment_details = cashcred_get_user_payment_details(); - foreach( $this->gateway_fields as $gateway_field_id => $gateway_field_data ){ + foreach( $this->gateway_fields as $gateway_field_id => $gateway_field_data ){ - $field_value = ''; + $field_value = ''; - if (! empty($user_payment_details[ $this->gateway_name ][ $gateway_field_id ]) ) { - $field_value = $user_payment_details[ $this->gateway_name ][ $gateway_field_id ]; - } + if ( ! empty( $user_payment_details[ $this->gateway_name ][ $gateway_field_id ] ) ) { + $field_value = $user_payment_details[ $this->gateway_name ][ $gateway_field_id ]; + } - $this->{ $gateway_field_id } = $field_value; - } + $this->{ $gateway_field_id } = $field_value; + } - } + } - public function field_name( $field_name ) - { + public function field_name( $field_name ) { - return "cashcred_user_settings[$this->gateway_name][$field_name]"; + return "cashcred_user_settings[$this->gateway_name][$field_name]"; - } + } - public function generate_form() - { + public function generate_form() { - foreach ( $this->gateway_fields as $gateway_field_id => $gateway_field_data ): ?> + foreach ( $this->gateway_fields as $gateway_field_id => $gateway_field_data ): ?> -
    - - -
    +
    + + +
    - 'disable', - 'fees' => array( - 'use' => 0, - 'account' => 0, - 'types' => array( - 'mycred_default' => array( - 'by' => 'percent', - 'amount' => 0, - 'min_cap' => 0, - 'max_cap' => 0, - 'presentation' => '( %fee% + %min% ) max. %max% = %total%' - ) - ) - ) - ); - - $settings = mycred_get_addon_settings('cashcreds'); - $settings = wp_parse_args($settings, $defaults); - - return apply_filters('mycred_get_cashcred_settings', $settings); - - } +if ( ! function_exists( 'mycred_get_cashcred_settings' ) ) : + function mycred_get_cashcred_settings() { + + $defaults = array( + 'debugging' => 'disable', + 'fees' => array( + 'use' => 0, + 'account' => 0, + 'types' => array( + 'mycred_default' => array( + 'by' => 'percent', + 'amount' => 0, + 'min_cap' => 0, + 'max_cap' => 0, + 'presentation' => '( %fee% + %min% ) max. %max% = %total%' + ) + ) + ) + ); + + $settings = mycred_get_addon_settings( 'cashcreds' ); + $settings = wp_parse_args( $settings, $defaults ); + + return apply_filters( 'mycred_get_cashcred_settings', $settings ); + + } endif; /** * add postmeta by checking multisite and current blog - * -* @param $post_id post id -* @param $key meta key -* @param bool $unique +* @param $post_id post id +* @param $key meta key +* @param bool $unique * @return mixed */ -if(!function_exists('check_site_add_post_meta') ) : - function check_site_add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) - { - if(is_multisite() AND !is_main_site() AND mycred_override_settings()) { - return add_post_meta($post_id, $meta_key, $meta_value, $unique); - } - else { - return mycred_add_post_meta($post_id, $meta_key, $meta_value, $unique); - } - } +if( !function_exists('check_site_add_post_meta') ): + function check_site_add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) { + if(is_multisite() AND !is_main_site() AND mycred_override_settings()) { + return add_post_meta( $post_id, $meta_key, $meta_value, $unique ); + } + else { + return mycred_add_post_meta( $post_id, $meta_key, $meta_value, $unique ); + } + } endif; /** * Returns postmeta by checking multisite and current blog - * -* @param $post_id post id -* @param $key meta key -* @param bool $single +* @param $post_id post id +* @param $key meta key +* @param bool $single * @return mixed */ -if(! function_exists('check_site_get_post_meta') ) : - function check_site_get_post_meta( $post_id, $key, $single = false ) - { - if(is_multisite() AND !is_main_site() AND mycred_override_settings() ) { - return get_post_meta($post_id, $key, $single); - } - else { - return mycred_get_post_meta($post_id, $key, $single); - } - } +if( ! function_exists('check_site_get_post_meta') ): + function check_site_get_post_meta( $post_id, $key, $single = false ) { + if( is_multisite() AND !is_main_site() AND mycred_override_settings() ) { + return get_post_meta( $post_id, $key, $single ); + } + else { + return mycred_get_post_meta( $post_id, $key, $single ); + } + } endif; /** * cashCred get user's settings */ -if(!function_exists('cashcred_get_user_settings')) : - function cashcred_get_user_settings() - { +if(!function_exists('cashcred_get_user_settings')): + function cashcred_get_user_settings() { $check = ''; - $cashcred_user_setting = ''; - - if(is_multisite() AND !is_main_site() AND mycred_override_settings() ) { - $check = true; - } - else { - $check = false; - } - - if($check ) { - return 'cashcred_user_settings_' . get_current_blog_id(); - } - else { - return 'cashcred_user_settings'; - } + $cashcred_user_setting = ''; + + if( is_multisite() AND !is_main_site() AND mycred_override_settings() ) { + $check = true; + } + else { + $check = false; + } + + if( $check ) { + return 'cashcred_user_settings_' . get_current_blog_id(); + } + else { + return 'cashcred_user_settings'; + } } endif; /** *Checks site is multisite or not and update post meta - * -* @param $post_id post id -* @param $key meta key -* @param $new_value new meta value +* @param $post_id post id +* @param $key meta key +* @param $new_value new meta value * @return mixed */ -if(! function_exists('check_site_update_post_meta') ) : - function check_site_update_post_meta( $post_id, $meta_key, $new_value ) - { +if( ! function_exists( 'check_site_update_post_meta' ) ): + function check_site_update_post_meta( $post_id, $meta_key, $new_value ) { if(is_multisite() AND !is_main_site() AND mycred_override_settings()) { - return update_post_meta($post_id, $meta_key, $new_value); - } - else { - return mycred_update_post_meta($post_id, $meta_key, $new_value); - } + return update_post_meta( $post_id, $meta_key, $new_value ); + } + else { + return mycred_update_post_meta( $post_id, $meta_key, $new_value ); + } } endif; /** * Update payment status */ -if(! function_exists('mycred_cashcred_update_status') ) : - function mycred_cashcred_update_status( $post_id, $meta_key, $meta_value ) - { - check_site_update_post_meta($post_id, $meta_key, $meta_value); - - $mycred_pref_cashcreds = mycred_get_option('mycred_pref_cashcreds', false); - - $point_type = check_site_get_post_meta($post_id, 'point_type', true); - $points = check_site_get_post_meta($post_id, 'points', true); - $cashcred_pay_method = check_site_get_post_meta($post_id, 'gateway', true); - - $user_id = get_post_field('post_author', $post_id); - $user_balance = mycred_get_users_balance($user_id, $point_type); - $payment_withdrawal_request = array( - 'point_type' => $point_type, - 'cashcred_pay_method' => $cashcred_pay_method, - 'points' => $points, - 'user_balance' => $user_balance, - 'user_id' => $user_id, - 'post_id' => $post_id - ); - - do_action('mycred_after_payment_request', $payment_withdrawal_request, $meta_value); - } -endif; +if( ! function_exists( 'mycred_cashcred_update_status' ) ): + function mycred_cashcred_update_status( $post_id, $meta_key, $meta_value ) { + check_site_update_post_meta( $post_id, $meta_key, $meta_value ); + + $mycred_pref_cashcreds = mycred_get_option( 'mycred_pref_cashcreds',false ); + + $point_type = check_site_get_post_meta( $post_id, 'point_type', true ); + $points = check_site_get_post_meta( $post_id, 'points', true ); + $cashcred_pay_method = check_site_get_post_meta( $post_id, 'gateway' , true ); + + $user_id = get_post_field( 'post_author', $post_id ); + $user_balance = mycred_get_users_balance( $user_id, $point_type ); + $payment_withdrawal_request = array( + 'point_type' => $point_type, + 'cashcred_pay_method' => $cashcred_pay_method, + 'points' => $points, + 'user_balance' => $user_balance, + 'user_id' => $user_id, + 'post_id' => $post_id + ); + + do_action( 'mycred_after_payment_request', $payment_withdrawal_request , $meta_value ); + } +endif; \ No newline at end of file diff --git a/addons/cash-creds/includes/cashcred-shortcodes.php b/addons/cash-creds/includes/cashcred-shortcodes.php index 04b0149..ef29291 100644 --- a/addons/cash-creds/includes/cashcred-shortcodes.php +++ b/addons/cash-creds/includes/cashcred-shortcodes.php @@ -1,446 +1,424 @@ __('Submit Request', 'mycred'), - 'gateways' => '', - 'types' => '', - 'amount' => '', - 'excluded' => 'You have excluded from this point type.', - 'insufficient' => 'Insufficient Points for Withdrawal.' - ), $atts, MYCRED_SLUG . '_cashcred' - ) - ); - - // If we are not logged in - if (! is_user_logged_in() ) { return $content; - } - - global $cashcred_instance, $mycred_modules, $cashcred_withdraw; - - // Prepare - $user_id = get_current_user_id(); - - $gateways = cashcred_get_usable_gateways($gateways); - - // Make sure we have a gateway we can use - if (empty($gateways) ) { - return __('No gateway available.', 'mycred'); - } - - $point_types = cashcred_get_point_types($types, $user_id); - - //We are excluded - if (empty($point_types) ) { return $excluded; - } - - $point_types = cashcred_is_user_have_balances($point_types, $user_id); - - //Insufficient points for withdrawal. - if (empty($point_types) ) { return $insufficient; - } - - // From this moment on, we need to indicate the shortcode usage for scripts and styles. - $cashcred_withdraw = true; - - // Button Label - $button_label = $point_types[ current(array_keys($point_types)) ]->template_tags_general($button); - - $cashcred_setting = mycred_get_cashcred_settings(); - - ob_start(); - - $pending_withdrawal = cashcred_get_withdraw_requests('Pending'); - ?> +if ( ! function_exists( 'mycred_render_cashcred' ) ) : + function mycred_render_cashcred( $atts = array(), $content = '' ) { + + extract( shortcode_atts( array( + 'button' => __( 'Submit Request', 'mycred' ), + 'gateways' => '', + 'types' => '', + 'amount' => '', + 'excluded' => 'You have excluded from this point type.', + 'insufficient' => 'Insufficient Points for Withdrawal.' + ), $atts, MYCRED_SLUG . '_cashcred' ) ); + + // If we are not logged in + if ( ! is_user_logged_in() ) return $content; + + global $cashcred_instance, $mycred_modules, $cashcred_withdraw; + + // Prepare + $user_id = get_current_user_id(); + + $gateways = cashcred_get_usable_gateways( $gateways ); + + // Make sure we have a gateway we can use + if ( empty( $gateways ) ) return __( 'No gateway available.', 'mycred' ); + + $point_types = cashcred_get_point_types( $types, $user_id ); + + //We are excluded + if ( empty( $point_types ) ) return $excluded; + + $point_types = cashcred_is_user_have_balances( $point_types, $user_id ); + + //Insufficient points for withdrawal. + if ( empty( $point_types ) ) return $insufficient; + + // From this moment on, we need to indicate the shortcode usage for scripts and styles. + $cashcred_withdraw = true; + + // Button Label + $button_label = $point_types[ current(array_keys($point_types)) ]->template_tags_general( $button ); + + $cashcred_setting = mycred_get_cashcred_settings(); + + ob_start(); + + $pending_withdrawal = cashcred_get_withdraw_requests('Pending'); + ?>
    - -
    - -
    - - - 0 ) { ?> -

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    IDPointsFeeAmountPoint TypeGatewayDate
    post_name; ?>ID, 'points', true);?>ID, 'point_type', true)]; - - if ($type_data['by'] == 'percent' ) { - $fee = ( ( $type_data['amount'] / 100 ) * (int)get_post_meta($post->ID, 'points', true) ); - } - else{ - $fee = $type_data['amount']; - } - - if($type_data['min_cap'] != 0 ) { - $fee = $fee + $type_data['min_cap']; - } - - if($type_data['max_cap'] != 0 && $fee > $type_data['max_cap'] ) { - $fee = $type_data['max_cap']; - } - - echo $fee; ?> - - ID, 'currency', true). " " .get_post_meta($post->ID, 'points', true) * get_post_meta($post->ID, 'cost', true); ?> - ID, 'point_type', true)];?> - ID, 'gateway', true); - $installed = $mycred_modules['solo']['cashcred']->get(); - if (isset($installed[ $gateway ]) ) { - echo $installed[ $gateway ]['title']; - } else { - echo $gateway; - } - ?> - post_date; ?>
    - - -
    - -
    - - - - 1 ) {?> -
    - - -
    - - - - - 1 ) { ?> -
    - - -
    - - - - -
    - - - -

    - - - -

    - - - -

    $value) { - $format[$key] = $point_types[$key]->core['format']; - - } - - wp_localize_script( - 'cashcred-withdraw', 'cashcred_data', - array( - 'cashcred_setting' => $cashcred_setting['fees'], - 'format' => $format, - ) - ); - - } - ?> -
    - -
    - -
    - - - -
    -

    Approved Requests

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    IDPointsFeeAmountPoint TypeGatewayDate
    post_name; ?>ID, 'points', true);?>ID, 'point_type', true)]; - - if ($type_data['by'] == 'percent' ) { - $fee = ( ( $type_data['amount'] / 100 ) * (int)get_post_meta($post->ID, 'points', true) ); - } - else{ - $fee = $type_data['amount']; - } - - if($type_data['min_cap'] != 0 ) { - $fee = $fee + $type_data['min_cap']; - } - - if($type_data['max_cap'] != 0 && $fee > $type_data['max_cap'] ) { - $fee = $type_data['max_cap']; - } - - echo $fee; ?> - - ID, 'currency', true). " " .get_post_meta($post->ID, 'points', true) * get_post_meta($post->ID, 'cost', true);?> - ID, 'point_type', true)]; ?> - ID, 'gateway', true); - $installed = $mycred_modules['solo']['cashcred']->get(); - if (isset($installed[ $gateway ]) ) { - echo $installed[ $gateway ]['title']; - } else { - echo $gateway; - } - ?> - post_date; ?>
    -
    - - - -
    -

    Cancelled Requests

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    IDPointsFeeAmountPoint TypeGatewayDate
    post_name; ?>ID, 'points', true);?>ID, 'point_type', true)]; - - if ($type_data['by'] == 'percent' ) { - $fee = ( ( $type_data['amount'] / 100 ) * (int)get_post_meta($post->ID, 'points', true) ); - } - else{ - $fee = $type_data['amount']; - } - - if($type_data['min_cap'] != 0 ) { - $fee = $fee + $type_data['min_cap']; - } - - if($type_data['max_cap'] != 0 && $fee > $type_data['max_cap'] ) { - $fee = $type_data['max_cap']; - } - - echo $fee; ?> - - ID, 'currency', true). " " .get_post_meta($post->ID, 'points', true) * get_post_meta($post->ID, 'cost', true);?> - ID, 'point_type', true)];?> - ID, 'gateway', true); - $installed = $mycred_modules['solo']['cashcred']->get(); - if (isset($installed[ $gateway ]) ) { - echo $installed[ $gateway ]['title']; - } else { - echo $gateway; - } - ?> - post_date; ?>
    -
    - - - -
    -
    - 1 ) :?> - - - - - $active_gateways_value ) { - - $MyCred_payment_setting_call = new $active_gateways_value['callback'][0]($key); - $MyCred_payment_setting_call->cashcred_payment_settings($key); - - } - ?> -
    - -
    -
    -
    - -
    + +
    + +
    + + + 0 ){ ?> +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    IDPointsFeeAmountPoint TypeGatewayDate
    post_name; ?>ID,'points',true);?>ID,'point_type',true)]; + + if ( $type_data['by'] == 'percent' ) { + $fee = ( ( $type_data['amount'] / 100 ) * (int)get_post_meta($post->ID,'points',true) ); + } + else{ + $fee = $type_data['amount']; + } + + if( $type_data['min_cap'] != 0 ) + $fee = $fee + $type_data['min_cap']; + + if( $type_data['max_cap'] != 0 && $fee > $type_data['max_cap'] ) + $fee = $type_data['max_cap']; + + echo $fee; ?> + + ID,'currency',true). " " .get_post_meta($post->ID,'points',true) * get_post_meta($post->ID,'cost',true); ?> + ID,'point_type',true)];?> + ID,'gateway',true); + $installed = $mycred_modules['solo']['cashcred']->get(); + if ( isset( $installed[ $gateway ] ) ) + echo $installed[ $gateway ]['title']; + else + echo $gateway; + ?> + post_date; ?>
    + + +
    + +
    + + + + 1 ) {?> +
    + + +
    + + + + + 1 ) { ?> +
    + + +
    + + + + +
    + + + +

    + + + +

    + + + +

    $value) { + $format[$key] = $point_types[$key]->core['format']; + + } + + wp_localize_script( 'cashcred-withdraw', 'cashcred_data', + array( + 'cashcred_setting' => $cashcred_setting['fees'], + 'format' => $format, + ) + ); + + } + ?> +
    + +
    + +
    + + + +
    +

    Approved Requests

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    IDPointsFeeAmountPoint TypeGatewayDate
    post_name; ?>ID,'points',true);?>ID,'point_type',true)]; + + if ( $type_data['by'] == 'percent' ) { + $fee = ( ( $type_data['amount'] / 100 ) * (int)get_post_meta($post->ID,'points',true) ); + } + else{ + $fee = $type_data['amount']; + } + + if( $type_data['min_cap'] != 0 ) + $fee = $fee + $type_data['min_cap']; + + if( $type_data['max_cap'] != 0 && $fee > $type_data['max_cap'] ) + $fee = $type_data['max_cap']; + + echo $fee; ?> + + ID,'currency',true). " " .get_post_meta($post->ID,'points',true) * get_post_meta($post->ID,'cost',true);?> + ID,'point_type',true)]; ?> + ID,'gateway',true); + $installed = $mycred_modules['solo']['cashcred']->get(); + if ( isset( $installed[ $gateway ] ) ) + echo $installed[ $gateway ]['title']; + else + echo $gateway; + ?> + post_date; ?>
    +
    + + + +
    +

    Cancelled Requests

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    IDPointsFeeAmountPoint TypeGatewayDate
    post_name; ?>ID,'points',true);?>ID,'point_type',true)]; + + if ( $type_data['by'] == 'percent' ) { + $fee = ( ( $type_data['amount'] / 100 ) * (int)get_post_meta($post->ID,'points',true) ); + } + else{ + $fee = $type_data['amount']; + } + + if( $type_data['min_cap'] != 0 ) + $fee = $fee + $type_data['min_cap']; + + if( $type_data['max_cap'] != 0 && $fee > $type_data['max_cap'] ) + $fee = $type_data['max_cap']; + + echo $fee; ?> + + ID,'currency',true). " " .get_post_meta($post->ID,'points',true) * get_post_meta($post->ID,'cost',true);?> + ID,'point_type',true)];?> + ID,'gateway',true); + $installed = $mycred_modules['solo']['cashcred']->get(); + if ( isset( $installed[ $gateway ] ) ) + echo $installed[ $gateway ]['title']; + else + echo $gateway; + ?> + post_date; ?>
    +
    + + + +
    +
    + 1 ):?> + + + + + $active_gateways_value ) { + + $MyCred_payment_setting_call = new $active_gateways_value['callback'][0]($key); + $MyCred_payment_setting_call->cashcred_payment_settings($key) ; + + } + ?> +
    + +
    +
    +
    + +
    - +?> \ No newline at end of file diff --git a/addons/cash-creds/index.php b/addons/cash-creds/index.php index 1580272..4e6c07c 100644 --- a/addons/cash-creds/index.php +++ b/addons/cash-creds/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/cash-creds/modules/cashcred-module-core.php b/addons/cash-creds/modules/cashcred-module-core.php index 241b512..14f6ba9 100644 --- a/addons/cash-creds/modules/cashcred-module-core.php +++ b/addons/cash-creds/modules/cashcred-module-core.php @@ -359,7 +359,7 @@ public function cashcred_update_payment_status( $post_id , $manual ) { 'comment_author_email' => $author_email, 'comment_content' => $comment, 'comment_type' => 'cashcred', - 'comment_author_IP' => sanitize_text_field($_SERVER['REMOTE_ADDR']), + 'comment_author_IP' => $_SERVER['REMOTE_ADDR'], 'comment_date' => $time, 'comment_approved' => 1, 'user_id' => 0 @@ -529,7 +529,7 @@ public function process_new_withdraw_request( $gateway_id ){ check_site_add_post_meta( $post_id, 'cost', $cost, true ); check_site_add_post_meta( $post_id, 'currency', $currency, true ); check_site_add_post_meta( $post_id, 'from', get_current_user_id(), true ); - check_site_add_post_meta( $post_id, 'user_ip', sanitize_text_field($_SERVER['REMOTE_ADDR']), true ); + check_site_add_post_meta( $post_id, 'user_ip', $_SERVER['REMOTE_ADDR'], true ); check_site_add_post_meta( $post_id, 'manual', 'Manual', true ); if( isset( $mycred_pref_cashcreds['gateway_prefs'][ $cashcred_pay_method ]["allow_auto_withdrawal"] ) && diff --git a/addons/cash-creds/modules/cashcred-module-withdrawal.php b/addons/cash-creds/modules/cashcred-module-withdrawal.php index 3cbad6f..12f6db0 100644 --- a/addons/cash-creds/modules/cashcred-module-withdrawal.php +++ b/addons/cash-creds/modules/cashcred-module-withdrawal.php @@ -1,1301 +1,1225 @@ 'cashCRED_Payments', - 'option_id' => '', - 'defaults' => array(), - 'screen_id' => '', - 'accordion' => false, - 'add_to_core' => false, - 'menu_pos' => 81 - ), $type - ); - - } - - /** - * Load - * - * @version 1.0.1 - */ - public function load() - { - - add_action('mycred_init', array( $this, 'module_init' ), $this->menu_pos); - add_action('mycred_admin_init', array( $this, 'module_admin_init' ), $this->menu_pos); - - } - - /** - * Module Init - * - * @since 1.7 - * @version 1.2 - */ - public function module_init() - { - - $this->register_cashcred_payments(); - - add_action('mycred_add_menu', array( $this, 'add_to_menu' ), $this->menu_pos); - - } - - /** - * Module Admin Init - * - * @since 1.7 - * @version 1.1 - */ - public function module_admin_init() - { - - add_filter('parent_file', array( $this, 'parent_file' )); - add_filter('submenu_file', array( $this, 'subparent_file' ), 10, 2); - - add_action('admin_notices', array( $this, 'admin_notices' )); +if ( ! class_exists( 'cashCRED_Pending_Payments' ) ) : + class cashCRED_Pending_Payments extends myCRED_Module { + + /** + * Construct + */ + function __construct( $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( 'cashCRED_Payments', array( + 'module_name' => 'cashCRED_Payments', + 'option_id' => '', + 'defaults' => array(), + 'screen_id' => '', + 'accordion' => false, + 'add_to_core' => false, + 'menu_pos' => 81 + ), $type ); + + } + + /** + * Load + * @version 1.0.1 + */ + public function load() { + + add_action( 'mycred_init', array( $this, 'module_init' ), $this->menu_pos ); + add_action( 'mycred_admin_init', array( $this, 'module_admin_init' ), $this->menu_pos ); + + } + + /** + * Module Init + * @since 1.7 + * @version 1.2 + */ + public function module_init() { + + $this->register_cashcred_payments(); + + add_action( 'mycred_add_menu', array( $this, 'add_to_menu' ), $this->menu_pos ); + + } + + /** + * Module Admin Init + * @since 1.7 + * @version 1.1 + */ + public function module_admin_init() { + + add_filter( 'parent_file', array( $this, 'parent_file' ) ); + add_filter( 'submenu_file', array( $this, 'subparent_file' ), 10, 2 ); + + add_action( 'admin_notices', array( $this, 'admin_notices' ) ); - add_action('admin_head-post.php', array( $this, 'edit_pending_payment_style' )); - add_filter('post_updated_messages', array( $this, 'post_updated_messages' )); - - add_filter('manage_' . MYCRED_CASHCRED_KEY . '_posts_columns', array( $this, 'adjust_column_headers' )); - add_action('manage_' . MYCRED_CASHCRED_KEY . '_posts_custom_column', array( $this, 'adjust_column_content' ), 10, 2); - add_filter('bulk_actions-edit-' . MYCRED_CASHCRED_KEY, array( $this, 'bulk_actions' )); - add_action('save_post_' . MYCRED_CASHCRED_KEY, array( $this, 'save_pending_payment' ), 10, 2); - - add_action('restrict_manage_posts', array( $this, 'cashcred_filter_html' )); - add_action('parse_query', array( $this, 'cashcred_filter_query' )); - - add_action('admin_enqueue_scripts', array( $this, 'cashcred_admin_assets' )); - - } - - public function cashcred_admin_assets() - { - - global $post_type; - - if ($post_type == MYCRED_CASHCRED_KEY ) { - - wp_register_style('cashcred-admin', plugins_url('assets/css/admin-style.css', MYCRED_CASHCRED), array(), MYCRED_CASHCRED_VERSION, 'all'); - wp_enqueue_style('cashcred-admin'); - - wp_register_script('cashcred-admin-script', plugins_url('assets/js/admin-script.js', MYCRED_CASHCRED), array( 'jquery' ), MYCRED_CASHCRED_VERSION, 'all'); - wp_enqueue_script('cashcred-admin-script'); - - } - - } - - public function cashcred_filter_html() - { - - global $wp_query, $mycred_modules, $post_type; - - if ($post_type == MYCRED_CASHCRED_KEY ) { - - $status = array( 'Approved', 'Pending', 'Cancelled' ); - - $current_plugin = ''; - if(isset($_GET['Status']) ) { - $current_plugin = sanitize_key( $_GET['Status'] ); - } - ?> - - - - array( 'ID' , 'user_nicename') )); - ?> - - 'gateway', - 'value' => $_GET['gateway'], - 'compare' => '=' - ); - } - - /* Payment status filter */ - if (is_admin() && $pagenow=='edit.php' && $post_type == 'cashcred_withdrawal' && isset($_GET['Status']) && $_GET['Status'] !='all' ) { - - $meta_query[] = array( - 'key' => 'Status', - 'value' => $_GET['Status'], - 'compare' => '=' - ); - - } - - /* User filter */ - if (is_admin() && $post_type == 'cashcred_withdrawal' && isset($_GET['user_id']) && $_GET['user_id'] !='all') { - - $meta_query[] = array( - 'key' => 'from', - 'value' => $_GET['user_id'], - 'compare' => '=' - ); - } - - if(! empty($meta_query) ) { - $query->set('meta_query', $meta_query); - } - - } - - /** - * Register Pending Payments - * - * @since 1.5 - * @version 1.1 - */ - protected function register_cashcred_payments() - { - - $labels = array( - 'name' => _x('cashCred Withdrawal', 'Post Type General Name', 'mycred'), - 'singular_name' => _x('cashCred Withdrawal', 'Post Type Singular Name', 'mycred'), - 'menu_name' => __('cashCred Withdrawal', 'mycred'), - 'parent_item_colon' => '', - 'all_items' => __('cashCred Withdrawal', 'mycred'), - 'view_item' => '', - 'add_new_item' => '', - 'add_new' => '', - 'edit_item' => __('Edit Withdrawal Request', 'mycred'), - 'update_item' => '', - 'search_items' => '', - 'not_found' => __('Not found in Trash', 'mycred'), - 'not_found_in_trash' => __('Not found in Trash', 'mycred'), - ); - $args = array( - 'labels' => $labels, - 'supports' => array( 'title', 'comments' ), - 'hierarchical' => false, - 'public' => false, - 'show_ui' => true, - 'show_in_menu' => false, - 'show_in_nav_menus' => false, - 'show_in_admin_bar' => false, - 'can_export' => true, - 'has_archive' => false, - 'exclude_from_search' => true, - 'publicly_queryable' => false, - 'register_meta_box_cb' => array( $this, 'add_metaboxes' ) - ); - register_post_type(MYCRED_CASHCRED_KEY, apply_filters('mycred_setup_cashcred_payment', $args)); - - } - - /** - * Adjust Post Updated Messages - * - * @since 1.7 - * @version 1.1 - */ - public function post_updated_messages( $messages ) - { - - $messages[ MYCRED_CASHCRED_KEY ] = array( - 0 => '', - 1 => __('Payment Updated.', 'mycred'), - 2 => __('Payment Updated.', 'mycred'), - 3 => __('Payment Updated.', 'mycred'), - 4 => __('Payment Updated.', 'mycred'), - 5 => __('Payment Updated.', 'mycred'), - 6 => __('Payment Updated.', 'mycred'), - 7 => __('Payment Updated.', 'mycred'), - 8 => __('Payment Updated.', 'mycred'), - 9 => __('Payment Updated.', 'mycred'), - 10 => '' - ); - - return $messages; - - } - - /** - * Add Comment - * - * @since 1.7 - * @version 1.0 - */ - public function add_comment( $post_id, $event = '', $time = null ) - { - - return cashcred_add_comment($post_id, $event, $time); - - } - - /** - * Admin Notices - * - * @since 1.7 - * @version 1.1 - */ - public function admin_notices() - { - - if (isset($_GET['post_type']) && $_GET['post_type'] == MYCRED_CASHCRED_KEY && isset($_GET['credited']) ) { - - if ($_GET['credited'] == 1 ) { - echo '

    ' . __('Pending payment successfully credited to account.', 'mycred') . '

    '; - - } elseif ($_GET['credited'] == 0 ) { - echo '

    ' . __('Failed to credit the pending payment to account.', 'mycred') . '

    '; - } - - } - - } - - /** - * Add Admin Menu Item - * - * @since 1.7 - * @version 1.1 - */ - public function add_to_menu() - { - - // In case we are using the Master Template feautre on multisites, and this is not the main - // site in the network, bail. - //if ( mycred_override_settings() && ! mycred_is_main_site() ) return; - - mycred_add_main_submenu( - __('cashCred Withdrawal', 'mycred'), - __('cashCred Withdrawal', 'mycred'), - $this->core->get_point_editor_capability(), - 'edit.php?post_type=' . MYCRED_CASHCRED_KEY - ); - - } - - /** - * Parent File - * - * @since 1.7 - * @version 1.0.1 - */ - public function parent_file( $parent = '' ) - { - - global $pagenow; - - if (isset($_GET['post']) && mycred_get_post_type($_GET['post']) == MYCRED_CASHCRED_KEY && isset($_GET['action']) && $_GET['action'] == 'edit' ) { - return MYCRED_MAIN_SLUG; - } - - return $parent; - - } - - /** - * Sub Parent File - * - * @since 1.7.8 - * @version 1.0 - */ - public function subparent_file( $subparent = '', $parent = '' ) - { - - global $pagenow; - - if (( $pagenow == 'edit.php' || $pagenow == 'post-new.php' ) && isset($_GET['post_type']) && $_GET['post_type'] == MYCRED_CASHCRED_KEY ) { - - return 'edit.php?post_type=' . MYCRED_CASHCRED_KEY; - - } - - elseif ($pagenow == 'post.php' && isset($_GET['post']) && mycred_get_post_type($_GET['post']) == MYCRED_CASHCRED_KEY ) { - - return 'edit.php?post_type=' . MYCRED_CASHCRED_KEY; - - } - - return $subparent; - - } - - /** - * Pending Payment Column Headers - * - * @since 1.5 - * @version 1.0 - */ - public function adjust_column_headers( $columns ) - { - - return array( - 'cb' => $columns['cb'], - 'title' => __('Request ID', 'mycred'), - 'User' => __('User', 'mycred'), - 'Points' => __('Points Withdrawal', 'mycred'), - 'cost' => __('Cost', 'mycred'), - 'amount' => __('Amount', 'mycred'), - 'gateway' => __('Gateway', 'mycred'), - 'ctype' => __('Point Type', 'mycred'), - 'status' => __('Status', 'mycred'), - 'date' => $columns['date'], - ); - - } - - - /** - * Pending Payment Column Content - * - * @since 1.5 - * @version 1.0 - */ - public function adjust_column_content( $column_name, $post_id ) - { - - global $mycred_modules; - switch ( $column_name ) { - case 'User' : - - $from = (int) check_site_get_post_meta($post_id, 'from', true); - $from = (int) check_site_get_post_meta($post_id, 'from', true); - $user = get_userdata($from); - - if (isset($user->display_name) ) { - echo '' . $user->display_name . ''; - } else { - echo 'ID: ' . $from; - } - - break; - case 'Points'; - - $type = check_site_get_post_meta($post_id, 'point_type', true); - $points = check_site_get_post_meta($post_id, 'points', true); - $mycred = mycred($type); - - echo $mycred->format_creds($points); - - break; - case 'cost'; - - $cost = check_site_get_post_meta($post_id, 'cost', true); - $currency = check_site_get_post_meta($post_id, 'currency', true); - echo $cost . ' ' . $currency; - - break; - case 'amount'; - - $points = check_site_get_post_meta($post_id, 'points', true); - $cost = check_site_get_post_meta($post_id, 'cost', true); - $currency = check_site_get_post_meta($post_id, 'currency', true); - echo $currency .' ' . $points * $cost; - - break; - case 'gateway'; - - $gateway = check_site_get_post_meta($post_id, 'gateway', true); - $installed = $mycred_modules['solo']['cashcred']->get(); - - if (isset($installed[ $gateway ]) ) { - echo $installed[ $gateway ]['title']; - } else { - echo $gateway; - } - - break; - case 'ctype'; - - $type = check_site_get_post_meta($post_id, 'point_type', true); - - if (isset($this->point_types[ $type ]) ) { - echo $this->point_types[ $type ]; - } else { - echo $type; - } - - break; - case 'status'; - $status = check_site_get_post_meta($post_id, 'status', true); - echo "
    " . $status . "
    "; - - break; - - } - - } - - /** - * Adjust Bulk Actions - * - * @since 1.5 - * @version 1.0 - */ - public function bulk_actions( $actions ) - { - - unset($actions['edit']); - return $actions; - - } - - - - /** - * Edit Pending Payment Style - * - * @since 1.7 - * @version 1.0.1 - */ - public function edit_pending_payment_style() - { - - global $post_type; - - if ($post_type !== MYCRED_CASHCRED_KEY ) { return; - } - - wp_enqueue_style('mycred-bootstrap-grid'); - wp_enqueue_style('mycred-forms'); - - add_filter('postbox_classes_buycred_payment_buycred-pending-payment', array( $this, 'metabox_classes' )); - add_filter('postbox_classes_buycred_payment_cashcred-comments', array( $this, 'metabox_classes' )); - - } - - /** - * Add Metaboxes - * - * @since 1.7 - * @version 1.1 - */ - public function add_metaboxes() - { - - add_meta_box( - 'cashcred_withdrawal_request', - __('Withdrawal Request', 'mycred'), - array( $this, 'metabox_pending_payment' ), - MYCRED_CASHCRED_KEY, - 'normal', - 'high' - ); - - add_meta_box( - 'cashcred-user-info', - __('User Information', 'mycred'), - array( $this, 'cashcred_user_info' ), - MYCRED_CASHCRED_KEY, - 'normal', - 'high' - ); - - add_meta_box( - 'payment_gateway_detail', - __('Payment Gateway Detail', 'mycred'), - array( $this, 'payment_gateway_detail' ), - MYCRED_CASHCRED_KEY, - 'side', - 'high' - ); - - add_meta_box( - 'cashcred-payment-status', - __('Withdrawal Payment Status', 'mycred'), - array( $this, 'cashcred_payment_pay' ), - MYCRED_CASHCRED_KEY, - 'side', - 'high' - ); - - add_meta_box( - 'cashcred-comments', - __('History', 'mycred'), - array( $this, 'metabox_cashcred_comments' ), - MYCRED_CASHCRED_KEY, - 'normal', - 'default' - ); - - $mycred_pref_cashcreds = mycred_get_cashcred_settings(); - - if(isset($mycred_pref_cashcreds["debugging"]) && $mycred_pref_cashcreds["debugging"] == 'enable' ) { - - add_meta_box( - 'cashcred-developer-log', - __('Debugging Log', 'mycred'), - array( $this, 'cashcred_developer_log' ), - MYCRED_CASHCRED_KEY, - 'normal', - 'default' - ); - - } - - remove_meta_box('commentstatusdiv', MYCRED_CASHCRED_KEY, 'normal'); - remove_meta_box('commentsdiv', MYCRED_CASHCRED_KEY, 'normal'); - - remove_meta_box('submitdiv', MYCRED_CASHCRED_KEY, 'side'); - - add_meta_box( - 'submitdiv', - __('Actions', 'mycred'), - array( $this, 'metabox_pending_actions' ), - MYCRED_CASHCRED_KEY, - 'side', - 'high' - ); - - } - - - public function cashcred_developer_log() - { - - $counter = (int) mycred_get_post_meta(get_the_ID(), 'cashcred_log_counter', true); - $orderdesc = $counter; - - for ( $log = 1; $log <= $counter; $log++ ) { - - $payment_log = ''; - - $payment_log = mycred_get_post_meta(get_the_ID(), 'cashcred_log_' . $orderdesc, true); - - echo "
    ";    
    -                echo "Date Time: ".$payment_log['datetime']."
    "; - echo "Payment Gateway: ".$payment_log['payment_gateway']."
    "; - print_r(json_decode($payment_log["response"])); - echo "
    "; - - $orderdesc = $counter - 1; - - } - - } - - - public function payment_gateway_detail() - { - - global $mycred_modules; - - foreach ( $mycred_modules['solo']['cashcred']->get() as $gateway_id => $info ) { - - if(!$mycred_modules['solo']['cashcred']->is_active($gateway_id)) { continue ; - } - - $MyCred_payment_setting_call = new $info['callback'][0]($gateway_id); - $MyCred_payment_setting_call->cashcred_payment_settings($gateway_id); - - } - } - - public function cashcred_payment_pay() - { - - global $mycred_modules; - - $user_id = get_post_meta(get_the_ID(), 'from', true); - $status = get_post_meta(get_the_ID(), 'status', true); - $transfer_date = get_post_meta(get_the_ID(), 'cashcred_payment_transfer_date', true); - - $manual = get_post_meta(get_the_ID(), 'manual', true); - - $cashcred_user_settings = get_user_meta($user_id, 'cashcred_user_settings', true); - - $get_payment_settings = cashcred_get_payment_settings(get_the_ID()); - - ?> - -
    -
    -
    Amount Transfer :
    -
    -
    -
    -
    -
    - -
    -
    -
    Payment Method :
    -
    -
    -
    - get() as $gateway_id => $info ) { - if($get_payment_settings->gateway_id == $gateway_id ) { - echo $info['title']; - ?> -
    -
    -
    - -
    -
    -
    Amount :
    -
    - -
    -
    currency ." ". $get_payment_settings->points * $get_payment_settings->cost;?>
    -
    -
    - -
    -
    -
    Transfer Date :
    -
    - -
    -
    - -
    -
    -
    - -
    -
    -
    Transfer Mode :
    -
    - -
    -
    -
    -
    -
    - is_paid_request($user_id, get_the_ID()) ) { - $disabled = 'disabled'; - } - - ?> - - -
    -
    - - - -
    - -
    -
    User ID :
    -
    - -
    -
    -
    - -
    - -
    - -
    -
    User Name :
    -
    -
    -
    data->display_name;?>
    -
    - -
    - -
    - -
    -
    User Email :
    -
    -
    -
    data->user_email;?>
    -
    - -
    - -
    - -
    -
    User IP :
    -
    -
    -
    -
    - -
    - - -
    - -
    -
    User withdraw total amount:
    -
    -
    -
    currency .' '. get_user_meta($user_id, 'cashcred_total', true); - }else{ - echo 0; - } - ?> -
    -
    - -
    -
    - - - - -
    - - - - $post->post_type, - 'credit' => $post->ID, - 'token' => wp_create_nonce('buycred-payout-pending') - ), admin_url('edit.php') - ); - - $delete_url = get_delete_post_link($post->ID); - - $status = mycred_get_post_meta($post->ID, 'status', true); - - ?> + add_action( 'admin_head-post.php', array( $this, 'edit_pending_payment_style' ) ); + add_filter( 'post_updated_messages', array( $this, 'post_updated_messages' ) ); + + add_filter( 'manage_' . MYCRED_CASHCRED_KEY . '_posts_columns', array( $this, 'adjust_column_headers' ) ); + add_action( 'manage_' . MYCRED_CASHCRED_KEY . '_posts_custom_column', array( $this, 'adjust_column_content' ), 10, 2 ); + add_filter( 'bulk_actions-edit-' . MYCRED_CASHCRED_KEY, array( $this, 'bulk_actions' ) ); + add_action( 'save_post_' . MYCRED_CASHCRED_KEY, array( $this, 'save_pending_payment' ), 10, 2 ); + + add_action( 'restrict_manage_posts', array( $this, 'cashcred_filter_html' ) ); + add_action( 'parse_query', array( $this, 'cashcred_filter_query' ) ); + + add_action( 'admin_enqueue_scripts', array( $this, 'cashcred_admin_assets' ) ); + + } + + public function cashcred_admin_assets() { + + global $post_type; + + if ( $post_type == MYCRED_CASHCRED_KEY ) { + + wp_register_style( 'cashcred-admin', plugins_url( 'assets/css/admin-style.css', MYCRED_CASHCRED ), array(), MYCRED_CASHCRED_VERSION, 'all' ); + wp_enqueue_style( 'cashcred-admin' ); + + wp_register_script( 'cashcred-admin-script', plugins_url( 'assets/js/admin-script.js', MYCRED_CASHCRED ), array( 'jquery' ), MYCRED_CASHCRED_VERSION, 'all' ); + wp_enqueue_script( 'cashcred-admin-script' ); + + } + + } + + public function cashcred_filter_html() { + + global $wp_query, $mycred_modules, $post_type; + + if ( $post_type == MYCRED_CASHCRED_KEY ) { + + $status = array( 'Approved', 'Pending', 'Cancelled' ); + + $current_plugin = ''; + if( isset( $_GET['Status'] ) ) { + $current_plugin = sanitize_key( $_GET['Status'] ); + } + ?> + + + + array( 'ID' , 'user_nicename') ) ); + ?> + + 'gateway', + 'value' => $_GET['gateway'], + 'compare' => '=' + ); + } + + /* Payment status filter */ + if ( is_admin() && $pagenow=='edit.php' && $post_type == 'cashcred_withdrawal' && isset( $_GET['Status'] ) && $_GET['Status'] !='all' ) { + + $meta_query[] = array( + 'key' => 'Status', + 'value' => $_GET['Status'], + 'compare' => '=' + ); + + } + + /* User filter */ + if ( is_admin() && $post_type == 'cashcred_withdrawal' && isset( $_GET['user_id'] ) && $_GET['user_id'] !='all') { + + $meta_query[] = array( + 'key' => 'from', + 'value' => $_GET['user_id'], + 'compare' => '=' + ); + } + + if( ! empty( $meta_query ) ) + $query->set( 'meta_query', $meta_query ); + + } + + /** + * Register Pending Payments + * @since 1.5 + * @version 1.1 + */ + protected function register_cashcred_payments() { + + $labels = array( + 'name' => _x( 'cashCred Withdrawal', 'Post Type General Name', 'mycred' ), + 'singular_name' => _x( 'cashCred Withdrawal', 'Post Type Singular Name', 'mycred' ), + 'menu_name' => __( 'cashCred Withdrawal', 'mycred' ), + 'parent_item_colon' => '', + 'all_items' => __( 'cashCred Withdrawal', 'mycred' ), + 'view_item' => '', + 'add_new_item' => '', + 'add_new' => '', + 'edit_item' => __( 'Edit Withdrawal Request', 'mycred' ), + 'update_item' => '', + 'search_items' => '', + 'not_found' => __( 'Not found in Trash', 'mycred' ), + 'not_found_in_trash' => __( 'Not found in Trash', 'mycred' ), + ); + $args = array( + 'labels' => $labels, + 'supports' => array( 'title', 'comments' ), + 'hierarchical' => false, + 'public' => false, + 'show_ui' => true, + 'show_in_menu' => false, + 'show_in_nav_menus' => false, + 'show_in_admin_bar' => false, + 'can_export' => true, + 'has_archive' => false, + 'exclude_from_search' => true, + 'publicly_queryable' => false, + 'register_meta_box_cb' => array( $this, 'add_metaboxes' ) + ); + register_post_type( MYCRED_CASHCRED_KEY, apply_filters( 'mycred_setup_cashcred_payment', $args ) ); + + } + + /** + * Adjust Post Updated Messages + * @since 1.7 + * @version 1.1 + */ + public function post_updated_messages( $messages ) { + + $messages[ MYCRED_CASHCRED_KEY ] = array( + 0 => '', + 1 => __( 'Payment Updated.', 'mycred' ), + 2 => __( 'Payment Updated.', 'mycred' ), + 3 => __( 'Payment Updated.', 'mycred' ), + 4 => __( 'Payment Updated.', 'mycred' ), + 5 => __( 'Payment Updated.', 'mycred' ), + 6 => __( 'Payment Updated.', 'mycred' ), + 7 => __( 'Payment Updated.', 'mycred' ), + 8 => __( 'Payment Updated.', 'mycred' ), + 9 => __( 'Payment Updated.', 'mycred' ), + 10 => '' + ); + + return $messages; + + } + + /** + * Add Comment + * @since 1.7 + * @version 1.0 + */ + public function add_comment( $post_id, $event = '', $time = NULL ) { + + return cashcred_add_comment( $post_id, $event, $time ); + + } + + /** + * Admin Notices + * @since 1.7 + * @version 1.1 + */ + public function admin_notices() { + + if ( isset( $_GET['post_type'] ) && $_GET['post_type'] == MYCRED_CASHCRED_KEY && isset( $_GET['credited'] ) ) { + + if ( $_GET['credited'] == 1 ) + echo '

    ' . __( 'Pending payment successfully credited to account.', 'mycred' ) . '

    '; + + elseif ( $_GET['credited'] == 0 ) + echo '

    ' . __( 'Failed to credit the pending payment to account.', 'mycred' ) . '

    '; + + } + + } + + /** + * Add Admin Menu Item + * @since 1.7 + * @version 1.1 + */ + public function add_to_menu() { + + // In case we are using the Master Template feautre on multisites, and this is not the main + // site in the network, bail. + //if ( mycred_override_settings() && ! mycred_is_main_site() ) return; + + mycred_add_main_submenu( + __( 'cashCred Withdrawal', 'mycred' ), + __( 'cashCred Withdrawal', 'mycred' ), + $this->core->get_point_editor_capability(), + 'edit.php?post_type=' . MYCRED_CASHCRED_KEY + ); + + } + + /** + * Parent File + * @since 1.7 + * @version 1.0.1 + */ + public function parent_file( $parent = '' ) { + + global $pagenow; + + if ( isset( $_GET['post'] ) && mycred_get_post_type( $_GET['post'] ) == MYCRED_CASHCRED_KEY && isset( $_GET['action'] ) && $_GET['action'] == 'edit' ) + return MYCRED_MAIN_SLUG; + + return $parent; + + } + + /** + * Sub Parent File + * @since 1.7.8 + * @version 1.0 + */ + public function subparent_file( $subparent = '', $parent = '' ) { + + global $pagenow; + + if ( ( $pagenow == 'edit.php' || $pagenow == 'post-new.php' ) && isset( $_GET['post_type'] ) && $_GET['post_type'] == MYCRED_CASHCRED_KEY ) { + + return 'edit.php?post_type=' . MYCRED_CASHCRED_KEY; + + } + + elseif ( $pagenow == 'post.php' && isset( $_GET['post'] ) && mycred_get_post_type( $_GET['post'] ) == MYCRED_CASHCRED_KEY ) { + + return 'edit.php?post_type=' . MYCRED_CASHCRED_KEY; + + } + + return $subparent; + + } + + /** + * Pending Payment Column Headers + * @since 1.5 + * @version 1.0 + */ + public function adjust_column_headers( $columns ) { + + return array( + 'cb' => $columns['cb'], + 'title' => __( 'Request ID', 'mycred' ), + 'User' => __( 'User', 'mycred' ), + 'Points' => __( 'Points Withdrawal', 'mycred' ), + 'cost' => __( 'Cost', 'mycred' ), + 'amount' => __( 'Amount', 'mycred' ), + 'gateway' => __( 'Gateway', 'mycred' ), + 'ctype' => __( 'Point Type', 'mycred' ), + 'status' => __( 'Status', 'mycred' ), + 'date' => $columns['date'], + ); + + } + + + /** + * Pending Payment Column Content + * @since 1.5 + * @version 1.0 + */ + public function adjust_column_content( $column_name, $post_id ) { + + global $mycred_modules; + switch ( $column_name ) { + case 'User' : + + $from = (int) check_site_get_post_meta( $post_id, 'from', true ); + $from = (int) check_site_get_post_meta( $post_id, 'from', true ); + $user = get_userdata( $from ); + + if ( isset( $user->display_name ) ) + echo '' . $user->display_name . ''; + else + echo 'ID: ' . $from; + + break; + case 'Points'; + + $type = check_site_get_post_meta( $post_id, 'point_type', true ); + $points = check_site_get_post_meta( $post_id, 'points', true ); + $mycred = mycred( $type ); + + echo $mycred->format_creds( $points ); + + break; + case 'cost'; + + $cost = check_site_get_post_meta( $post_id, 'cost', true ); + $currency = check_site_get_post_meta( $post_id, 'currency', true ); + echo $cost . ' ' . $currency; + + break; + case 'amount'; + + $points = check_site_get_post_meta( $post_id, 'points', true ); + $cost = check_site_get_post_meta( $post_id, 'cost', true ); + $currency = check_site_get_post_meta( $post_id, 'currency', true ); + echo $currency .' ' . $points * $cost; + + break; + case 'gateway'; + + $gateway = check_site_get_post_meta( $post_id, 'gateway', true ); + $installed = $mycred_modules['solo']['cashcred']->get(); + + if ( isset( $installed[ $gateway ] ) ) + echo $installed[ $gateway ]['title']; + else + echo $gateway; + + break; + case 'ctype'; + + $type = check_site_get_post_meta( $post_id, 'point_type', true ); + + if ( isset( $this->point_types[ $type ] ) ) + echo $this->point_types[ $type ]; + else + echo $type; + + break; + case 'status'; + $status = check_site_get_post_meta( $post_id, 'status', true ); + echo "
    " . $status . "
    "; + + break; + + } + + } + + /** + * Adjust Bulk Actions + * @since 1.5 + * @version 1.0 + */ + public function bulk_actions( $actions ) { + + unset( $actions['edit'] ); + return $actions; + + } + + + + /** + * Edit Pending Payment Style + * @since 1.7 + * @version 1.0.1 + */ + public function edit_pending_payment_style() { + + global $post_type; + + if ( $post_type !== MYCRED_CASHCRED_KEY ) return; + + wp_enqueue_style( 'mycred-bootstrap-grid' ); + wp_enqueue_style( 'mycred-forms' ); + + add_filter( 'postbox_classes_buycred_payment_buycred-pending-payment', array( $this, 'metabox_classes' ) ); + add_filter( 'postbox_classes_buycred_payment_cashcred-comments', array( $this, 'metabox_classes' ) ); + + } + + /** + * Add Metaboxes + * @since 1.7 + * @version 1.1 + */ + public function add_metaboxes() { + + add_meta_box( + 'cashcred_withdrawal_request', + __( 'Withdrawal Request', 'mycred' ), + array( $this, 'metabox_pending_payment' ), + MYCRED_CASHCRED_KEY, + 'normal', + 'high' + ); + + add_meta_box( + 'cashcred-user-info', + __( 'User Information', 'mycred' ), + array( $this, 'cashcred_user_info' ), + MYCRED_CASHCRED_KEY, + 'normal', + 'high' + ); + + add_meta_box( + 'payment_gateway_detail', + __( 'Payment Gateway Detail', 'mycred' ), + array( $this, 'payment_gateway_detail' ), + MYCRED_CASHCRED_KEY, + 'side', + 'high' + ); + + add_meta_box( + 'cashcred-payment-status', + __( 'Withdrawal Payment Status', 'mycred' ), + array( $this, 'cashcred_payment_pay' ), + MYCRED_CASHCRED_KEY, + 'side', + 'high' + ); + + add_meta_box( + 'cashcred-comments', + __( 'History', 'mycred' ), + array( $this, 'metabox_cashcred_comments' ), + MYCRED_CASHCRED_KEY, + 'normal', + 'default' + ); + + $mycred_pref_cashcreds = mycred_get_cashcred_settings(); + + if( isset( $mycred_pref_cashcreds["debugging"] ) && $mycred_pref_cashcreds["debugging"] == 'enable' ) { + + add_meta_box( + 'cashcred-developer-log', + __( 'Debugging Log', 'mycred' ), + array( $this, 'cashcred_developer_log' ), + MYCRED_CASHCRED_KEY, + 'normal', + 'default' + ); + + } + + remove_meta_box( 'commentstatusdiv', MYCRED_CASHCRED_KEY, 'normal' ); + remove_meta_box( 'commentsdiv', MYCRED_CASHCRED_KEY, 'normal' ); + + remove_meta_box( 'submitdiv', MYCRED_CASHCRED_KEY, 'side' ); + + add_meta_box( + 'submitdiv', + __( 'Actions', 'mycred' ), + array( $this, 'metabox_pending_actions' ), + MYCRED_CASHCRED_KEY, + 'side', + 'high' + ); + + } + + + public function cashcred_developer_log () { + + $counter = (int) mycred_get_post_meta( get_the_ID(), 'cashcred_log_counter', true ); + $orderdesc = $counter; + + for ( $log = 1; $log <= $counter; $log++ ) { + + $payment_log = ''; + + $payment_log = mycred_get_post_meta( get_the_ID(), 'cashcred_log_' . $orderdesc, true ); + + echo "
    ";	
    +				echo "Date Time: ".$payment_log['datetime']."
    "; + echo "Payment Gateway: ".$payment_log['payment_gateway']."
    "; + print_r( json_decode( $payment_log["response"] ) ); + echo "
    "; + + $orderdesc = $counter - 1; + + } + + } + + + public function payment_gateway_detail(){ + + global $mycred_modules; + + foreach ( $mycred_modules['solo']['cashcred']->get() as $gateway_id => $info ) { + + if(!$mycred_modules['solo']['cashcred']->is_active( $gateway_id )) continue ; + + $MyCred_payment_setting_call = new $info['callback'][0]($gateway_id); + $MyCred_payment_setting_call->cashcred_payment_settings($gateway_id) ; + + } + } + + public function cashcred_payment_pay(){ + + global $mycred_modules; + + $user_id = get_post_meta( get_the_ID(), 'from', true ); + $status = get_post_meta( get_the_ID(), 'status', true ); + $transfer_date = get_post_meta( get_the_ID(), 'cashcred_payment_transfer_date', true ); + + $manual = get_post_meta( get_the_ID(), 'manual', true ); + + $cashcred_user_settings = get_user_meta( $user_id, 'cashcred_user_settings', true ); + + $get_payment_settings = cashcred_get_payment_settings( get_the_ID() ); + + ?> + +
    +
    +
    Amount Transfer :
    +
    +
    +
    +
    +
    + +
    +
    +
    Payment Method :
    +
    +
    +
    + get() as $gateway_id => $info ) { + if($get_payment_settings->gateway_id == $gateway_id ){ + echo $info['title']; + ?> +
    +
    +
    + +
    +
    +
    Amount :
    +
    + +
    +
    currency ." ". $get_payment_settings->points * $get_payment_settings->cost;?>
    +
    +
    + +
    +
    +
    Transfer Date :
    +
    + +
    +
    + +
    +
    +
    + +
    +
    +
    Transfer Mode :
    +
    + +
    +
    +
    +
    +
    + is_paid_request( $user_id, get_the_ID() ) ) + $disabled = 'disabled'; + + ?> + + +
    +
    + + + +
    + +
    +
    User ID :
    +
    + +
    +
    +
    + +
    + +
    + +
    +
    User Name :
    +
    +
    +
    data->display_name;?>
    +
    + +
    + +
    + +
    +
    User Email :
    +
    +
    +
    data->user_email;?>
    +
    + +
    + +
    + +
    +
    User IP :
    +
    +
    +
    +
    + +
    + + +
    + +
    +
    User withdraw total amount:
    +
    +
    +
    currency .' '. get_user_meta( $user_id, 'cashcred_total', true ); + }else{ + echo 0; + } + ?> +
    +
    + +
    +
    + + + + +
    + + + + $post->post_type, + 'credit' => $post->ID, + 'token' => wp_create_nonce( 'buycred-payout-pending' ) + ), admin_url( 'edit.php' ) ); + + $delete_url = get_delete_post_link( $post->ID ); + + $status = mycred_get_post_meta( $post->ID, 'status', true ); + +?>
    -
    -
    - -
    - -
    - -
    - - - -
    - -
    - -
    - -
    - -
    -
    -
    - -
    - - - - -
    -
    -
    +
    +
    + +
    + +
    + +
    + + + +
    + +
    + +
    + +
    + +
    +
    +
    + +
    + + + + +
    +
    +
    - ID, 'point_type', true)]; - - if ($type_data['by'] == 'percent' ) { - $fee = ( ( $type_data['amount'] / 100 ) * (int)get_post_meta($post->ID, 'points', true) ); - } - else{ - $fee = $type_data['amount']; - } - - if($type_data['min_cap'] != 0 ) { - $fee = $fee + $type_data['min_cap']; - } - - if($type_data['max_cap'] != 0 && $fee > $type_data['max_cap'] ) { - $fee = $type_data['max_cap']; - } - } - wp_localize_script('cashcred-admin-script', 'cashcred_data', $cashcred_setting['fees']); - } - - if($payment_status == 'Approved' || $this->is_paid_request($user_id, get_the_ID()) ) { - $readonly = 'readonly'; - } - - if($payment_status == 'Approved' || $this->is_paid_request($user_id, get_the_ID()) ) { - $disabled = 'disabled'; - } - - $pending_payment = cashcred_get_payment_settings($post->ID); - - if ($pending_payment->point_type == $this->core->cred_id ) { - $mycred = $this->core; - } else { - $mycred = mycred($pending_payment->point_type); - } - ?> +ID,'point_type',true)]; + + if ( $type_data['by'] == 'percent' ) { + $fee = ( ( $type_data['amount'] / 100 ) * (int)get_post_meta($post->ID,'points',true) ); + } + else{ + $fee = $type_data['amount']; + } + + if( $type_data['min_cap'] != 0 ) + $fee = $fee + $type_data['min_cap']; + + if( $type_data['max_cap'] != 0 && $fee > $type_data['max_cap'] ) + $fee = $type_data['max_cap']; + } + wp_localize_script( 'cashcred-admin-script', 'cashcred_data', $cashcred_setting['fees'] ); + } + + if($payment_status == 'Approved' || $this->is_paid_request( $user_id, get_the_ID() ) ) + $readonly = 'readonly'; + + if( $payment_status == 'Approved' || $this->is_paid_request( $user_id, get_the_ID() ) ) + $disabled = 'disabled'; + + $pending_payment = cashcred_get_payment_settings( $post->ID ); + + if ( $pending_payment->point_type == $this->core->cred_id ) + $mycred = $this->core; + else + $mycred = mycred( $pending_payment->point_type ); +?>
    -
    -
    -
    - +
    +
    +
    + - + ?> + -
    -
    -
    -
    - - -
    -
    -
    -
    - - name="cashcred_pending_payment[points]" id="cashcred-pending-payment-points" class="form-control readonly_fields" value="number($pending_payment->points); ?>" /> -
    -
    - -
    -
    - - name="cashcred_pending_payment[fee]" id="cashcred-pending-payment-fee" class="form-control readonly_fields" value="" readonly/> -
    -
    -
    -
    - - name="cashcred_pending_payment[cost]" id="cashcred-pending-payment-cost" class="form-control readonly_fields" value="cost); ?>" /> -
    -
    -
    -
    - - name="cashcred_pending_payment[currency]" id="cashcred-pending-payment-currency" class="form-control readonly_fields" value="currency); ?>" /> -
    -
    -
    +
    +
    +
    +
    + + +
    +
    +
    +
    + + name="cashcred_pending_payment[points]" id="cashcred-pending-payment-points" class="form-control readonly_fields" value="number( $pending_payment->points ); ?>" /> +
    +
    + +
    +
    + + name="cashcred_pending_payment[fee]" id="cashcred-pending-payment-fee" class="form-control readonly_fields" value="" readonly/> +
    +
    +
    +
    + + name="cashcred_pending_payment[cost]" id="cashcred-pending-payment-cost" class="form-control readonly_fields" value="cost ); ?>" /> +
    +
    +
    +
    + + name="cashcred_pending_payment[currency]" id="cashcred-pending-payment-currency" class="form-control readonly_fields" value="currency ); ?>" /> +
    +
    +
    - $post->ID )); + $comments = get_comments( array( 'post_id' => $post->ID ) ); - echo ''; - } + } - /** - * Save Pending Payment - * - * @since 1.7 - * @version 1.0 - */ - public function save_pending_payment( $post_id, $post ) - { + /** + * Save Pending Payment + * @since 1.7 + * @version 1.0 + */ + public function save_pending_payment( $post_id, $post ) { - if (! $this->core->user_is_point_editor() || ! isset($_POST['cashcred_pending_payment']) ) { return; - } + if ( ! $this->core->user_is_point_editor() || ! isset( $_POST['cashcred_pending_payment'] ) ) return; - $pending_payment = $_POST['cashcred_pending_payment']; + $pending_payment = $_POST['cashcred_pending_payment']; - $old_status = mycred_get_post_meta($post_id, 'status', true); - $new_status = sanitize_text_field($_POST['status']); + $old_status = mycred_get_post_meta( $post_id, 'status', true ); + $new_status = sanitize_text_field( $_POST['status'] ); - $user_settings = mycred_get_user_meta($_POST['user_id'], cashcred_get_user_settings(), '', true); - $updated_user_settings = $_POST['cashcred_user_settings']; - - $changed_fields = array(); + $user_settings = mycred_get_user_meta( $_POST['user_id'], cashcred_get_user_settings(), '', true ); + $updated_user_settings = $_POST['cashcred_user_settings']; + + $changed_fields = array(); - $withdraw_request_messages = array( - 'point_type' => __('Point type', 'mycred'), - 'gateway' => __('Gateway', 'mycred'), - 'points' => __('Points', 'mycred'), - 'cost' => __('Cost', 'mycred'), - 'currency' => __('Currency', 'mycred') - ); + $withdraw_request_messages = array( + 'point_type' => __( 'Point type', 'mycred' ), + 'gateway' => __( 'Gateway', 'mycred' ), + 'points' => __( 'Points', 'mycred' ), + 'cost' => __( 'Cost', 'mycred' ), + 'currency' => __( 'Currency', 'mycred' ) + ); - mycred_cashcred_update_status($post_id, 'status', $new_status); + mycred_cashcred_update_status( $post_id, 'status', $new_status ); - mycred_update_user_meta($_POST['user_id'], cashcred_get_user_settings(), '', $updated_user_settings); + mycred_update_user_meta( $_POST['user_id'], cashcred_get_user_settings(), '', $updated_user_settings ); - foreach ( $pending_payment as $meta_key => $meta_value ) { + foreach ( $pending_payment as $meta_key => $meta_value ) { - $new_value = sanitize_text_field($meta_value); - $old_value = check_site_get_post_meta($post_id, $meta_key, true); + $new_value = sanitize_text_field( $meta_value ); + $old_value = check_site_get_post_meta( $post_id, $meta_key, true ); - if ($new_value != $old_value ) { - mycred_cashcred_update_status($post_id, $meta_key, $new_value); - $changed_fields[] = $withdraw_request_messages[ $meta_key ]; - } - - } + if ( $new_value != $old_value ) { + mycred_cashcred_update_status( $post_id, $meta_key, $new_value ); + $changed_fields[] = $withdraw_request_messages[ $meta_key ]; + } + + } - $changes = join(", ", $changed_fields); - - $user = wp_get_current_user(); + $changes = join( ", ", $changed_fields ); + + $user = wp_get_current_user(); - if (serialize($user_settings) != serialize($updated_user_settings) ) { - $this->add_comment($post_id, sprintf(__('User\'s detail updated by %s', 'mycred'), $user->user_login)); - } + if ( serialize( $user_settings ) != serialize( $updated_user_settings ) ) { + $this->add_comment( $post_id, sprintf( __( 'User\'s detail updated by %s', 'mycred' ), $user->user_login ) ); + } - if (! empty($changed_fields) ) { - $this->add_comment($post_id, sprintf(__('%s updated by %s', 'mycred'), $changes, $user->user_login)); - } + if ( ! empty( $changed_fields ) ) { + $this->add_comment( $post_id, sprintf( __( '%s updated by %s', 'mycred' ), $changes, $user->user_login ) ); + } - if ($old_status != $new_status ) { - $this->add_comment($post_id, sprintf(__('Status changed from %s to %s updated by %s', 'mycred'), $old_status, $new_status, $user->user_login)); - } + if ( $old_status != $new_status ) { + $this->add_comment( $post_id, sprintf( __( 'Status changed from %s to %s updated by %s', 'mycred' ), $old_status, $new_status, $user->user_login ) ); + } - } - - /** - * Withdraw Request Paid - * - * @version 1.0 - */ - public function is_paid_request( $user_id, $post_id ) - { + } + + /** + * Withdraw Request Paid + * @version 1.0 + */ + public function is_paid_request( $user_id, $post_id ) { - $args = array( - 'ref' => 'cashcred_withdrawal', - 'user_id' => $user_id, - 'ref_id' => $post_id - ); + $args = array( + 'ref' => 'cashcred_withdrawal', + 'user_id' => $user_id, + 'ref_id' => $post_id + ); - $log = new myCRED_Query_Log($args); + $log = new myCRED_Query_Log( $args ); - return $log->have_entries(); + return $log->have_entries(); - } + } - } + } endif; /** * Load buyCRED Pending Module - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_load_cashcred_pending_addon') ) : - function mycred_load_cashcred_pending_addon( $modules, $point_types ) - { +if ( ! function_exists( 'mycred_load_cashcred_pending_addon' ) ) : + function mycred_load_cashcred_pending_addon( $modules, $point_types ) { - $modules['solo']['cashcred-pending'] = new cashCRED_Pending_Payments(); - $modules['solo']['cashcred-pending']->load(); + $modules['solo']['cashcred-pending'] = new cashCRED_Pending_Payments(); + $modules['solo']['cashcred-pending']->load(); - return $modules; + return $modules; - } + } endif; -add_filter('mycred_load_modules', 'mycred_load_cashcred_pending_addon', 40, 2); +add_filter( 'mycred_load_modules', 'mycred_load_cashcred_pending_addon', 40, 2 ); diff --git a/addons/cash-creds/modules/index.php b/addons/cash-creds/modules/index.php index 1580272..4e6c07c 100644 --- a/addons/cash-creds/modules/index.php +++ b/addons/cash-creds/modules/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/cash-creds/myCRED-addon-cash-creds.php b/addons/cash-creds/myCRED-addon-cash-creds.php index 7d69433..c4ddff2 100644 --- a/addons/cash-creds/myCRED-addon-cash-creds.php +++ b/addons/cash-creds/myCRED-addon-cash-creds.php @@ -5,24 +5,21 @@ * Addon URI: http://codex.mycred.me/chapter-iii/cashcred/ * Version: 1.0 */ -if (! defined('myCRED_VERSION') ) { exit; -} +if ( ! defined( 'myCRED_VERSION' ) ) exit; -define('MYCRED_CASHCRED', __FILE__); -define('MYCRED_CASHCRED_VERSION', '1.0'); -define('MYCRED_CASHCRED_DIR', myCRED_ADDONS_DIR . 'cash-creds/'); -define('MYCRED_CASHCRED_ABSTRACT_DIR', MYCRED_CASHCRED_DIR . 'abstracts/'); -define('MYCRED_CASHCRED_GATEWAYS_DIR', MYCRED_CASHCRED_DIR . 'gateways/'); -define('MYCRED_CASHCRED_MODULES_DIR', MYCRED_CASHCRED_DIR . 'modules/'); -define('MYCRED_CASHCRED_INCLUDES_DIR', MYCRED_CASHCRED_DIR . 'includes/'); +define( 'MYCRED_CASHCRED', __FILE__ ); +define( 'MYCRED_CASHCRED_VERSION', '1.0' ); +define( 'MYCRED_CASHCRED_DIR', myCRED_ADDONS_DIR . 'cash-creds/' ); +define( 'MYCRED_CASHCRED_ABSTRACT_DIR', MYCRED_CASHCRED_DIR . 'abstracts/' ); +define( 'MYCRED_CASHCRED_GATEWAYS_DIR', MYCRED_CASHCRED_DIR . 'gateways/' ); +define( 'MYCRED_CASHCRED_MODULES_DIR', MYCRED_CASHCRED_DIR . 'modules/' ); +define( 'MYCRED_CASHCRED_INCLUDES_DIR', MYCRED_CASHCRED_DIR . 'includes/' ); -if (! defined('MYCRED_CASHCRED_PENDING_COMMENTS') ) { - define('MYCRED_CASHCRED_PENDING_COMMENTS', true); -} +if ( ! defined( 'MYCRED_CASHCRED_PENDING_COMMENTS' ) ) + define( 'MYCRED_CASHCRED_PENDING_COMMENTS', true ); -if (! defined('MYCRED_CASHCRED_KEY') ) { - define('MYCRED_CASHCRED_KEY', 'cashcred_withdrawal'); -} +if ( ! defined( 'MYCRED_CASHCRED_KEY' ) ) + define( 'MYCRED_CASHCRED_KEY', 'cashcred_withdrawal' ); /** * Load Dependencies @@ -34,18 +31,16 @@ /** * Load Built-in Gateways - * - * @since 1.4 + * @since 1.4 * @version 1.0 */ require_once MYCRED_CASHCRED_GATEWAYS_DIR . 'bank-transfer.php'; -do_action('mycred_cashcred_load_gateways'); +do_action( 'mycred_cashcred_load_gateways' ); /** * Load Modules - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ require_once MYCRED_CASHCRED_MODULES_DIR . 'cashcred-module-core.php'; diff --git a/addons/coupons/assets/css/admin.css b/addons/coupons/assets/css/admin.css index 6c751d4..28fe102 100644 --- a/addons/coupons/assets/css/admin.css +++ b/addons/coupons/assets/css/admin.css @@ -1,64 +1,64 @@ .mycred-border{ - border: 1px solid #e9e9e9; - padding: 0 1em; - margin: 0 0 .8em; + border: 1px solid #e9e9e9; + padding: 0 1em; + margin: 0 0 .8em; } .mycred-select-coupon-reward{ - display: inline-block; - margin-left: 15px; + display: inline-block; + margin-left: 15px; } .mycred-select-coupon-rewards{ - width: 113px; + width: 113px; } .mycred-coupon-form{ - padding: 15px 10px; + padding: 15px 10px; } .mycred-title{ - border-bottom: 1px solid #e9e9e9; - background-color: #fafafa; - min-height: 1.5em; - margin-bottom: 20px; + border-bottom: 1px solid #e9e9e9; + background-color: #fafafa; + min-height: 1.5em; + margin-bottom: 20px; } .show-badges { - display: block !important; - /*border-top: 1px solid #e9e9e9;*/ - margin-bottom: 10px; - margin-top: 11px; + display: block !important; + /*border-top: 1px solid #e9e9e9;*/ + margin-bottom: 10px; + margin-top: 11px; } .show-ranks { - display: block !important; - /*border-top: 1px solid #e9e9e9;*/ - margin-bottom: 10px; - margin-top: 11px; + display: block !important; + /*border-top: 1px solid #e9e9e9;*/ + margin-bottom: 10px; + margin-top: 11px; } .mycred-select-coupon { - display: inline-block; - margin-left: 67px; - margin-top: 10px; + display: inline-block; + margin-left: 67px; + margin-top: 10px; } .mycred-select-ids { - width: 113px; + width: 113px; } .mycred-select-coupon-ranks { - display: inline-block; - margin-left: 76px; - margin-top: 10px; + display: inline-block; + margin-left: 76px; + margin-top: 10px; } .mycred-select-ranks { - width: 113px; - text-align: center; + width: 113px; + text-align: center; } .close-button{ - cursor: pointer; - color: #a00; - opacity: 1; - -webkit-appearance: none!important; - background: 0 0!important; - border: none!important; - position: relative; - top: 0.87em; - line-height: 3em; - display: inline-block;" + cursor: pointer; + color: #a00; + opacity: 1; + -webkit-appearance: none!important; + background: 0 0!important; + border: none!important; + position: relative; + top: 0.87em; + line-height: 3em; + display: inline-block;" } .close-button:hover { color: deeppink !important; diff --git a/addons/coupons/includes/index.php b/addons/coupons/includes/index.php index 1580272..4e6c07c 100644 --- a/addons/coupons/includes/index.php +++ b/addons/coupons/includes/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/coupons/includes/mycred-coupon-functions.php b/addons/coupons/includes/mycred-coupon-functions.php index 63d2bed..0818107 100644 --- a/addons/coupons/includes/mycred-coupon-functions.php +++ b/addons/coupons/includes/mycred-coupon-functions.php @@ -1,429 +1,367 @@ post_id || strtoupper($coupon_id) === strtoupper($mycred_coupon->code)) - ) { - return $mycred_coupon; - } + if ( isset( $mycred_coupon ) + && ( $mycred_coupon instanceof myCRED_Coupon ) + && ( $coupon_id === $mycred_coupon->post_id || strtoupper($coupon_id) === strtoupper($mycred_coupon->code)) + ) { + return $mycred_coupon; + } - $mycred_coupon = new myCRED_Coupon($coupon_id); + $mycred_coupon = new myCRED_Coupon( $coupon_id ); - do_action('mycred_get_coupon'); + do_action( 'mycred_get_coupon' ); - return $mycred_coupon; + return $mycred_coupon; - } + } endif; /** * Get Coupon Value - * - * @filter mycred_coupon_value - * @since 1.4 + * @filter mycred_coupon_value + * @since 1.4 * @version 1.0 */ -if (! function_exists('mycred_get_coupon_value') ) : - function mycred_get_coupon_value( $post_id = 0 ) - { +if ( ! function_exists( 'mycred_get_coupon_value' ) ) : + function mycred_get_coupon_value( $post_id = 0 ) { - return apply_filters('mycred_coupon_value', mycred_get_post_meta($post_id, 'value', true), $post_id); + return apply_filters( 'mycred_coupon_value', mycred_get_post_meta( $post_id, 'value', true ), $post_id ); - } + } endif; /** * Get Coupon Expire Date - * - * @filter mycred_coupon_max_balance - * @since 1.4 + * @filter mycred_coupon_max_balance + * @since 1.4 * @version 1.0.1 */ -if (! function_exists('mycred_get_coupon_expire_date') ) : - function mycred_get_coupon_expire_date( $post_id = 0, $unix = false ) - { +if ( ! function_exists( 'mycred_get_coupon_expire_date' ) ) : + function mycred_get_coupon_expire_date( $post_id = 0, $unix = false ) { - $expires = mycred_get_post_meta($post_id, 'expires', true); + $expires = mycred_get_post_meta( $post_id, 'expires', true ); - if (! empty($expires) && $unix ) { - $expires = ( strtotime($expires . ' midnight') + ( DAY_IN_SECONDS - 1 ) ); - } + if ( ! empty( $expires ) && $unix ) + $expires = ( strtotime( $expires . ' midnight' ) + ( DAY_IN_SECONDS - 1 ) ); - if (empty($expires) ) { $expires = false; - } + if ( empty( $expires ) ) $expires = false; - return apply_filters('mycred_coupon_expires', $expires, $post_id, $unix); + return apply_filters( 'mycred_coupon_expires', $expires, $post_id, $unix ); - } + } endif; /** * Get Coupon User Max * The maximum number a user can use this coupon. - * - * @filter mycred_coupon_user_max - * @since 1.4 + * @filter mycred_coupon_user_max + * @since 1.4 * @version 1.0.1 */ -if (! function_exists('mycred_get_coupon_user_max') ) : - function mycred_get_coupon_user_max( $post_id = 0 ) - { +if ( ! function_exists( 'mycred_get_coupon_user_max' ) ) : + function mycred_get_coupon_user_max( $post_id = 0 ) { - return (int) apply_filters('mycred_coupon_user_max', mycred_get_post_meta($post_id, 'user', true), $post_id); + return (int) apply_filters( 'mycred_coupon_user_max', mycred_get_post_meta( $post_id, 'user', true ), $post_id ); - } + } endif; /** * Get Coupons Global Max - * - * @filter mycred_coupon_global_max - * @since 1.4 + * @filter mycred_coupon_global_max + * @since 1.4 * @version 1.0.1 */ -if (! function_exists('mycred_get_coupon_global_max') ) : - function mycred_get_coupon_global_max( $post_id = 0 ) - { +if ( ! function_exists( 'mycred_get_coupon_global_max' ) ) : + function mycred_get_coupon_global_max( $post_id = 0 ) { - return (int) apply_filters('mycred_coupon_global_max', mycred_get_post_meta($post_id, 'global', true), $post_id); + return (int) apply_filters( 'mycred_coupon_global_max', mycred_get_post_meta( $post_id, 'global', true ), $post_id ); - } + } endif; /** * Create New Coupon * Creates a new myCRED coupon post. - * - * @filter mycred_create_new_coupon_post - * @filter mycred_create_new_coupon + * @filter mycred_create_new_coupon_post + * @filter mycred_create_new_coupon * @returns false if data is missing, post ID on success or wp_error / 0 if * post creation failed. - * @since 1.4 + * @since 1.4 * @version 1.1.1 */ -if (! function_exists('mycred_create_new_coupon') ) : - function mycred_create_new_coupon( $data = array() ) - { - - // Required data is missing - if (empty($data) ) { return false; - } - - // Apply defaults - extract( - shortcode_atts( - array( - 'code' => mycred_get_unique_coupon_code(), - 'value' => 0, - 'global_max' => 1, - 'user_max' => 1, - 'min_balance' => 0, - 'min_balance_type' => MYCRED_DEFAULT_TYPE_KEY, - 'max_balance' => 0, - 'max_balance_type' => MYCRED_DEFAULT_TYPE_KEY, - 'expires' => '', - 'type' => MYCRED_DEFAULT_TYPE_KEY - ), $data - ) - ); - - // Create Coupon Post - $post_id = wp_insert_post( - apply_filters( - 'mycred_create_new_coupon_post', array( - 'post_type' => MYCRED_COUPON_KEY, - 'post_title' => $code, - 'post_status' => 'publish', - 'comment_status' => 'closed', - 'ping_status' => 'closed' - ), $data - ) - ); - - // Error - if ($post_id !== 0 && ! is_wp_error($post_id) ) { - - // Save Coupon Details - mycred_add_post_meta($post_id, 'type', $type, true); - mycred_add_post_meta($post_id, 'value', $value, true); - mycred_add_post_meta($post_id, 'global', $global_max, true); - mycred_add_post_meta($post_id, 'user', $user_max, true); - mycred_add_post_meta($post_id, 'min_balance', $min_balance, true); - mycred_add_post_meta($post_id, 'min_balance_type', $min_balance_type, true); - mycred_add_post_meta($post_id, 'max_balance', $max_balance, true); - mycred_add_post_meta($post_id, 'max_balance_type', $max_balance_type, true); - - if (! empty($expires) ) { - mycred_add_post_meta($post_id, 'expires', $expires); - } - - } - - return apply_filters('mycred_create_new_coupon', $post_id, $data); - - } +if ( ! function_exists( 'mycred_create_new_coupon' ) ) : + function mycred_create_new_coupon( $data = array() ) { + + // Required data is missing + if ( empty( $data ) ) return false; + + // Apply defaults + extract( shortcode_atts( array( + 'code' => mycred_get_unique_coupon_code(), + 'value' => 0, + 'global_max' => 1, + 'user_max' => 1, + 'min_balance' => 0, + 'min_balance_type' => MYCRED_DEFAULT_TYPE_KEY, + 'max_balance' => 0, + 'max_balance_type' => MYCRED_DEFAULT_TYPE_KEY, + 'expires' => '', + 'type' => MYCRED_DEFAULT_TYPE_KEY + ), $data ) ); + + // Create Coupon Post + $post_id = wp_insert_post( apply_filters( 'mycred_create_new_coupon_post', array( + 'post_type' => MYCRED_COUPON_KEY, + 'post_title' => $code, + 'post_status' => 'publish', + 'comment_status' => 'closed', + 'ping_status' => 'closed' + ), $data ) ); + + // Error + if ( $post_id !== 0 && ! is_wp_error( $post_id ) ) { + + // Save Coupon Details + mycred_add_post_meta( $post_id, 'type', $type, true ); + mycred_add_post_meta( $post_id, 'value', $value, true ); + mycred_add_post_meta( $post_id, 'global', $global_max, true ); + mycred_add_post_meta( $post_id, 'user', $user_max, true ); + mycred_add_post_meta( $post_id, 'min_balance', $min_balance, true ); + mycred_add_post_meta( $post_id, 'min_balance_type', $min_balance_type, true ); + mycred_add_post_meta( $post_id, 'max_balance', $max_balance, true ); + mycred_add_post_meta( $post_id, 'max_balance_type', $max_balance_type, true ); + + if ( ! empty( $expires ) ) + mycred_add_post_meta( $post_id, 'expires', $expires ); + + } + + return apply_filters( 'mycred_create_new_coupon', $post_id, $data ); + + } endif; /** * Get Unique Coupon Code * Generates a unique 12 character alphanumeric coupon code. - * - * @filter mycred_get_unique_coupon_code - * @since 1.4 + * @filter mycred_get_unique_coupon_code + * @since 1.4 * @version 1.0.2 */ -if (! function_exists('mycred_get_unique_coupon_code') ) : - function mycred_get_unique_coupon_code() - { +if ( ! function_exists( 'mycred_get_unique_coupon_code' ) ) : + function mycred_get_unique_coupon_code() { - global $wpdb; + global $wpdb; - $table = mycred_get_db_column('posts'); + $table = mycred_get_db_column( 'posts' ); - do { + do { - $id = strtoupper(wp_generate_password(12, false, false)); - $query = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE post_title = %s AND post_type = %s;", $id, MYCRED_COUPON_KEY)); + $id = strtoupper( wp_generate_password( 12, false, false ) ); + $query = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE post_title = %s AND post_type = %s;", $id, MYCRED_COUPON_KEY ) ); - } while ( ! empty($query) ); + } while ( ! empty( $query ) ); - return apply_filters('mycred_get_unique_coupon_code', $id); + return apply_filters( 'mycred_get_unique_coupon_code', $id ); - } + } endif; /** * Get Coupon Post - * - * @filter mycred_get_coupon_by_code - * @since 1.4 + * @filter mycred_get_coupon_by_code + * @since 1.4 * @version 1.0.1 */ -if (! function_exists('mycred_get_coupon_post') ) : - function mycred_get_coupon_post( $code = '' ) - { +if ( ! function_exists( 'mycred_get_coupon_post' ) ) : + function mycred_get_coupon_post( $code = '' ) { - if ($code == '' ) { return false; - } + if ( $code == '' ) return false; - return apply_filters('mycred_get_coupon_by_code', mycred_get_page_by_title(strtoupper($code), 'OBJECT', MYCRED_COUPON_KEY), $code); + return apply_filters( 'mycred_get_coupon_by_code', mycred_get_page_by_title( strtoupper( $code ), 'OBJECT', MYCRED_COUPON_KEY ), $code ); - } + } endif; /** * Use Coupon * Will attempt to use a given coupon and award it's value * to a given user. Requires you to provide a log entry template. - * - * @action mycred_use_coupon - * @since 1.4 + * @action mycred_use_coupon + * @since 1.4 * @version 1.2 */ -if (! function_exists('mycred_use_coupon') ) : - function mycred_use_coupon( $code = '', $user_id = 0 ) - { +if ( ! function_exists( 'mycred_use_coupon' ) ) : + function mycred_use_coupon( $code = '', $user_id = 0 ) { - // Missing required information - if (empty($code) || $user_id === 0 ) { return 'invalid'; - } + // Missing required information + if ( empty( $code ) || $user_id === 0 ) return 'invalid'; - $coupon = mycred_get_coupon($code); + $coupon = mycred_get_coupon( $code ); - // Coupon does not exist - if ($coupon === false ) { return 'invalid'; - } + // Coupon does not exist + if ( $coupon === false ) return 'invalid'; - return $coupon->use_coupon($user_id); + return $coupon->use_coupon( $user_id ); - } + } endif; /** * Was Coupon Successfully Used? * Checks to see if mycred_use_coupon() successfully paid out or if * we ran into issues. - * - * @since 1.7.5 + * @since 1.7.5 * @version 1.0 */ -if (! function_exists('mycred_coupon_was_successfully_used') ) : - function mycred_coupon_was_successfully_used( $code = '' ) - { +if ( ! function_exists( 'mycred_coupon_was_successfully_used' ) ) : + function mycred_coupon_was_successfully_used( $code = '' ) { - $results = true; - $error_codes = apply_filters('mycred_coupon_error_codes', array( 'invalid', 'expired', 'user_limit', 'min', 'max', 'excluded' )); + $results = true; + $error_codes = apply_filters( 'mycred_coupon_error_codes', array( 'invalid', 'expired', 'user_limit', 'min', 'max', 'excluded' ) ); - if ($code === false || in_array($code, $error_codes) ) { - $results = false; - } + if ( $code === false || in_array( $code, $error_codes ) ) + $results = false; - return $results; + return $results; - } + } endif; /** * Coupon Error Message * Translates a coupon error code into a readable message. * we ran into issues. - * - * @since 1.7.5 + * @since 1.7.5 * @version 1.1 */ -if (! function_exists('mycred_get_coupon_error_message') ) : - function mycred_get_coupon_error_message( $code = '', $coupon = null ) - { +if ( ! function_exists( 'mycred_get_coupon_error_message' ) ) : + function mycred_get_coupon_error_message( $code = '', $coupon = NULL ) { - $message = __('An unknown error occurred. Coupon not used.', 'mycred'); - $settings = mycred_get_addon_settings('coupons'); + $message = __( 'An unknown error occurred. Coupon not used.', 'mycred' ); + $settings = mycred_get_addon_settings( 'coupons' ); - if (array_key_exists($code, $settings) ) { - $message = $settings[ $code ]; - } + if ( array_key_exists( $code, $settings ) ) + $message = $settings[ $code ]; - if ($code == 'min' && is_object($coupon) ) { + if ( $code == 'min' && is_object( $coupon ) ) { - $mycred = mycred($coupon->requires_min_type); - $message = str_replace(array( '%min%', '%amount%' ), $mycred->format_creds($coupon->requires_min['value']), $message); + $mycred = mycred( $coupon->requires_min_type ); + $message = str_replace( array( '%min%', '%amount%' ), $mycred->format_creds( $coupon->requires_min['value'] ), $message ); - } + } - elseif ($code == 'max' && is_object($coupon) ) { + elseif ( $code == 'max' && is_object( $coupon ) ) { - $mycred = mycred($coupon->requires_max_type); - $message = str_replace(array( '%max%', '%amount%' ), $mycred->format_creds($coupon->requires_max['value']), $message); + $mycred = mycred( $coupon->requires_max_type ); + $message = str_replace( array( '%max%', '%amount%' ), $mycred->format_creds( $coupon->requires_max['value'] ), $message ); - } + } - return apply_filters('mycred_coupon_error_message', $message, $code, $coupon); + return apply_filters( 'mycred_coupon_error_message', $message, $code, $coupon ); - } + } endif; /** * Get Users Coupon Count * Counts the number of times a user has used a given coupon. - * - * @filter mycred_get_users_coupon_count - * @since 1.4 + * @filter mycred_get_users_coupon_count + * @since 1.4 * @version 1.0 */ -if (! function_exists('mycred_get_users_coupon_count') ) : - function mycred_get_users_coupon_count( $code = '', $user_id = '' ) - { +if ( ! function_exists( 'mycred_get_users_coupon_count' ) ) : + function mycred_get_users_coupon_count( $code = '', $user_id = '' ) { - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - // Count how many times a given user has used a given coupon - $result = $wpdb->get_var( - $wpdb->prepare( - " + // Count how many times a given user has used a given coupon + $result = $wpdb->get_var( $wpdb->prepare( " SELECT COUNT( * ) FROM {$mycred_log_table} WHERE ref = %s AND user_id = %d - AND data = %s;", 'coupon', $user_id, $code - ) - ); + AND data = %s;", 'coupon', $user_id, $code ) ); - return apply_filters('mycred_get_users_coupon_count', $result, $code, $user_id); + return apply_filters( 'mycred_get_users_coupon_count', $result, $code, $user_id ); - } + } endif; /** * Get Coupons Global Count - * - * @filter mycred_get_global_coupon_count - * @since 1.4 + * @filter mycred_get_global_coupon_count + * @since 1.4 * @version 1.2 */ -if (! function_exists('mycred_get_global_coupon_count') ) : - function mycred_get_global_coupon_count( $coupon_id = 0 ) - { +if ( ! function_exists( 'mycred_get_global_coupon_count' ) ) : + function mycred_get_global_coupon_count( $coupon_id = 0 ) { - $coupon = mycred_get_coupon($coupon_id); - if ($coupon === false ) { return 0; - } + $coupon = mycred_get_coupon( $coupon_id ); + if ( $coupon === false ) return 0; - return $coupon->get_usage_count(); + return $coupon->get_usage_count(); - } + } endif; /** * Get Coupons Minimum Balance Requirement - * - * @filter mycred_coupon_min_balance - * @since 1.4 + * @filter mycred_coupon_min_balance + * @since 1.4 * @version 1.1.1 */ -if (! function_exists('mycred_get_coupon_min_balance') ) : - function mycred_get_coupon_min_balance( $post_id = 0 ) - { - - $type = mycred_get_post_meta($post_id, 'min_balance_type', true); - if (! mycred_point_type_exists($type) ) { $type = MYCRED_DEFAULT_TYPE_KEY; - } - - $min = mycred_get_post_meta($post_id, 'min_balance', true); - if ($min == '' ) { $min = 0; - } - - return apply_filters( - 'mycred_coupon_min_balance', array( - 'type' => $type, - 'value' => $min - ), $post_id - ); - - } +if ( ! function_exists( 'mycred_get_coupon_min_balance' ) ) : + function mycred_get_coupon_min_balance( $post_id = 0 ) { + + $type = mycred_get_post_meta( $post_id, 'min_balance_type', true ); + if ( ! mycred_point_type_exists( $type ) ) $type = MYCRED_DEFAULT_TYPE_KEY; + + $min = mycred_get_post_meta( $post_id, 'min_balance', true ); + if ( $min == '' ) $min = 0; + + return apply_filters( 'mycred_coupon_min_balance', array( + 'type' => $type, + 'value' => $min + ), $post_id ); + + } endif; /** * Get Coupons Maximum Balance Requirement - * - * @filter mycred_coupon_max_balance - * @since 1.4 + * @filter mycred_coupon_max_balance + * @since 1.4 * @version 1.1.1 */ -if (! function_exists('mycred_get_coupon_max_balance') ) : - function mycred_get_coupon_max_balance( $post_id = 0 ) - { - - $type = mycred_get_post_meta($post_id, 'max_balance_type', true); - if (! mycred_point_type_exists($type) ) { $type = MYCRED_DEFAULT_TYPE_KEY; - } - - $max = mycred_get_post_meta($post_id, 'max_balance', true); - if ($max == '' ) { $max = 0; - } - - return apply_filters( - 'mycred_coupon_max_balance', array( - 'type' => $type, - 'value' => $max - ), $post_id - ); - - } +if ( ! function_exists( 'mycred_get_coupon_max_balance' ) ) : + function mycred_get_coupon_max_balance( $post_id = 0 ) { + + $type = mycred_get_post_meta( $post_id, 'max_balance_type', true ); + if ( ! mycred_point_type_exists( $type ) ) $type = MYCRED_DEFAULT_TYPE_KEY; + + $max = mycred_get_post_meta( $post_id, 'max_balance', true ); + if ( $max == '' ) $max = 0; + + return apply_filters( 'mycred_coupon_max_balance', array( + 'type' => $type, + 'value' => $max + ), $post_id ); + + } endif; diff --git a/addons/coupons/includes/mycred-coupon-object.php b/addons/coupons/includes/mycred-coupon-object.php index dc6e178..603f080 100644 --- a/addons/coupons/includes/mycred-coupon-object.php +++ b/addons/coupons/includes/mycred-coupon-object.php @@ -1,408 +1,376 @@ post_type == MYCRED_COUPON_KEY ) { - $coupon_id = $coupon->ID; - $coupon_code = $coupon->post_title; - } - - } - - // If we provide the post ID - else { - - $coupon_id = absint($coupon_id); - if (mycred_get_post_type($coupon_id) != MYCRED_COUPON_KEY ) { - $coupon_id = 0; - } - - } - - if ($coupon_id === 0 ) { return false; - } - - $this->populate($coupon_id, $coupon_code); - - } - - /** - * Populate - * - * @since 1.0 - * @version 1.0 - */ - protected function populate( $coupon_id = null, $code = '' ) - { - - $this->post_id = absint($coupon_id); - $this->coupon_code = ( $code == '' ) ? mycred_get_the_title($this->post_id) : $code; - $this->code = $this->coupon_code; - - $this->value = mycred_get_coupon_value($this->post_id); - $this->point_type = mycred_get_post_meta($this->post_id, 'type', true); - $this->max_global = mycred_get_coupon_global_max($this->post_id); - $this->max_user = mycred_get_coupon_user_max($this->post_id); - - $this->requires_min = mycred_get_coupon_min_balance($this->post_id); - $this->requires_min_type = $this->requires_min['type']; + /** + * Usage count + */ + public $used = 0; - $this->requires_max = mycred_get_coupon_max_balance($this->post_id); - $this->requires_max_type = $this->requires_max['type']; + /** + * If coupon expires + */ + public $expires = false; - $this->used = $this->get_usage_count(); - $this->enabled_disabled = mycred_get_post_meta($this->post_id, 'check', true); - $this->rewards = mycred_get_post_meta($this->post_id, 'reward', true); + /** + * Expiraion UNIX timestamp + */ + public $expires_unix = 0; - if (! mycred_point_type_exists($this->point_type) ) { - $this->point_type = MYCRED_DEFAULT_TYPE_KEY; - } + /** + * Check badges/ranks + */ + public $enabled_disabled = ''; - if (! mycred_point_type_exists($this->requires_min_type) ) { - $this->requires_min_type = MYCRED_DEFAULT_TYPE_KEY; - } + /** + * Assign badges/ranks rewards + */ + public $rewards = 0; - if (! mycred_point_type_exists($this->requires_max_type) ) { - $this->requires_max_type = MYCRED_DEFAULT_TYPE_KEY; - } + /** + * Construct + */ + function __construct( $coupon_id = NULL ) { - $this->expires = mycred_get_coupon_expire_date($this->post_id); - $this->expires_unix = false; + parent::__construct(); - // If there is an expiration date - if ($this->expires !== false ) { + $coupon_code = ''; - $this->expires_unix = ( strtotime($this->expires . ' midnight') + ( DAY_IN_SECONDS - 1 ) ); + // If we provide the coupon code + if ( ! is_numeric( $coupon_id ) ) { - // Ill formatted expiration date. Not using a format strtotime() understands - // Prevent expiration and warn user when editing the coupon - if ($this->expires_unix <= 0 || $this->expires_unix === false ) { + $coupon_id = 0; + $coupon = mycred_get_coupon_post( $coupon_id ); + if ( $coupon !== NULL && $coupon->post_type == MYCRED_COUPON_KEY ) { + $coupon_id = $coupon->ID; + $coupon_code = $coupon->post_title; + } - $this->expires = false; + } - mycred_update_post_meta($this->post_id, '_warning_bad_expiration', $this->expires); - mycred_delete_post_meta($this->post_id, 'expires'); + // If we provide the post ID + else { - } + $coupon_id = absint( $coupon_id ); + if ( mycred_get_post_type( $coupon_id ) != MYCRED_COUPON_KEY ) + $coupon_id = 0; - } + } - $this->settings = shortcode_atts( - array( - 'log' => 'Coupon redemption', - 'invalid' => 'This is not a valid coupon', - 'expired' => 'This coupon has expired', - 'user_limit' => 'You have already used this coupon', - 'min' => 'A minimum of %amount% is required to use this coupon', - 'max' => 'A maximum of %amount% is required to use this coupon', - 'excluded' => 'You can not use coupons.', - 'success' => '%amount% successfully deposited into your account' - ), (array) mycred_get_addon_settings('coupons') - ); + if ( $coupon_id === 0 ) return false; - } + $this->populate( $coupon_id, $coupon_code ); - /** - * Get Usage Count - * - * @since 1.0 - * @version 1.0 - */ - public function get_usage_count() - { + } - $count = mycred_get_post_meta($this->post_id, 'usage-count', true); - if ($count == '' ) { + /** + * Populate + * @since 1.0 + * @version 1.0 + */ + protected function populate( $coupon_id = NULL, $code = '' ) { - global $wpdb, $mycred_log_table; + $this->post_id = absint( $coupon_id ); + $this->coupon_code = ( $code == '' ) ? mycred_get_the_title( $this->post_id ) : $code; + $this->code = $this->coupon_code; - $count = $wpdb->get_var( - $wpdb->prepare( - " + $this->value = mycred_get_coupon_value( $this->post_id ); + $this->point_type = mycred_get_post_meta( $this->post_id, 'type', true ); + $this->max_global = mycred_get_coupon_global_max( $this->post_id ); + $this->max_user = mycred_get_coupon_user_max( $this->post_id ); + + $this->requires_min = mycred_get_coupon_min_balance( $this->post_id ); + $this->requires_min_type = $this->requires_min['type']; + + $this->requires_max = mycred_get_coupon_max_balance( $this->post_id ); + $this->requires_max_type = $this->requires_max['type']; + + $this->used = $this->get_usage_count(); + $this->enabled_disabled = mycred_get_post_meta( $this->post_id, 'check', true ); + $this->rewards = mycred_get_post_meta( $this->post_id, 'reward', true ); + + if ( ! mycred_point_type_exists( $this->point_type ) ) + $this->point_type = MYCRED_DEFAULT_TYPE_KEY; + + if ( ! mycred_point_type_exists( $this->requires_min_type ) ) + $this->requires_min_type = MYCRED_DEFAULT_TYPE_KEY; + + if ( ! mycred_point_type_exists( $this->requires_max_type ) ) + $this->requires_max_type = MYCRED_DEFAULT_TYPE_KEY; + + $this->expires = mycred_get_coupon_expire_date( $this->post_id ); + $this->expires_unix = false; + + // If there is an expiration date + if ( $this->expires !== false ) { + + $this->expires_unix = ( strtotime( $this->expires . ' midnight' ) + ( DAY_IN_SECONDS - 1 ) ); + + // Ill formatted expiration date. Not using a format strtotime() understands + // Prevent expiration and warn user when editing the coupon + if ( $this->expires_unix <= 0 || $this->expires_unix === false ) { + + $this->expires = false; + + mycred_update_post_meta( $this->post_id, '_warning_bad_expiration', $this->expires ); + mycred_delete_post_meta( $this->post_id, 'expires' ); + + } + + } + + $this->settings = shortcode_atts( array( + 'log' => 'Coupon redemption', + 'invalid' => 'This is not a valid coupon', + 'expired' => 'This coupon has expired', + 'user_limit' => 'You have already used this coupon', + 'min' => 'A minimum of %amount% is required to use this coupon', + 'max' => 'A maximum of %amount% is required to use this coupon', + 'excluded' => 'You can not use coupons.', + 'success' => '%amount% successfully deposited into your account' + ), (array) mycred_get_addon_settings( 'coupons' ) ); + + } + + /** + * Get Usage Count + * @since 1.0 + * @version 1.0 + */ + public function get_usage_count() { + + $count = mycred_get_post_meta( $this->post_id, 'usage-count', true ); + if ( $count == '' ) { + + global $wpdb, $mycred_log_table; + + $count = $wpdb->get_var( $wpdb->prepare( " SELECT COUNT(*) FROM {$mycred_log_table} - WHERE ref = 'coupon' AND ref_id = %d AND ctype = %s;", $this->post_id, $this->point_type - ) - ); + WHERE ref = 'coupon' AND ref_id = %d AND ctype = %s;", $this->post_id, $this->point_type ) ); - if ($count === null ) { $count = 0; - } + if ( $count === NULL ) $count = 0; - mycred_update_post_meta($this->post_id, 'usage-count', $count); + mycred_update_post_meta( $this->post_id, 'usage-count', $count ); - } + } - return apply_filters('mycred_get_global_coupon_count', $count, $this->post_id, $this); + return apply_filters( 'mycred_get_global_coupon_count', $count, $this->post_id, $this ); - } + } - /** - * Update Usage Count - * - * @since 1.0 - * @version 1.0 - */ - public function update_usage_count() - { + /** + * Update Usage Count + * @since 1.0 + * @version 1.0 + */ + public function update_usage_count() { - $this->used ++; + $this->used ++; - mycred_update_post_meta($this->post_id, 'usage-count', $this->used); + mycred_update_post_meta( $this->post_id, 'usage-count', $this->used ); - } + } - /** - * Use Coupon - * - * @since 1.0 - * @version 1.0 - */ - public function use_coupon( $user_id = false ) - { + /** + * Use Coupon + * @since 1.0 + * @version 1.0 + */ + public function use_coupon( $user_id = false ) { - if ($this->post_id === false || $user_id === false ) { return 'invalid'; - } + if ( $this->post_id === false || $user_id === false ) return 'invalid'; - $can_use = true; - $now = current_time('timestamp'); + $can_use = true; + $now = current_time( 'timestamp' ); - // Check Expiration - if ($this->expires !== false && $this->expires_unix <= $now ) { - $can_use = 'expired'; - } + // Check Expiration + if ( $this->expires !== false && $this->expires_unix <= $now ) + $can_use = 'expired'; - // Get Global Count - if ($can_use === true ) { + // Get Global Count + if ( $can_use === true ) { - if ($this->used >= $this->max_global ) { - $can_use = 'expired'; - } + if ( $this->used >= $this->max_global ) + $can_use = 'expired'; - } + } - // Get User max - if ($can_use === true ) { + // Get User max + if ( $can_use === true ) { - $user_count = mycred_get_users_coupon_count($this->code, $user_id); - if ($user_count >= $this->max_user ) { - $can_use = 'user_limit'; - } + $user_count = mycred_get_users_coupon_count( $this->code, $user_id ); + if ( $user_count >= $this->max_user ) + $can_use = 'user_limit'; - } + } - $mycred = mycred($this->point_type); - if ($mycred->exclude_user($user_id) ) { return 'excluded'; - } + $mycred = mycred( $this->point_type ); + if ( $mycred->exclude_user( $user_id ) ) return 'excluded'; - $users_balance = $mycred->get_users_balance($user_id, $this->point_type); + $users_balance = $mycred->get_users_balance( $user_id, $this->point_type ); - if ($can_use === true ) { + if ( $can_use === true ) { - // Min balance requirement - if ($this->requires_min_type != $this->point_type ) { + // Min balance requirement + if ( $this->requires_min_type != $this->point_type ) { - $mycred_min = mycred($this->requires_min_type); - $users_balance = $mycred_min->get_users_balance($user_id, $this->requires_min_type); + $mycred_min = mycred( $this->requires_min_type ); + $users_balance = $mycred_min->get_users_balance( $user_id, $this->requires_min_type ); - } + } - if ($mycred->number($this->requires_min['value']) > $mycred->zero() && $users_balance < $mycred->number($this->requires_min['value']) ) { - $can_use = 'min'; - } + if ( $mycred->number( $this->requires_min['value'] ) > $mycred->zero() && $users_balance < $mycred->number( $this->requires_min['value'] ) ) + $can_use = 'min'; - // Max balance requirement - if ($can_use === true ) { + // Max balance requirement + if ( $can_use === true ) { - if ($this->requires_max_type != $this->point_type ) { + if ( $this->requires_max_type != $this->point_type ) { - $mycred_max = mycred($this->requires_max_type); - $users_balance = $mycred_max->get_users_balance($user_id, $this->requires_max_type); + $mycred_max = mycred( $this->requires_max_type ); + $users_balance = $mycred_max->get_users_balance( $user_id, $this->requires_max_type ); - } + } - if ($mycred->number($this->requires_max['value']) > $mycred->zero() && $users_balance >= $mycred->number($this->requires_max['value']) ) { - $can_use = 'max'; - } + if ( $mycred->number( $this->requires_max['value'] ) > $mycred->zero() && $users_balance >= $mycred->number( $this->requires_max['value'] ) ) + $can_use = 'max'; - } + } - } + } - // Let other play and change the value of $can_use - $can_use = apply_filters('mycred_can_use_coupon', $can_use, $this->code, $user_id, $this); + // Let other play and change the value of $can_use + $can_use = apply_filters( 'mycred_can_use_coupon', $can_use, $this->code, $user_id, $this ); - // Ready to use coupon! - if ($can_use === true ) { + // Ready to use coupon! + if ( $can_use === true ) { - $this->settings['log'] = str_replace('%coupon_code%', $this->code, $this->settings['log']); + $this->settings['log'] = str_replace( '%coupon_code%', $this->code, $this->settings['log'] ); - // Apply Coupon - $mycred->add_creds( - 'coupon', - $user_id, - $this->value, - $this->settings['log'], - $this->post_id, - $this->code, - $this->point_type - ); + // Apply Coupon + $mycred->add_creds( + 'coupon', + $user_id, + $this->value, + $this->settings['log'], + $this->post_id, + $this->code, + $this->point_type + ); - $enabled_disabled = $this->enabled_disabled; - $rewards = $this->rewards; - - if($enabled_disabled == 'on' ) { + $enabled_disabled = $this->enabled_disabled; + $rewards = $this->rewards; + + if( $enabled_disabled == 'on' ) { - if(! empty($rewards) ) { - - foreach ($rewards as $key => $value) { - - if(class_exists('myCRED_Badge') && $value['types'] == 'mycred_coupon_badges' ) { - mycred_assign_badge_to_user($user_id, $value['ids']); + if( ! empty ( $rewards ) ) { + + foreach ($rewards as $key => $value) { + + if( class_exists( 'myCRED_Badge' ) && $value['types'] == 'mycred_coupon_badges' ) { + mycred_assign_badge_to_user( $user_id, $value['ids'] ); - } + } - if(class_exists('myCRED_Ranks_Module') && $value['types'] == 'mycred_coupon_ranks' && mycred_manual_ranks($this->point_type) ) { - $ranks = new myCRED_Rank($value['ids']); - $ranks->assign($user_id); + if( class_exists( 'myCRED_Ranks_Module' ) && $value['types'] == 'mycred_coupon_ranks' && mycred_manual_ranks( $this->point_type ) ) { + $ranks = new myCRED_Rank( $value['ids'] ); + $ranks->assign($user_id); - } - } - } - } + } + } + } + } - do_action('mycred_use_coupon', $user_id, $this); + do_action( 'mycred_use_coupon', $user_id, $this ); - // Increment global counter - $this->update_usage_count(); + // Increment global counter + $this->update_usage_count(); - // If the updated counter reaches the max, trash the coupon now - if ($this->used >= $this->max_global ) { - mycred_trash_post($this->post_id); - } + // If the updated counter reaches the max, trash the coupon now + if ( $this->used >= $this->max_global ) + mycred_trash_post( $this->post_id ); - // This should resolves issues where caching prevents the new global count from being loaded. - else { + // This should resolves issues where caching prevents the new global count from being loaded. + else { - clean_post_cache($this->post_id); + clean_post_cache( $this->post_id ); - } + } - return $mycred->number($users_balance + $this->value); + return $mycred->number( $users_balance + $this->value ); - } + } - // Trash expired coupons to preent further usage - elseif ($can_use == 'expired' ) { + // Trash expired coupons to preent further usage + elseif ( $can_use == 'expired' ) { - mycred_trash_post($this->post_id); + mycred_trash_post( $this->post_id ); - } + } - return $can_use; + return $can_use; - } + } - } + } endif; diff --git a/addons/coupons/includes/mycred-coupon-shortcodes.php b/addons/coupons/includes/mycred-coupon-shortcodes.php index 94b902c..ef3d481 100644 --- a/addons/coupons/includes/mycred-coupon-shortcodes.php +++ b/addons/coupons/includes/mycred-coupon-shortcodes.php @@ -1,113 +1,102 @@ 'Coupon', - 'button' => 'Apply Coupon', - 'placeholder' => '' - ), $atts, MYCRED_SLUG . '_load_coupon' - ) - ); + extract( shortcode_atts( array( + 'label' => 'Coupon', + 'button' => 'Apply Coupon', + 'placeholder' => '' + ), $atts, MYCRED_SLUG . '_load_coupon' ) ); - $mycred = mycred(); - if (! isset($mycred->coupons) ) { - return '

    Coupon Add-on settings are missing! Please visit the myCRED > Settings page to save your settings before using this shortcode.

    '; - } + $mycred = mycred(); + if ( ! isset( $mycred->coupons ) ) + return '

    Coupon Add-on settings are missing! Please visit the myCRED > Settings page to save your settings before using this shortcode.

    '; - // Prep - $user_id = get_current_user_id(); + // Prep + $user_id = get_current_user_id(); - $output = '
    '; + $output = '
    '; - // On submits - if (isset($_POST['mycred_coupon_load']['token']) && wp_verify_nonce($_POST['mycred_coupon_load']['token'], 'mycred-load-coupon' . $user_id) ) { + // On submits + if ( isset( $_POST['mycred_coupon_load']['token'] ) && wp_verify_nonce( $_POST['mycred_coupon_load']['token'], 'mycred-load-coupon' . $user_id ) ) { - $coupon_code = sanitize_text_field($_POST['mycred_coupon_load']['couponkey']); - $coupon_post = mycred_get_coupon_post($coupon_code); - if (isset($coupon_post->ID) ) { + $coupon_code = sanitize_text_field( $_POST['mycred_coupon_load']['couponkey'] ); + $coupon_post = mycred_get_coupon_post( $coupon_code ); + if ( isset( $coupon_post->ID ) ) { - $coupon = mycred_get_coupon($coupon_post->ID); + $coupon = mycred_get_coupon( $coupon_post->ID ); - // Attempt to use this coupon - $load = mycred_use_coupon($coupon_code, $user_id); + // Attempt to use this coupon + $load = mycred_use_coupon( $coupon_code, $user_id ); - // Load myCRED in the type we are paying out for messages - if (isset($coupon->point_type) && $coupon->point_type != $mycred->cred_id ) { - $mycred = mycred($coupon->point_type); - } + // Load myCRED in the type we are paying out for messages + if ( isset( $coupon->point_type ) && $coupon->point_type != $mycred->cred_id ) + $mycred = mycred( $coupon->point_type ); - // That did not work out well, need to show an error message - if (! mycred_coupon_was_successfully_used($load) ) { + // That did not work out well, need to show an error message + if ( ! mycred_coupon_was_successfully_used( $load ) ) { - $message = mycred_get_coupon_error_message($load, $coupon); - $message = $mycred->template_tags_general($message); - $output .= '
    ' . $message . '
    '; + $message = mycred_get_coupon_error_message( $load, $coupon ); + $message = $mycred->template_tags_general( $message ); + $output .= '
    ' . $message . '
    '; - } + } - // Success! - else { + // Success! + else { - //$message = $mycred->template_tags_amount( $mycred->coupons['success'], $coupon->value ); - $updated_coupon_value=$coupon->value; - $updated_coupon_value=apply_filters('mycred_show_custom_coupon_value', $updated_coupon_value); - $coupon_settings = mycred_get_addon_settings('coupons', $coupon->point_type); - $message = $mycred->template_tags_amount($coupon_settings['success'], $updated_coupon_value); // without filter - $message = str_replace('%amount%', $mycred->format_creds($updated_coupon_value), $message); - $output .= '
    ' . $message . '
    '; + //$message = $mycred->template_tags_amount( $mycred->coupons['success'], $coupon->value ); + $updated_coupon_value=$coupon->value; + $updated_coupon_value=apply_filters('mycred_show_custom_coupon_value',$updated_coupon_value); + $coupon_settings = mycred_get_addon_settings( 'coupons' , $coupon->point_type ); + $message = $mycred->template_tags_amount( $coupon_settings['success'], $updated_coupon_value ); // without filter + $message = str_replace( '%amount%', $mycred->format_creds( $updated_coupon_value ), $message ); + $output .= '
    ' . $message . '
    '; - } + } - } + } - // Invalid coupon - else { + // Invalid coupon + else { - $message = mycred_get_coupon_error_message('invalid'); - $message = $mycred->template_tags_general($message); - $output .= '
    ' . $message . '
    '; + $message = mycred_get_coupon_error_message( 'invalid' ); + $message = $mycred->template_tags_general( $message ); + $output .= '
    ' . $message . '
    '; - } + } - } + } - if ($label != '' ) { - $label = ''; - } + if ( $label != '' ) + $label = ''; - $output .= ' + $output .= '
    ' . $label . ' - +
    - +
    '; - return apply_filters('mycred_load_coupon', $output, $atts, $content); + return apply_filters( 'mycred_load_coupon', $output, $atts, $content ); - } + } endif; diff --git a/addons/coupons/index.php b/addons/coupons/index.php index 1580272..4e6c07c 100644 --- a/addons/coupons/index.php +++ b/addons/coupons/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/coupons/myCRED-addon-coupons.php b/addons/coupons/myCRED-addon-coupons.php index 4716b47..9b70251 100644 --- a/addons/coupons/myCRED-addon-coupons.php +++ b/addons/coupons/myCRED-addon-coupons.php @@ -4,17 +4,15 @@ * Addon URI: http://codex.mycred.me/chapter-iii/coupons/ * Version: 1.4 */ -if (! defined('myCRED_VERSION') ) { exit; -} +if ( ! defined( 'myCRED_VERSION' ) ) exit; -define('myCRED_COUPONS', __FILE__); -define('myCRED_COUPONS_DIR', myCRED_ADDONS_DIR . 'coupons/'); -define('myCRED_COUPONS_VERSION', '1.3'); +define( 'myCRED_COUPONS', __FILE__ ); +define( 'myCRED_COUPONS_DIR', myCRED_ADDONS_DIR . 'coupons/' ); +define( 'myCRED_COUPONS_VERSION', '1.3' ); // Coupon Key -if (! defined('MYCRED_COUPON_KEY') ) { - define('MYCRED_COUPON_KEY', 'mycred_coupon'); -} +if ( ! defined( 'MYCRED_COUPON_KEY' ) ) + define( 'MYCRED_COUPON_KEY', 'mycred_coupon' ); require_once myCRED_COUPONS_DIR . 'includes/mycred-coupon-functions.php'; require_once myCRED_COUPONS_DIR . 'includes/mycred-coupon-object.php'; @@ -22,1164 +20,1077 @@ /** * myCRED_Coupons_Module class - * - * @since 1.4 + * @since 1.4 * @version 1.4 */ -if (! class_exists('myCRED_Coupons_Module') ) : - class myCRED_Coupons_Module extends myCRED_Module - { +if ( ! class_exists( 'myCRED_Coupons_Module' ) ) : + class myCRED_Coupons_Module extends myCRED_Module { + + /** + * Construct + */ + function __construct() { + + parent::__construct( 'myCRED_Coupons_Module', array( + 'module_name' => 'coupons', + 'defaults' => mycred_get_addon_defaults( 'coupons' ), + 'register' => false, + 'add_to_core' => true, + 'menu_pos' => 90 + ) ); + + add_filter( 'mycred_parse_log_entry_coupon', array( $this, 'parse_log_entry' ), 10, 2 ); + + } + + /** + * Hook into Init + * @since 1.4 + * @version 1.0 + */ + public function module_init() { + + $this->register_coupons(); + + add_shortcode( MYCRED_SLUG . '_load_coupon', 'mycred_render_shortcode_load_coupon' ); + + add_action( 'mycred_add_menu', array( $this, 'add_to_menu' ), $this->menu_pos ); + add_action( 'admin_notices', array( $this, 'warn_bad_expiration' ), $this->menu_pos ); + add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) ); + + } + + /** + * Hook into Admin Init + * @since 1.4 + * @version 1.1 + */ + public function module_admin_init() { + + add_filter( 'post_updated_messages', array( $this, 'post_updated_messages' ) ); + + add_filter( 'parent_file', array( $this, 'parent_file' ) ); + add_filter( 'submenu_file', array( $this, 'subparent_file' ), 10, 2 ); + + add_filter( 'enter_title_here', array( $this, 'enter_title_here' ) ); + add_filter( 'post_row_actions', array( $this, 'adjust_row_actions' ), 10, 2 ); + + add_action( 'admin_head-post.php', array( $this, 'edit_coupons_style' ) ); + add_action( 'admin_head-post-new.php', array( $this, 'edit_coupons_style' ) ); + add_action( 'admin_head-edit.php', array( $this, 'coupon_style' ) ); + + add_filter( 'manage_' . MYCRED_COUPON_KEY . '_posts_columns', array( $this, 'adjust_column_headers' ) ); + add_action( 'manage_' . MYCRED_COUPON_KEY . '_posts_custom_column', array( $this, 'adjust_column_content' ), 10, 2 ); + add_filter( 'bulk_actions-edit-' . MYCRED_COUPON_KEY, array( $this, 'bulk_actions' ) ); + add_action( 'save_post_' . MYCRED_COUPON_KEY, array( $this, 'save_coupon' ), 10, 2 ); + + //AJAX + add_action( 'wp_ajax_mycred_change_dropdown', array( $this, 'mycred_change_dropdown_ajax_handler' ) ); + + } + + /** + * Register Coupons Post Type + * @since 1.4 + * @version 1.0.2 + */ + protected function register_coupons() { + + $labels = array( + 'name' => __( 'Coupons', 'mycred' ), + 'singular_name' => __( 'Coupon', 'mycred' ), + 'add_new' => __( 'Create New', 'mycred' ), + 'add_new_item' => __( 'Create New', 'mycred' ), + 'edit_item' => __( 'Edit Coupon', 'mycred' ), + 'new_item' => __( 'New Coupon', 'mycred' ), + 'all_items' => __( 'Coupons', 'mycred' ), + 'view_item' => '', + 'search_items' => __( 'Search coupons', 'mycred' ), + 'not_found' => __( 'No coupons found', 'mycred' ), + 'not_found_in_trash' => __( 'No coupons found in Trash', 'mycred' ), + 'parent_item_colon' => '', + 'menu_name' => __( 'Email Notices', 'mycred' ) + ); + $args = array( + 'labels' => $labels, + 'supports' => array( 'title' ), + 'hierarchical' => false, + 'public' => false, + 'show_ui' => true, + 'show_in_menu' => false, + 'show_in_nav_menus' => false, + 'show_in_admin_bar' => false, + 'can_export' => true, + 'has_archive' => false, + 'exclude_from_search' => true, + 'publicly_queryable' => false, + 'register_meta_box_cb' => array( $this, 'add_metaboxes' ) + ); + + register_post_type( MYCRED_COUPON_KEY, apply_filters( 'mycred_register_coupons', $args ) ); + + } + + /** + * Adjust Update Messages + * @since 1.4 + * @version 1.0.2 + */ + public function post_updated_messages( $messages ) { + + $messages[ MYCRED_COUPON_KEY ] = array( + 0 => '', + 1 => __( 'Coupon updated.', 'mycred' ), + 2 => __( 'Coupon updated.', 'mycred' ), + 3 => __( 'Coupon updated.', 'mycred' ), + 4 => __( 'Coupon updated.', 'mycred' ), + 5 => false, + 6 => __( 'Coupon published.', 'mycred' ), + 7 => __( 'Coupon updated.', 'mycred' ), + 8 => __( 'Coupon updated.', 'mycred' ), + 9 => __( 'Coupon updated.', 'mycred' ), + 10 => __( 'Coupon updated.', 'mycred' ), + ); + + return $messages; + + } + + /** + * Add Admin Menu Item + * @since 1.7 + * @version 1.1 + */ + public function add_to_menu() { + + // In case we are using the Master Template feautre on multisites, and this is not the main + // site in the network, bail. + if ( mycred_override_settings() && ! mycred_is_main_site() ) return; + + mycred_add_main_submenu( + __( 'Coupons', 'mycred' ), + __( 'Coupons', 'mycred' ), + $this->core->get_point_editor_capability(), + 'edit.php?post_type=' . MYCRED_COUPON_KEY + ); + + } + + /** + * Parent File + * @since 1.7 + * @version 1.0.2 + */ + public function parent_file( $parent = '' ) { + + global $pagenow; + + if ( isset( $_GET['post'] ) && mycred_get_post_type( $_GET['post'] ) == MYCRED_COUPON_KEY && isset( $_GET['action'] ) && $_GET['action'] == 'edit' ) + return MYCRED_MAIN_SLUG; + + if ( $pagenow == 'post-new.php' && isset( $_GET['post_type'] ) && $_GET['post_type'] == MYCRED_COUPON_KEY ) + return MYCRED_MAIN_SLUG; + + return $parent; - /** - * Construct - */ - function __construct() - { - - parent::__construct( - 'myCRED_Coupons_Module', array( - 'module_name' => 'coupons', - 'defaults' => mycred_get_addon_defaults('coupons'), - 'register' => false, - 'add_to_core' => true, - 'menu_pos' => 90 - ) - ); - - add_filter('mycred_parse_log_entry_coupon', array( $this, 'parse_log_entry' ), 10, 2); - - } - - /** - * Hook into Init - * - * @since 1.4 - * @version 1.0 - */ - public function module_init() - { - - $this->register_coupons(); - - add_shortcode(MYCRED_SLUG . '_load_coupon', 'mycred_render_shortcode_load_coupon'); - - add_action('mycred_add_menu', array( $this, 'add_to_menu' ), $this->menu_pos); - add_action('admin_notices', array( $this, 'warn_bad_expiration' ), $this->menu_pos); - add_action('admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' )); - - } - - /** - * Hook into Admin Init - * - * @since 1.4 - * @version 1.1 - */ - public function module_admin_init() - { - - add_filter('post_updated_messages', array( $this, 'post_updated_messages' )); - - add_filter('parent_file', array( $this, 'parent_file' )); - add_filter('submenu_file', array( $this, 'subparent_file' ), 10, 2); - - add_filter('enter_title_here', array( $this, 'enter_title_here' )); - add_filter('post_row_actions', array( $this, 'adjust_row_actions' ), 10, 2); - - add_action('admin_head-post.php', array( $this, 'edit_coupons_style' )); - add_action('admin_head-post-new.php', array( $this, 'edit_coupons_style' )); - add_action('admin_head-edit.php', array( $this, 'coupon_style' )); - - add_filter('manage_' . MYCRED_COUPON_KEY . '_posts_columns', array( $this, 'adjust_column_headers' )); - add_action('manage_' . MYCRED_COUPON_KEY . '_posts_custom_column', array( $this, 'adjust_column_content' ), 10, 2); - add_filter('bulk_actions-edit-' . MYCRED_COUPON_KEY, array( $this, 'bulk_actions' )); - add_action('save_post_' . MYCRED_COUPON_KEY, array( $this, 'save_coupon' ), 10, 2); - - //AJAX - add_action('wp_ajax_mycred_change_dropdown', array( $this, 'mycred_change_dropdown_ajax_handler' )); - - } - - /** - * Register Coupons Post Type - * - * @since 1.4 - * @version 1.0.2 - */ - protected function register_coupons() - { - - $labels = array( - 'name' => __('Coupons', 'mycred'), - 'singular_name' => __('Coupon', 'mycred'), - 'add_new' => __('Create New', 'mycred'), - 'add_new_item' => __('Create New', 'mycred'), - 'edit_item' => __('Edit Coupon', 'mycred'), - 'new_item' => __('New Coupon', 'mycred'), - 'all_items' => __('Coupons', 'mycred'), - 'view_item' => '', - 'search_items' => __('Search coupons', 'mycred'), - 'not_found' => __('No coupons found', 'mycred'), - 'not_found_in_trash' => __('No coupons found in Trash', 'mycred'), - 'parent_item_colon' => '', - 'menu_name' => __('Email Notices', 'mycred') - ); - $args = array( - 'labels' => $labels, - 'supports' => array( 'title' ), - 'hierarchical' => false, - 'public' => false, - 'show_ui' => true, - 'show_in_menu' => false, - 'show_in_nav_menus' => false, - 'show_in_admin_bar' => false, - 'can_export' => true, - 'has_archive' => false, - 'exclude_from_search' => true, - 'publicly_queryable' => false, - 'register_meta_box_cb' => array( $this, 'add_metaboxes' ) - ); - - register_post_type(MYCRED_COUPON_KEY, apply_filters('mycred_register_coupons', $args)); - - } - - /** - * Adjust Update Messages - * - * @since 1.4 - * @version 1.0.2 - */ - public function post_updated_messages( $messages ) - { - - $messages[ MYCRED_COUPON_KEY ] = array( - 0 => '', - 1 => __('Coupon updated.', 'mycred'), - 2 => __('Coupon updated.', 'mycred'), - 3 => __('Coupon updated.', 'mycred'), - 4 => __('Coupon updated.', 'mycred'), - 5 => false, - 6 => __('Coupon published.', 'mycred'), - 7 => __('Coupon updated.', 'mycred'), - 8 => __('Coupon updated.', 'mycred'), - 9 => __('Coupon updated.', 'mycred'), - 10 => __('Coupon updated.', 'mycred'), - ); - - return $messages; - - } - - /** - * Add Admin Menu Item - * - * @since 1.7 - * @version 1.1 - */ - public function add_to_menu() - { - - // In case we are using the Master Template feautre on multisites, and this is not the main - // site in the network, bail. - if (mycred_override_settings() && ! mycred_is_main_site() ) { return; - } - - mycred_add_main_submenu( - __('Coupons', 'mycred'), - __('Coupons', 'mycred'), - $this->core->get_point_editor_capability(), - 'edit.php?post_type=' . MYCRED_COUPON_KEY - ); - - } - - /** - * Parent File - * - * @since 1.7 - * @version 1.0.2 - */ - public function parent_file( $parent = '' ) - { - - global $pagenow; - - if (isset($_GET['post']) && mycred_get_post_type($_GET['post']) == MYCRED_COUPON_KEY && isset($_GET['action']) && $_GET['action'] == 'edit' ) { - return MYCRED_MAIN_SLUG; - } - - if ($pagenow == 'post-new.php' && isset($_GET['post_type']) && $_GET['post_type'] == MYCRED_COUPON_KEY ) { - return MYCRED_MAIN_SLUG; - } - - return $parent; - - } + } - /** - * Sub Parent File - * - * @since 1.7 - * @version 1.0.1 - */ - public function subparent_file( $subparent = '', $parent = '' ) - { + /** + * Sub Parent File + * @since 1.7 + * @version 1.0.1 + */ + public function subparent_file( $subparent = '', $parent = '' ) { - global $pagenow; + global $pagenow; - if (( $pagenow == 'edit.php' || $pagenow == 'post-new.php' ) && isset($_GET['post_type']) && $_GET['post_type'] == MYCRED_COUPON_KEY ) { + if ( ( $pagenow == 'edit.php' || $pagenow == 'post-new.php' ) && isset( $_GET['post_type'] ) && $_GET['post_type'] == MYCRED_COUPON_KEY ) { - return 'edit.php?post_type=' . MYCRED_COUPON_KEY; - - } + return 'edit.php?post_type=' . MYCRED_COUPON_KEY; + + } - elseif ($pagenow == 'post.php' && isset($_GET['post']) && get_post_type($_GET['post']) == MYCRED_COUPON_KEY ) { + elseif ( $pagenow == 'post.php' && isset( $_GET['post'] ) && get_post_type( $_GET['post'] ) == MYCRED_COUPON_KEY ) { - return 'edit.php?post_type=' . MYCRED_COUPON_KEY; + return 'edit.php?post_type=' . MYCRED_COUPON_KEY; - } + } - return $subparent; + return $subparent; - } + } - /** - * Adjust Enter Title Here - * - * @since 1.4 - * @version 1.0.1 - */ - public function enter_title_here( $title ) - { + /** + * Adjust Enter Title Here + * @since 1.4 + * @version 1.0.1 + */ + public function enter_title_here( $title ) { - global $post_type; + global $post_type; - if ($post_type == MYCRED_COUPON_KEY ) { - return __('Coupon Code', 'mycred'); - } + if ( $post_type == MYCRED_COUPON_KEY ) + return __( 'Coupon Code', 'mycred' ); - return $title; + return $title; - } + } - /** - * Adjust Column Header - * - * @since 1.4 - * @version 1.1 - */ - public function adjust_column_headers( $defaults ) - { + /** + * Adjust Column Header + * @since 1.4 + * @version 1.1 + */ + public function adjust_column_headers( $defaults ) { - $columns = array(); - $columns['cb'] = $defaults['cb']; + $columns = array(); + $columns['cb'] = $defaults['cb']; - // Add / Adjust - $columns['title'] = __('Coupon Code', 'mycred'); - $columns['value'] = __('Value', 'mycred'); - $columns['usage'] = __('Used', 'mycred'); - $columns['limits'] = __('Limits', 'mycred'); - $columns['expires'] = __('Expires', 'mycred'); + // Add / Adjust + $columns['title'] = __( 'Coupon Code', 'mycred' ); + $columns['value'] = __( 'Value', 'mycred' ); + $columns['usage'] = __( 'Used', 'mycred' ); + $columns['limits'] = __( 'Limits', 'mycred' ); + $columns['expires'] = __( 'Expires', 'mycred' ); - if (count($this->point_types) > 1 ) { - $columns['ctype'] = __('Point Type', 'mycred'); - } + if ( count( $this->point_types ) > 1 ) + $columns['ctype'] = __( 'Point Type', 'mycred' ); - return $columns; + return $columns; - } + } - /** - * Adjust Column Body - * - * @since 1.4 - * @version 1.1.3 - */ - public function adjust_column_content( $column_name, $post_id ) - { + /** + * Adjust Column Body + * @since 1.4 + * @version 1.1.3 + */ + public function adjust_column_content( $column_name, $post_id ) { - $coupon = mycred_get_coupon($post_id); + $coupon = mycred_get_coupon( $post_id ); - switch ( $column_name ) { + switch ( $column_name ) { - case 'value' : + case 'value' : - $mycred = mycred($coupon->point_type); + $mycred = mycred( $coupon->point_type ); - echo $mycred->format_creds($coupon->value); + echo $mycred->format_creds( $coupon->value ); - break; + break; - case 'usage' : + case 'usage' : - if ($coupon->used == 0 ) { - echo '-'; + if ( $coupon->used == 0 ) + echo '-'; - } else { + else { - $set_type = $coupon->point_type; - $page = MYCRED_SLUG; + $set_type = $coupon->point_type; + $page = MYCRED_SLUG; - if ($set_type != MYCRED_DEFAULT_TYPE_KEY && array_key_exists($set_type, $this->point_types) ) { - $page .= '_' . $set_type; - } + if ( $set_type != MYCRED_DEFAULT_TYPE_KEY && array_key_exists( $set_type, $this->point_types ) ) + $page .= '_' . $set_type; - $url = add_query_arg(array( 'page' => $page, 'ref' => 'coupon', 'ref_id' => $post_id ), admin_url('admin.php')); - echo '' . sprintf(_n('1 time', '%d times', $coupon->used, 'mycred'), $coupon->used) . ''; + $url = add_query_arg( array( 'page' => $page, 'ref' => 'coupon', 'ref_id' => $post_id ), admin_url( 'admin.php' ) ); + echo '' . sprintf( _n( '1 time', '%d times', $coupon->used, 'mycred' ), $coupon->used ) . ''; - } + } - break; + break; - case 'limits' : + case 'limits' : - printf('%1$s: %2$d
    %3$s: %4$d', __('Total', 'mycred'), $coupon->max_global, __('Per User', 'mycred'), $coupon->max_user); + printf( '%1$s: %2$d
    %3$s: %4$d', __( 'Total', 'mycred' ), $coupon->max_global, __( 'Per User', 'mycred' ), $coupon->max_user ); - break; + break; - case 'expires' : + case 'expires' : - if ($coupon->expires === false ) { - echo '-'; + if ( $coupon->expires === false ) + echo '-'; - } else { + else { - if ($coupon->expires_unix < current_time('timestamp') ) { + if ( $coupon->expires_unix < current_time( 'timestamp' ) ) { - mycred_trash_post($post_id); + mycred_trash_post( $post_id ); - echo '' . __('Expired', 'mycred') . ''; + echo '' . __( 'Expired', 'mycred' ) . ''; - } + } - else { + else { - echo sprintf(__('In %s time', 'mycred'), human_time_diff($coupon->expires_unix)) . '
    ' . date(get_option('date_format'), $coupon->expires_unix) . ''; + echo sprintf( __( 'In %s time', 'mycred' ), human_time_diff( $coupon->expires_unix ) ) . '
    ' . date( get_option( 'date_format' ), $coupon->expires_unix ) . ''; - } + } - } + } - break; + break; - case 'ctype' : + case 'ctype' : - if (isset($this->point_types[ $coupon->point_type ]) ) { - echo $this->point_types[ $coupon->point_type ]; + if ( isset( $this->point_types[ $coupon->point_type ] ) ) + echo $this->point_types[ $coupon->point_type ]; - } else { - echo '-'; - } + else + echo '-'; - break; + break; - } - } + } + } - /** - * Adjust Bulk Actions - * - * @since 1.7 - * @version 1.0 - */ - public function bulk_actions( $actions ) - { + /** + * Adjust Bulk Actions + * @since 1.7 + * @version 1.0 + */ + public function bulk_actions( $actions ) { - unset($actions['edit']); - return $actions; + unset( $actions['edit'] ); + return $actions; - } + } - /** - * Adjust Row Actions - * - * @since 1.4 - * @version 1.0.1 - */ - public function adjust_row_actions( $actions, $post ) - { + /** + * Adjust Row Actions + * @since 1.4 + * @version 1.0.1 + */ + public function adjust_row_actions( $actions, $post ) { - if ($post->post_type == MYCRED_COUPON_KEY ) { - unset($actions['inline hide-if-no-js']); - unset($actions['view']); - } + if ( $post->post_type == MYCRED_COUPON_KEY ) { + unset( $actions['inline hide-if-no-js'] ); + unset( $actions['view'] ); + } - return $actions; + return $actions; - } + } - /** - * Edit Coupon Style - * - * @since 1.7 - * @version 1.0.2 - */ - public function edit_coupons_style() - { + /** + * Edit Coupon Style + * @since 1.7 + * @version 1.0.2 + */ + public function edit_coupons_style() { - global $post_type; + global $post_type; - if ($post_type !== MYCRED_COUPON_KEY ) { return; - } + if ( $post_type !== MYCRED_COUPON_KEY ) return; - wp_enqueue_style('mycred-bootstrap-grid'); - wp_enqueue_style('mycred-forms'); - wp_enqueue_style(MYCRED_SLUG . '-buttons'); - add_filter('postbox_classes_' . MYCRED_COUPON_KEY . '_mycred-coupon-setup', array( $this, 'metabox_classes' )); - add_filter('postbox_classes_' . MYCRED_COUPON_KEY . '_mycred-coupon-limits', array( $this, 'metabox_classes' )); - add_filter('postbox_classes_' . MYCRED_COUPON_KEY . '_mycred-coupon-requirements', array( $this, 'metabox_classes' )); - add_filter('postbox_classes_' . MYCRED_COUPON_KEY . '_mycred-coupon-usage', array( $this, 'metabox_classes' )); + wp_enqueue_style( 'mycred-bootstrap-grid' ); + wp_enqueue_style( 'mycred-forms' ); + wp_enqueue_style( MYCRED_SLUG . '-buttons' ); + add_filter( 'postbox_classes_' . MYCRED_COUPON_KEY . '_mycred-coupon-setup', array( $this, 'metabox_classes' ) ); + add_filter( 'postbox_classes_' . MYCRED_COUPON_KEY . '_mycred-coupon-limits', array( $this, 'metabox_classes' ) ); + add_filter( 'postbox_classes_' . MYCRED_COUPON_KEY . '_mycred-coupon-requirements', array( $this, 'metabox_classes' ) ); + add_filter( 'postbox_classes_' . MYCRED_COUPON_KEY . '_mycred-coupon-usage', array( $this, 'metabox_classes' ) ); - echo ''; + echo ''; - } + } - /** - * Coupon Style - * - * @since 1.7 - * @version 1.0 - */ - public function coupon_style() - { + /** + * Coupon Style + * @since 1.7 + * @version 1.0 + */ + public function coupon_style() { - } + } - /** + /** * Enqueue Admin Script - * - * @since 2.4 + * @since 2.4 * @version 1.0 */ - public function enqueue_admin_scripts() - { + public function enqueue_admin_scripts() { - wp_register_style('mycred-coupon-badge-rank-style', plugins_url('assets/css/admin.css', myCRED_COUPONS), '', myCRED_COUPONS_VERSION); - wp_register_script('mycred-coupon-badge-rank-js', plugins_url('assets/js/admin.js', myCRED_COUPONS), array( 'jquery' ), myCRED_COUPONS_VERSION, true); + wp_register_style( 'mycred-coupon-badge-rank-style', plugins_url( 'assets/css/admin.css', myCRED_COUPONS ), '', myCRED_COUPONS_VERSION ); + wp_register_script( 'mycred-coupon-badge-rank-js', plugins_url( 'assets/js/admin.js', myCRED_COUPONS ), array( 'jquery' ), myCRED_COUPONS_VERSION, true ); } - /** - * Add Meta Boxes - * - * @since 1.4 - * @version 1.1.1 - */ - public function add_metaboxes( $post ) - { - - add_meta_box( - 'mycred-coupon-setup', - __('Coupon Setup', 'mycred'), - array( $this, 'metabox_coupon_setup' ), - MYCRED_COUPON_KEY, - 'normal', - 'core' - ); - - add_meta_box( - 'mycred-coupon-limits', - __('Coupon Limits', 'mycred'), - array( $this, 'metabox_coupon_limits' ), - MYCRED_COUPON_KEY, - 'normal', - 'core' - ); - - add_meta_box( - 'mycred-coupon-requirements', - __('Coupon Requirements', 'mycred'), - array( $this, 'mycred_coupon_requirements' ), - MYCRED_COUPON_KEY, - 'side', - 'core' - ); - - if(class_exists('myCRED_Badge') || class_exists('myCRED_Ranks_Module') ) { - add_meta_box( - 'mycred-coupon-badges-ranks', - __('Assign Badge/Ranks To Users', 'mycred'), - array( $this, 'mycred_coupon_badges_ranks' ), - MYCRED_COUPON_KEY, - 'advanced', - 'core' - ); - } - - if ($post->post_status == 'publish' ) { - add_meta_box( - 'mycred-coupon-usage', - __('Coupon Usage', 'mycred'), - array( $this, 'mycred_coupon_usage' ), - MYCRED_COUPON_KEY, - 'side', - 'core' - ); - } - - } - - /** - * Admin Notice - * If we are have an issue with the expiration date set for this coupon we need to warn the user. - * - * @since 1.7.5 - * @version 1.0.1 - */ - public function warn_bad_expiration() - { - - if (isset($_GET['post']) && isset($_GET['action']) && $_GET['action'] == 'edit' && get_post_type(absint($_GET['post'])) == MYCRED_COUPON_KEY ) { - - $post_id = absint($_GET['post']); - $expiration_warning = mycred_get_post_meta($post_id, '_warning_bad_expiration', true); - - if ($expiration_warning != '' ) { - - mycred_delete_post_meta($post_id, '_warning_bad_expiration'); - - echo '

    ' . __('Warning. The previous expiration date set for this coupon was formatted incorrectly and was deleted. If you still want the coupon to expire, please enter a new date or leave empty to disable.', 'mycred') . '

    '; - - } - - } - - } - - /** - * Metabox: Coupon Setup - * - * @since 1.4 - * @version 1.2.1 - */ - public function metabox_coupon_setup( $post ) - { - - $coupon = mycred_get_coupon($post->ID); - - if ($coupon->point_type != $this->core->cred_id ) { - $mycred = mycred($coupon->point_type); - } else { - $mycred = $this->core; - } - - ?> + /** + * Add Meta Boxes + * @since 1.4 + * @version 1.1.1 + */ + public function add_metaboxes( $post ) { + + add_meta_box( + 'mycred-coupon-setup', + __( 'Coupon Setup', 'mycred' ), + array( $this, 'metabox_coupon_setup' ), + MYCRED_COUPON_KEY, + 'normal', + 'core' + ); + + add_meta_box( + 'mycred-coupon-limits', + __( 'Coupon Limits', 'mycred' ), + array( $this, 'metabox_coupon_limits' ), + MYCRED_COUPON_KEY, + 'normal', + 'core' + ); + + add_meta_box( + 'mycred-coupon-requirements', + __( 'Coupon Requirements', 'mycred' ), + array( $this, 'mycred_coupon_requirements' ), + MYCRED_COUPON_KEY, + 'side', + 'core' + ); + + if( class_exists( 'myCRED_Badge' ) || class_exists( 'myCRED_Ranks_Module' ) ) { + add_meta_box( + 'mycred-coupon-badges-ranks', + __( 'Assign Badge/Ranks To Users', 'mycred' ), + array( $this, 'mycred_coupon_badges_ranks' ), + MYCRED_COUPON_KEY, + 'advanced', + 'core' + ); + } + + if ( $post->post_status == 'publish' ) + add_meta_box( + 'mycred-coupon-usage', + __( 'Coupon Usage', 'mycred' ), + array( $this, 'mycred_coupon_usage' ), + MYCRED_COUPON_KEY, + 'side', + 'core' + ); + + } + + /** + * Admin Notice + * If we are have an issue with the expiration date set for this coupon we need to warn the user. + * @since 1.7.5 + * @version 1.0.1 + */ + public function warn_bad_expiration() { + + if ( isset( $_GET['post'] ) && isset( $_GET['action'] ) && $_GET['action'] == 'edit' && get_post_type( absint( $_GET['post'] ) ) == MYCRED_COUPON_KEY ) { + + $post_id = absint( $_GET['post'] ); + $expiration_warning = mycred_get_post_meta( $post_id, '_warning_bad_expiration', true ); + + if ( $expiration_warning != '' ) { + + mycred_delete_post_meta( $post_id, '_warning_bad_expiration' ); + + echo '

    ' . __( 'Warning. The previous expiration date set for this coupon was formatted incorrectly and was deleted. If you still want the coupon to expire, please enter a new date or leave empty to disable.', 'mycred' ) . '

    '; + + } + + } + + } + + /** + * Metabox: Coupon Setup + * @since 1.4 + * @version 1.2.1 + */ + public function metabox_coupon_setup( $post ) { + + $coupon = mycred_get_coupon( $post->ID ); + + if ( $coupon->point_type != $this->core->cred_id ) + $mycred = mycred( $coupon->point_type ); + else + $mycred = $this->core; + +?>
    -
    -
    -
    - - - template_tags_general(__('The amount of %plural% a user receives when redeeming this coupon.', 'mycred')); ?> -
    -
    -
    -
    - - point_types) > 1 ) : ?> - - point_type, false, ' class="form-control"'); ?>
    - - - - -

    plural(); ?>

    - - - -
    -
    -
    -
    - - - -
    -
    -
    +
    +
    +
    + + + template_tags_general( __( 'The amount of %plural% a user receives when redeeming this coupon.', 'mycred' ) ); ?> +
    +
    +
    +
    + + point_types ) > 1 ) : ?> + + point_type, false, ' class="form-control"' ); ?>
    + + + + +

    plural(); ?>

    + + + +
    +
    +
    +
    + + + +
    +
    +
    - ID); + $coupon = mycred_get_coupon( $post->ID ); - if ($coupon->point_type != $this->core->cred_id ) { - $mycred = mycred($coupon->point_type); - } else { - $mycred = $this->core; - } + if ( $coupon->point_type != $this->core->cred_id ) + $mycred = mycred( $coupon->point_type ); + else + $mycred = $this->core; - ?> +?>
    -
    -
    -
    - - - Description', 'mycred'); ?> -
    -
    -
    -
    - - - -
    -
    -
    +
    +
    +
    + + + Description', 'mycred' ); ?> +
    +
    +
    +
    + + + +
    +
    +
    - ID); + $coupon = mycred_get_coupon( $post->ID ); - if ($coupon->point_type != $this->core->cred_id ) { - $mycred = mycred($coupon->point_type); - } else { - $mycred = $this->core; - } + if ( $coupon->point_type != $this->core->cred_id ) + $mycred = mycred( $coupon->point_type ); + else + $mycred = $this->core; - ?> +?>
    -
    -
    -
    - -
    - point_types) > 1 ) { echo 'size="8"'; -} else { echo ' style="width: 99%;"'; - } ?> id="mycred-coupon-min_balance" value="number($coupon->requires_min['value']); ?>" /> - requires_min_type, true, ' style="vertical-align: top;"'); ?> -
    - -
    -
    -
    -
    -
    -
    - -
    - point_types) > 1 ) { echo 'size="8"'; -} else { echo ' style="width: 99%;"'; - } ?> id="mycred-coupon-max_balance" value="number($coupon->requires_max['value']); ?>" /> - requires_max_type, true, ' style="vertical-align: top;"'); ?> -
    - -
    -
    -
    +
    +
    +
    + +
    + point_types ) > 1 ) echo 'size="8"'; else echo ' style="width: 99%;"'; ?> id="mycred-coupon-min_balance" value="number( $coupon->requires_min['value'] ); ?>" /> + requires_min_type, true, ' style="vertical-align: top;"' ); ?> +
    + +
    +
    +
    +
    +
    +
    + +
    + point_types ) > 1 ) echo 'size="8"'; else echo ' style="width: 99%;"'; ?> id="mycred-coupon-max_balance" value="number( $coupon->requires_max['value'] ); ?>" /> + requires_max_type, true, ' style="vertical-align: top;"' ); ?> +
    + +
    +
    +
    - ID, 'reward'); - $check_enable_disable = mycred_get_post_meta($post->ID, 'check', true); - $enable_disable = ! empty($check_enable_disable); - $coupon = mycred_get_coupon($post->ID); - $manual_rank = ''; - - if(class_exists('myCRED_Badge') ) { - $badge_id = mycred_get_badge_ids(); - } - if(class_exists('myCRED_Ranks_Module') ) { - $ranks = mycred_get_ranks(); - $manual_rank = mycred_manual_ranks($coupon->point_type); - } - ob_start(); ?> -
    -
    -
    -
    -
    -
    - -
    - -
    -
    -
    -
    - -
    -
    -
    -
    - -
    - -
    -
    -
    -
    -
    -
    - - - -
    -
    - - -
    -
    -
    > - $values ) { - echo $this->mycred_coupon_badge_rank_html($values['types'], $values['ids'], $manual_rank); - } - }else { - echo $html; - }?> - -
    -
    $html, - ) - ); - } - - public function mycred_coupon_badge_rank_html( $types, $ids, $manual_rank ) - { - - $selected_type = ''; - - if(class_exists('myCRED_Badge') ) { - $badge_id = mycred_get_badge_ids(); - } - if(class_exists('myCRED_Ranks_Module') ) { - $ranks = mycred_get_ranks(); - } - - ?> - -
    -
    -
    -
    -
    -
    - -
    - -
    -
    -
    - -
    - -
    -
    -
    -
    - -
    - - - -
    -
    -
    -
    -
    -
    $value) { - - $badges = mycred_get_badge($value); - $badge_title = $badges->title; - $badge_id = $value; - $ids_title[] = array( $badge_id, $badge_title ); - - } - - $ids_title = json_encode($ids_title); - - echo $ids_title; - wp_die(); - } - - if ($value == 'mycred_coupon_ranks' ) { - - $ids_title = array(); - foreach ($ranks as $key => $value) { - - $rank_title = $value->post->post_title; - $rank_id = $value->post_id; - $ids_title[] = array( $rank_id, $rank_title ); - - } - - $ids_title = json_encode($ids_title); - - echo $ids_title; - wp_die(); - } - + ID, 'reward' ); + $check_enable_disable = mycred_get_post_meta( $post->ID, 'check', true ); + $enable_disable = ! empty( $check_enable_disable ); + $coupon = mycred_get_coupon( $post->ID ); + $manual_rank = ''; + + if( class_exists( 'myCRED_Badge' ) ) { + $badge_id = mycred_get_badge_ids(); + } + if( class_exists( 'myCRED_Ranks_Module' ) ){ + $ranks = mycred_get_ranks(); + $manual_rank = mycred_manual_ranks( $coupon->point_type ); + } + ob_start(); ?> +
    +
    +
    +
    +
    +
    + +
    + +
    +
    +
    +
    + +
    +
    +
    +
    + +
    + +
    +
    +
    +
    +
    +
    + + + +
    +
    + + +
    +
    +
    > + $values ) { + echo $this->mycred_coupon_badge_rank_html( $values['types'], $values['ids'], $manual_rank ); + } + }else { + echo $html; + }?> + +
    +
    $html, + ) + ); + } + + public function mycred_coupon_badge_rank_html( $types, $ids, $manual_rank ){ + + $selected_type = ''; + + if( class_exists( 'myCRED_Badge' ) ) { + $badge_id = mycred_get_badge_ids(); + } + if( class_exists( 'myCRED_Ranks_Module' ) ){ + $ranks = mycred_get_ranks(); + } + + ?> + +
    +
    +
    +
    +
    +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    +
    + +
    + + + +
    +
    +
    +
    +
    +
    $value) { + + $badges = mycred_get_badge( $value ); + $badge_title = $badges->title; + $badge_id = $value; + $ids_title[] = array( $badge_id, $badge_title ); + + } + + $ids_title = json_encode( $ids_title ); + + echo $ids_title; + wp_die(); + } + + if ( $value == 'mycred_coupon_ranks' ){ + + $ids_title = array(); + foreach ($ranks as $key => $value) { + + $rank_title = $value->post->post_title; + $rank_id = $value->post_id; + $ids_title[] = array( $rank_id, $rank_title ); + + } + + $ids_title = json_encode( $ids_title ); + + echo $ids_title; + wp_die(); + } + } - /** - * Metabox: Coupon Usage - * - * @since 1.6 - * @version 1.0.1 - */ - public function mycred_coupon_usage( $post ) - { + /** + * Metabox: Coupon Usage + * @since 1.6 + * @version 1.0.1 + */ + public function mycred_coupon_usage( $post ) { - $count = mycred_get_global_coupon_count($post->ID); - if (empty($count) ) { - echo '-'; + $count = mycred_get_global_coupon_count( $post->ID ); + if ( empty( $count ) ) + echo '-'; - } else { + else { - $set_type = mycred_get_post_meta($post->ID, 'type', true); - $page = MYCRED_SLUG; + $set_type = mycred_get_post_meta( $post->ID, 'type', true ); + $page = MYCRED_SLUG; - if ($set_type != MYCRED_DEFAULT_TYPE_KEY && array_key_exists($set_type, $this->point_types) ) { - $page .= '_' . $set_type; - } + if ( $set_type != MYCRED_DEFAULT_TYPE_KEY && array_key_exists( $set_type, $this->point_types ) ) + $page .= '_' . $set_type; - $url = add_query_arg(array( 'page' => $page, 'ref' => 'coupon', 'data' => $post->post_title ), admin_url('admin.php')); - echo '' . sprintf(_n('1 time', '%d times', $count, 'mycred'), $count) . ''; + $url = add_query_arg( array( 'page' => $page, 'ref' => 'coupon', 'data' => $post->post_title ), admin_url( 'admin.php' ) ); + echo '' . sprintf( _n( '1 time', '%d times', $count, 'mycred' ), $count ) . ''; - } + } - } + } - /** - * Save Coupon - * - * @since 1.4 - * @version 1.0.1 - */ - public function save_coupon( $post_id, $post = null ) - { + /** + * Save Coupon + * @since 1.4 + * @version 1.0.1 + */ + public function save_coupon( $post_id, $post = NULL ) { - if ($post === null || ! $this->core->user_is_point_editor() || ! isset($_POST['mycred_coupon']) ) { return $post_id; - } - - if(! isset($_POST['mycred_coupon']['check']) ) { - $_POST['mycred_coupon']['check'] = false; - } + if ( $post === NULL || ! $this->core->user_is_point_editor() || ! isset( $_POST['mycred_coupon'] ) ) return $post_id; + + if( ! isset( $_POST['mycred_coupon']['check'] ) ){ + $_POST['mycred_coupon']['check'] = false; + } - foreach ( $_POST['mycred_coupon'] as $meta_key => $meta_value ) { + foreach ( $_POST['mycred_coupon'] as $meta_key => $meta_value ) { - if($meta_key == 'reward' ) { + if( $meta_key == 'reward' ){ - $types_ids = array(); - foreach ($meta_value['types'] as $key => $value) { - - $reward_value = sanitize_text_field($value); - $reward_id = sanitize_text_field($meta_value['ids'][$key]); + $types_ids = array(); + foreach ($meta_value['types'] as $key => $value) { + + $reward_value = sanitize_text_field( $value ); + $reward_id = sanitize_text_field( $meta_value['ids'][$key] ); - $types_ids[] = array( 'types' => $reward_value , 'ids' => $reward_id ) ; - - } + $types_ids[] = array( 'types' => $reward_value , 'ids' => $reward_id ) ; + + } - $new_value = $types_ids; - } - else{ + $new_value = $types_ids; + } + else{ - $new_value = sanitize_text_field($meta_value); - } + $new_value = sanitize_text_field( $meta_value ); + } - // Make sure we provide a valid date that strtotime() can understand - if ($meta_key == 'expires' && $new_value != '' ) { + // Make sure we provide a valid date that strtotime() can understand + if ( $meta_key == 'expires' && $new_value != '' ) { - // Always expires at midnight - $check = ( strtotime($new_value . ' midnight') + ( DAY_IN_SECONDS - 1 ) ); + // Always expires at midnight + $check = ( strtotime( $new_value . ' midnight' ) + ( DAY_IN_SECONDS - 1 ) ); - // Thats not good. Date is in the past? - if ($check === false || $check < current_time('timestamp') ) { - $new_value = ''; - } + // Thats not good. Date is in the past? + if ( $check === false || $check < current_time( 'timestamp' ) ) + $new_value = ''; - } + } - // No need to update if it's still the same value - $old_value = mycred_get_post_meta($post_id, $meta_key, true); + // No need to update if it's still the same value + $old_value = mycred_get_post_meta( $post_id, $meta_key, true ); - if ($new_value != $old_value ) { - mycred_update_post_meta($post_id, $meta_key, $new_value); - } - } + if ( $new_value != $old_value ) + mycred_update_post_meta( $post_id, $meta_key, $new_value ); + } - } + } - /** - * Add to General Settings - * - * @since 1.4 - * @version 1.1 - */ - public function after_general_settings( $mycred = null ) - { + /** + * Add to General Settings + * @since 1.4 + * @version 1.1 + */ + public function after_general_settings( $mycred = NULL ) { - if (! isset($this->coupons) ) { - $prefs = $this->default_prefs; - } else { - $prefs = mycred_apply_defaults($this->default_prefs, $this->coupons); - } + if ( ! isset( $this->coupons ) ) + $prefs = $this->default_prefs; + else + $prefs = mycred_apply_defaults( $this->default_prefs, $this->coupons ); - ?> -

    +?> +

    - data, $content); + return str_replace( '%coupon%', $log_entry->data, $content ); - } + } - } + } endif; /** * Load Coupons Module - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_load_coupons_addon') ) : - function mycred_load_coupons_addon( $modules, $point_types ) - { +if ( ! function_exists( 'mycred_load_coupons_addon' ) ) : + function mycred_load_coupons_addon( $modules, $point_types ) { - $modules['solo']['coupons'] = new myCRED_Coupons_Module(); - $modules['solo']['coupons']->load(); + $modules['solo']['coupons'] = new myCRED_Coupons_Module(); + $modules['solo']['coupons']->load(); - return $modules; + return $modules; - } + } endif; -add_filter('mycred_load_modules', 'mycred_load_coupons_addon', 50, 2); +add_filter( 'mycred_load_modules', 'mycred_load_coupons_addon', 50, 2 ); diff --git a/addons/email-notices/assets/css/index.php b/addons/email-notices/assets/css/index.php index 1580272..4e6c07c 100644 --- a/addons/email-notices/assets/css/index.php +++ b/addons/email-notices/assets/css/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/email-notices/assets/index.php b/addons/email-notices/assets/index.php index 1580272..4e6c07c 100644 --- a/addons/email-notices/assets/index.php +++ b/addons/email-notices/assets/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/email-notices/assets/js/edit-email.js b/addons/email-notices/assets/js/edit-email.js index 746bf81..32b55bf 100644 --- a/addons/email-notices/assets/js/edit-email.js +++ b/addons/email-notices/assets/js/edit-email.js @@ -1,50 +1,42 @@ -jQuery( - function ($) { +jQuery(function($){ - $(document).ready( - function () { + $(document).ready(function(){ - $('select#mycred-email-instance').change( - function (e) { + $( 'select#mycred-email-instance' ).change(function(e){ - var selectedevent = $(this).find(':selected'); - console.log(selectedevent.val()); - if (selectedevent.val() == 'custom' ) { + var selectedevent = $(this).find( ':selected' ); + console.log( selectedevent.val() ); + if ( selectedevent.val() == 'custom' ) { - $('#reference-selection').show(); + $( '#reference-selection' ).show(); - } - else { + } + else { - $('#reference-selection').hide(); + $( '#reference-selection' ).hide(); - } + } - } - ); + }); - $('select#mycred-email-reference').change( - function (e) { + $( 'select#mycred-email-reference' ).change(function(e){ - var selectedevent = $(this).find(':selected'); - if (selectedevent.val() == 'mycred_custom' ) { + var selectedevent = $(this).find( ':selected' ); + if ( selectedevent.val() == 'mycred_custom' ) { - $('#custom-reference-selection').show(); - $('#mycred-email-custom-ref').focus(); + $( '#custom-reference-selection' ).show(); + $( '#mycred-email-custom-ref' ).focus(); - } - else { + } + else { - $('#custom-reference-selection').hide(); - $('#mycred-email-custom-ref').blur(); + $( '#custom-reference-selection' ).hide(); + $( '#mycred-email-custom-ref' ).blur(); - } + } - } - ); + }); - } - ); + }); - } -); \ No newline at end of file +}); \ No newline at end of file diff --git a/addons/email-notices/assets/js/index.php b/addons/email-notices/assets/js/index.php index 1580272..4e6c07c 100644 --- a/addons/email-notices/assets/js/index.php +++ b/addons/email-notices/assets/js/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/email-notices/css/index.php b/addons/email-notices/css/index.php index 1580272..4e6c07c 100644 --- a/addons/email-notices/css/index.php +++ b/addons/email-notices/css/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/email-notices/includes/index.php b/addons/email-notices/includes/index.php index 1580272..4e6c07c 100644 --- a/addons/email-notices/includes/index.php +++ b/addons/email-notices/includes/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/email-notices/includes/mycred-email-functions.php b/addons/email-notices/includes/mycred-email-functions.php index d8bbb9d..34102c0 100644 --- a/addons/email-notices/includes/mycred-email-functions.php +++ b/addons/email-notices/includes/mycred-email-functions.php @@ -1,560 +1,507 @@ post_id ) - ) { - return $mycred_email; - } + if ( isset( $mycred_email ) + && ( $mycred_email instanceof myCRED_Email ) + && ( $notice_id === $mycred_email->post_id ) + ) { + return $mycred_email; + } - $mycred_email = new myCRED_Email($notice_id); + $mycred_email = new myCRED_Email( $notice_id ); - do_action('mycred_get_email_notice'); + do_action( 'mycred_get_email_notice' ); - return $mycred_email; + return $mycred_email; - } + } endif; /** * User Wants Email Notice * Returns true if user has not selected to unsubscribe from this email address else false if they did. - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_user_wants_email') ) : - function mycred_user_wants_email( $user_id = false, $notice_id = false ) - { +if ( ! function_exists( 'mycred_user_wants_email' ) ) : + function mycred_user_wants_email( $user_id = false, $notice_id = false ) { - if ($user_id === false || absint($user_id) === 0 ) { return false; - } + if ( $user_id === false || absint( $user_id ) === 0 ) return false; - $wants_email = true; - $account = mycred_get_account($user_id); + $wants_email = true; + $account = mycred_get_account( $user_id ); - if (isset($account->email_block) && ! empty($account->email_block) && in_array($notice_id, $account->email_block) ) { - $wants_email = false; + if ( isset( $account->email_block ) && ! empty( $account->email_block ) && in_array( $notice_id, $account->email_block ) ) + $wants_email = false; - } elseif (! isset($account->email_block) ) { + elseif ( ! isset( $account->email_block ) ) { - $unsubscriptions = (array) mycred_get_user_meta($user_id, 'mycred_email_unsubscriptions', '', true); - if (! empty($unsubscriptions) && in_array($notice_id, $unsubscriptions) ) { - $wants_email = false; - } + $unsubscriptions = (array) mycred_get_user_meta( $user_id, 'mycred_email_unsubscriptions', '', true ); + if ( ! empty( $unsubscriptions ) && in_array( $notice_id, $unsubscriptions ) ) + $wants_email = false; - } + } - return apply_filters('mycred_email_notice_user_wants', $wants_email, $user_id, $notice_id); + return apply_filters( 'mycred_email_notice_user_wants', $wants_email, $user_id, $notice_id ); - } + } endif; /** * Get Email Triggers * Retreaves the saved email triggers for a given point type. - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_get_email_triggers') ) : - function mycred_get_email_triggers( $point_type = MYCRED_DEFAULT_TYPE_KEY, $force = false ) - { - - $generic_events = array( - 'any' => array(), - 'positive' => array(), - 'negative' => array(), - 'zero' => array(), - 'minus' => array(), - 'badge_new' => array(), - 'badge_level' => array(), - 'rank_up' => array(), - 'rank_down' => array(), - 'transfer_out' => array(), - 'transfer_in' => array(), - 'cashcred_approved' => array(), - 'cashcred_pending' => array(), - 'cashcred_cancel' =>array() - ); - - $defaults = array( - 'generic' => $generic_events, - 'specific' => array() - ); - - $setup = (array) mycred_get_option('mycred-email-triggers-' . $point_type, $defaults); - - if (empty($setup) || $force ) { - $setup = $defaults; - } - - return apply_filters('mycred_get_email_triggers', $setup, $point_type, $force); - - } +if ( ! function_exists( 'mycred_get_email_triggers' ) ) : + function mycred_get_email_triggers( $point_type = MYCRED_DEFAULT_TYPE_KEY, $force = false ) { + + $generic_events = array( + 'any' => array(), + 'positive' => array(), + 'negative' => array(), + 'zero' => array(), + 'minus' => array(), + 'badge_new' => array(), + 'badge_level' => array(), + 'rank_up' => array(), + 'rank_down' => array(), + 'transfer_out' => array(), + 'transfer_in' => array(), + 'cashcred_approved' => array(), + 'cashcred_pending' => array(), + 'cashcred_cancel' =>array() + ); + + $defaults = array( + 'generic' => $generic_events, + 'specific' => array() + ); + + $setup = (array) mycred_get_option( 'mycred-email-triggers-' . $point_type, $defaults ); + + if ( empty( $setup ) || $force ) + $setup = $defaults; + + return apply_filters( 'mycred_get_email_triggers', $setup, $point_type, $force ); + + } endif; /** * Add Email Trigger * Adds an email post to the nominated instance for a particular point type. - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_add_email_trigger') ) : - function mycred_add_email_trigger( $event_type = '', $instance = '', $notice_id = false, $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_add_email_trigger' ) ) : + function mycred_add_email_trigger( $event_type = '', $instance = '', $notice_id = false, $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $event_type = sanitize_key($event_type); - $instance = sanitize_key($instance); - $notice_id = absint($notice_id); + $event_type = sanitize_key( $event_type ); + $instance = sanitize_key( $instance ); + $notice_id = absint( $notice_id ); - if (empty($event_type) || empty($instance) || $notice_id === 0 ) { return false; - } + if ( empty( $event_type ) || empty( $instance ) || $notice_id === 0 ) return false; - $triggers = mycred_get_email_triggers($point_type); + $triggers = mycred_get_email_triggers( $point_type ); - if (array_key_exists($event_type, $triggers) ) { + if ( array_key_exists( $event_type, $triggers ) ) { - if (! array_key_exists($instance, $triggers[ $event_type ]) ) { + if ( ! array_key_exists( $instance, $triggers[ $event_type ] ) ) { - if (! is_array($triggers[ $event_type ]) ) { - $triggers[ $event_type ] = array(); - } + if ( ! is_array( $triggers[ $event_type ] ) ) + $triggers[ $event_type ] = array(); - $triggers[ $event_type ][ $instance ] = array(); - $triggers[ $event_type ][ $instance ][] = $notice_id; + $triggers[ $event_type ][ $instance ] = array(); + $triggers[ $event_type ][ $instance ][] = $notice_id; - } - else { + } + else { - if (empty($triggers[ $event_type ]) || ! in_array($notice_id, $triggers[ $event_type ][ $instance ]) ) { - $triggers[ $event_type ][ $instance ][] = $notice_id; - } + if ( empty( $triggers[ $event_type ] ) || ! in_array( $notice_id, $triggers[ $event_type ][ $instance ] ) ) + $triggers[ $event_type ][ $instance ][] = $notice_id; - } + } - $triggers = apply_filters('mycred_update_email_triggers', $triggers, $event_type, $instance, $notice_id, $point_type); + $triggers = apply_filters( 'mycred_update_email_triggers', $triggers, $event_type, $instance, $notice_id, $point_type ); - if (! empty($triggers) ) { - mycred_update_option('mycred-email-triggers-' . $point_type, $triggers); - } + if ( ! empty( $triggers ) ) + mycred_update_option( 'mycred-email-triggers-' . $point_type, $triggers ); - return true; + return true; - } + } - return false; + return false; - } + } endif; /** * Add Email Trigger * Adds an email post to the nominated instance for a particular point type. - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_delete_email_trigger') ) : - function mycred_delete_email_trigger( $notice_id = false, $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_delete_email_trigger' ) ) : + function mycred_delete_email_trigger( $notice_id = false, $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $notice_id = absint($notice_id); - $point_type = sanitize_key($point_type); + $notice_id = absint( $notice_id ); + $point_type = sanitize_key( $point_type ); - if ($notice_id === 0 ) { return false; - } + if ( $notice_id === 0 ) return false; - $triggers = mycred_get_email_triggers($point_type); - $original = $triggers; + $triggers = mycred_get_email_triggers( $point_type ); + $original = $triggers; - if (! empty($triggers) ) { + if ( ! empty( $triggers ) ) { - // Generics - here the keys needs to be preserved, even if it's an empty array. - if (array_key_exists('generic', $triggers) ) { - foreach ( $triggers['generic'] as $instance => $notice_ids ) { + // Generics - here the keys needs to be preserved, even if it's an empty array. + if ( array_key_exists( 'generic', $triggers ) ) { + foreach ( $triggers['generic'] as $instance => $notice_ids ) { - if (! empty($notice_ids) && in_array($notice_id, $notice_ids) ) { + if ( ! empty( $notice_ids ) && in_array( $notice_id, $notice_ids ) ) { - $new_list = array(); - foreach ( $notice_ids as $id ) { + $new_list = array(); + foreach ( $notice_ids as $id ) { - $id = absint($id); - if ($id !== 0 && $id !== $notice_id ) { - $new_list[] = $id; - } + $id = absint( $id ); + if ( $id !== 0 && $id !== $notice_id ) + $new_list[] = $id; - } + } - $triggers['generic'][ $instance ] = $new_list; + $triggers['generic'][ $instance ] = $new_list; - } + } - } + } - } + } - // Specific - here we only keep instances that have notice IDs, no empty values. - if (array_key_exists('specific', $triggers) ) { - foreach ( $triggers['specific'] as $instance => $notice_ids ) { + // Specific - here we only keep instances that have notice IDs, no empty values. + if ( array_key_exists( 'specific', $triggers ) ) { + foreach ( $triggers['specific'] as $instance => $notice_ids ) { - // If our notice is in this array, remove it by building a new array - // take this opportuniy to make sure we have integers and no zero values - if (! empty($notice_ids) && in_array($notice_id, $notice_ids) ) { + // If our notice is in this array, remove it by building a new array + // take this opportuniy to make sure we have integers and no zero values + if ( ! empty( $notice_ids ) && in_array( $notice_id, $notice_ids ) ) { - $new_list = array(); - foreach ( $notice_ids as $id ) { + $new_list = array(); + foreach ( $notice_ids as $id ) { - $id = absint($id); - if ($id !== 0 && $id !== $notice_id ) { - $new_list[] = $id; - } + $id = absint( $id ); + if ( $id !== 0 && $id !== $notice_id ) + $new_list[] = $id; - } + } - if (! empty($new_list) ) { - $triggers['specific'][ $instance ] = $new_list; + if ( ! empty( $new_list ) ) + $triggers['specific'][ $instance ] = $new_list; - } else { + else { - unset($triggers['specific'][ $instance ]); + unset( $triggers['specific'][ $instance ] ); - } + } - } + } - // No notice ID = should not be in here. - elseif (empty($notice_ids) ) { + // No notice ID = should not be in here. + elseif ( empty( $notice_ids ) ) { - unset($triggers['specific'][ $instance ]); + unset( $triggers['specific'][ $instance ] ); - } + } - } - } + } + } - $triggers = apply_filters('mycred_delete_email_triggers', $triggers, $notice_id, $original, $point_type); + $triggers = apply_filters( 'mycred_delete_email_triggers', $triggers, $notice_id, $original, $point_type ); - if (! empty($triggers) ) { - mycred_update_option('mycred-email-triggers-' . $point_type, $triggers); - } + if ( ! empty( $triggers ) ) + mycred_update_option( 'mycred-email-triggers-' . $point_type, $triggers ); - return true; + return true; - } + } - return false; + return false; - } + } endif; /** * Get Email Triggers * Retreaves the saved email triggers for a given point type. - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_get_triggered_emails') ) : - function mycred_get_triggered_emails( $mycred_event = array(), $new_balance = 0 ) - { - - extract( - shortcode_atts( - array( - 'ref' => '', - 'user_id' => 0, - 'amount' => 0, - 'entry' => '', - 'ref_id' => 0, - 'data' => '', - 'type' => MYCRED_DEFAULT_TYPE_KEY - ), $mycred_event - ) - ); - - $notices = array(); - if (empty($ref) || $user_id == 0 ) { return $notices; - } +if ( ! function_exists( 'mycred_get_triggered_emails' ) ) : + function mycred_get_triggered_emails( $mycred_event = array(), $new_balance = 0 ) { - $triggers = mycred_get_email_triggers($type); + extract( shortcode_atts( array( + 'ref' => '', + 'user_id' => 0, + 'amount' => 0, + 'entry' => '', + 'ref_id' => 0, + 'data' => '', + 'type' => MYCRED_DEFAULT_TYPE_KEY + ), $mycred_event ) ); - $gain = ( $amount > 0 ) ? true : false; - $zero = ( $new_balance == 0 ) ? true : false; - $minus = ( $new_balance < 0 ) ? true : false; + $notices = array(); + if ( empty( $ref ) || $user_id == 0 ) return $notices; - if (! empty($triggers) ) { + $triggers = mycred_get_email_triggers( $type ); - // Generic - any event - if (! empty($triggers['generic']['any']) ) { - foreach ( $triggers['generic']['any'] as $notice_id ) { + $gain = ( $amount > 0 ) ? true : false; + $zero = ( $new_balance == 0 ) ? true : false; + $minus = ( $new_balance < 0 ) ? true : false; - if (! in_array($notice_id, $notices) ) { - $notices[] = $notice_id; - } + if ( ! empty( $triggers ) ) { - } - } + // Generic - any event + if ( ! empty( $triggers['generic']['any'] ) ) { + foreach ( $triggers['generic']['any'] as $notice_id ) { - // Point gains - if ($gain && ! empty($triggers['generic']['positive']) ) { - foreach ( $triggers['generic']['positive'] as $notice_id ) { + if ( ! in_array( $notice_id, $notices ) ) + $notices[] = $notice_id; - if (! in_array($notice_id, $notices) ) { - $notices[] = $notice_id; - } + } + } - } - } + // Point gains + if ( $gain && ! empty( $triggers['generic']['positive'] ) ) { + foreach ( $triggers['generic']['positive'] as $notice_id ) { - // Point loss - elseif (! $gain && ! empty($triggers['generic']['negative']) ) { - foreach ( $triggers['generic']['negative'] as $notice_id ) { + if ( ! in_array( $notice_id, $notices ) ) + $notices[] = $notice_id; - if (! in_array($notice_id, $notices) ) { - $notices[] = $notice_id; - } + } + } - } - } + // Point loss + elseif ( ! $gain && ! empty( $triggers['generic']['negative'] ) ) { + foreach ( $triggers['generic']['negative'] as $notice_id ) { - // Balance is zero - if ($zero && ! empty($triggers['generic']['zero']) ) { - foreach ( $triggers['generic']['zero'] as $notice_id ) { + if ( ! in_array( $notice_id, $notices ) ) + $notices[] = $notice_id; - if (! in_array($notice_id, $notices) ) { - $notices[] = $notice_id; - } + } + } - } - } + // Balance is zero + if ( $zero && ! empty( $triggers['generic']['zero'] ) ) { + foreach ( $triggers['generic']['zero'] as $notice_id ) { - // Balance is negative - if ($minus && ! empty($triggers['generic']['minus']) ) { - foreach ( $triggers['generic']['minus'] as $notice_id ) { + if ( ! in_array( $notice_id, $notices ) ) + $notices[] = $notice_id; - if (! in_array($notice_id, $notices) ) { - $notices[] = $notice_id; - } + } + } - } - } + // Balance is negative + if ( $minus && ! empty( $triggers['generic']['minus'] ) ) { + foreach ( $triggers['generic']['minus'] as $notice_id ) { + + if ( ! in_array( $notice_id, $notices ) ) + $notices[] = $notice_id; + + } + } // check if trasfer trigger has notice id - if (! empty($ref) && $ref == 'transfer' && floatval($amount) > 0 && ! empty($triggers['generic']['transfer_in']) ) { + if ( ! empty( $ref ) && $ref == 'transfer' && floatval( $amount ) > 0 && ! empty( $triggers['generic']['transfer_in'] ) ) { foreach ( $triggers['generic']['transfer_in'] as $notice_id ) { - if (! in_array($notice_id, $notices) ) { + if ( ! in_array( $notice_id, $notices ) ) $notices[] = $notice_id; - } } } // check if trasfer trigger has notice ids - if (! empty($ref) && $ref == 'transfer' && floatval($amount) < 0 && ! empty($triggers['generic']['transfer_out']) ) { + if ( ! empty( $ref ) && $ref == 'transfer' && floatval( $amount ) < 0 && ! empty( $triggers['generic']['transfer_out'] ) ) { foreach ( $triggers['generic']['transfer_out'] as $notice_id ) { - if (! in_array($notice_id, $notices) ) { + if ( ! in_array( $notice_id, $notices ) ) $notices[] = $notice_id; - } } } // Specific instances based on reference - if (! empty($triggers['specific']) && array_key_exists($ref, $triggers['specific']) && ! empty($triggers['specific'][ $ref ]) ) { - foreach ( $triggers['specific'][ $ref ] as $notice_id ) { + if ( ! empty( $triggers['specific'] ) && array_key_exists( $ref, $triggers['specific'] ) && ! empty( $triggers['specific'][ $ref ] ) ) { + foreach ( $triggers['specific'][ $ref ] as $notice_id ) { - if (! in_array($notice_id, $notices) ) { - $notices[] = $notice_id; - } + if ( ! in_array( $notice_id, $notices ) ) + $notices[] = $notice_id; - } - } + } + } - } + } - return apply_filters('mycred_get_triggered_emails', $notices, $triggers, $mycred_event, $new_balance); + return apply_filters( 'mycred_get_triggered_emails', $notices, $triggers, $mycred_event, $new_balance ); - } + } endif; /** * Get Event Emails * Returns all the notice IDs that exists for a given event type + instance. - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_get_event_emails') ) : - function mycred_get_event_emails( $point_type = MYCRED_DEFAULT_TYPE_KEY, $event_type = '', $instance = '' ) - { +if ( ! function_exists( 'mycred_get_event_emails' ) ) : + function mycred_get_event_emails( $point_type = MYCRED_DEFAULT_TYPE_KEY, $event_type = '', $instance = '' ) { - $triggers = mycred_get_email_triggers($point_type); - $notices = array(); + $triggers = mycred_get_email_triggers( $point_type ); + $notices = array(); - if (array_key_exists($event_type, $triggers) ) { + if ( array_key_exists( $event_type, $triggers ) ) { - if (array_key_exists($instance, $triggers[ $event_type ]) && ! empty($triggers[ $event_type ][ $instance ]) ) { - $notices = $triggers[ $event_type ][ $instance ]; - } + if ( array_key_exists( $instance, $triggers[ $event_type ] ) && ! empty( $triggers[ $event_type ][ $instance ] ) ) + $notices = $triggers[ $event_type ][ $instance ]; - } + } - return apply_filters('mycred_get_event_emails', $notices, $triggers, $point_type, $event_type, $instance); + return apply_filters( 'mycred_get_event_emails', $notices, $triggers, $point_type, $event_type, $instance ); - } + } endif; /** * Send New Email - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_send_new_email') ) : - function mycred_send_new_email( $notice_id = false, $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_send_new_email' ) ) : + function mycred_send_new_email( $notice_id = false, $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - if ($notice_id === false || get_post_status($notice_id) !== 'publish' ) { return false; - } + if ( $notice_id === false || get_post_status ( $notice_id ) !== 'publish' ) return false; - $notice_id = absint($notice_id); - $email = mycred_get_email_notice($notice_id); + $notice_id = absint( $notice_id ); + $email = mycred_get_email_notice( $notice_id ); //if $email notice object is empty skip this if (!empty($email->settings) ) { // Schedule for later - if ($email->emailnotices['send'] != '' ) { - $email->schedule($event, $point_type); + if ( $email->emailnotices['send'] != '' ){ + $email->schedule( $event, $point_type ); } // Run now else { - $email->send($event, $point_type); + $email->send( $event, $point_type ); } } - return true; + return true; - } + } endif; /** * Get Email Content Type - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_get_email_content_type') ) : - function mycred_get_email_content_type() - { +if ( ! function_exists( 'mycred_get_email_content_type' ) ) : + function mycred_get_email_content_type() { - $format = 'text/plain'; - $mycred_version = (float) explode(' ', myCRED_VERSION)[0]; - if($mycred_version >= 1.8 ) { - $settings = mycred_get_addon_settings('emailnotices'); - }else{ - $settings = mycred_get_addon_settings('emails'); + $format = 'text/plain'; + $mycred_version = (float) explode(' ', myCRED_VERSION)[0]; + if( $mycred_version >= 1.8 ){ + $settings = mycred_get_addon_settings( 'emailnotices' ); + }else{ + $settings = mycred_get_addon_settings( 'emails' ); - } - if ($settings['use_html'] ) { - $format = 'text/html'; - } + } + if ( $settings['use_html'] ) + $format = 'text/html'; - return apply_filters('mycred_get_email_content_type', $format, $settings); + return apply_filters( 'mycred_get_email_content_type', $format, $settings ); - } + } endif; /** * Cron Schedule Handler - * - * @since 1.3 + * @since 1.3 * @version 1.1 */ -if (! function_exists('mycred_email_notice_cron_job') ) : - function mycred_email_notice_cron_job() - { +if ( ! function_exists( 'mycred_email_notice_cron_job' ) ) : + function mycred_email_notice_cron_job() { - if (! class_exists('myCRED_Email_Notice_Module') ) { return; - } + if ( ! class_exists( 'myCRED_Email_Notice_Module' ) ) return; - global $wpdb; + global $wpdb; - $pending = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->usermeta} WHERE meta_key = %s;", mycred_get_meta_key('mycred_scheduled_email_notices'))); + $pending = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->usermeta} WHERE meta_key = %s;", mycred_get_meta_key( 'mycred_scheduled_email_notices' ) ) ); - if ($pending ) { + if ( $pending ) { - foreach ( $pending as $pending_notice ) { + foreach ( $pending as $pending_notice ) { - $notice = maybe_unserialize($pending_notice->meta_value); + $notice = maybe_unserialize( $pending_notice->meta_value ); - $notice_id = absint($notice['notice_id']); - $email = mycred_get_email_notice($notice_id); + $notice_id = absint( $notice['notice_id'] ); + $email = mycred_get_email_notice( $notice_id ); - // Send email now - $email->send($notice['event'], $notice['point_type']); + // Send email now + $email->send( $notice['event'], $notice['point_type'] ); - // Delete record - mycred_delete_user_meta($pending_notice->user_id, 'mycred_scheduled_email_notices', '', $notice); + // Delete record + mycred_delete_user_meta( $pending_notice->user_id, 'mycred_scheduled_email_notices', '', $notice ); - } + } - } + } - } + } endif; /** * Get Email Settings - * - * @since 1.4 + * @since 1.4 * @version 1.0 */ -if (! function_exists('mycred_render_email_subscriptions') ) : - function mycred_get_email_settings( $post_id ) - { - - $emailnotices = mycred_get_addon_settings('emailnotices'); - $settings = (array) mycred_get_post_meta($post_id, 'mycred_email_settings', true); - - if ($settings == '' || empty($settings) ) { - $settings = array(); - } - - // Defaults - $default = array( - 'recipient' => 'user', - 'senders_name' => $emailnotices['from']['name'], - 'senders_email' => $emailnotices['from']['email'], - 'reply_to' => $emailnotices['from']['reply_to'], - 'label' => get_the_title($post_id) - ); - - $settings = mycred_apply_defaults($default, $settings); - return apply_filters('mycred_email_notice_settings', $settings, $post_id); - } -endif; +if ( ! function_exists( 'mycred_render_email_subscriptions' ) ) : + function mycred_get_email_settings( $post_id ) { + + $emailnotices = mycred_get_addon_settings( 'emailnotices' ); + $settings = (array) mycred_get_post_meta( $post_id, 'mycred_email_settings', true ); + + if ( $settings == '' || empty($settings) ) + $settings = array(); + + // Defaults + $default = array( + 'recipient' => 'user', + 'senders_name' => $emailnotices['from']['name'], + 'senders_email' => $emailnotices['from']['email'], + 'reply_to' => $emailnotices['from']['reply_to'], + 'label' => get_the_title($post_id) + ); + + $settings = mycred_apply_defaults( $default, $settings ); + return apply_filters( 'mycred_email_notice_settings', $settings, $post_id ); + } +endif; \ No newline at end of file diff --git a/addons/email-notices/includes/mycred-email-object.php b/addons/email-notices/includes/mycred-email-object.php index fe44fff..6f653a2 100644 --- a/addons/email-notices/includes/mycred-email-object.php +++ b/addons/email-notices/includes/mycred-email-object.php @@ -1,577 +1,517 @@ populate($notice_id); + /** + * The Email Notice post object + */ + public $post = false; - } + /** + * Point Types that trigger this email + */ + public $point_types = array(); - /** - * Populate - * - * @since 1.0 - * @version 1.0 - */ - protected function populate( $notice_id = null ) - { + /** + * The Add-on settings + */ + public $emailnotices = array(); - $this->post_id = absint($notice_id); - $this->post = mycred_get_post($this->post_id); + /** + * The Email notice settings + */ + public $settings = array(); - $this->point_types = mycred_get_post_meta( $this->post_id, 'mycred_email_ctype', true); + /** + * Email Trigger + */ + protected $trigger = ''; - if ( empty($this->point_types) ) { - $this->point_types = array( MYCRED_DEFAULT_TYPE_KEY ); - } + /** + * Last time the email was sent + */ + public $last_run = ''; - $this->emailnotices = mycred_get_addon_settings('emailnotices'); - $settings = shortcode_atts( - array( - 'recipient' => 'user', - 'senders_name' => $this->emailnotices['from']['name'], - 'senders_email' => $this->emailnotices['from']['email'], - 'reply_to' => $this->emailnotices['from']['reply_to'] - ), (array) mycred_get_post_meta($this->post_id, 'mycred_email_settings', true) - ); - - // Default to the main settings - if ($settings['senders_name'] == '' ) { $settings['senders_name'] = $this->emailnotices['from']['name']; - } - if ($settings['senders_email'] == '' ) { $settings['senders_email'] = $this->emailnotices['from']['email']; - } - if ($settings['reply_to'] == '' ) { $settings['reply_to'] = $this->emailnotices['from']['reply_to']; - } + /** + * Construct + */ + function __construct( $notice_id = NULL ) { - $this->settings = apply_filters('mycred_email_notice_settings', $settings, $this->post_id, $this); + parent::__construct(); - $this->trigger = mycred_get_post_meta($this->post_id, 'mycred_email_instance', true); - $this->last_run = mycred_get_post_meta($this->post_id, 'mycred_email_last_run', true); + $notice_id = absint( $notice_id ); + if ( $notice_id === 0 ) return; - } + if ( mycred_get_post_type( $notice_id ) != MYCRED_EMAIL_KEY ) return; - /** - * Save Settings - * - * @since 1.0 - * @version 1.0 - */ - public function save_settings( $setup = array() ) - { + $this->populate( $notice_id ); - $setup = shortcode_atts( - array( - 'recipient' => $this->settings['recipient'], - 'senders_name' => $this->settings['senders_name'], - 'senders_email' => $this->settings['senders_email'], - 'reply_to' => $this->settings['reply_to'] - ), $setup - ); + } - $saved = mycred_update_post_meta($this->post_id, 'mycred_email_settings', $setup); + /** + * Populate + * @since 1.0 + * @version 1.0 + */ + protected function populate( $notice_id = NULL ) { - $saved = apply_filters('mycred_email_save_settings', $saved, $this->post_id, $setup, $this); + $this->post_id = absint( $notice_id ); + $this->post = mycred_get_post( $this->post_id ); - if ($saved ) { - $this->settings = $setup; - } + $this->point_types = (array) mycred_get_post_meta( $this->post_id, 'mycred_email_ctype', true ); + if ( empty( $this->point_types ) ) $this->point_types = array( MYCRED_DEFAULT_TYPE_KEY ); - return $saved; + $this->emailnotices = mycred_get_addon_settings( 'emailnotices' ); + $settings = shortcode_atts( array( + 'recipient' => 'user', + 'senders_name' => $this->emailnotices['from']['name'], + 'senders_email' => $this->emailnotices['from']['email'], + 'reply_to' => $this->emailnotices['from']['reply_to'] + ), (array) mycred_get_post_meta( $this->post_id, 'mycred_email_settings', true ) ); - } + // Default to the main settings + if ( $settings['senders_name'] == '' ) $settings['senders_name'] = $this->emailnotices['from']['name']; + if ( $settings['senders_email'] == '' ) $settings['senders_email'] = $this->emailnotices['from']['email']; + if ( $settings['reply_to'] == '' ) $settings['reply_to'] = $this->emailnotices['from']['reply_to']; - /** - * Get Trigger - * - * @since 1.0 - * @version 1.0 - */ - public function get_trigger() - { + $this->settings = apply_filters( 'mycred_email_notice_settings', $settings, $this->post_id, $this ); - return apply_filters('mycred_get_emails_trigger', $this->trigger, $this); + $this->trigger = mycred_get_post_meta( $this->post_id, 'mycred_email_instance', true ); + $this->last_run = mycred_get_post_meta( $this->post_id, 'mycred_email_last_run', true ); - } + } - /** - * Set Trigger - * - * @since 1.0 - * @version 1.0 - */ - public function set_trigger( $instance = '' ) - { + /** + * Save Settings + * @since 1.0 + * @version 1.0 + */ + public function save_settings( $setup = array() ) { - $instance = sanitize_key($instance); - $current = $this->get_trigger(); + $setup = shortcode_atts( array( + 'recipient' => $this->settings['recipient'], + 'senders_name' => $this->settings['senders_name'], + 'senders_email' => $this->settings['senders_email'], + 'reply_to' => $this->settings['reply_to'] + ), $setup ); - $new = $current; - if ($current != $instance ) { - $new = $instance; - } + $saved = mycred_update_post_meta( $this->post_id, 'mycred_email_settings', $setup ); - $trigger = apply_filters('mycred_set_email_trigger', $new, $instance, $this); + $saved = apply_filters( 'mycred_email_save_settings', $saved, $this->post_id, $setup, $this ); - if ($trigger !== false ) { + if ( $saved ) + $this->settings = $setup; - mycred_update_post_meta($this->post_id, 'mycred_email_instance', $trigger); + return $saved; - $this->trigger = $trigger; + } - return true; + /** + * Get Trigger + * @since 1.0 + * @version 1.0 + */ + public function get_trigger() { - } + return apply_filters( 'mycred_get_emails_trigger', $this->trigger, $this ); - return false; + } - } + /** + * Set Trigger + * @since 1.0 + * @version 1.0 + */ + public function set_trigger( $instance = '' ) { - /** - * Schedule Email - * - * @since 1.0 - * @version 1.0 - */ - public function schedule( $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { + $instance = sanitize_key( $instance ); + $current = $this->get_trigger(); - if (empty($event) || ! array_key_exists('user_id', $event) ) { return false; - } + $new = $current; + if ( $current != $instance ) + $new = $instance; + + $trigger = apply_filters( 'mycred_set_email_trigger', $new, $instance, $this ); + + if ( $trigger !== false ) { + + mycred_update_post_meta( $this->post_id, 'mycred_email_instance', $trigger ); + + $this->trigger = $trigger; - $user_id = absint($event['user_id']); + return true; - $schedule = mycred_add_user_meta( - $user_id, 'mycred_scheduled_email_notices', '', array( - 'notice_id' => $this->post_id, - 'event' => $event, - 'point_type' => $point_type - ), false - ); + } + + return false; + + } + + /** + * Schedule Email + * @since 1.0 + * @version 1.0 + */ + public function schedule( $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) { + + if ( empty( $event ) || ! array_key_exists( 'user_id', $event ) ) return false; + + $user_id = absint( $event['user_id'] ); + + $schedule = mycred_add_user_meta( $user_id, 'mycred_scheduled_email_notices', '', array( + 'notice_id' => $this->post_id, + 'event' => $event, + 'point_type' => $point_type + ), false ); //added these line to get user balance to fix warning error undefine variable $balance. $mycred = mycred($point_type); - $balance = $mycred->get_users_balance($user_id); + $balance = $mycred->get_users_balance( $user_id ); //ends here - return apply_filters('mycred_schedule_email', $schedule, $event, $balance, $point_type, $this); + return apply_filters( 'mycred_schedule_email', $schedule, $event, $balance, $point_type, $this ); - } + } - /** - * Send Email - * - * @since 1.0 - * @version 1.0 - */ - public function send( $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { + /** + * Send Email + * @since 1.0 + * @version 1.0 + */ + public function send( $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - if (empty($event) || ! array_key_exists('user_id', $event) ) { return false; - } + if ( empty( $event ) || ! array_key_exists( 'user_id', $event ) ) return false; - $user_id = absint($event['user_id']); + $user_id = absint( $event['user_id'] ); - $user = get_userdata($user_id); - $admin = get_option('admin_email'); - $recipients = $this->get_recipients($user->user_email, $admin); + $user = get_userdata( $user_id ); + $admin = get_option( 'admin_email' ); + $recipients = $this->get_recipients( $user->user_email, $admin ); - $headers = $this->get_headers(); - $subject = $this->get_subject($event, $point_type); - $message = $this->get_message($event, $point_type); + $headers = $this->get_headers(); + $subject = $this->get_subject( $event, $point_type ); + $message = $this->get_message( $event, $point_type ); - add_filter('wp_mail_content_type', 'mycred_get_email_content_type'); + add_filter( 'wp_mail_content_type', 'mycred_get_email_content_type' ); - $result = wp_mail($recipients, $subject, $message, $headers); + $result = wp_mail( $recipients, $subject, $message, $headers ); - remove_filter('wp_mail_content_type', 'mycred_get_email_content_type'); + remove_filter( 'wp_mail_content_type', 'mycred_get_email_content_type' ); - $this->update_last_run(); + $this->update_last_run(); //added mycred object here for error undefine variable $mycred - $mycred = mycred($point_type); - return apply_filters('mycred_email_send', $result, $event, $mycred, $this); - - } - - /** - * Update Last Run - * - * @since 1.0 - * @version 1.0 - */ - public function update_last_run( $timestamp = null ) - { - - if ($timestamp === null ) { - $timestamp = current_time('timestamp'); - } + $mycred = mycred( $point_type ); + return apply_filters( 'mycred_email_send', $result, $event, $mycred, $this ); - $timestamp = apply_filters('mycred_email_update_last_run', absint($timestamp), $this); + } - if ($timestamp > 0 ) { + /** + * Update Last Run + * @since 1.0 + * @version 1.0 + */ + public function update_last_run( $timestamp = NULL ) { - $result = mycred_update_post_meta($this->post_id, 'mycred_email_last_run', $timestamp); - $this->last_run = $timestamp; + if ( $timestamp === NULL ) + $timestamp = current_time( 'timestamp' ); - } + $timestamp = apply_filters( 'mycred_email_update_last_run', absint( $timestamp ), $this ); - return $result; + if ( $timestamp > 0 ) { - } + $result = mycred_update_post_meta( $this->post_id, 'mycred_email_last_run', $timestamp ); + $this->last_run = $timestamp; - /** - * Get Email Styling - * - * @since 1.0 - * @version 1.0 - */ - public function get_email_styling() - { + } - if ($this->emailnotices['use_html'] === false ) { return ''; - } + return $result; - $style = mycred_get_post_meta($this->post_id, 'mycred_email_styling', true); + } - // Defaults - if (empty($style) ) { - $style = $this->emailnotices['styling']; - } + /** + * Get Email Styling + * @since 1.0 + * @version 1.0 + */ + public function get_email_styling() { - return apply_filters('mycred_email_notice_get_styling', $style, $this); + if ( $this->emailnotices['use_html'] === false ) return ''; - } + $style = mycred_get_post_meta( $this->post_id, 'mycred_email_styling', true ); - /** - * Get Recipients - * Returns an array of email addresses that this email should be sent to, based on our setup. - * Returns false if used incorrectly. - * - * @since 1.0 - * @version 1.0 - */ - public function get_recipients( $user = '', $admin = '' ) - { + // Defaults + if ( empty( $style ) ) + $style = $this->emailnotices['styling']; - if (empty($user) || ! is_email($user) || empty($admin) || ! is_email($admin) ) { return false; - } + return apply_filters( 'mycred_email_notice_get_styling', $style, $this ); - $recipient = 'user'; - if (isset($this->settings['recipient']) ) { - $recipient = $this->settings['recipient']; - } + } - $emails = array( $user ); - if ($recipient == 'both' ) { - $emails = array( $user, $admin ); + /** + * Get Recipients + * Returns an array of email addresses that this email should be sent to, based on our setup. + * Returns false if used incorrectly. + * @since 1.0 + * @version 1.0 + */ + public function get_recipients( $user = '', $admin = '' ) { - } elseif ($recipient == 'admin' ) { - $emails = array( $admin ); - } + if ( empty( $user ) || ! is_email( $user ) || empty( $admin ) || ! is_email( $admin ) ) return false; - return apply_filters('mycred_email_notice_get_recipients', $emails, $user, $admin, $this); + $recipient = 'user'; + if ( isset( $this->settings['recipient'] ) ) + $recipient = $this->settings['recipient']; - } + $emails = array( $user ); + if ( $recipient == 'both' ) + $emails = array( $user, $admin ); - /** - * Get Headers - * Returns a header array based on our setup. - * - * @since 1.0 - * @version 1.0 - */ - public function get_headers() - { + elseif ( $recipient == 'admin' ) + $emails = array( $admin ); - $headers = array(); + return apply_filters( 'mycred_email_notice_get_recipients', $emails, $user, $admin, $this ); - // Construct headers - if ($this->emailnotices['use_html'] === true ) { - $headers[] = 'MIME-Version: 1.0'; - $headers[] = 'Content-Type: text/HTML; charset="' . get_option('blog_charset') . '"'; - } + } - if ($this->settings['senders_name'] != '' && $this->settings['senders_email'] != '' ) { - $headers[] = 'From: ' . $this->settings['senders_name'] . ' <' . $this->settings['senders_email'] . '>'; + /** + * Get Headers + * Returns a header array based on our setup. + * @since 1.0 + * @version 1.0 + */ + public function get_headers() { - } elseif ($this->settings['senders_name'] == '' && $this->settings['senders_email'] != '' ) { - $headers[] = 'From: <' . $this->settings['senders_email'] . '>'; - } + $headers = array(); - // Reply-To - if ($this->settings['senders_name'] != '' && $this->settings['reply_to'] != '' ) { - $headers[] = 'Reply-To: ' . $this->settings['senders_name'] . ' <' . $this->settings['reply_to'] . '>'; + // Construct headers + if ( $this->emailnotices['use_html'] === true ) { + $headers[] = 'MIME-Version: 1.0'; + $headers[] = 'Content-Type: text/HTML; charset="' . get_option( 'blog_charset' ) . '"'; + } - } elseif ($this->settings['senders_name'] == '' && $this->settings['reply_to'] != '' ) { - $headers[] = 'Reply-To: <' . $this->settings['reply_to'] . '>'; - } + if ( $this->settings['senders_name'] != '' && $this->settings['senders_email'] != '' ) + $headers[] = 'From: ' . $this->settings['senders_name'] . ' <' . $this->settings['senders_email'] . '>'; - return apply_filters('mycred_email_notice_get_headers', $headers, $this); + elseif ( $this->settings['senders_name'] == '' && $this->settings['senders_email'] != '' ) + $headers[] = 'From: <' . $this->settings['senders_email'] . '>'; - } + // Reply-To + if ( $this->settings['senders_name'] != '' && $this->settings['reply_to'] != '' ) + $headers[] = 'Reply-To: ' . $this->settings['senders_name'] . ' <' . $this->settings['reply_to'] . '>'; - /** - * Get Subject - * Returns the email notices subject. - * - * @since 1.0 - * @version 1.0 - */ - public function get_subject( $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { + elseif ( $this->settings['senders_name'] == '' && $this->settings['reply_to'] != '' ) + $headers[] = 'Reply-To: <' . $this->settings['reply_to'] . '>'; - $subject = $this->post->post_title; + return apply_filters( 'mycred_email_notice_get_headers', $headers, $this ); - if (! empty($subject) ) { + } - $mycred = mycred($point_type); + /** + * Get Subject + * Returns the email notices subject. + * @since 1.0 + * @version 1.0 + */ + public function get_subject( $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - if ($this->emailnotices['filter']['subject'] === true ) { - $subject = mycred_get_the_title($this->post); - } + $subject = $this->post->post_title; - $subject = $mycred->template_tags_amount($subject, $event['amount']); - $subject = $mycred->template_tags_user($subject, $event['user_id']); + if ( ! empty( $subject ) ) { - if (array_key_exists('data', $event) && is_array($event['data']) && ! empty($event['data']) && array_key_exists('ref_type', $event['data']) && $event['data']['ref_type'] == 'post' ) { - $subject = $mycred->template_tags_post($subject, $event['ref_id']); - } + $mycred = mycred( $point_type ); - $subject = str_replace('%amount%', $event['amount'], $subject); + if ( $this->emailnotices['filter']['subject'] === true ) + $subject = mycred_get_the_title( $this->post ); - } + $subject = $mycred->template_tags_amount( $subject, $event['amount'] ); + $subject = $mycred->template_tags_user( $subject, $event['user_id'] ); - return apply_filters('mycred_email_notice_get_subject', $subject, $this); + if ( array_key_exists( 'data', $event ) && is_array($event['data']) && ! empty( $event['data'] ) && array_key_exists( 'ref_type', $event['data'] ) && $event['data']['ref_type'] == 'post' ) + $subject = $mycred->template_tags_post( $subject, $event['ref_id'] ); - } + $subject = str_replace( '%amount%', $event['amount'], $subject ); - /** - * Get Body - * Returns the email notices body. - * - * @since 1.0 - * @version 1.0 - */ - public function get_body( $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { + } - $content = $this->post->post_content; + return apply_filters( 'mycred_email_notice_get_subject', $subject, $this ); - if (! empty($content) ) { + } - if (class_exists('myCRED_Ranks_Module') && ( strpos($content, '%rank_title%') !== false || strpos($content, '%rank_image%') !== false ) ) { - - if (is_array($event) && array_key_exists('ref_id', $event) ) { + /** + * Get Body + * Returns the email notices body. + * @since 1.0 + * @version 1.0 + */ + public function get_body( $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $rank = mycred_get_rank($event['ref_id']); + $content = $this->post->post_content; + + if ( ! empty( $content ) ) { + + if ( class_exists( 'myCRED_Ranks_Module' ) && ( strpos( $content, '%rank_title%' ) !== false || strpos( $content, '%rank_image%' ) !== false ) ) { + + if ( is_array( $event ) && array_key_exists( 'ref_id', $event ) ) { + + $rank = mycred_get_rank( $event['ref_id'] ); - if (is_object($rank) ) { + if ( is_object( $rank ) ) { - //rank-title - $rank_title = $rank->title; - $content = str_replace('%rank_title%', $rank_title, $content); - - //rank-image - $rank_image = ""; - $content = str_replace('%rank_image%', $rank_image, $content); + //rank-title + $rank_title = $rank->title; + $content = str_replace( '%rank_title%', $rank_title, $content ); + + //rank-image + $rank_image = ""; + $content = str_replace( '%rank_image%', $rank_image, $content ); } } - } - - $mycred = mycred($point_type); - - if ($this->emailnotices['use_html'] === true ) { - $content = wpautop($content); - } - - $content = wptexturize($content); - - if ($this->emailnotices['filter']['content'] === true ) { - $content = apply_filters('the_content', $content); - $content = do_shortcode($content); - } - - // Template tags can only be used if the email triggers for one point type only. - $content = str_replace('%entry%', $event['entry'], $content); - $content = $mycred->template_tags_amount($content, $event['amount']); - - // to display correct user names in transfer email - if($event['ref']==='transfer' ) { - - $content = $mycred->template_tags_user($content, $event['user_id']); - - $content = str_replace('%user_id_o%', '%user_id%', $content); - $content = str_replace('%user_name_o%', '%user_name%', $content); - $content = str_replace('%user_name_en_o%', '%user_name_en%', $content); - $content = str_replace('%display_name_o%', '%display_name%', $content); - $content = str_replace('%user_profile_url_o%', '%user_profile_url%', $content); - $content = str_replace('%user_profile_link_o%', '%user_profile_link%', $content); - $content = str_replace('%user_nicename_o%', '%user_nicename%', $content); - $content = str_replace('%user_email_o%', '%user_email%', $content); - $content = str_replace('%user_url_o%', '%user_url%', $content); - $content = str_replace('%balance_o%', '%balance%', $content); - $content = str_replace('%balance_f_o%', '%balance_f%', $content); - - $content = $mycred->template_tags_user($content, $event['ref_id']); - $content = mycred_transfer_render_message($content, $event['data']); - - } - elseif($event['ref']==='woocommerce_payment' ) { - - $content = str_replace('%order_id%', $event['ref_id'], $content); - - } - else{ - - $content = $mycred->template_tags_user($content, $event['user_id']); - - } - - if (array_key_exists('data', $event) && is_array($event['data']) && ! empty($event['data']) && array_key_exists('ref_type', $event['data']) && $event['data']['ref_type'] == 'post' ) { - $content = $mycred->template_tags_post($content, $event['ref_id']); - } - - if (class_exists('myCRED_Badge_Module') ) { + } + + $mycred = mycred( $point_type ); + + if ( $this->emailnotices['use_html'] === true ) + $content = wpautop( $content ); + + $content = wptexturize( $content ); + + if ( $this->emailnotices['filter']['content'] === true ) { + $content = apply_filters( 'the_content', $content ); + $content = do_shortcode( $content ); + } + + // Template tags can only be used if the email triggers for one point type only. + $content = str_replace( '%entry%', $event['entry'], $content ); + $content = $mycred->template_tags_amount( $content, $event['amount'] ); + + // to display correct user names in transfer email + if( $event['ref']==='transfer' ){ + + $content = $mycred->template_tags_user( $content, $event['user_id'] ); + + $content = str_replace( '%user_id_o%', '%user_id%', $content ); + $content = str_replace( '%user_name_o%', '%user_name%', $content ); + $content = str_replace( '%user_name_en_o%', '%user_name_en%', $content ); + $content = str_replace( '%display_name_o%', '%display_name%', $content ); + $content = str_replace( '%user_profile_url_o%', '%user_profile_url%', $content ); + $content = str_replace( '%user_profile_link_o%', '%user_profile_link%', $content ); + $content = str_replace( '%user_nicename_o%', '%user_nicename%', $content ); + $content = str_replace( '%user_email_o%', '%user_email%', $content ); + $content = str_replace( '%user_url_o%', '%user_url%', $content ); + $content = str_replace( '%balance_o%', '%balance%', $content ); + $content = str_replace( '%balance_f_o%', '%balance_f%', $content ); + + $content = $mycred->template_tags_user( $content, $event['ref_id'] ); + $content = mycred_transfer_render_message( $content, $event['data'] ); + + } + elseif( $event['ref']==='woocommerce_payment' ){ + + $content = str_replace( '%order_id%', $event['ref_id'], $content ); + + } + else{ + + $content = $mycred->template_tags_user( $content, $event['user_id'] ); + + } + + if ( array_key_exists( 'data', $event ) && is_array($event['data']) && ! empty( $event['data'] ) && array_key_exists( 'ref_type', $event['data'] ) && $event['data']['ref_type'] == 'post' ) + $content = $mycred->template_tags_post( $content, $event['ref_id'] ); + + if ( class_exists( 'myCRED_Badge_Module' ) ) { //Badge-image - if (is_array($event) && array_key_exists('ref_id', $event) ) { + if ( is_array( $event ) && array_key_exists( 'ref_id', $event ) ) { - $badge = mycred_get_badge($event['ref_id']); + $badge = mycred_get_badge( $event['ref_id'] ); - if (is_object($badge) ) { + if ( is_object( $badge ) ) { - $image_url = $badge->main_image_url; - $image_url = "Badge Image"; - $content = str_replace('%badge_image%', $image_url, $content); + $image_url = $badge->main_image_url; + $image_url = "Badge Image"; + $content = str_replace( '%badge_image%', $image_url, $content ); } } //Badge-title - if (is_array($event) && array_key_exists('ref_id', $event) ) { + if ( is_array( $event ) && array_key_exists( 'ref_id', $event ) ) { - $badge = mycred_get_badge($event['ref_id']); - - if (is_object($badge) ) { + $badge = mycred_get_badge( $event['ref_id'] ); + + if ( is_object( $badge ) ) { - $title = $badge->title; - $content = str_replace('%badge_title%', $title, $content); + $title = $badge->title; + $content = str_replace( '%badge_title%', $title , $content ); - } + } } } - $content = str_replace('%amount%', $mycred->format_creds($event['amount']), $content); - $content = str_replace('%new_balance%', $mycred->format_creds($event['new']), $content); - $content = str_replace('%old_balance%', $mycred->format_creds($event['old']), $content); + $content = str_replace( '%amount%', $mycred->format_creds( $event['amount'] ), $content ); + $content = str_replace( '%new_balance%', $mycred->format_creds( $event['new'] ), $content ); + $content = str_replace( '%old_balance%', $mycred->format_creds( $event['old'] ), $content ); - + - $content = str_replace('%blog_name%', get_option('blogname'), $content); - $content = str_replace('%blog_url%', get_option('home'), $content); - $content = str_replace('%blog_info%', get_option('blogdescription'), $content); - $content = str_replace('%admin_email%', get_option('admin_email'), $content); + $content = str_replace( '%blog_name%', get_option( 'blogname' ), $content ); + $content = str_replace( '%blog_url%', get_option( 'home' ), $content ); + $content = str_replace( '%blog_info%', get_option( 'blogdescription' ), $content ); + $content = str_replace( '%admin_email%', get_option( 'admin_email' ), $content ); - $content = str_replace('%rank_title%', get_option('blogname'), $content); + $content = str_replace( '%rank_title%', get_option( 'blogname' ), $content ); } - return apply_filters('mycred_email_notice_get_body', $content, $this); + return apply_filters( 'mycred_email_notice_get_body', $content, $this ); - } + } - /** - * Get Message - * Returns the email message with HTML formatting (if used). - * - * @since 1.0 - * @version 1.0 - */ - public function get_message( $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { + /** + * Get Message + * Returns the email message with HTML formatting (if used). + * @since 1.0 + * @version 1.0 + */ + public function get_message( $event = array(), $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $message = $this->get_body($event, $point_type); + $message = $this->get_body( $event, $point_type ); - if ($this->emailnotices['use_html'] ) { + if ( $this->emailnotices['use_html'] ) { - $subject = $this->get_subject($event, $point_type); - $styling = $this->get_email_styling(); + $subject = $this->get_subject( $event, $point_type ); + $styling = $this->get_email_styling(); - $message = '' . $subject . '' . $message . ''; + $message = '' . $subject . '' . $message . ''; - } + } - // Backwards comp. - $message = apply_filters('mycred_email_content_body', $message, $event, $this); + // Backwards comp. + $message = apply_filters( 'mycred_email_content_body', $message, $event, $this ); - return apply_filters('mycred_email_notice_get_message', $message, $this); + return apply_filters( 'mycred_email_notice_get_message', $message, $this ); - } + } - } + } endif; diff --git a/addons/email-notices/includes/mycred-email-shortcodes.php b/addons/email-notices/includes/mycred-email-shortcodes.php index c91596d..b18c66b 100644 --- a/addons/email-notices/includes/mycred-email-shortcodes.php +++ b/addons/email-notices/includes/mycred-email-shortcodes.php @@ -1,57 +1,45 @@ __('Settings Updated', 'mycred') - ), $atts, MYCRED_SLUG . '_email_subscriptions' - ) - ); + extract( shortcode_atts( array( + 'success' => __( 'Settings Updated', 'mycred' ) + ), $atts, MYCRED_SLUG . '_email_subscriptions' ) ); - if (! is_user_logged_in() ) { return $content; - } + if ( ! is_user_logged_in() ) return $content; - $user_id = get_current_user_id(); - $unsubscriptions = mycred_get_user_meta($user_id, 'mycred_email_unsubscriptions', '', true); + $user_id = get_current_user_id(); + $unsubscriptions = mycred_get_user_meta( $user_id, 'mycred_email_unsubscriptions', '', true ); - if ($unsubscriptions == '' ) { $unsubscriptions = array(); - } + if ( $unsubscriptions == '' ) $unsubscriptions = array(); - // Save - $saved = false; - if (isset($_REQUEST['do']) && $_REQUEST['do'] == 'mycred-unsubscribe' && wp_verify_nonce($_REQUEST['token'], 'update-mycred-email-subscriptions') ) { + // Save + $saved = false; + if ( isset( $_REQUEST['do'] ) && $_REQUEST['do'] == 'mycred-unsubscribe' && wp_verify_nonce( $_REQUEST['token'], 'update-mycred-email-subscriptions' ) ) { - if (isset($_POST['mycred_email_unsubscribe']) && ! empty($_POST['mycred_email_unsubscribe']) ) { - $new_selection = sanitize_email($_POST['mycred_email_unsubscribe']); - } else { - $new_selection = array(); - } + if ( isset( $_POST['mycred_email_unsubscribe'] ) && ! empty( $_POST['mycred_email_unsubscribe'] ) ) + $new_selection = sanitize_email( $_POST['mycred_email_unsubscribe'] ); + else + $new_selection = array(); - mycred_update_user_meta($user_id, 'mycred_email_unsubscriptions', '', $new_selection); - $unsubscriptions = $new_selection; - $saved = true; + mycred_update_user_meta( $user_id, 'mycred_email_unsubscriptions', '', $new_selection ); + $unsubscriptions = $new_selection; + $saved = true; - } + } - global $wpdb; + global $wpdb; - $email_notices = $wpdb->get_results( - $wpdb->prepare( - " + $email_notices = $wpdb->get_results( $wpdb->prepare( " SELECT * FROM {$wpdb->posts} notices @@ -60,62 +48,57 @@ function mycred_render_email_subscriptions( $atts = array(), $content = '' ) WHERE notices.post_type = 'mycred_email_notice' AND notices.post_status = 'publish' - AND ( prefs.meta_value LIKE %s OR prefs.meta_value LIKE %s );", '%s:9:"recipient";s:4:"user";%', '%s:9:"recipient";s:4:"both";%' - ) - ); + AND ( prefs.meta_value LIKE %s OR prefs.meta_value LIKE %s );", '%s:9:"recipient";s:4:"user";%', '%s:9:"recipient";s:4:"both";%' ) ); - ob_start(); + ob_start(); - if ($saved ) { - echo '

    ' . $success . '

    '; - } + if ( $saved ) + echo '

    ' . $success . '

    '; - $url = add_query_arg(array( 'do' => 'mycred-unsubscribe', 'user' => get_current_user_id(), 'token' => wp_create_nonce('update-mycred-email-subscriptions') )); + $url = add_query_arg( array( 'do' => 'mycred-unsubscribe', 'user' => get_current_user_id(), 'token' => wp_create_nonce( 'update-mycred-email-subscriptions' ) ) ); - ?> -
    - - - - - - - - +?> + +
    + + + + + + + - + - ID); ?> + ID ); ?> - + - - - - + + + + - - - + + + - - - + + + - + - -
    ID, $unsubscriptions) ) { echo ' checked="checked"'; - } ?> value="ID; ?>" />
    ID, $unsubscriptions ) ) echo ' checked="checked"'; ?> value="ID; ?>" />
    - + + +
    - +?> \ No newline at end of file diff --git a/addons/email-notices/myCRED-addon-email-notices.php b/addons/email-notices/myCRED-addon-email-notices.php index 4156f68..b5090b6 100644 --- a/addons/email-notices/myCRED-addon-email-notices.php +++ b/addons/email-notices/myCRED-addon-email-notices.php @@ -279,7 +279,7 @@ public function parent_file( $parent = '' ) { global $pagenow; - if ( isset( $_GET['post'] ) && mycred_get_post_type( $_GET['post'] ) == MYCRED_EMAIL_KEY && isset( $_GET['action'] ) && $_GET['action'] == 'edit' ) + if ( isset( $_GET['post'] ) && mycred_get_post_type( sanitize_key( $_GET['post'] ) ) == MYCRED_EMAIL_KEY && isset( $_GET['action'] ) && $_GET['action'] == 'edit' ) return MYCRED_MAIN_SLUG; if ( $pagenow == 'post-new.php' && isset( $_GET['post_type'] ) && $_GET['post_type'] == MYCRED_EMAIL_KEY ) @@ -304,7 +304,7 @@ public function subparent_file( $subparent = '', $parent = '' ) { } - elseif ( $pagenow == 'post.php' && isset( $_GET['post'] ) && mycred_get_post_type( $_GET['post'] ) == MYCRED_EMAIL_KEY ) { + elseif ( $pagenow == 'post.php' && isset( $_GET['post'] ) && mycred_get_post_type( sanitize_key( $_GET['post'] ) ) == MYCRED_EMAIL_KEY ) { return 'edit.php?post_type=' . MYCRED_EMAIL_KEY; @@ -368,19 +368,17 @@ public function adjust_column_content( $column_name, $post_id ) { if ( $column_name == 'mycred-email-status' ) { if ( $email->post->post_status != 'publish' && $email->post->post_status != 'future' ) - echo '

    ' . __( 'Not Active', 'mycred' ) . '

    '; + echo '

    ' . esc_html__( 'Not Active', 'mycred' ) . '

    '; elseif ( $email->post->post_status == 'future' ) - echo '

    ' . sprintf( '%s %s', __( 'Scheduled', 'mycred' ), date( get_option( 'date_format' ) . ' @ ' . get_option( 'time_format' ), strtotime( $email->post->post_date ) ) ) . '

    '; + echo '

    ' . sprintf( '%s %s', esc_html__( 'Scheduled', 'mycred' ), esc_html( date( get_option( 'date_format' ) . ' @ ' . get_option( 'time_format' ), strtotime( $email->post->post_date ) ) ) ) . '

    '; else { if ( empty( $email->last_run ) ) - echo '

    ' . __( 'Active', 'mycred' ) . '

    '; - else { - $allowed_html = [ 'strong' => [] ]; - echo '

    ' . wp_kses( sprintf( '%s %s', __( 'Active - Last run', 'mycred' ), date( get_option( 'date_format' ) . ' @ ' . get_option( 'time_format' ), $email->last_run ) ), $allowed_html ) . '

    '; - } + echo '

    ' . esc_html__( 'Active', 'mycred' ) . '

    '; + else + echo '

    ' . sprintf( '%s %s', esc_html__( 'Active - Last run', 'mycred' ), esc_html( date( get_option( 'date_format' ) . ' @ ' . get_option( 'time_format' ), $email->last_run ) ) ) . '

    '; } @@ -416,12 +414,7 @@ public function adjust_column_content( $column_name, $post_id ) { else $description[] = sprintf( '%s: %s', __( 'Recipient', 'mycred' ), __( 'Both', 'mycred' ) ); - $allowed_html = [ - 'br' => [], - 'strong' => [] - ]; - - echo '

    ' . wp_kses( implode( '
    ', $description ), $allowed_html ) . '

    '; + echo wp_kses_post( '

    ' . implode( '
    ', $description ) . '

    ' ); } @@ -429,9 +422,9 @@ public function adjust_column_content( $column_name, $post_id ) { elseif ( $column_name == 'mycred-email-ctype' ) { echo '

    '; - if ( empty( $email->point_types ) ) { + if ( empty( $email->point_types ) ) esc_html_e( 'No point types selected', 'mycred' ); - } + else { $types = array(); foreach ( $email->point_types as $type_key ) { @@ -986,7 +979,7 @@ public function save_email_notice( $post_id, $post = NULL ) { } } - + mycred_update_post_meta( $post_id, 'mycred_email_ctype', $point_types ); } diff --git a/addons/gateway/carts/index.php b/addons/gateway/carts/index.php index 1580272..4e6c07c 100644 --- a/addons/gateway/carts/index.php +++ b/addons/gateway/carts/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/gateway/carts/mycred-wpecommerce.php b/addons/gateway/carts/mycred-wpecommerce.php index 0a42551..32f52d2 100644 --- a/addons/gateway/carts/mycred-wpecommerce.php +++ b/addons/gateway/carts/mycred-wpecommerce.php @@ -1,512 +1,467 @@ __('Payment for Order: #%order_id%', 'mycred'), - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'share' => 0, - 'share_log' => __('Store sale', 'mycred'), - 'rate' => 1, - 'visitor' => __('You must be logged in to use this gateway', 'mycred'), - 'low_funds' => __('Insufficient Funds.', 'mycred'), - 'message' => __('Deduct the amount from your balance.', 'mycred') - ), (array) get_option('mycred_wpecom_settings', '') - ); - - // Add gateway - $nzshpcrt_gateways[] = array( - 'id' => 'mycred', - 'name' => mycred_label(true), - 'has_recurring_billing' => false, - 'wp_admin_cannot_cancel' => false, - 'requirements' => array( 'php_version' => '5.2.4' ), - 'form' => 'mycred_wpecom_gateway_settings', - 'submit_function' => 'mycred_wpecom_gateway_settings_save', - 'payment_type' => 'mycred', - // this may be legacy, not yet decided - 'internalname' => 'mycred' - ); - - class myCRED_WP_E_Commerce_Gateway - { - - public $core = ''; - public $prefs = array(); - public $mycred_type = MYCRED_DEFAULT_TYPE_KEY; - - /** - * Construct - */ - function __construct() - { - - global $mycred_wpecom_settings; - - $this->prefs = $mycred_wpecom_settings; - $type = MYCRED_DEFAULT_TYPE_KEY; - if (isset($mycred_wpecom_settings['type']) ) { - $type = $mycred_wpecom_settings['type']; - } - - $this->core = mycred($type); - $this->mycred_type = $type; - - add_action('wpsc_submit_checkout_gateway', array( $this, 'process_gateway' ), 1, 2); - add_filter('wpsc_gateway_checkout_form_mycred', array( $this, 'checkout_form' )); - add_filter('mycred_parse_log_entry_wpecom_payment', array( $this, 'parse_template_tags' ), 10, 2); - - } - - /** - * Process Payment - * - * @since 1.3 - * @version 1.1 - */ - function process_gateway( $gateway, $purchase_log ) - { - - if ($gateway != 'mycred' ) { return; - } - - // Prep - $log_id = $purchase_log->get('id'); - - // Load Gateway - $merchant_instance = new wpsc_merchant_mycred($log_id, false, $this->prefs, $this->core, $this->mycred_type); - $merchant_instance->construct_value_array(); - - // Validate - $merchant_instance->validate($purchase_log); - - // Charge - do_action_ref_array('wpsc_pre_submit_gateway', array( &$merchant_instance )); - $merchant_instance->submit(); - - } - - /** - * Checkout Form - * - * @since 1.3 - * @version 1.1 - */ - function checkout_form() - { - - $output = ''; - if (! is_user_logged_in() ) { - return '' . $this->core->template_tags_general($this->prefs['visitor']) . ''; - } - - $output .= ''; - - $total = 0; - while ( wpsc_have_cart_items() ) : wpsc_the_cart_item(); - - $price = wpsc_cart_item_price(false); - if ($this->prefs['rate'] != 1 ) { - $price = $this->prefs['rate']*$price; - } - - $total = $total+$price; - - endwhile; - - $output .= ''; - $balance = $this->core->get_users_balance(get_current_user_id(), $this->mycred_type); - - if ($balance < $total ) { - $highlight = ' style="color:red;"'; - } else { - $highlight = ''; - } - - $output .= '
    ' . __('Item', 'mycred') . '' . $this->core->plural() . '
    ' . __('Total Cost', 'mycred') . '' . $this->core->format_creds($total) . '
    ' . __('Your current balance', 'mycred') . '' . $this->core->format_creds($balance) . '
    '; - - if (! empty($this->prefs['message']) ) { - $output .= '' . $this->core->template_tags_general($this->prefs['message']) . ''; - } - - return apply_filters('mycred_wpecom_form', $output); - - } - - /** - * Parse Custom Template Tags - * - * @since 1.3 - * @version 1.0 - */ - function parse_template_tags( $content, $log_entry ) - { +if ( ! function_exists( 'mycred_init_wpecom_construct_gateway' ) ) : + function mycred_init_wpecom_construct_gateway() { + + if ( ! class_exists( 'wpsc_merchant' ) ) return; + + global $nzshpcrt_gateways, $mycred_wpecom_settings; + + $mycred_wpecom_settings = shortcode_atts( array( + 'log' => __( 'Payment for Order: #%order_id%', 'mycred' ), + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'share' => 0, + 'share_log' => __( 'Store sale', 'mycred' ), + 'rate' => 1, + 'visitor' => __( 'You must be logged in to use this gateway', 'mycred' ), + 'low_funds' => __( 'Insufficient Funds.', 'mycred' ), + 'message' => __( 'Deduct the amount from your balance.', 'mycred' ) + ), (array) get_option( 'mycred_wpecom_settings', '' ) ); + + // Add gateway + $nzshpcrt_gateways[] = array( + 'id' => 'mycred', + 'name' => mycred_label( true ), + 'has_recurring_billing' => false, + 'wp_admin_cannot_cancel' => false, + 'requirements' => array( 'php_version' => '5.2.4' ), + 'form' => 'mycred_wpecom_gateway_settings', + 'submit_function' => 'mycred_wpecom_gateway_settings_save', + 'payment_type' => 'mycred', + // this may be legacy, not yet decided + 'internalname' => 'mycred' + ); + + class myCRED_WP_E_Commerce_Gateway { + + public $core = ''; + public $prefs = array(); + public $mycred_type = MYCRED_DEFAULT_TYPE_KEY; + + /** + * Construct + */ + function __construct() { + + global $mycred_wpecom_settings; + + $this->prefs = $mycred_wpecom_settings; + $type = MYCRED_DEFAULT_TYPE_KEY; + if ( isset( $mycred_wpecom_settings['type'] ) ) + $type = $mycred_wpecom_settings['type']; + + $this->core = mycred( $type ); + $this->mycred_type = $type; + + add_action( 'wpsc_submit_checkout_gateway', array( $this, 'process_gateway' ), 1, 2 ); + add_filter( 'wpsc_gateway_checkout_form_mycred', array( $this, 'checkout_form' ) ); + add_filter( 'mycred_parse_log_entry_wpecom_payment', array( $this, 'parse_template_tags' ), 10, 2 ); + + } + + /** + * Process Payment + * @since 1.3 + * @version 1.1 + */ + function process_gateway( $gateway, $purchase_log ) { + + if ( $gateway != 'mycred' ) return; + + // Prep + $log_id = $purchase_log->get( 'id' ); + + // Load Gateway + $merchant_instance = new wpsc_merchant_mycred( $log_id, false, $this->prefs, $this->core, $this->mycred_type ); + $merchant_instance->construct_value_array(); + + // Validate + $merchant_instance->validate( $purchase_log ); + + // Charge + do_action_ref_array( 'wpsc_pre_submit_gateway', array( &$merchant_instance ) ); + $merchant_instance->submit(); + + } + + /** + * Checkout Form + * @since 1.3 + * @version 1.1 + */ + function checkout_form() { + + $output = ''; + if ( ! is_user_logged_in() ) + return '' . $this->core->template_tags_general( $this->prefs['visitor'] ) . ''; + + $output .= ''; + + $total = 0; + while ( wpsc_have_cart_items() ) : wpsc_the_cart_item(); + + $price = wpsc_cart_item_price( false ); + if ( $this->prefs['rate'] != 1 ) + $price = $this->prefs['rate']*$price; + + $total = $total+$price; + + endwhile; + + $output .= ''; + $balance = $this->core->get_users_balance( get_current_user_id(), $this->mycred_type ); + + if ( $balance < $total ) + $highlight = ' style="color:red;"'; + else + $highlight = ''; + + $output .= '
    ' . __( 'Item', 'mycred' ) . '' . $this->core->plural() . '
    ' . __( 'Total Cost', 'mycred' ) . '' . $this->core->format_creds( $total ) . '
    ' . __( 'Your current balance', 'mycred' ) . '' . $this->core->format_creds( $balance ) . '
    '; + + if ( ! empty( $this->prefs['message'] ) ) + $output .= '' . $this->core->template_tags_general( $this->prefs['message'] ) . ''; + + return apply_filters( 'mycred_wpecom_form', $output ); + + } + + /** + * Parse Custom Template Tags + * @since 1.3 + * @version 1.0 + */ + function parse_template_tags( $content, $log_entry ) { + + if ( ! empty( $log_entry->data ) ) + $content = str_replace( '%order_id%', $log_entry->data, $content ); + else + $content = str_replace( '%order_id%', 'missing', $content ); + + return $content; + + } - if (! empty($log_entry->data) ) { - $content = str_replace('%order_id%', $log_entry->data, $content); - } else { - $content = str_replace('%order_id%', 'missing', $content); - } + } - return $content; - - } - - } - - new myCRED_WP_E_Commerce_Gateway(); - - class wpsc_merchant_mycred extends wpsc_merchant - { - - var $prefs = array(); - var $core = ''; - var $mycred_type = MYCRED_DEFAULT_TYPE_KEY; - var $cost = 0; - var $transaction_id = ''; - - /** - * Construct - */ - function __construct( $purchase_id = null, $is_receiving = false, $prefs = null, $mycred = null, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct($purchase_id, $is_receiving); - $this->prefs = $prefs; - $this->core = $mycred; - $this->mycred_type = $type; - - } - - /** - * Validate - * Checks to make sure the current user can use this gateway. - * - * @since 1.3 - * @version 1.1 - */ - function validate( $purchase_log ) - { - - $error = false; - $user_id = get_current_user_id(); - - // Get cost - $cart_total = $this->cart_data['total_price']; - if ($this->prefs['rate'] != 1 ) { - $cart_total = $this->prefs['rate']*$cart_total; - } - - $cart_total = $this->core->number($cart_total); - $this->cost = $cart_total; - - // User is not logged in - if (! is_user_logged_in() ) { - $error = $this->core->template_tags_general($this->prefs['visitor']); - } - - // Else if user is excluded - elseif ($this->core->exclude_user($user_id) ) { - $error = __('You can not use this gateway.', 'mycred'); - } - - // Else check balance - else { - - // Rate - $balance = $this->core->get_users_balance($user_id, $this->mycred_type); - if ($balance < $this->cost ) { - $error = $this->core->template_tags_general($this->prefs['low_funds']); - } + new myCRED_WP_E_Commerce_Gateway(); - } + class wpsc_merchant_mycred extends wpsc_merchant { - // Let others decline a store order - $decline = apply_filters('mycred_decline_store_purchase', $error, $purchase_log, $this); - if ($decline !== false ) { + var $prefs = array(); + var $core = ''; + var $mycred_type = MYCRED_DEFAULT_TYPE_KEY; + var $cost = 0; + var $transaction_id = ''; - wpsc_delete_customer_meta('selected_gateway'); + /** + * Construct + */ + function __construct( $purchase_id = NULL, $is_receiving = false, $prefs = NULL, $mycred = NULL, $type = MYCRED_DEFAULT_TYPE_KEY ) { - $this->set_error_message($decline); - $purchase_log->delete($this->purchase_id); + parent::__construct( $purchase_id, $is_receiving ); + $this->prefs = $prefs; + $this->core = $mycred; + $this->mycred_type = $type; - unset($_SESSION['WpscGatewayErrorMessage']); + } - $this->return_to_checkout(); + /** + * Validate + * Checks to make sure the current user can use this gateway. + * @since 1.3 + * @version 1.1 + */ + function validate( $purchase_log ) { - exit; + $error = false; + $user_id = get_current_user_id(); - } + // Get cost + $cart_total = $this->cart_data['total_price']; + if ( $this->prefs['rate'] != 1 ) + $cart_total = $this->prefs['rate']*$cart_total; - // Prep for payment - $this->user_id = $user_id; - $this->transaction_id = strtoupper(MYCRED_SLUG) . $user_id . time(); + $cart_total = $this->core->number( $cart_total ); + $this->cost = $cart_total; - } + // User is not logged in + if ( ! is_user_logged_in() ) + $error = $this->core->template_tags_general( $this->prefs['visitor'] ); - /** - * Submit - * Charges the user for the purchase and if profit sharing is enabled - * each product owner. - * - * @since 1.3 - * @version 1.3 - */ - function submit() - { + // Else if user is excluded + elseif ( $this->core->exclude_user( $user_id ) ) + $error = __( 'You can not use this gateway.', 'mycred' ); - // Since the wpsc_pre_submit_gateway action could change these values, we need to check - if ($this->cost > 0 && $this->user_id != 0 && !empty($this->transaction_id) ) { + // Else check balance + else { - // Let other play before we start - do_action_ref_array('mycred_wpecom_charg', array( &$this )); + // Rate + $balance = $this->core->get_users_balance( $user_id, $this->mycred_type ); + if ( $balance < $this->cost ) { + $error = $this->core->template_tags_general( $this->prefs['low_funds'] ); + } - // Charge - $this->core->add_creds( - 'wpecom_payment', - $this->user_id, - 0-$this->cost, - $this->prefs['log'], - '', - $this->purchase_id, - $this->mycred_type - ); + } - // Update Order - $this->set_transaction_details($this->transaction_id, 3); - transaction_results($this->cart_data['session_id'], false); + // Let others decline a store order + $decline = apply_filters( 'mycred_decline_store_purchase', $error, $purchase_log, $this ); + if ( $decline !== false ) { - // Payout Share - if ($this->prefs['share'] > 0 ) { + wpsc_delete_customer_meta( 'selected_gateway' ); - // Loop though items - foreach ( (array) $this->cart_items as $item ) { + $this->set_error_message( $decline ); + $purchase_log->delete( $this->purchase_id ); - // Get product - $product = mycred_get_post((int) $item['product_id']); + unset( $_SESSION['WpscGatewayErrorMessage'] ); - // Continue if product has just been deleted or owner is buyer - if ($product === null || $product->post_author == $this->user_id ) { continue; - } + $this->return_to_checkout(); - // Calculate Cost - $price = $item['price']; - $quantity = $item['quantity']; - $cost = $price*$quantity; + exit; - // Calculate Share - $percentage = apply_filters('mycred_wpecom_profit_share', $this->prefs['share'], $this, $product); - if ($percentage == 0 ) { continue; - } + } - $share = ( $percentage / 100 ) * $cost; + // Prep for payment + $this->user_id = $user_id; + $this->transaction_id = strtoupper( MYCRED_SLUG ) . $user_id . time(); - // Payout - $this->core->add_creds( - 'store_sale', - $product->post_author, - $share, - $this->prefs['share_log'], - $product->ID, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); + } - } + /** + * Submit + * Charges the user for the purchase and if profit sharing is enabled + * each product owner. + * @since 1.3 + * @version 1.3 + */ + function submit() { - } + // Since the wpsc_pre_submit_gateway action could change these values, we need to check + if ( $this->cost > 0 && $this->user_id != 0 && !empty( $this->transaction_id ) ) { - // Let others play before we end - do_action_ref_array('mycred_wpecom_charged', array( &$this )); + // Let other play before we start + do_action_ref_array( 'mycred_wpecom_charg', array( &$this ) ); - // Empty Cart, Redirect & Exit - wpsc_empty_cart(); + // Charge + $this->core->add_creds( + 'wpecom_payment', + $this->user_id, + 0-$this->cost, + $this->prefs['log'], + '', + $this->purchase_id, + $this->mycred_type + ); - $this->go_to_transaction_results($this->cart_data['session_id']); + // Update Order + $this->set_transaction_details( $this->transaction_id, 3 ); + transaction_results( $this->cart_data['session_id'], false ); - exit; + // Payout Share + if ( $this->prefs['share'] > 0 ) { - } + // Loop though items + foreach ( (array) $this->cart_items as $item ) { - // Else save this as pending - elseif (! empty($this->transaction_id) ) { + // Get product + $product = mycred_get_post( (int) $item['product_id'] ); - $this->set_transaction_details($this->transaction_id, 2); + // Continue if product has just been deleted or owner is buyer + if ( $product === NULL || $product->post_author == $this->user_id ) continue; - } + // Calculate Cost + $price = $item['price']; + $quantity = $item['quantity']; + $cost = $price*$quantity; - } + // Calculate Share + $percentage = apply_filters( 'mycred_wpecom_profit_share', $this->prefs['share'], $this, $product ); + if ( $percentage == 0 ) continue; - } + $share = ( $percentage / 100 ) * $cost; - } + // Payout + $this->core->add_creds( + 'store_sale', + $product->post_author, + $share, + $this->prefs['share_log'], + $product->ID, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + + } + + } + + // Let others play before we end + do_action_ref_array( 'mycred_wpecom_charged', array( &$this ) ); + + // Empty Cart, Redirect & Exit + wpsc_empty_cart(); + + $this->go_to_transaction_results( $this->cart_data['session_id'] ); + + exit; + + } + + // Else save this as pending + elseif ( ! empty( $this->transaction_id ) ) { + + $this->set_transaction_details( $this->transaction_id, 2 ); + + } + + } + + } + + } endif; -add_action('after_setup_theme', 'mycred_init_wpecom_construct_gateway'); +add_action( 'after_setup_theme', 'mycred_init_wpecom_construct_gateway' ); /** * Gateway Settings - * - * @filter mycred_wpecom_settings - * @since 1.3 + * @filter mycred_wpecom_settings + * @since 1.3 * @version 1.1 */ -if (! function_exists('mycred_wpecom_gateway_settings') ) : - function mycred_wpecom_gateway_settings() - { +if ( ! function_exists( 'mycred_wpecom_gateway_settings' ) ) : + function mycred_wpecom_gateway_settings() { - global $wpdb, $mycred_wpecom_settings; + global $wpdb, $mycred_wpecom_settings; - if (! isset($mycred_wpecom_settings['type']) ) { - $type = MYCRED_DEFAULT_TYPE_KEY; - } else { - $type = $mycred_wpecom_settings['type']; - } + if ( ! isset( $mycred_wpecom_settings['type'] ) ) + $type = MYCRED_DEFAULT_TYPE_KEY; + else + $type = $mycred_wpecom_settings['type']; - $mycred = mycred($type); + $mycred = mycred( $type ); - // Get current currency - $currency_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_CURRENCY_LIST . "` ORDER BY `country` ASC", ARRAY_A); - $selected_currency = esc_attr(get_option('currency_type')); + // Get current currency + $currency_data = $wpdb->get_results( "SELECT * FROM `" . WPSC_TABLE_CURRENCY_LIST . "` ORDER BY `country` ASC", ARRAY_A ); + $selected_currency = esc_attr( get_option( 'currency_type' ) ); - foreach ( $currency_data as $currency ) { + foreach ( $currency_data as $currency ) { - if ($selected_currency != $currency['id'] ) { continue; - } + if ( $selected_currency != $currency['id'] ) continue; - if (! empty($currency['symbol_html']) ) { - $selected_currency = $currency['symbol_html']; - } else { - $selected_currency = $currency['code']; - } + if ( ! empty( $currency['symbol_html'] ) ) + $selected_currency = $currency['symbol_html']; + else + $selected_currency = $currency['code']; - break; + break; - } + } - $output = ' + $output = ' - ' . __('General', 'mycred') . ' + ' . __( 'General', 'mycred' ) . ' - ' . __('Log Template for Payments', 'mycred') . ' -
    ' . $mycred->available_template_tags(array( 'general' ), '%order_id%') . ' + ' . __( 'Log Template for Payments', 'mycred' ) . ' +
    ' . $mycred->available_template_tags( array( 'general' ), '%order_id%' ) . ' '; - $mycred_types = mycred_get_types(); - if (count($mycred_types) == 1 ) { - $output .= ''; - } else { - $output .= ' + $mycred_types = mycred_get_types(); + if ( count( $mycred_types ) == 1 ) + $output .= ''; + else + $output .= ' - ' . __('Point Type', 'mycred') . ' - ' . mycred_types_select_from_dropdown('mycred_gateway[type]', 'mycred-point-type', $type, true) . ' + ' . __( 'Point Type', 'mycred' ) . ' + ' . mycred_types_select_from_dropdown( 'mycred_gateway[type]', 'mycred-point-type', $type, true ) . ' '; - } - $output .= ' + $output .= ' - ' . __('Exchange Rate', 'mycred') . ' -
    ' . sprintf(__('How much is 1 %s worth in %s', 'mycred'), $selected_currency, $mycred->plural()) . ' + ' . __( 'Exchange Rate', 'mycred' ) . ' +
    ' . sprintf( __( 'How much is 1 %s worth in %s', 'mycred' ), $selected_currency, $mycred->plural() ) . ' - ' . __('Profit Sharing', 'mycred') . ' + ' . __( 'Profit Sharing', 'mycred' ) . ' - ' . __('Payout', 'mycred') . ' - %
    ' . __('Option to share sales with the product owner. Use zero to disable.', 'mycred') . ' + ' . __( 'Payout', 'mycred' ) . ' + %
    ' . __( 'Option to share sales with the product owner. Use zero to disable.', 'mycred' ) . ' - ' . __('Log Template', 'mycred') . ' -
    ' . $mycred->available_template_tags(array( 'general', 'post' )) . ' + ' . __( 'Log Template', 'mycred' ) . ' +
    ' . $mycred->available_template_tags( array( 'general', 'post' ) ) . ' - ' . __('Messages', 'mycred') . ' + ' . __( 'Messages', 'mycred' ) . ' - ' . __('Instructions', 'mycred') . ' -
    ' . __('Optional instructions to show users when selecting this gateway. Leave empty to hide.', 'mycred') . ' + ' . __( 'Instructions', 'mycred' ) . ' +
    ' . __( 'Optional instructions to show users when selecting this gateway. Leave empty to hide.', 'mycred' ) . ' - ' . __('Visitors', 'mycred') . ' -
    ' . __('Message to show visitors who are not logged in.', 'mycred') . ' + ' . __( 'Visitors', 'mycred' ) . ' +
    ' . __( 'Message to show visitors who are not logged in.', 'mycred' ) . ' - ' . __('Insufficient Funds', 'mycred') . ' -
    ' . $mycred->template_tags_general(__('Message to show when users does not have enough %plural% to pay using this gateway.', 'mycred')) . ' + ' . __( 'Insufficient Funds', 'mycred' ) . ' +
    ' . $mycred->template_tags_general( __( 'Message to show when users does not have enough %plural% to pay using this gateway.', 'mycred' ) ) . ' '; - return apply_filters('mycred_wpecom_settings', $output); + return apply_filters( 'mycred_wpecom_settings', $output ); - } + } endif; /** * Save Gateway Settings - * - * @filter mycred_wpecom_save_settings - * @since 1.3 + * @filter mycred_wpecom_save_settings + * @since 1.3 * @version 1.1 */ -if (! function_exists('mycred_wpecom_gateway_settings_save') ) : - function mycred_wpecom_gateway_settings_save() - { - - if (isset($_POST['mycred_gateway']) ) { - $new_settings = apply_filters( - 'mycred_wpecom_save_settings', array( - 'log' => sanitize_text_field($_POST['mycred_gateway']['log']), - 'type' => sanitize_key($_POST['mycred_gateway']['type']), - 'share' => abs($_POST['mycred_gateway']['share']), - 'share_log' => sanitize_text_field($_POST['mycred_gateway']['share_log']), - 'rate' => sanitize_text_field($_POST['mycred_gateway']['rate']), - 'visitor' => sanitize_text_field($_POST['mycred_gateway']['visitor']), - 'low_funds' => sanitize_text_field($_POST['mycred_gateway']['low_funds']), - 'message' => sanitize_text_field($_POST['mycred_gateway']['message']) - ) - ); - update_option('mycred_wpecom_settings', $new_settings); - } - - return true; - - } +if ( ! function_exists( 'mycred_wpecom_gateway_settings_save' ) ) : + function mycred_wpecom_gateway_settings_save() { + + if ( isset( $_POST['mycred_gateway'] ) ) { + $new_settings = apply_filters( 'mycred_wpecom_save_settings', array( + 'log' => sanitize_text_field( $_POST['mycred_gateway']['log'] ), + 'type' => sanitize_key( $_POST['mycred_gateway']['type'] ), + 'share' => abs( $_POST['mycred_gateway']['share'] ), + 'share_log' => sanitize_text_field( $_POST['mycred_gateway']['share_log'] ), + 'rate' => sanitize_text_field( $_POST['mycred_gateway']['rate'] ), + 'visitor' => sanitize_text_field( $_POST['mycred_gateway']['visitor'] ), + 'low_funds' => sanitize_text_field( $_POST['mycred_gateway']['low_funds'] ), + 'message' => sanitize_text_field( $_POST['mycred_gateway']['message'] ) + ) ); + update_option( 'mycred_wpecom_settings', $new_settings ); + } + + return true; + + } endif; /** * Parse Email Notice - * - * @since 1.2.2 + * @since 1.2.2 * @version 1.0 */ -if (! function_exists('mycred_wpecom_parse_email') ) : - function mycred_wpecom_parse_email( $email ) - { +if ( ! function_exists( 'mycred_wpecom_parse_email' ) ) : + function mycred_wpecom_parse_email( $email ) { - if ($email['request']['ref'] == 'wpecom_payment' ) { - $email['request']['entry'] = str_replace('%order_id%', $email['request']['data'], $email['request']['entry']); - } + if ( $email['request']['ref'] == 'wpecom_payment' ) + $email['request']['entry'] = str_replace( '%order_id%', $email['request']['data'], $email['request']['entry'] ); - return $email; + return $email; - } + } endif; -add_filter('mycred_email_before_send', 'mycred_wpecom_parse_email', 30); +add_filter( 'mycred_email_before_send', 'mycred_wpecom_parse_email', 30 ); diff --git a/addons/gateway/event-booking/index.php b/addons/gateway/event-booking/index.php index 1580272..4e6c07c 100644 --- a/addons/gateway/event-booking/index.php +++ b/addons/gateway/event-booking/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/gateway/event-booking/mycred-eventespresso3.php b/addons/gateway/event-booking/mycred-eventespresso3.php index 4756579..23d1931 100644 --- a/addons/gateway/event-booking/mycred-eventespresso3.php +++ b/addons/gateway/event-booking/mycred-eventespresso3.php @@ -1,658 +1,612 @@ array( - 'gateway' => $this->label, - 'payment' => $this->label . ' ' . __('Payments', 'mycred'), - 'button' => __('Pay Now', 'mycred') - ), - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'rate' => 100, - 'share' => 0, - 'log' => __('Payment for Event Registration', 'mycred'), - 'messages' => array( - 'solvent' => 'Click "Pay Now" to pay using your %plural%.', - 'insolvent' => 'Unfortunately you do not have enough %plural% to pay for this event.', - 'visitors' => 'Payments using %_plural% is only available for registered members.' - ) - ); - - // Settings - $settings = get_option('mycred_espresso_gateway_prefs'); - $this->prefs = mycred_apply_defaults($defaults, $settings); - $this->mycred_type = $this->prefs['type']; - $this->core = mycred($this->mycred_type); - - } - - /** - * Load Gateway - * Hook in on init and setup our gateway. - * - * @since 1.2 - * @version 1.0 - */ - public function load() - { - - add_action('init', array( $this, 'gateway_setup' )); - - } - - /** - * Gateway Active - * Checks to see if a given gateway is active. - * - * @since 1.2 - * @version 1.0 - */ - public function gateway_active( $id = 'mycred' ) - { - - global $active_gateways; - - if (! isset($active_gateways) || ! is_array($active_gateways) ) { - $active_gateways = get_option('event_espresso_active_gateways', array()); - } - - if (array_key_exists($id, $active_gateways) ) { return true; - } - return false; - - } - - /** - * Gateway Setup - * - * @since 1.2 - * @version 1.0 - */ - public function gateway_setup() - { - - // Capture Settings Update - if (isset($_REQUEST['mycred-gateway-action']) && isset($_REQUEST['mycred-gateway-token']) ) { - $this->update_settings(); - } - - add_filter('action_hook_espresso_gateway_formal_name', array( $this, 'formal_name' )); - add_filter('action_hook_espresso_gateway_payment_type', array( $this, 'paymenttype_name' )); - add_action('action_hook_espresso_display_gateway_settings', array( $this, 'gateway_settings_page' ), 11); - - // Make sure gateway is enabled - if ($this->gateway_active() ) { - - // Hook into Payment Page - add_action('action_hook_espresso_display_onsite_payment_gateway', array( $this, 'payment_page' )); - - // Capture myCRED Payment Requests - if ($this->is_payment() ) { - add_filter('filter_hook_espresso_transactions_get_attendee_id', array( $this, 'set_attendee_id' )); - add_filter('filter_hook_espresso_thank_you_get_payment_data', array( $this, 'process_payment' )); - } - - add_action('action_hook_espresso_display_onsite_payment_header', 'espresso_display_onsite_payment_header'); - add_action('action_hook_espresso_display_onsite_payment_footer', 'espresso_display_onsite_payment_footer'); - - } - - } - - /** - * Is Payment Request? - * - * @since 1.2 - * @version 1.0 - */ - public function is_payment() - { - - if (( isset($_REQUEST['payment_type']) && $_REQUEST['payment_type'] == 'mycred' ) - && ( isset($_REQUEST['token']) && wp_verify_nonce($_REQUEST['token'], 'pay-with-mycred') ) - ) { return true; - } - - return false; - - } - - /** - * Formal Name - * - * @since 1.2 - * @version 1.0 - */ - public function formal_name( $gateway_formal_names ) - { - - $gateway_formal_names['mycred'] = $this->prefs['labels']['gateway']; - - return $gateway_formal_names; - - } +if ( ! class_exists( 'myCRED_Espresso_Gateway' ) ) : + class myCRED_Espresso_Gateway { + + public $label = ''; + public $core = NULL; + public $mycred_type = MYCRED_DEFAULT_TYPE_KEY; + public $prefs = array(); + public $update = false; + + /** + * Construct + */ + function __construct() { + + $defaults = array( + 'labels' => array( + 'gateway' => $this->label, + 'payment' => $this->label . ' ' . __( 'Payments', 'mycred' ), + 'button' => __( 'Pay Now', 'mycred' ) + ), + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'rate' => 100, + 'share' => 0, + 'log' => __( 'Payment for Event Registration', 'mycred' ), + 'messages' => array( + 'solvent' => 'Click "Pay Now" to pay using your %plural%.', + 'insolvent' => 'Unfortunately you do not have enough %plural% to pay for this event.', + 'visitors' => 'Payments using %_plural% is only available for registered members.' + ) + ); + + // Settings + $settings = get_option( 'mycred_espresso_gateway_prefs' ); + $this->prefs = mycred_apply_defaults( $defaults, $settings ); + $this->mycred_type = $this->prefs['type']; + $this->core = mycred( $this->mycred_type ); + + } + + /** + * Load Gateway + * Hook in on init and setup our gateway. + * @since 1.2 + * @version 1.0 + */ + public function load() { + + add_action( 'init', array( $this, 'gateway_setup' ) ); + + } + + /** + * Gateway Active + * Checks to see if a given gateway is active. + * @since 1.2 + * @version 1.0 + */ + public function gateway_active( $id = 'mycred' ) { - /** - * Payment Type - * - * @since 1.2 - * @version 1.0 - */ - public function paymenttype_name( $gateway_payment_types ) - { - - $gateway_payment_types['mycred'] = $this->prefs['labels']['payment']; - - return $gateway_payment_types; - - } + global $active_gateways; + + if ( ! isset( $active_gateways ) || ! is_array( $active_gateways ) ) + $active_gateways = get_option( 'event_espresso_active_gateways', array() ); + + if ( array_key_exists( $id, $active_gateways ) ) return true; + return false; - /** - * Set Attendee ID - * - * @since 1.2 - * @version 1.0 - */ - public function set_attendee_id( $attendee_id ) - { + } + + /** + * Gateway Setup + * @since 1.2 + * @version 1.0 + */ + public function gateway_setup() { - if (isset($_REQUEST['id']) ) { - $attendee_id = $_REQUEST['id']; - } + // Capture Settings Update + if ( isset( $_REQUEST['mycred-gateway-action'] ) && isset( $_REQUEST['mycred-gateway-token'] ) ) + $this->update_settings(); - return $attendee_id; + add_filter( 'action_hook_espresso_gateway_formal_name', array( $this, 'formal_name' ) ); + add_filter( 'action_hook_espresso_gateway_payment_type', array( $this, 'paymenttype_name' ) ); + add_action( 'action_hook_espresso_display_gateway_settings', array( $this, 'gateway_settings_page' ), 11 ); - } - - /** - * Process Payment - * - * @since 1.2 - * @version 1.2 - */ - public function process_payment( $payment_data ) - { + // Make sure gateway is enabled + if ( $this->gateway_active() ) { - if (! is_user_logged_in() ) { return $payment_data; - } + // Hook into Payment Page + add_action( 'action_hook_espresso_display_onsite_payment_gateway', array( $this, 'payment_page' ) ); - // Security - if (! isset($_REQUEST['token']) || ! wp_verify_nonce($_REQUEST['token'], 'pay-with-mycred') ) { return $payment_data; - } + // Capture myCRED Payment Requests + if ( $this->is_payment() ) { + add_filter( 'filter_hook_espresso_transactions_get_attendee_id', array( $this, 'set_attendee_id' ) ); + add_filter( 'filter_hook_espresso_thank_you_get_payment_data', array( $this, 'process_payment' ) ); + } - // Let others play - do_action('mycred_espresso_process', $payment_data, $this->prefs, $this->core); + add_action( 'action_hook_espresso_display_onsite_payment_header', 'espresso_display_onsite_payment_header' ); + add_action( 'action_hook_espresso_display_onsite_payment_footer', 'espresso_display_onsite_payment_footer' ); - // Check if this event does not accept myCRED payments - if (isset($event_meta['mycred_no_sale']) ) { return; - } + } - $user_id = get_current_user_id(); + } - // Make sure this is unique - if ($this->core->has_entry('event_payment', $payment_data['event_id'], $user_id, $payment_data['registration_id']) ) { return $payment_data; - } + /** + * Is Payment Request? + * @since 1.2 + * @version 1.0 + */ + public function is_payment() { - $balance = $this->core->get_users_balance($user_id, $this->mycred_type); - $event_cost = $this->prefs['rate']*$payment_data['total_cost']; - $after_purchase = $balance-$event_cost; + if ( + ( isset( $_REQUEST['payment_type'] ) && $_REQUEST['payment_type'] == 'mycred' ) && + ( isset( $_REQUEST['token'] ) && wp_verify_nonce( $_REQUEST['token'], 'pay-with-mycred' ) ) ) return true; - // This should never happen - if ($after_purchase < 0 ) { return $payment_data; - } + return false; - $entry = $this->prefs['log']; + } - // Deduct - $this->core->add_creds( - 'event_payment', - $user_id, - 0-$event_cost, - $entry, - $payment_data['event_id'], - $payment_data['registration_id'], - $this->mycred_type - ); + /** + * Formal Name + * @since 1.2 + * @version 1.0 + */ + public function formal_name( $gateway_formal_names ) { - // Update Payment Data - $payment_data['payment_status'] = 'Completed'; - $payment_data['txn_type'] = $this->prefs['labels']['payment']; - $payment_data['txn_id'] = $payment_data['attendee_session']; - $payment_data['txn_details'] = $this->core->template_tags_general($entry); + $gateway_formal_names['mycred'] = $this->prefs['labels']['gateway']; - // Let others play - do_action('mycred_espresso_processed', $payment_data, $this->prefs, $this->core); + return $gateway_formal_names; - // Profit sharing - if ($this->prefs['share'] != 0 ) { + } - $event_post = mycred_get_post((int) $payment_data['event_id']); + /** + * Payment Type + * @since 1.2 + * @version 1.0 + */ + public function paymenttype_name( $gateway_payment_types ) { - if ($event_post !== null ) { + $gateway_payment_types['mycred'] = $this->prefs['labels']['payment']; - $share = ( $this->prefs['share']/100 ) * $price; + return $gateway_payment_types; - $this->core->add_creds( - 'event_sale', - $event_post->post_author, - $share, - $this->prefs['log'], - $payment_data['event_id'], - $payment_data['registration_id'], - $this->mycred_type - ); + } - } + /** + * Set Attendee ID + * @since 1.2 + * @version 1.0 + */ + public function set_attendee_id( $attendee_id ) { - } + if ( isset( $_REQUEST['id'] ) ) + $attendee_id = absint( $_REQUEST['id'] ); - return $payment_data; + return $attendee_id; - } + } - /** - * Payment Page - * - * @since 1.2 - * @version 1.1.1 - */ - public function payment_page( $payment_data ) - { + /** + * Process Payment + * @since 1.2 + * @version 1.2 + */ + public function process_payment( $payment_data ) { - extract($payment_data); + if ( ! is_user_logged_in() ) return $payment_data; - // Check if this event does not accept myCRED payments - if (isset($event_meta['mycred_no_sale']) ) { return; - } + // Security + if ( ! isset( $_REQUEST['token'] ) || ! wp_verify_nonce( $_REQUEST['token'], 'pay-with-mycred' ) ) return $payment_data; - global $org_options; + // Let others play + do_action( 'mycred_espresso_process', $payment_data, $this->prefs, $this->core ); - $member = $solvent = $user_id = false; + // Check if this event does not accept myCRED payments + if ( isset( $event_meta['mycred_no_sale'] ) ) return; - if (is_user_logged_in() ) { + $user_id = get_current_user_id(); - $member = true; - $user_id = get_current_user_id(); - $balance = $this->core->get_users_balance($user_id, $this->mycred_type); + // Make sure this is unique + if ( $this->core->has_entry( 'event_payment', $payment_data['event_id'], $user_id, $payment_data['registration_id'] ) ) return $payment_data; - // Calculate Cost - $event_cost = $this->prefs['rate']*$event_cost; - $after_purchase = $balance-$event_cost; + $balance = $this->core->get_users_balance( $user_id, $this->mycred_type ); + $event_cost = $this->prefs['rate']*$payment_data['total_cost']; + $after_purchase = $balance-$event_cost; - if ($after_purchase >= 0 ) { - $solvent = true; - } + // This should never happen + if ( $after_purchase < 0 ) return $payment_data; - $args = array( - 'page_id' => $org_options['return_url'], - 'r_id' => $registration_id, - 'id' => $attendee_id, - 'payment_type' => 'mycred', - 'token' => wp_create_nonce('pay-with-mycred') - ); - $finalize_link = add_query_arg($args, home_url()); + $entry = $this->prefs['log']; - } + // Deduct + $this->core->add_creds( + 'event_payment', + $user_id, + 0-$event_cost, + $entry, + $payment_data['event_id'], + $payment_data['registration_id'], + $this->mycred_type + ); - ?> + // Update Payment Data + $payment_data['payment_status'] = 'Completed'; + $payment_data['txn_type'] = $this->prefs['labels']['payment']; + $payment_data['txn_id'] = $payment_data['attendee_session']; + $payment_data['txn_details'] = $this->core->template_tags_general( $entry ); + + // Let others play + do_action( 'mycred_espresso_processed', $payment_data, $this->prefs, $this->core ); + + // Profit sharing + if ( $this->prefs['share'] != 0 ) { + + $event_post = mycred_get_post( (int) $payment_data['event_id'] ); + + if ( $event_post !== NULL ) { + + $share = ( $this->prefs['share']/100 ) * $price; + + $this->core->add_creds( + 'event_sale', + $event_post->post_author, + $share, + $this->prefs['log'], + $payment_data['event_id'], + $payment_data['registration_id'], + $this->mycred_type + ); + + } + + } + + return $payment_data; + + } + + /** + * Payment Page + * @since 1.2 + * @version 1.1.1 + */ + public function payment_page( $payment_data ) { + + extract( $payment_data ); + + // Check if this event does not accept myCRED payments + if ( isset( $event_meta['mycred_no_sale'] ) ) return; + + global $org_options; + + $member = $solvent = $user_id = false; + + if ( is_user_logged_in() ) { + + $member = true; + $user_id = get_current_user_id(); + $balance = $this->core->get_users_balance( $user_id, $this->mycred_type ); + + // Calculate Cost + $event_cost = $this->prefs['rate']*$event_cost; + $after_purchase = $balance-$event_cost; + + if ( $after_purchase >= 0 ) + $solvent = true; + + $args = array( + 'page_id' => $org_options['return_url'], + 'r_id' => $registration_id, + 'id' => $attendee_id, + 'payment_type' => 'mycred', + 'token' => wp_create_nonce( 'pay-with-mycred' ) + ); + $finalize_link = add_query_arg( $args, home_url() ); + + } + +?>

    - -
    -
    prefs['labels']['gateway']; ?>
    -
    -

    -
    - - - - prefs['messages']['solvent']) != '' ) : ?> - -

    core->template_tags_general($this->prefs['messages']['solvent']); ?>

    - - - -
    -

    prefs['labels']['payment']; ?>

    - - - - - - - - - - - - - -
    core->format_creds($balance); ?>
    core->format_creds($event_cost); ?>
    core->format_creds($after_purchase); ?>
    -

    prefs['labels']['button']; ?>

    -
    - - - -
    - -

    core->template_tags_general($this->prefs['messages']['insolvent']); ?>

    -
    -
    -

    prefs['labels']['payment']; ?>

    - - - - - - - - - - - - - -
    core->format_creds($balance); ?>
    core->format_creds($event_cost); ?>
    core->format_creds($after_purchase); ?>
    -
    + +
    +
    prefs['labels']['gateway'] ); ?>
    +
    +

    +
    + + + + prefs['messages']['solvent'] ) != '' ) : ?> + +

    core->template_tags_general( $this->prefs['messages']['solvent'] ) ); ?>

    + + + +
    +

    prefs['labels']['payment'] ); ?>

    + + + + + + + + + + + + + +
    core->format_creds( $balance ) ); ?>
    core->format_creds( $event_cost ) ); ?>
    core->format_creds( $after_purchase ) ); ?>
    +

    prefs['labels']['button'] ); ?>

    +
    + + + +
    + +

    core->template_tags_general( $this->prefs['messages']['insolvent'] ) ); ?>

    +
    +
    +

    prefs['labels']['payment'] ); ?>

    + + + + + + + + + + + + + +
    core->format_creds( $balance ) ); ?>
    core->format_creds( $event_cost ) ); ?>
    core->format_creds( $after_purchase ) ); ?>
    +
    -
    - -

    core->template_tags_general($this->prefs['messages']['visitors']); ?>

    -
    +
    + +

    core->template_tags_general( $this->prefs['messages']['visitors'] ) ); ?>

    +
    -
    +
    - label); - - // deactivate - if (! empty($_REQUEST['deactivate_check_payment']) ) { - unset($active_gateways['mycred']); - update_option('event_espresso_active_gateways', $active_gateways); - } - - $deactivate_url = admin_url('admin.php?page=payment_gateways&deactivate_mycred_payment=true'); - $deactivate_text = sprintf(__('Deactivate %s', 'mycred'), $this->label); - - //Open or close the postbox div - $postbox_style = 'closed'; - if (empty($_REQUEST['deactivate_mycred_payment']) && ( ! empty($_REQUEST['deactivate_mycred_payment']) || array_key_exists('mycred', $active_gateways) ) ) { - $postbox_style = ''; - } - - ?> +label ); + + // deactivate + if ( ! empty( $_REQUEST['deactivate_check_payment'] ) ) { + unset( $active_gateways['mycred'] ); + update_option( 'event_espresso_active_gateways', $active_gateways ); + } + + $deactivate_url = admin_url( 'admin.php?page=payment_gateways&deactivate_mycred_payment=true' ); + $deactivate_text = sprintf( __( 'Deactivate %s', 'mycred' ), $this->label ); + + //Open or close the postbox div + $postbox_style = 'closed'; + if ( empty( $_REQUEST['deactivate_mycred_payment'] ) && ( ! empty( $_REQUEST['deactivate_mycred_payment'] ) || array_key_exists( 'mycred', $active_gateways ) ) ) + $postbox_style = ''; + +?>

     

    -
    -

    -

    - label . ' ' . __('Gateway Settings', 'mycred'); ?> -

    -
    -
    -
      - "> +

      +

      + label ) . ' ' . esc_html__( 'Gateway Settings', 'mycred' ); ?> +

      +
      +
      +
        +' . $deactivate_text . ''; - $this->gateway_settings(); + echo '
      • ' . esc_url( $deactivate_text ) . '
      • '; + $this->gateway_settings(); - } - else { + } + else { - echo '
      • ' . $activate_text . '
      • '; + echo '
      • ' . esc_url( $activate_text ) . '
      • '; - } - echo '
      '; + } + echo '
    '; - ?> -
    -
    -
    +?> +
    +
    +
    - core->plural(), - $org_options['currency_symbol'] - ); - - $mycred_types = mycred_get_types(); - - ?> - update ) : ?> -

    - -
    - - - - - - - - -
    -

    -
      -
    • - -
      - . -
    • -
    • - -
      - . -
    • -
    • - -
      - -
    • -
    - - 1 ) : ?> - -
      -
    • - - prefs['type']); ?> - -
    • -
    - - - - - - - -

    -
      -
    • - -
      - -
    • -
    • -

      -
        -
      1. mycred_no_sale', 'mycred'); ?>
      2. -
      3. -
      -
    • -
    • - - %
      - -
    • -
    -

    -
      -
    • - -
      - core->available_template_tags(array( 'general' )); ?> -
    • -
    -
    -

    -
      -
    • - -
      -
      core->available_template_tags(array( 'general' )); ?>
      -
    • -
    • - -
      -
      core->available_template_tags(array( 'general' )); ?>
      -
    • -
    • - -
      -
      core->available_template_tags(array( 'general' )); ?>
      -
    • -
    -
    - - - - - -

    +core->plural(), + $org_options['currency_symbol'] + ); + + $mycred_types = mycred_get_types(); + +?> +update ) : ?> +

    + + + + + + + + + + +
    +

    +
      +
    • + +
      + . +
    • +
    • + +
      + . +
    • +
    • + +
      + +
    • +
    + + 1 ) : ?> + +
      +
    • + + prefs['type'] ); ?> + +
    • +
    + + + + + + + +

    +
      +
    • + +
      + +
    • +
    • +

      +
        +
      1. mycred_no_sale', 'mycred' ); ?>
      2. +
      3. +
      +
    • +
    • + + %
      + +
    • +
    +

    +
      +
    • + +
      + core->available_template_tags( array( 'general' ) ) ); ?> +
    • +
    +
    +

    +
      +
    • + +
      +
      core->available_template_tags( array( 'general' ) ) ); ?>
      +
    • +
    • + +
      +
      core->available_template_tags( array( 'general' ) ) ); ?>
      +
    • +
    • + +
      +
      core->available_template_tags( array( 'general' ) ) ); ?>
      +
    • +
    +
    + + + + + +

    - label = mycred_label(); - - // Security - if (! wp_verify_nonce($_REQUEST['mycred-gateway-token'], 'mycred-espresso-update') ) { return; - } - if (! $this->core->user_is_point_admin() ) { return; - } - - // Prep - $new_settings = array(); - $post = $_POST['mycred_prefs']; - - if (! is_array($post) || empty($post) ) { return; - } - - // Labels - $new_settings['labels']['gateway'] = strip_tags($post['labels']['gateway'], ''); - $new_settings['labels']['payment'] = strip_tags($post['labels']['payment'], ''); - $new_settings['labels']['button'] = sanitize_text_field($post['labels']['button']); - - // Point Type - $new_settings['type'] = sanitize_text_field($post['type']); - - // Exchange Rate - $new_settings['rate'] = sanitize_text_field($post['rate']); - - // Profit Share - $new_settings['share'] = abs($post['share']); - - // Log - $new_settings['log'] = sanitize_text_field($post['log']); - - // Messages - $new_settings['messages']['solvent'] = sanitize_text_field(stripslashes($post['messages']['solvent'])); - $new_settings['messages']['insolvent'] = sanitize_text_field(stripslashes($post['messages']['insolvent'])); - $new_settings['messages']['visitors'] = sanitize_text_field(stripslashes($post['messages']['visitors'])); - - // Let others play - $new_settings = apply_filters('mycred_espresso_save_pref', $new_settings); - - // Save new settings - $current = $this->prefs; - $this->prefs = mycred_apply_defaults($current, $new_settings); - update_option('mycred_espresso_gateway_prefs', $this->prefs); - - // Flag update - $this->update = true; - - } - - } +label = mycred_label(); + + // Security + if ( ! wp_verify_nonce( $_REQUEST['mycred-gateway-token'], 'mycred-espresso-update' ) ) return; + if ( ! $this->core->user_is_point_admin() ) return; + + // Prep + $new_settings = array(); + + if ( ! is_array( $_POST['mycred_prefs'] ) || empty( $_POST['mycred_prefs'] ) ) return; + + // Labels + $new_settings['labels']['gateway'] = strip_tags( sanitize_text_field( $_POST['mycred_prefs']['labels']['gateway'] ), '' ); + $new_settings['labels']['payment'] = strip_tags( sanitize_text_field( $_POST['mycred_prefs']['labels']['payment'] ), '' ); + $new_settings['labels']['button'] = isset( $_POST['mycred_prefs']['labels']['button'] ) ? sanitize_text_field( $_POST['mycred_prefs']['labels']['button'] ) : ''; + + // Point Type + $new_settings['type'] = isset( $_POST['mycred_prefs']['type'] ) ? sanitize_text_field( $_POST['mycred_prefs']['type'] ) : ''; + + // Exchange Rate + $new_settings['rate'] = isset( $_POST['mycred_prefs']['rate'] ) ? sanitize_text_field( $_POST['mycred_prefs']['rate'] ) : ''; + + // Profit Share + $new_settings['share'] = isset( $_POST['mycred_prefs']['share'] ) ? abs( $_POST['mycred_prefs']['share'] ) : ''; + + // Log + $new_settings['log'] = isset( $_POST['mycred_prefs']['log'] ) ? sanitize_text_field( $_POST['mycred_prefs']['log'] ) : ''; + + // Messages + $new_settings['messages']['solvent'] = stripslashes( sanitize_text_field( $_POST['mycred_prefs']['messages']['solvent'] ) ); + $new_settings['messages']['insolvent'] = stripslashes( sanitize_text_field( $_POST['mycred_prefs']['messages']['insolvent'] ) ); + $new_settings['messages']['visitors'] = stripslashes( sanitize_text_field( $_POST['mycred_prefs']['messages']['visitors'] ) ); + + // Let others play + $new_settings = apply_filters( 'mycred_espresso_save_pref', $new_settings ); + + // Save new settings + $current = $this->prefs; + $this->prefs = mycred_apply_defaults( $current, $new_settings ); + update_option( 'mycred_espresso_gateway_prefs', $this->prefs ); + + // Flag update + $this->update = true; + + } + + } endif; diff --git a/addons/gateway/event-booking/mycred-eventsmanager.php b/addons/gateway/event-booking/mycred-eventsmanager.php index e79bf2f..17d6cc9 100644 --- a/addons/gateway/event-booking/mycred-eventsmanager.php +++ b/addons/gateway/event-booking/mycred-eventsmanager.php @@ -1,851 +1,787 @@ 'off', - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'rate' => 100, - 'share' => 0, - 'log' => array( - 'purchase' => __('Payment for tickets to %link_with_title%', 'mycred'), - 'refund' => __('Ticket refund for %link_with_title%', 'mycred') - ), - 'refund' => 0, - 'labels' => array( - 'header' => __('Pay using your %_plural% balance', 'mycred'), - 'button' => __('Pay Now', 'mycred'), - 'link' => __('Pay', 'mycred') - ), - 'messages' => array( - 'success' => __('Thank you for your payment!', 'mycred'), - 'error' => __("I'm sorry but you can not pay for these tickets using %_plural%", 'mycred') - ) - ); - - // Settings - $settings = get_option('mycred_eventsmanager_gateway_prefs', $defaults); - $this->prefs = wp_parse_args($settings, $defaults); - - $this->mycred_type = $this->prefs['type']; - - // Load myCRED - $this->core = mycred($this->mycred_type); - - // Apply Whitelabeling - $this->label = mycred_label(); - } - - /** - * Load Gateway - * - * @since 1.2 - * @version 1.0 - */ - public function load() - { - - // Settings - add_action('em_options_page_footer_bookings', array( $this, 'settings_page' )); - add_action('em_options_save', array( $this, 'save_settings' )); - - // In case gateway has not yet been enabled bail here. - if (! $this->use_gateway() ) { return; - } - - // Currency - add_filter('em_get_currencies', array( $this, 'add_currency' )); - if ($this->single_currency() ) { - add_filter('em_get_currency_formatted', array( $this, 'format_price' ), 10, 4); - } - - // Adjust Ticket Columns - add_filter('em_booking_form_tickets_cols', array( $this, 'ticket_columns' ), 10, 2); - add_action('em_booking_form_tickets_col_mycred', array( $this, 'ticket_col' ), 10, 2); - - // Add Pay Button - add_filter('em_my_bookings_booking_actions', array( $this, 'add_pay_button' ), 1, 2); - add_action('em_my_bookings_booking_loop', array( $this, 'payment_box' )); - add_action('em_template_my_bookings_footer', array( $this, 'insert_scripting' )); - - // Ajax Payments - add_action('wp_ajax_mycred-pay-em-booking', array( $this, 'process_payment' )); - if ($this->prefs['refund'] != 0 ) { - add_filter('em_booking_set_status', array( $this, 'refunds' ), 10, 2); - } - - } - - /** - * Add Currency - * Adds "Points" as a form of currency - * - * @since 1.2 - * @version 1.1 - */ - public function add_currency( $currencies ) - { - - $currencies->names['XMY'] = $this->core->plural(); - $currencies->symbols['XMY'] = ''; - $currencies->true_symbols['XMY'] = ''; - - if (! empty($this->core->before) ) { - $currencies->symbols['XMY'] = $this->core->before; - - } elseif (! empty($this->core->after) ) { - $currencies->symbols['XMY'] = $this->core->after; - } - - if (! empty($this->core->before) ) { - $currencies->true_symbols['XMY'] = $this->core->before; - - } elseif (! empty($this->core->after) ) { - $currencies->true_symbols['XMY'] = $this->core->after; - } - - return $currencies; - - } - - /** - * Format Price - * - * @since 1.2 - * @version 1.1 - */ - public function format_price( $formatted_price, $price, $currency, $format ) - { - - if ($currency == 'XMY' ) { - return $this->core->format_creds($price); - } - - return $formatted_price; - - } - - /** - * Use Gateway - * Checks if this gateway has been enabled. - * - * @since 1.2 - * @version 1.0 - */ - public function use_gateway() - { - - if ($this->prefs['setup'] == 'off' ) { return false; - } - - return true; - - } - - /** - * Check if using Single Currency - * - * @since 1.2 - * @version 1.0 - */ - public function single_currency() - { +if ( ! class_exists( 'myCRED_Events_Manager_Gateway' ) && defined( 'EM_VERSION' ) ) : + class myCRED_Events_Manager_Gateway { + + public $label = ''; + public $prefs = NULL; + public $mycred_type = MYCRED_DEFAULT_TYPE_KEY; + public $core = NULL; + public $booking_cols = 0; + + /** + * Construct + */ + function __construct() { + + // Default settings + $defaults = array( + 'setup' => 'off', + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'rate' => 100, + 'share' => 0, + 'log' => array( + 'purchase' => __( 'Payment for tickets to %link_with_title%', 'mycred' ), + 'refund' => __( 'Ticket refund for %link_with_title%', 'mycred' ) + ), + 'refund' => 0, + 'labels' => array( + 'header' => __( 'Pay using your %_plural% balance', 'mycred' ), + 'button' => __( 'Pay Now', 'mycred' ), + 'link' => __( 'Pay', 'mycred' ) + ), + 'messages' => array( + 'success' => __( 'Thank you for your payment!', 'mycred' ), + 'error' => __( "I'm sorry but you can not pay for these tickets using %_plural%", 'mycred' ) + ) + ); + + // Settings + $settings = get_option( 'mycred_eventsmanager_gateway_prefs', $defaults ); + $this->prefs = wp_parse_args( $settings, $defaults ); + + $this->mycred_type = $this->prefs['type']; + + // Load myCRED + $this->core = mycred( $this->mycred_type ); + + // Apply Whitelabeling + $this->label = mycred_label(); + } + + /** + * Load Gateway + * @since 1.2 + * @version 1.0 + */ + public function load() { + + // Settings + add_action( 'em_options_page_footer_bookings', array( $this, 'settings_page' ) ); + add_action( 'em_options_save', array( $this, 'save_settings' ) ); + + // In case gateway has not yet been enabled bail here. + if ( ! $this->use_gateway() ) return; + + // Currency + add_filter( 'em_get_currencies', array( $this, 'add_currency' ) ); + if ( $this->single_currency() ) + add_filter( 'em_get_currency_formatted', array( $this, 'format_price' ), 10, 4 ); + + // Adjust Ticket Columns + add_filter( 'em_booking_form_tickets_cols', array( $this, 'ticket_columns' ), 10, 2 ); + add_action( 'em_booking_form_tickets_col_mycred', array( $this, 'ticket_col' ), 10, 2 ); + + // Add Pay Button + add_filter( 'em_my_bookings_booking_actions', array( $this, 'add_pay_button' ), 1, 2 ); + add_action( 'em_my_bookings_booking_loop', array( $this, 'payment_box' ) ); + add_action( 'em_template_my_bookings_footer', array( $this, 'insert_scripting' ) ); + + // Ajax Payments + add_action( 'wp_ajax_mycred-pay-em-booking', array( $this, 'process_payment' ) ); + if ( $this->prefs['refund'] != 0 ) + add_filter( 'em_booking_set_status', array( $this, 'refunds' ), 10, 2 ); + + } + + /** + * Add Currency + * Adds "Points" as a form of currency + * @since 1.2 + * @version 1.1 + */ + public function add_currency( $currencies ) { + + $currencies->names['XMY'] = $this->core->plural(); + $currencies->symbols['XMY'] = ''; + $currencies->true_symbols['XMY'] = ''; + + if ( ! empty( $this->core->before ) ) + $currencies->symbols['XMY'] = $this->core->before; + + elseif ( ! empty( $this->core->after ) ) + $currencies->symbols['XMY'] = $this->core->after; - if ($this->prefs['setup'] == 'single' ) { return true; - } + if ( ! empty( $this->core->before ) ) + $currencies->true_symbols['XMY'] = $this->core->before; - return false; + elseif ( ! empty( $this->core->after ) ) + $currencies->true_symbols['XMY'] = $this->core->after; - } + return $currencies; + + } - /** - * Can Pay Check - * Checks if the user can pay for their booking. - * - * @since 1.2 - * @version 1.2 - */ - public function can_pay( $EM_Booking ) - { + /** + * Format Price + * @since 1.2 + * @version 1.1 + */ + public function format_price( $formatted_price, $price, $currency, $format ) { - $EM_Event = $EM_Booking->get_event(); - - // You cant pay for free events - if ($EM_Event->is_free() ) { return false; - } + if ( $currency == 'XMY' ) + return $this->core->format_creds( $price ); - // Only pending events can be paid for - if ($EM_Event->get_bookings()->has_open_time() ) { - - $balance = $this->core->get_users_balance($EM_Booking->person->ID, $this->mycred_type); - if ($balance <= 0 ) { return false; - } - - $price = $this->core->number($EM_Booking->booking_price); - if ($price == 0 ) { return true; - } + return $formatted_price; - if (! $this->single_currency() ) { - $exchange_rate = $this->prefs['rate']; - $price = $this->core->number($exchange_rate * $price); - } + } - if ($balance - $price < 0 ) { return false; - } + /** + * Use Gateway + * Checks if this gateway has been enabled. + * @since 1.2 + * @version 1.0 + */ + public function use_gateway() { - return true; + if ( $this->prefs['setup'] == 'off' ) return false; - } + return true; - return false; + } - } - - /** - * Has Paid - * Checks if the user has paid for booking - * - * @since 1.2 - * @version 1.2 - */ - public function has_paid( $EM_Booking ) - { + /** + * Check if using Single Currency + * @since 1.2 + * @version 1.0 + */ + public function single_currency() { - if ($this->core->has_entry('ticket_purchase', $EM_Booking->event->post_id, $EM_Booking->person->ID, array( 'ref_type' => 'post', 'bid' => (int) $EM_Booking->booking_id ), $this->mycred_type) ) { return true; - } + if ( $this->prefs['setup'] == 'single' ) return true; - return false; + return false; - } + } - /** - * AJAX: Process Payment - * - * @since 1.2 - * @version 1.0.2 - */ - public function process_payment() - { + /** + * Can Pay Check + * Checks if the user can pay for their booking. + * @since 1.2 + * @version 1.2 + */ + public function can_pay( $EM_Booking ) { - // Security - check_ajax_referer('mycred-pay-booking', 'token'); + $EM_Event = $EM_Booking->get_event(); - // Requirements - if (! isset($_POST['booking_id']) || ! is_user_logged_in() ) { die('ERROR_1'); - } + // You cant pay for free events + if ( $EM_Event->is_free() ) return false; - // Get Booking - $booking_id = sanitize_text_field($_POST['booking_id']); - $booking = em_get_booking($booking_id); + // Only pending events can be paid for + if ( $EM_Event->get_bookings()->has_open_time() ) { - // User - if ($this->core->exclude_user($booking->person->ID) ) { die('ERROR_2'); - } + $balance = $this->core->get_users_balance( $EM_Booking->person->ID, $this->mycred_type ); + if ( $balance <= 0 ) return false; - // User can not pay for this - if (! $this->can_pay($booking) ) { + $price = $this->core->number( $EM_Booking->booking_price ); + if ( $price == 0 ) return true; - $message = $this->prefs['messages']['error']; - $status = 'ERROR'; + if ( ! $this->single_currency() ) { + $exchange_rate = $this->prefs['rate']; + $price = $this->core->number( $exchange_rate * $price ); + } - // Let others play - do_action('mycred_em_booking_cantpay', $booking, $this); + if ( $balance - $price < 0 ) return false; - } - - // User has not yet paid - elseif (! $this->has_paid($booking) ) { - - // Price - $price = $this->core->number($booking->booking_price); - if (! $this->single_currency() ) { - $exchange_rate = $this->prefs['rate']; - $price = $this->core->number($exchange_rate * $price); - } - - // Charge - $this->core->add_creds( - 'ticket_purchase', - $booking->person->ID, - 0 - $price, - $this->prefs['log']['purchase'], - $booking->event->post_id, - array( 'ref_type' => 'post', 'bid' => (int) $booking_id ), - $this->mycred_type - ); - - // Update Booking if approval is required (with option to disable this feature) - if (get_option('dbem_bookings_approval') == 1 && apply_filters('mycred_em_approve_on_pay', true, $booking, $this) ) { - $booking->approve(); - } - - $message = $this->prefs['messages']['success']; - $status = 'OK'; - - // Let others play - do_action('mycred_em_booking_paid', $booking, $this); + return true; - // Profit sharing - if ($this->prefs['share'] != 0 ) { + } - $event_post = mycred_get_post((int) $booking->event->post_id); + return false; - if ($event_post !== null ) { - - $share = ( $this->prefs['share'] / 100 ) * $price; - $this->core->add_creds( - 'ticket_sale', - $event_post->post_author, - $share, - $this->prefs['log']['purchase'], - $event_post->ID, - array( 'ref_type' => 'post', 'bid' => (int) $booking_id ), - $this->mycred_type - ); + } - } + /** + * Has Paid + * Checks if the user has paid for booking + * @since 1.2 + * @version 1.2 + */ + public function has_paid( $EM_Booking ) { - } + if ( $this->core->has_entry( 'ticket_purchase', $EM_Booking->event->post_id, $EM_Booking->person->ID, array( 'ref_type' => 'post', 'bid' => (int) $EM_Booking->booking_id ), $this->mycred_type ) ) return true; - } + return false; - else { - $message = ''; - $status = ''; - } + } - wp_send_json(array( 'status' => $status, 'message' => $message )); - - } - - /** - * Refunds - * - * @since 1.2 - * @version 1.1 - */ - public function refunds( $result, $EM_Booking ) - { + /** + * AJAX: Process Payment + * @since 1.2 + * @version 1.0.2 + */ + public function process_payment() { - // Cancellation - if ($EM_Booking->booking_status == 3 && $EM_Booking->previous_status != 3 ) { - - // Make sure user has paid for this to refund - if ($this->has_paid($EM_Booking) ) { - - // Price - if ($this->single_currency() ) { - $price = $this->core->number($EM_Booking->booking_price); - - } else { - $price = $this->core->number($this->prefs['rate']*$EM_Booking->booking_price); - } - - // Refund - if ($this->prefs['refund'] != 100 ) { - $refund = ( $this->prefs['refund'] / 100 ) * $price; - } else { - $refund = $price; - } - - // Charge - $this->core->add_creds( - 'ticket_purchase_refund', - $EM_Booking->person->ID, - $refund, - $this->prefs['log']['refund'], - $EM_Booking->event->post_id, - array( 'ref_type' => 'post', 'bid' => (int) $booking_id ), - $this->mycred_type - ); - - } - - } + // Security + check_ajax_referer( 'mycred-pay-booking', 'token' ); - return $result; + // Requirements + if ( ! isset( $_POST['booking_id'] ) || ! is_user_logged_in() ) die( 'ERROR_1' ); - } + // Get Booking + $booking_id = absint( $_POST['booking_id'] ); + $booking = em_get_booking( $booking_id ); - /** - * Adjust Ticket Columns - * - * @since 1.2 - * @version 1.0 - */ - public function ticket_columns( $columns, $EM_Event ) - { + // User + if ( $this->core->exclude_user( $booking->person->ID ) ) die( 'ERROR_2' ); - if (! $EM_Event->is_free() ) { + // User can not pay for this + if ( ! $this->can_pay( $booking ) ) { - unset($columns['price']); - unset($columns['type']); - unset($columns['spaces']); + $message = $this->prefs['messages']['error']; + $status = 'ERROR'; - $columns['type'] = __('Ticket Type', 'mycred'); + // Let others play + do_action( 'mycred_em_booking_cantpay', $booking, $this ); - if ($this->single_currency() ) { - $columns['mycred'] = __('Price', 'mycred'); - } + } - else { - $columns['price'] = __('Price', 'mycred'); - $columns['mycred'] = $this->core->plural(); - } + // User has not yet paid + elseif ( ! $this->has_paid( $booking ) ) { - $columns['spaces'] = __('Spaces', 'mycred'); + // Price + $price = $this->core->number( $booking->booking_price ); + if ( ! $this->single_currency() ) { + $exchange_rate = $this->prefs['rate']; + $price = $this->core->number( $exchange_rate * $price ); + } - } + // Charge + $this->core->add_creds( + 'ticket_purchase', + $booking->person->ID, + 0 - $price, + $this->prefs['log']['purchase'], + $booking->event->post_id, + array( 'ref_type' => 'post', 'bid' => (int) $booking_id ), + $this->mycred_type + ); - $this->booking_cols = count($columns); + // Update Booking if approval is required (with option to disable this feature) + if ( get_option( 'dbem_bookings_approval' ) == 1 && apply_filters( 'mycred_em_approve_on_pay', true, $booking, $this ) ) + $booking->approve(); - return $columns; + $message = $this->prefs['messages']['success']; + $status = 'OK'; - } + // Let others play + do_action( 'mycred_em_booking_paid', $booking, $this ); - /** - * Adjust Ticket Column Content - * - * @since 1.2 - * @version 1.0 - */ - public function ticket_col( $EM_Ticket, $EM_Event ) - { - - if ($this->single_currency() ) { - $price = $EM_Ticket->get_price(true); - } else { - $price = ( $this->prefs['rate'] * $EM_Ticket->get_price(true) ); - } - - ?> -core->format_creds($price); ?> - can_pay($EM_Booking) && ! $this->has_paid($EM_Booking) ) { - - if (! empty($cancel_link) ) { - $cancel_link .= ' • '; - } - - $cancel_link .= '' . $this->prefs['labels']['link'] . ''; - - $mycred_em_pay = true; - - } - - return $cancel_link; - - } + // Profit sharing + if ( $this->prefs['share'] != 0 ) { - /** - * Payment Box - * - * @since 1.2 - * @version 1.1.1 - */ - public function payment_box( $EM_Booking ) - { + $event_post = mycred_get_post( (int) $booking->event->post_id ); - global $mycred_em_pay; - - if ($mycred_em_pay && is_object($EM_Booking) ) { - - $balance = $this->core->get_users_balance($EM_Booking->person->ID, $this->mycred_type); - - if ($balance <= 0 ) { return; - } - - $price = $EM_Booking->booking_price; - if ($price == 0 ) { return; - } + if ( $event_post !== NULL ) { - if (! $this->single_currency() ) { - $exchange_rate = $this->prefs['rate']; - $price = $this->core->number($exchange_rate * $price); - } - - if ($balance-$price < 0 ) { return; - } - - ?> - - -
    core->template_tags_general($this->prefs['labels']['header']); ?>
    - - - - - - - - - - - - - - - - - - -
    core->format_creds($balance); ?>
    core->format_creds($price); ?>
    core->format_creds($balance-$price); ?>
    - - - -
    -

    - - - - + $share = ( $this->prefs['share'] / 100 ) * $price; + $this->core->add_creds( + 'ticket_sale', + $event_post->post_author, + $share, + $this->prefs['log']['purchase'], + $event_post->ID, + array( 'ref_type' => 'post', 'bid' => (int) $booking_id ), + $this->mycred_type + ); + + } + + } + + } + + else { + $message = ''; + $status = ''; + } + + wp_send_json( array( 'status' => $status, 'message' => $message ) ); + + } + + /** + * Refunds + * @since 1.2 + * @version 1.1 + */ + public function refunds( $result, $EM_Booking ) { + + // Cancellation + if ( $EM_Booking->booking_status == 3 && $EM_Booking->previous_status != 3 ) { + + // Make sure user has paid for this to refund + if ( $this->has_paid( $EM_Booking ) ) { + + // Price + if ( $this->single_currency() ) + $price = $this->core->number( $EM_Booking->booking_price ); + + else + $price = $this->core->number( $this->prefs['rate']*$EM_Booking->booking_price ); + + // Refund + if ( $this->prefs['refund'] != 100 ) + $refund = ( $this->prefs['refund'] / 100 ) * $price; + else + $refund = $price; + + // Charge + $this->core->add_creds( + 'ticket_purchase_refund', + $EM_Booking->person->ID, + $refund, + $this->prefs['log']['refund'], + $EM_Booking->event->post_id, + array( 'ref_type' => 'post', 'bid' => (int) $booking_id ), + $this->mycred_type + ); + + } + + } + + return $result; + + } + + /** + * Adjust Ticket Columns + * @since 1.2 + * @version 1.0 + */ + public function ticket_columns( $columns, $EM_Event ) { + + if ( ! $EM_Event->is_free() ) { + + unset( $columns['price'] ); + unset( $columns['type'] ); + unset( $columns['spaces'] ); + + $columns['type'] = __( 'Ticket Type', 'mycred' ); + + if ( $this->single_currency() ) { + $columns['mycred'] = __( 'Price', 'mycred' ); + } + + else { + $columns['price'] = __( 'Price', 'mycred' ); + $columns['mycred'] = $this->core->plural(); + } + + $columns['spaces'] = __( 'Spaces', 'mycred' ); + + } + + $this->booking_cols = count( $columns ); + + return $columns; + + } + + /** + * Adjust Ticket Column Content + * @since 1.2 + * @version 1.0 + */ + public function ticket_col( $EM_Ticket, $EM_Event ) { + + if ( $this->single_currency() ) + $price = $EM_Ticket->get_price(true); + else + $price = ( $this->prefs['rate'] * $EM_Ticket->get_price(true) ); + +?> +core->format_creds( $price ) ); ?> +can_pay( $EM_Booking ) && ! $this->has_paid( $EM_Booking ) ) { + + if ( ! empty( $cancel_link ) ) + $cancel_link .= ' • '; + + $cancel_link .= '' . $this->prefs['labels']['link'] . ''; + + $mycred_em_pay = true; + + } + + return $cancel_link; + + } + + /** + * Payment Box + * @since 1.2 + * @version 1.1.1 + */ + public function payment_box( $EM_Booking ) { + + global $mycred_em_pay; + + if ( $mycred_em_pay && is_object( $EM_Booking ) ) { + + $balance = $this->core->get_users_balance( $EM_Booking->person->ID, $this->mycred_type ); + + if ( $balance <= 0 ) return; + + $price = $EM_Booking->booking_price; + if ( $price == 0 ) return; + + if ( ! $this->single_currency() ) { + $exchange_rate = $this->prefs['rate']; + $price = $this->core->number( $exchange_rate * $price ); + } + + if ( $balance-$price < 0 ) return; + +?> + + +
    core->template_tags_general( $this->prefs['labels']['header'] ) ); ?>
    + + + + + + + + + + + + + + + + + + +
    core->format_creds( $balance ) ); ?>
    core->format_creds( $price ) ); ?>
    core->format_creds( $balance-$price ) ); ?>
    + + + +
    +

    + + + + - +?> - prefs['setup'] == 'multi' ) { - $box = 'display: block;'; - } else { - $box = 'display: none;'; - } + if ( $this->prefs['setup'] == 'multi' ) + $box = 'display: block;'; + else + $box = 'display: none;'; - $exchange_message = sprintf(__('How many %s is 1 %s worth?', 'mycred'), $this->core->plural(), em_get_currency_symbol()); - $mycred_types = mycred_get_types(); + $exchange_message = sprintf( __( 'How many %s is 1 %s worth?', 'mycred' ), $this->core->plural(), em_get_currency_symbol() ); + $mycred_types = mycred_get_types(); - ?> +?>
    -

    -

    label); ?>

    -
    - - - -

    - - - - - - 1 ) : ?> - - - - - - - - - - - - - - - - - - - - -
    - prefs['setup'], 'off'); ?> />
    - prefs['setup'], 'single'); ?> />
    - prefs['setup'], 'multi'); ?> /> -
    - prefs['type']); ?> - -
    - %
    - -
    - %
    - -
    - - - - - -
    -
    - -
    -

    - - - - - - - - - -
    -
    - core->available_template_tags(array( 'general', 'post' )); ?> -
    -
    - core->available_template_tags(array( 'general', 'post' )); ?> -
    -

    - - - - - - - - - - - - - -
    -
    - -
    -
    - -
    -
    - -
    -

    - - - - - - - - - -
    -
    -
    core->available_template_tags(array( 'general' )); ?>
    -
    -
    -
    core->available_template_tags(array( 'general' )); ?>
    -
    - - +

    +

    label ) ); ?>

    +
    + + + +

    + + + + + + 1 ) : ?> + + + + + + + + + + + + + + + + + + + + +
    + prefs['setup'], 'off' ) ); ?> />
    + prefs['setup'], 'single' ) ); ?> />
    + prefs['setup'], 'multi' ) ); ?> /> +
    + prefs['type'] ); ?> + +
    + %
    + +
    + %
    + +
    + + + + + +
    +
    + +
    +

    + + + + + + + + + +
    +
    + core->available_template_tags( array( 'general', 'post' ) ) ); ?> +
    +
    + core->available_template_tags( array( 'general', 'post' ) ) ); ?> +
    +

    + + + + + + + + + + + + + +
    +
    + +
    +
    + +
    +
    + +
    +

    + + + + + + + + + +
    +
    +
    core->available_template_tags( array( 'general' ) ) ); ?>
    +
    +
    +
    core->available_template_tags( array( 'general' ) ) ); ?>
    +
    + + -
    +
    - prefs['rate']; - } + if ( $new_settings['setup'] == 'multi' ) + $new_settings['rate'] = isset( $_POST['mycred_gateway']['rate'] ) ? sanitize_text_field( $_POST['mycred_gateway']['rate'] ) : ''; + else + $new_settings['rate'] = $this->prefs['rate']; - // Override Pricing Options - if ($new_settings['setup'] == 'single' ) { + // Override Pricing Options + if ( $new_settings['setup'] == 'single' ) { - update_option('dbem_bookings_currency_decimal_point', $this->core->format['separators']['decimal']); - update_option('dbem_bookings_currency_thousands_sep', $this->core->format['separators']['thousand']); - update_option('dbem_bookings_currency', 'XMY'); + update_option( 'dbem_bookings_currency_decimal_point', $this->core->format['separators']['decimal'] ); + update_option( 'dbem_bookings_currency_thousands_sep', $this->core->format['separators']['thousand'] ); + update_option( 'dbem_bookings_currency', 'XMY' ); - if (empty($this->core->before) && ! empty($this->core->after) ) { - $format = '@ #'; + if ( empty( $this->core->before ) && ! empty( $this->core->after ) ) + $format = '@ #'; - } elseif (! empty($this->core->before) && empty($this->core->after) ) { - $format = '# @'; - } + elseif ( ! empty( $this->core->before ) && empty( $this->core->after ) ) + $format = '# @'; - update_option('dbem_bookings_currency_format', $format); + update_option( 'dbem_bookings_currency_format', $format ); - } + } - // Labels - $new_settings['labels']['link'] = sanitize_text_field(stripslashes($data['labels']['link'])); - $new_settings['labels']['header'] = sanitize_text_field(stripslashes($data['labels']['header'])); - $new_settings['labels']['button'] = sanitize_text_field(stripslashes($data['labels']['button'])); + // Labels + $new_settings['labels']['link'] = sanitize_text_field( stripslashes( $_POST['mycred_gateway']['labels']['link'] ) ); + $new_settings['labels']['header'] = sanitize_text_field( stripslashes( $_POST['mycred_gateway']['labels']['header'] ) ); + $new_settings['labels']['button'] = sanitize_text_field( stripslashes( $_POST['mycred_gateway']['labels']['button'] ) ); - // Messages - $new_settings['messages']['success'] = sanitize_text_field(stripslashes($data['messages']['success'])); - $new_settings['messages']['error'] = sanitize_text_field(stripslashes($data['messages']['error'])); + // Messages + $new_settings['messages']['success'] = sanitize_text_field( stripslashes( $_POST['mycred_gateway']['messages']['success'] ) ); + $new_settings['messages']['error'] = sanitize_text_field( stripslashes( $_POST['mycred_gateway']['messages']['error'] ) ); - // Save Settings - $current = $this->prefs; - $this->prefs = mycred_apply_defaults($current, $new_settings); - update_option('mycred_eventsmanager_gateway_prefs', $this->prefs); + // Save Settings + $current = $this->prefs; + $this->prefs = mycred_apply_defaults( $current, $new_settings ); + update_option( 'mycred_eventsmanager_gateway_prefs', $this->prefs ); - // Let others play - do_action('mycred_em_save_settings', $this); + // Let others play + do_action( 'mycred_em_save_settings', $this ); - } + } - } + } endif; diff --git a/addons/gateway/index.php b/addons/gateway/index.php index 1580272..4e6c07c 100644 --- a/addons/gateway/index.php +++ b/addons/gateway/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/gateway/myCRED-addon-gateway.php b/addons/gateway/myCRED-addon-gateway.php index 36bdc2b..caa44e4 100644 --- a/addons/gateway/myCRED-addon-gateway.php +++ b/addons/gateway/myCRED-addon-gateway.php @@ -4,16 +4,15 @@ * Addon URI: http://codex.mycred.me/chapter-iii/gateway/ * Version: 1.4 */ -if (! defined('myCRED_VERSION') ) { exit; -} +if ( ! defined( 'myCRED_VERSION' ) ) exit; -define('myCRED_GATE', __FILE__); -define('myCRED_GATE_DIR', myCRED_ADDONS_DIR . 'gateway/'); -define('myCRED_GATE_ASSETS_DIR', myCRED_GATE_DIR . 'assets/'); -define('myCRED_GATE_CART_DIR', myCRED_GATE_DIR . 'carts/'); -define('myCRED_GATE_EVENT_DIR', myCRED_GATE_DIR . 'event-booking/'); -define('myCRED_GATE_MEMBER_DIR', myCRED_GATE_DIR . 'membership/'); -define('myCRED_GATE_AFFILIATE_DIR', myCRED_GATE_DIR . 'affiliate/'); +define( 'myCRED_GATE', __FILE__ ); +define( 'myCRED_GATE_DIR', myCRED_ADDONS_DIR . 'gateway/' ); +define( 'myCRED_GATE_ASSETS_DIR', myCRED_GATE_DIR . 'assets/' ); +define( 'myCRED_GATE_CART_DIR', myCRED_GATE_DIR . 'carts/' ); +define( 'myCRED_GATE_EVENT_DIR', myCRED_GATE_DIR . 'event-booking/' ); +define( 'myCRED_GATE_MEMBER_DIR', myCRED_GATE_DIR . 'membership/' ); +define( 'myCRED_GATE_AFFILIATE_DIR', myCRED_GATE_DIR . 'affiliate/' ); /** * Supported Carts @@ -24,36 +23,32 @@ /** * Event Espresso */ -function mycred_load_event_espresso3() -{ +function mycred_load_event_espresso3() { - if (! defined('EVENT_ESPRESSO_VERSION') ) { return; - } + if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) return; - include_once myCRED_GATE_EVENT_DIR . 'mycred-eventespresso3.php'; - $gateway = new myCRED_Espresso_Gateway(); - $gateway->load(); + require_once myCRED_GATE_EVENT_DIR . 'mycred-eventespresso3.php'; + $gateway = new myCRED_Espresso_Gateway(); + $gateway->load(); } -add_action('mycred_init', 'mycred_load_event_espresso3'); +add_action( 'mycred_init', 'mycred_load_event_espresso3' ); /** * Events Manager */ -function mycred_load_events_manager() -{ +function mycred_load_events_manager() { - if (! defined('EM_VERSION') ) { return; - } + if ( ! defined( 'EM_VERSION' ) ) return; - // Free only - if (! class_exists('EM_Pro') ) { + // Free only + if ( ! class_exists( 'EM_Pro' ) ) { - include_once myCRED_GATE_EVENT_DIR . 'mycred-eventsmanager.php'; - $events = new myCRED_Events_Manager_Gateway(); - $events->load(); + require_once myCRED_GATE_EVENT_DIR . 'mycred-eventsmanager.php'; + $events = new myCRED_Events_Manager_Gateway(); + $events->load(); - } + } } -add_action('mycred_init', 'mycred_load_events_manager'); +add_action( 'mycred_init', 'mycred_load_events_manager' ); diff --git a/addons/index.php b/addons/index.php index 1580272..4e6c07c 100644 --- a/addons/index.php +++ b/addons/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/notifications/assets/css/index.php b/addons/notifications/assets/css/index.php index 1580272..4e6c07c 100644 --- a/addons/notifications/assets/css/index.php +++ b/addons/notifications/assets/css/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/notifications/assets/css/notify.css b/addons/notifications/assets/css/notify.css index 8cbd5ba..a7938d4 100644 --- a/addons/notifications/assets/css/notify.css +++ b/addons/notifications/assets/css/notify.css @@ -1,40 +1,40 @@ .notice-wrap { - position: fixed; - top: 50px; - right: 50px; - z-index: 9999; - opacity: 0.8; + position: fixed; + top: 50px; + right: 50px; + z-index: 9999; + opacity: 0.8; } * html .notice-wrap { - position: absolute; + position: absolute; } .notice-item { - position: relative; - display: block; - width: auto; - height: auto; - margin: 0 0 24px 0; - padding: 12px; - - line-height: 22px; - font-size: 12px; + position: relative; + display: block; + width: auto; + height: auto; + margin: 0 0 24px 0; + padding: 12px; + + line-height: 22px; + font-size: 12px; - border-radius: 5px; - background-color: #dedede; - color: #333; + border-radius: 5px; + background-color: #dedede; + color: #333; } .notice-item p { display: block; float: right; margin: 0; padding: 0; } .notice-item h1 { margin: 0 !important; padding: 0; } .notice-item-close{ - display: block; - float: left; - width: 22px; - height: 22px; - line-height: 22px; - font-size: 20px; - text-align: center; - cursor: pointer; + display: block; + float: left; + width: 22px; + height: 22px; + line-height: 22px; + font-size: 20px; + text-align: center; + cursor: pointer; } \ No newline at end of file diff --git a/addons/notifications/assets/index.php b/addons/notifications/assets/index.php index 1580272..4e6c07c 100644 --- a/addons/notifications/assets/index.php +++ b/addons/notifications/assets/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/notifications/assets/js/index.php b/addons/notifications/assets/js/index.php index 1580272..4e6c07c 100644 --- a/addons/notifications/assets/js/index.php +++ b/addons/notifications/assets/js/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/notifications/assets/js/notify.js b/addons/notifications/assets/js/notify.js index 18e6ad9..9c99f4a 100644 --- a/addons/notifications/assets/js/notify.js +++ b/addons/notifications/assets/js/notify.js @@ -1,83 +1,80 @@ /** - * jQuery.noticeAdd() and jQuery.noticeRemove() - * These functions create and remove growl-like notices - * - * Copyright © 2009 Tim Benniks - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * @author Tim Benniks - * @copyright 2009 timbenniks.com - * @version $Id: jquery.notice.js 1 2009-01-24 12:24:18Z timbenniks $ - **/ -(function (jQuery) { - jQuery.extend( - { - noticeAdd: function (options) { - var defaults = { - inEffect: {opacity: 'show'}, // in effect - inEffectDuration: 600, // in effect duration in miliseconds - stayTime: parseInt(myCRED_Notice.duration, 10) * 1000, // time in miliseconds before the item has to disappear - text: '', // content of the item - stay: true, // should the notice item stay or not? - type: 'succes' // could also be error, succes - } - - // declare varaibles - var options, noticeWrapAll, noticeItemOuter, noticeItemInner, noticeItemClose; - - options = jQuery.extend({}, defaults, options); - noticeWrapAll = (!jQuery('.notice-wrap').length) ? jQuery('
    ').addClass('notice-wrap').appendTo('body') : jQuery('.notice-wrap'); - noticeItemOuter = jQuery('
    ').addClass('notice-item-wrapper'); - noticeItemInner = jQuery('
    ').hide().addClass('notice-item ' + options.type).appendTo(noticeWrapAll).html(options.text).animate(options.inEffect, options.inEffectDuration).wrap(noticeItemOuter); - noticeItemClose = jQuery('
    ').addClass('notice-item-close').prependTo(noticeItemInner).html('×').click( - function () { - jQuery.noticeRemove(noticeItemInner) } - ); - - // hmmmz, zucht - if(navigator.userAgent.match(/MSIE 6/i)) { - noticeWrapAll.css({top: document.documentElement.scrollTop}); - } - - if(!options.stay) { - setTimeout( - function () { - jQuery.noticeRemove(noticeItemInner); - }, - options.stayTime - ); - } - - }, - - noticeRemove: function (obj) { - obj.animate( - {opacity: '0'}, 200, function () { - obj.parent().animate( - {height: '0px'}, 100, function () { - obj.parent().remove(); - } - ); - } - ); - } - } - ); +* jQuery.noticeAdd() and jQuery.noticeRemove() +* These functions create and remove growl-like notices +* +* Copyright © 2009 Tim Benniks +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in +* all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +* THE SOFTWARE. +* +* @author Tim Benniks +* @copyright 2009 timbenniks.com +* @version $Id: jquery.notice.js 1 2009-01-24 12:24:18Z timbenniks $ +**/ +(function(jQuery) +{ + jQuery.extend({ + noticeAdd: function(options) + { + var defaults = { + inEffect: {opacity: 'show'}, // in effect + inEffectDuration: 600, // in effect duration in miliseconds + stayTime: parseInt( myCRED_Notice.duration, 10 ) * 1000, // time in miliseconds before the item has to disappear + text: '', // content of the item + stay: true, // should the notice item stay or not? + type: 'succes' // could also be error, succes + } + + // declare varaibles + var options, noticeWrapAll, noticeItemOuter, noticeItemInner, noticeItemClose; + + options = jQuery.extend({}, defaults, options); + noticeWrapAll = (!jQuery('.notice-wrap').length) ? jQuery('
    ').addClass('notice-wrap').appendTo('body') : jQuery('.notice-wrap'); + noticeItemOuter = jQuery('
    ').addClass('notice-item-wrapper'); + noticeItemInner = jQuery('
    ').hide().addClass('notice-item ' + options.type).appendTo(noticeWrapAll).html( options.text ).animate(options.inEffect, options.inEffectDuration).wrap(noticeItemOuter); + noticeItemClose = jQuery('
    ').addClass('notice-item-close').prependTo(noticeItemInner).html('×').click(function() { jQuery.noticeRemove(noticeItemInner) }); + + // hmmmz, zucht + if(navigator.userAgent.match(/MSIE 6/i)) + { + noticeWrapAll.css({top: document.documentElement.scrollTop}); + } + + if(!options.stay) + { + setTimeout(function() + { + jQuery.noticeRemove(noticeItemInner); + }, + options.stayTime); + } + + }, + + noticeRemove: function(obj) + { + obj.animate({opacity: '0'}, 200, function() + { + obj.parent().animate({height: '0px'}, 100, function() + { + obj.parent().remove(); + }); + }); + } + }); })(jQuery); \ No newline at end of file diff --git a/addons/notifications/index.php b/addons/notifications/index.php index 1580272..4e6c07c 100644 --- a/addons/notifications/index.php +++ b/addons/notifications/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/notifications/myCRED-addon-notifications.php b/addons/notifications/myCRED-addon-notifications.php index 40ef49d..103a68f 100644 --- a/addons/notifications/myCRED-addon-notifications.php +++ b/addons/notifications/myCRED-addon-notifications.php @@ -4,352 +4,314 @@ * Addon URI: http://codex.mycred.me/chapter-iii/notifications/ * Version: 1.1.2 */ -if (! defined('myCRED_VERSION') ) { exit; -} +if ( ! defined( 'myCRED_VERSION' ) ) exit; -define('myCRED_NOTE', __FILE__); -define('myCRED_NOTE_VERSION', '1.1.2'); +define( 'myCRED_NOTE', __FILE__ ); +define( 'myCRED_NOTE_VERSION', '1.1.2' ); /** * myCRED_Notifications class - * - * @since 1.2.3 + * @since 1.2.3 * @version 1.3 */ -if (! class_exists('myCRED_Notifications_Module') ) : - class myCRED_Notifications_Module extends myCRED_Module - { - - /** - * Construct - */ - function __construct() - { - - parent::__construct( - 'myCRED_Notifications_Module', array( - 'module_name' => 'notifications', - 'defaults' => mycred_get_addon_defaults('notifications'), - 'register' => false, - 'add_to_core' => true - ) - ); - - add_filter('mycred_add_finished', array( $this, 'mycred_finished' ), 40, 3); - - } - - /** - * Module Init - * - * @since 1.2.3 - * @version 1.0.1 - */ - public function module_init() - { - - if (! is_user_logged_in() ) { return; - } - - add_action('mycred_front_enqueue', array( $this, 'register_assets' ), 20); - add_action('wp_footer', array( $this, 'get_notices' ), 1); - add_action('wp_footer', array( $this, 'wp_footer' ), 999); - - } - - /** - * Load Notice in Footer - * - * @since 1.2.3 - * @version 1.2 - */ - public function wp_footer() - { - - // Get notifications - $notices = apply_filters('mycred_notifications', array()); - if (empty($notices) ) { return; - } - - // Should the notice stay till closed / left page or removed automatically - $stay = 'false'; - if ($this->notifications['duration'] == 0 ) { - $stay = 'true'; - } - - // Let others play before we start - do_action_ref_array('mycred_before_notifications', array( &$notices )); - - // Loop Notifications - foreach ( (array) $notices as $notice ) { - - $notice = str_replace(array( "\r", "\n", "\t" ), '', $notice); - echo ''; - - } - - // Let others play after we finished - do_action_ref_array('mycred_after_notifications', array( &$notices )); - - } - - /** - * Register Assets - * - * @since 1.2.3 - * @version 1.1 - */ - public function register_assets() - { - - // Register script - wp_register_script( - 'mycred-notifications', - plugins_url('assets/js/notify.js', myCRED_NOTE), - array( 'jquery' ), - myCRED_NOTE_VERSION . '.2', - true - ); - - // Localize - wp_localize_script( - 'mycred-notifications', - 'myCRED_Notice', - array( - 'ajaxurl' => admin_url('admin-ajax.php'), - 'duration' => $this->notifications['duration'] - ) - ); - wp_enqueue_script('mycred-notifications'); - - // If not disabled, enqueue the stylesheet - if ($this->notifications['use_css'] == 1 ) { - - wp_register_style( - 'mycred-notifications', - plugins_url('assets/css/notify.css', myCRED_NOTE), - false, - myCRED_NOTE_VERSION . '.2', - 'all', - true - ); - - wp_enqueue_style('mycred-notifications'); - - } - - } - - /** - * myCRED Finished - * - * @since 1.6 - * @version 1.0 - */ - public function mycred_finished( $reply, $request, $mycred ) - { - - if ($reply === false || $this->notifications['template'] == '' ) { return $reply; - } - - // Parse template - $template = str_replace('%entry%', $request['entry'], $this->notifications['template']); - $template = str_replace('%amount%', $request['amount'], $template); - - // Attempt to parse the template tags now that we have the entire request. - // This way we just need to display it and we are done. - $template = $mycred->template_tags_amount($template, $request['amount']); - $template = $mycred->parse_template_tags($template, $this->request_to_entry($request)); - - // Let others play - $template = apply_filters('mycred_notifications_note', $template, $request, $mycred); - - // If template is not empty, add it now. - if (strlen($template) > 0 ) { - mycred_add_new_notice(array( 'user_id' => $request['user_id'], 'message' => $template ), $this->notifications['life']); - } - - return $reply; - - } - - /** - * Get Notices - * - * @since 1.2.3 - * @version 1.0.1 - */ - public function get_notices() - { - - $user_id = get_current_user_id(); - $data = get_transient('mycred_notice_' . $user_id); - - if ($data === false || ! is_array($data) ) { return; - } - - foreach ( $data as $notice ) { - - //add_filter( 'mycred_notifications', create_function( '$query', '$query[]=\'' . $notice . '\'; return $query;' ) ); - //replacing above filter second param create function with annonymus function to remove depricated error and passed notice - add_filter( - 'mycred_notifications', function ($query) use ($notice) { - $query[]= $notice ; return $query; - } - ); - } - - - delete_transient('mycred_notice_' . $user_id); - - } - - /** - * Settings Page - * - * @since 1.2.3 - * @version 1.2 - */ - public function after_general_settings( $mycred = null ) - { - - $prefs = $this->notifications; - - ?> -

    +if ( ! class_exists( 'myCRED_Notifications_Module' ) ) : + class myCRED_Notifications_Module extends myCRED_Module { + + /** + * Construct + */ + function __construct() { + + parent::__construct( 'myCRED_Notifications_Module', array( + 'module_name' => 'notifications', + 'defaults' => mycred_get_addon_defaults( 'notifications' ), + 'register' => false, + 'add_to_core' => true + ) ); + + add_filter( 'mycred_add_finished', array( $this, 'mycred_finished' ), 40, 3 ); + + } + + /** + * Module Init + * @since 1.2.3 + * @version 1.0.1 + */ + public function module_init() { + + if ( ! is_user_logged_in() ) return; + + add_action( 'mycred_front_enqueue', array( $this, 'register_assets' ), 20 ); + add_action( 'wp_footer', array( $this, 'get_notices' ), 1 ); + add_action( 'wp_footer', array( $this, 'wp_footer' ), 999 ); + + } + + /** + * Load Notice in Footer + * @since 1.2.3 + * @version 1.2 + */ + public function wp_footer() { + + // Get notifications + $notices = apply_filters( 'mycred_notifications', array() ); + if ( empty( $notices ) ) return; + + // Should the notice stay till closed / left page or removed automatically + $stay = 'false'; + if ( $this->notifications['duration'] == 0 ) + $stay = 'true'; + + // Let others play before we start + do_action_ref_array( 'mycred_before_notifications', array( &$notices ) ); + + // Loop Notifications + foreach ( (array) $notices as $notice ) { + + $notice = str_replace( array( "\r", "\n", "\t" ), '', $notice ); + echo ''; + + } + + // Let others play after we finished + do_action_ref_array( 'mycred_after_notifications', array( &$notices ) ); + + } + + /** + * Register Assets + * @since 1.2.3 + * @version 1.1 + */ + public function register_assets() { + + // Register script + wp_register_script( + 'mycred-notifications', + plugins_url( 'assets/js/notify.js', myCRED_NOTE ), + array( 'jquery' ), + myCRED_NOTE_VERSION . '.2', + true + ); + + // Localize + wp_localize_script( + 'mycred-notifications', + 'myCRED_Notice', + array( + 'ajaxurl' => admin_url( 'admin-ajax.php' ), + 'duration' => $this->notifications['duration'] + ) + ); + wp_enqueue_script( 'mycred-notifications' ); + + // If not disabled, enqueue the stylesheet + if ( $this->notifications['use_css'] == 1 ) { + + wp_register_style( + 'mycred-notifications', + plugins_url( 'assets/css/notify.css', myCRED_NOTE ), + false, + myCRED_NOTE_VERSION . '.2', + 'all', + true + ); + + wp_enqueue_style( 'mycred-notifications' ); + + } + + } + + /** + * myCRED Finished + * @since 1.6 + * @version 1.0 + */ + public function mycred_finished( $reply, $request, $mycred ) { + + if ( $reply === false || $this->notifications['template'] == '' ) return $reply; + + // Parse template + $template = str_replace( '%entry%', $request['entry'], $this->notifications['template'] ); + $template = str_replace( '%amount%', $request['amount'], $template ); + + // Attempt to parse the template tags now that we have the entire request. + // This way we just need to display it and we are done. + $template = $mycred->template_tags_amount( $template, $request['amount'] ); + $template = $mycred->parse_template_tags( $template, $this->request_to_entry( $request ) ); + + // Let others play + $template = apply_filters( 'mycred_notifications_note', $template, $request, $mycred ); + + // If template is not empty, add it now. + if ( strlen( $template ) > 0 ) + mycred_add_new_notice( array( 'user_id' => $request['user_id'], 'message' => $template ), $this->notifications['life'] ); + + return $reply; + + } + + /** + * Get Notices + * @since 1.2.3 + * @version 1.0.1 + */ + public function get_notices() { + + $user_id = get_current_user_id(); + $data = get_transient( 'mycred_notice_' . $user_id ); + + if ( $data === false || ! is_array( $data ) ) return; + + foreach ( $data as $notice ) + + //add_filter( 'mycred_notifications', create_function( '$query', '$query[]=\'' . $notice . '\'; return $query;' ) ); + //replacing above filter second param create function with annonymus function to remove depricated error and passed notice + add_filter( 'mycred_notifications', function ($query) use ($notice){ $query[]= $notice ; return $query; } ); + + + delete_transient( 'mycred_notice_' . $user_id ); + + } + + /** + * Settings Page + * @since 1.2.3 + * @version 1.2 + */ + public function after_general_settings( $mycred = NULL ) { + + $prefs = $this->notifications; + +?> +

    - core->allowed_html_tags()); - $new_data['notifications']['life'] = absint($data['notifications']['life']); - $new_data['notifications']['duration'] = absint($data['notifications']['duration']); + $new_data['notifications']['use_css'] = ( isset( $data['notifications']['use_css'] ) ) ? 1: 0; + $new_data['notifications']['template'] = wp_kses( $data['notifications']['template'], $this->core->allowed_html_tags() ); + $new_data['notifications']['life'] = absint( $data['notifications']['life'] ); + $new_data['notifications']['duration'] = absint( $data['notifications']['duration'] ); - // As of 1.6, we are going from miliseconds to seconds. - if (strlen($new_data['notifications']['duration']) >= 3 ) { - $new_data['notifications']['duration'] = $new_data['notifications']['duration'] / 1000; - } + // As of 1.6, we are going from miliseconds to seconds. + if ( strlen( $new_data['notifications']['duration'] ) >= 3 ) + $new_data['notifications']['duration'] = $new_data['notifications']['duration'] / 1000; - return $new_data; + return $new_data; - } - } + } + } endif; /** * Load Notifications Module - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_load_notices_addon') ) : - function mycred_load_notices_addon( $modules, $point_types ) - { +if ( ! function_exists( 'mycred_load_notices_addon' ) ) : + function mycred_load_notices_addon( $modules, $point_types ) { - $modules['solo']['notices'] = new myCRED_Notifications_Module(); - $modules['solo']['notices']->load(); + $modules['solo']['notices'] = new myCRED_Notifications_Module(); + $modules['solo']['notices']->load(); - return $modules; + return $modules; - } + } endif; -add_filter('mycred_load_modules', 'mycred_load_notices_addon', 70, 2); +add_filter( 'mycred_load_modules', 'mycred_load_notices_addon', 70, 2 ); /** * Add Notice - * - * @since 1.2.3 + * @since 1.2.3 * @version 1.0 */ -if (! function_exists('mycred_add_new_notice') ) : - function mycred_add_new_notice( $notice = array(), $life = 1 ) - { +if ( ! function_exists( 'mycred_add_new_notice' ) ) : + function mycred_add_new_notice( $notice = array(), $life = 1 ) { - // Minimum requirements - if (! isset($notice['user_id']) || ! isset($notice['message']) ) { return false; - } + // Minimum requirements + if ( ! isset( $notice['user_id'] ) || ! isset( $notice['message'] ) ) return false; - // Get transient - $data = get_transient('mycred_notice_' . $notice['user_id']); + // Get transient + $data = get_transient( 'mycred_notice_' . $notice['user_id'] ); - // If none exists create a new array - if ($data === false || ! is_array($data) ) { - $notices = array(); - } else { - $notices = $data; - } + // If none exists create a new array + if ( $data === false || ! is_array( $data ) ) + $notices = array(); + else + $notices = $data; - // Add new notice - $notices[] = addslashes($notice['message']); + // Add new notice + $notices[] = addslashes( $notice['message'] ); - // Save as a transient - set_transient('mycred_notice_' . $notice['user_id'], $notices, 86400*$life); + // Save as a transient + set_transient( 'mycred_notice_' . $notice['user_id'], $notices, 86400*$life ); - } + } endif; diff --git a/addons/ranks/assets/index.php b/addons/ranks/assets/index.php index 1580272..4e6c07c 100644 --- a/addons/ranks/assets/index.php +++ b/addons/ranks/assets/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/ranks/assets/js/index.php b/addons/ranks/assets/js/index.php index 1580272..4e6c07c 100644 --- a/addons/ranks/assets/js/index.php +++ b/addons/ranks/assets/js/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/ranks/assets/js/management.js b/addons/ranks/assets/js/management.js index ccdb43f..05c698c 100644 --- a/addons/ranks/assets/js/management.js +++ b/addons/ranks/assets/js/management.js @@ -1,105 +1,94 @@ /** * myCRED Management Scripts - * - * @since 1.3 + * @since 1.3 * @version 1.1.1 */ -jQuery( - function ($) { - - var mycred_action_delete_ranks = function ( button, pointtype ) { - var label = button.val(); - $.ajax( - { - type : "POST", - data : { - action : 'mycred-action-delete-ranks', - token : myCRED_Ranks.token, - ctype : pointtype - }, - dataType : "JSON", - url : myCRED_Ranks.ajaxurl, - beforeSend : function () { - button.attr('value', myCRED_Ranks.working); - button.attr('disabled', 'disabled'); - }, - success : function ( data ) { - console.log(data); - - if (data.status == 'OK' ) { - $('input#mycred-ranks-no-of-ranks').val(data.rows); - button.val(myCREDmanage.done); - button.removeClass('button-primary'); - } - else { - button.val(label); - button.removeAttr('disabled'); - } - }, - error : function ( jqXHR, textStatus, errorThrown ) { - // Debug - console.log(textStatus + ':' + errorThrown); - button.attr('value', label); - button.removeAttr('disabled'); - } - } - ); - }; - - $('input#mycred-manage-action-reset-ranks').click( - function () { - // Confirm action - if (confirm(myCRED_Ranks.confirm_del) ) { - mycred_action_delete_ranks($(this), $(this).data('type')); - } - } - ); - - var mycred_action_assign_ranks = function ( button, pointtype ) { - var label = button.val(); - $.ajax( - { - type : "POST", - data : { - action : 'mycred-action-assign-ranks', - token : myCRED_Ranks.token, - ctype : pointtype - }, - dataType : "JSON", - url : myCRED_Ranks.ajaxurl, - beforeSend : function () { - button.attr('value', myCRED_Ranks.working); - button.attr('disabled', 'disabled'); - }, - success : function ( data ) { - console.log(data); - - if (data.status == 'OK' ) { - button.val(myCREDmanage.done); - } - else { - button.val(label); - button.removeAttr('disabled'); - } - }, - error : function ( jqXHR, textStatus, errorThrown ) { - // Debug - console.log(textStatus + ':' + errorThrown); - button.attr('value', label); - button.removeAttr('disabled'); - } - } - ); - }; - - $('input#mycred-manage-action-assign-ranks').click( - function () { - // Confirm action - if (confirm(myCRED_Ranks.confirm_assign) ) { - mycred_action_assign_ranks($(this), $(this).data('type')); - } - } - ); +jQuery(function($){ + + var mycred_action_delete_ranks = function( button, pointtype ) { + var label = button.val(); + $.ajax({ + type : "POST", + data : { + action : 'mycred-action-delete-ranks', + token : myCRED_Ranks.token, + ctype : pointtype + }, + dataType : "JSON", + url : myCRED_Ranks.ajaxurl, + beforeSend : function() { + button.attr( 'value', myCRED_Ranks.working ); + button.attr( 'disabled', 'disabled' ); + }, + success : function( data ) { + console.log( data ); + + if ( data.status == 'OK' ) { + $( 'input#mycred-ranks-no-of-ranks' ).val( data.rows ); + button.val( myCREDmanage.done ); + button.removeClass( 'button-primary' ); + } + else { + button.val( label ); + button.removeAttr( 'disabled' ); + } + }, + error : function( jqXHR, textStatus, errorThrown ) { + // Debug + console.log( textStatus + ':' + errorThrown ); + button.attr( 'value', label ); + button.removeAttr( 'disabled' ); + } + }); + }; + + $( 'input#mycred-manage-action-reset-ranks' ).click(function(){ + // Confirm action + if ( confirm( myCRED_Ranks.confirm_del ) ) { + mycred_action_delete_ranks( $(this), $(this).data( 'type' ) ); + } + }); + + var mycred_action_assign_ranks = function( button, pointtype ) { + var label = button.val(); + $.ajax({ + type : "POST", + data : { + action : 'mycred-action-assign-ranks', + token : myCRED_Ranks.token, + ctype : pointtype + }, + dataType : "JSON", + url : myCRED_Ranks.ajaxurl, + beforeSend : function() { + button.attr( 'value', myCRED_Ranks.working ); + button.attr( 'disabled', 'disabled' ); + }, + success : function( data ) { + console.log( data ); + + if ( data.status == 'OK' ) { + button.val( myCREDmanage.done ); + } + else { + button.val( label ); + button.removeAttr( 'disabled' ); + } + }, + error : function( jqXHR, textStatus, errorThrown ) { + // Debug + console.log( textStatus + ':' + errorThrown ); + button.attr( 'value', label ); + button.removeAttr( 'disabled' ); + } + }); + }; + + $( 'input#mycred-manage-action-assign-ranks' ).click(function(){ + // Confirm action + if ( confirm( myCRED_Ranks.confirm_assign ) ) { + mycred_action_assign_ranks( $(this), $(this).data( 'type' ) ); + } + }); - } -); \ No newline at end of file +}); \ No newline at end of file diff --git a/addons/ranks/assets/js/tweaks.js b/addons/ranks/assets/js/tweaks.js index 34bf4cb..6d88593 100644 --- a/addons/ranks/assets/js/tweaks.js +++ b/addons/ranks/assets/js/tweaks.js @@ -1,21 +1,18 @@ /** * myCRED Rank Tweaks - * - * @since 1.6 + * @since 1.6 * @version 1.0.1 */ -(function ($) { +(function($) { - // When the page has loaded, append the point type to the "Add New" button url - // This will make sure the new rank is created for the correct point type. - $(document).ready( - function () { + // When the page has loaded, append the point type to the "Add New" button url + // This will make sure the new rank is created for the correct point type. + $( document ).ready(function() { - var newurl = $('a.add-new-h2').attr('href'); - newurl = newurl + '&ctype=' + myCRED_Ranks.rank_ctype; - $('a.add-new-h2').attr('href', newurl); + var newurl = $( 'a.add-new-h2' ).attr( 'href' ); + newurl = newurl + '&ctype=' + myCRED_Ranks.rank_ctype; + $( 'a.add-new-h2' ).attr( 'href', newurl ); - } - ); + }); -})(jQuery); \ No newline at end of file +})( jQuery ); \ No newline at end of file diff --git a/addons/ranks/includes/index.php b/addons/ranks/includes/index.php index 1580272..4e6c07c 100644 --- a/addons/ranks/includes/index.php +++ b/addons/ranks/includes/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/ranks/includes/mycred-rank-functions.php b/addons/ranks/includes/mycred-rank-functions.php index 60cc799..57aabb0 100644 --- a/addons/ranks/includes/mycred-rank-functions.php +++ b/addons/ranks/includes/mycred-rank-functions.php @@ -1,499 +1,445 @@ $count ) { - $total += $count; - } + $have_ranks = false; + $total = 0; + foreach ( wp_count_posts( MYCRED_RANK_KEY ) as $status => $count ) { + $total += $count; + } - if ($total > 0 ) { - $have_ranks = true; - } + if ( $total > 0 ) + $have_ranks = true; - return apply_filters('mycred_have_ranks', $have_ranks, $point_type, $count); + return apply_filters( 'mycred_have_ranks', $have_ranks, $point_type, $count ); - } + } endif; /** * Have Published Ranks * Checks if there are any published rank posts. - * * @returns (int) the number of published ranks found. - * @since 1.3.2 + * @since 1.3.2 * @version 1.2 */ -if (! function_exists('mycred_get_published_ranks_count') ) : - function mycred_get_published_ranks_count( $point_type = null ) - { +if ( ! function_exists( 'mycred_get_published_ranks_count' ) ) : + function mycred_get_published_ranks_count( $point_type = NULL ) { - $count = wp_count_posts(MYCRED_RANK_KEY)->publish; + $count = wp_count_posts( MYCRED_RANK_KEY )->publish; - if ($point_type === null ) { + if ( $point_type === NULL ) { - $cache_key = 'ranks-published-count-' . $point_type; - $count = wp_cache_get($cache_key, MYCRED_SLUG); + $cache_key = 'ranks-published-count-' . $point_type; + $count = wp_cache_get( $cache_key, MYCRED_SLUG ); - if ($count === false ) { + if ( $count === false ) { - global $wpdb; + global $wpdb; - $posts = mycred_get_db_column('posts'); - $type_filter = ''; + $posts = mycred_get_db_column( 'posts' ); + $type_filter = ''; - if ($point_type !== null && mycred_point_type_exists(sanitize_key($point_type)) ) { + if ( $point_type !== NULL && mycred_point_type_exists( sanitize_key( $point_type ) ) ) { - $postmeta = mycred_get_db_column('postmeta'); - $type_filter = $wpdb->prepare("INNER JOIN {$postmeta} ctype ON ( ranks.ID = ctype.post_id AND ctype.meta_key = 'ctype' AND ctype.meta_value = %s )", $point_type); + $postmeta = mycred_get_db_column( 'postmeta' ); + $type_filter = $wpdb->prepare( "INNER JOIN {$postmeta} ctype ON ( ranks.ID = ctype.post_id AND ctype.meta_key = 'ctype' AND ctype.meta_value = %s )", $point_type ); - } + } - $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$posts} ranks {$type_filter} WHERE ranks.post_type = %s AND ranks.post_status = 'publish';", MYCRED_RANK_KEY)); - if ($count === null ) { $count = 0; - } + $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$posts} ranks {$type_filter} WHERE ranks.post_type = %s AND ranks.post_status = 'publish';", MYCRED_RANK_KEY ) ); + if ( $count === NULL ) $count = 0; - wp_cache_set($cache_key, $count, MYCRED_SLUG); + wp_cache_set( $cache_key, $count, MYCRED_SLUG ); - } + } - } + } - return apply_filters('mycred_get_published_ranks_count', $count, $point_type); + return apply_filters( 'mycred_get_published_ranks_count', $count, $point_type ); - } + } endif; /** * Get Rank Object ID * Makes sure a given post ID is a rank post ID or converts a rank title into a rank ID. - * - * @since 1.7 + * @since 1.7 * @version 1.2 */ -if (! function_exists('mycred_get_rank_object_id') ) : - function mycred_get_rank_object_id( $identifier = null ) - { +if ( ! function_exists( 'mycred_get_rank_object_id' ) ) : + function mycred_get_rank_object_id( $identifier = NULL ) { - if ($identifier === null ) { return false; - } + if ( $identifier === NULL ) return false; - $rank_id = false; + $rank_id = false; - if (absint($identifier) !== 0 && mycred_get_post_type(absint($identifier)) == MYCRED_RANK_KEY ) { - $rank_id = absint($identifier); + if ( absint( $identifier ) !== 0 && mycred_get_post_type( absint( $identifier ) ) == MYCRED_RANK_KEY ) + $rank_id = absint( $identifier ); - } else { + else { - $rank = mycred_get_page_by_title($identifier, OBJECT, MYCRED_RANK_KEY); - if (isset($rank->post_type) && $rank->post_type === MYCRED_RANK_KEY ) { - $rank_id = $rank->ID; - } + $rank = mycred_get_page_by_title( $identifier, OBJECT, MYCRED_RANK_KEY ); + if ( isset( $rank->post_type ) && $rank->post_type === MYCRED_RANK_KEY ) + $rank_id = $rank->ID; - } + } - return $rank_id; + return $rank_id; - } + } endif; /** * Get Rank * Returns the rank object. - * - * @since 1.1 + * @since 1.1 * @version 1.3 */ -if (! function_exists('mycred_get_rank') ) : - function mycred_get_rank( $rank_identifier = null ) - { +if ( ! function_exists( 'mycred_get_rank' ) ) : + function mycred_get_rank( $rank_identifier = NULL ) { - global $mycred_rank; + global $mycred_rank; - $rank_id = mycred_get_rank_object_id($rank_identifier); - if ($rank_id === false ) { return false; - } + $rank_id = mycred_get_rank_object_id( $rank_identifier ); + if ( $rank_id === false ) return false; - if (isset($mycred_rank) - && ( $mycred_rank instanceof myCRED_Rank ) - && ( $rank_id === $mycred_rank->post_id ) - ) { - return $mycred_rank; - } + if ( isset( $mycred_rank ) + && ( $mycred_rank instanceof myCRED_Rank ) + && ( $rank_id === $mycred_rank->post_id ) + ) { + return $mycred_rank; + } - $mycred_rank = new myCRED_Rank($rank_id); + $mycred_rank = new myCRED_Rank( $rank_id ); - do_action('mycred_get_rank'); + do_action( 'mycred_get_rank' ); - return $mycred_rank; + return $mycred_rank; - } + } endif; /** * Rank Has Logo * Checks if a given rank has a logo. - * - * @since 1.1 + * @since 1.1 * @version 1.5 */ -if (! function_exists('mycred_rank_has_logo') ) : - function mycred_rank_has_logo( $rank_identifier = null ) - { +if ( ! function_exists( 'mycred_rank_has_logo' ) ) : + function mycred_rank_has_logo( $rank_identifier = NULL ) { - $return = false; - $rank_id = mycred_get_rank_object_id($rank_identifier); + $return = false; + $rank_id = mycred_get_rank_object_id( $rank_identifier ); - if ($rank_id === false ) { return $return; - } + if ( $rank_id === false ) return $return; - if (mycred_override_settings() && ! mycred_is_main_site() ) { + if ( mycred_override_settings() && ! mycred_is_main_site() ) { - switch_to_blog(get_network()->site_id); + switch_to_blog( get_network()->site_id ); - if (has_post_thumbnail($rank_id) ) { - $return = true; - } + if ( has_post_thumbnail( $rank_id ) ) + $return = true; - restore_current_blog(); + restore_current_blog(); - } + } - else { + else { - if (has_post_thumbnail($rank_id) ) { - $return = true; - } + if ( has_post_thumbnail( $rank_id ) ) + $return = true; - } + } - return apply_filters('mycred_rank_has_logo', $return, $rank_id); + return apply_filters( 'mycred_rank_has_logo', $return, $rank_id ); - } + } endif; /** * Get Rank Logo * Returns the given ranks logo. - * - * @since 1.1 + * @since 1.1 * @version 1.4 */ -if (! function_exists('mycred_get_rank_logo') ) : - function mycred_get_rank_logo( $rank_identifier = null, $size = 'post-thumbnail', $attr = null ) - { +if ( ! function_exists( 'mycred_get_rank_logo' ) ) : + function mycred_get_rank_logo( $rank_identifier = NULL, $size = 'post-thumbnail', $attr = NULL ) { - $rank_id = mycred_get_rank_object_id($rank_identifier); - if ($rank_id === false ) { return false; - } + $rank_id = mycred_get_rank_object_id( $rank_identifier ); + if ( $rank_id === false ) return false; - if (is_numeric($size) ) { - $size = array( $size, $size ); - } + if ( is_numeric( $size ) ) + $size = array( $size, $size ); - if (mycred_override_settings() && ! mycred_is_main_site() ) { + if ( mycred_override_settings() && ! mycred_is_main_site() ) { - switch_to_blog(get_network()->site_id); + switch_to_blog( get_network()->site_id ); - $logo = get_the_post_thumbnail($rank_id, $size, $attr); + $logo = get_the_post_thumbnail( $rank_id, $size, $attr ); - restore_current_blog(); + restore_current_blog(); - } + } - else { + else { - $logo = get_the_post_thumbnail($rank_id, $size, $attr); + $logo = get_the_post_thumbnail( $rank_id, $size, $attr ); - } + } - return apply_filters('mycred_get_rank_logo', $logo, $rank_id, $size, $attr); + return apply_filters( 'mycred_get_rank_logo', $logo, $rank_id, $size, $attr ); - } + } endif; /** * Count Users with Rank - * - * @since 1.6 + * @since 1.6 * @version 1.2 */ -if (! function_exists('mycred_count_users_with_rank') ) : - function mycred_count_users_with_rank( $rank_identifier = null ) - { +if ( ! function_exists( 'mycred_count_users_with_rank' ) ) : + function mycred_count_users_with_rank( $rank_identifier = NULL ) { - $rank_id = mycred_get_rank_object_id($rank_identifier); - if ($rank_id === false ) { return 0; - } + $rank_id = mycred_get_rank_object_id( $rank_identifier ); + if ( $rank_id === false ) return 0; - $user_count = mycred_get_post_meta($rank_id, 'mycred_rank_users', true); + $user_count = mycred_get_post_meta( $rank_id, 'mycred_rank_users', true ); - if (empty($user_count) ) { + if ( empty($user_count) ) { - $point_type = mycred_get_post_meta($rank_id, 'ctype', true); - if ($point_type == '' ) { return 0; - } + $point_type = mycred_get_post_meta( $rank_id, 'ctype', true ); + if ( $point_type == '' ) return 0; - global $wpdb; + global $wpdb; - $user_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT( user_id ) FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value = %d;", mycred_get_meta_key(MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' )), $rank_id)); + $user_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( user_id ) FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value = %d;", mycred_get_meta_key( MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' ) ), $rank_id ) ); - if ($user_count === null ) { $user_count = 0; - } + if ( $user_count === NULL ) $user_count = 0; - mycred_update_post_meta($rank_id, 'mycred_rank_users', $user_count); + mycred_update_post_meta( $rank_id, 'mycred_rank_users', $user_count ); - } + } - return $user_count; + return $user_count; - } + } endif; /** * Get Users Rank ID * Returns the rank post ID for the given point type. - * - * @since 1.6 + * @since 1.6 * @version 1.0.1 */ -if (! function_exists('mycred_get_users_rank_id') ) : - function mycred_get_users_rank_id( $user_id = null, $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_get_users_rank_id' ) ) : + function mycred_get_users_rank_id( $user_id = NULL, $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - if ($user_id === null ) { - $user_id = get_current_user_id(); - } + if ( $user_id === NULL ) + $user_id = get_current_user_id(); - $user_id = absint($user_id); - if ($user_id === 0 ) { return false; - } + $user_id = absint( $user_id ); + if ( $user_id === 0 ) return false; - $account_object = mycred_get_account($user_id); - if (isset($account_object->ranks) && $account_object->balance[ $point_type ] !== false && ! empty($account_object->balance[ $point_type ]->rank) ) { - return $account_object->balance[ $point_type ]->rank->post_id; - } + $account_object = mycred_get_account( $user_id ); + if ( isset( $account_object->ranks ) && $account_object->balance[ $point_type ] !== false && ! empty( $account_object->balance[ $point_type ]->rank ) ) + return $account_object->balance[ $point_type ]->rank->post_id; - $rank_id = mycred_get_user_meta($user_id, MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' ), true); + $rank_id = mycred_get_user_meta( $user_id, MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' ), true ); - if ($rank_id == '' ) { + if ( $rank_id == '' ) { - $rank = mycred_find_users_rank($user_id, $point_type); + $rank = mycred_find_users_rank( $user_id, $point_type ); - // Found a rank, save it - if ($rank !== false ) { - mycred_save_users_rank($user_id, $rank->rank_id, $point_type); - $rank_id = $rank->rank_id; - } + // Found a rank, save it + if ( $rank !== false ) { + mycred_save_users_rank( $user_id, $rank->rank_id, $point_type ); + $rank_id = $rank->rank_id; + } - } + } - return $rank_id; + return $rank_id; - } + } endif; /** * Save Users Rank * Saves a given rank for a user. - * - * @since 1.7.4 + * @since 1.7.4 * @version 1.0 */ -if (! function_exists('mycred_save_users_rank') ) : - function mycred_save_users_rank( $user_id = null, $rank_id = null, $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_save_users_rank' ) ) : + function mycred_save_users_rank( $user_id = NULL, $rank_id = NULL, $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - if ($user_id === null || $rank_id === null ) { return false; - } + if ( $user_id === NULL || $rank_id === NULL ) return false; - $user_id = absint($user_id); - $rank_id = absint($rank_id); - $point_type = sanitize_key($point_type); + $user_id = absint( $user_id ); + $rank_id = absint( $rank_id ); + $point_type = sanitize_key( $point_type ); - $current_rank = mycred_get_users_current_rank_id($user_id, $point_type); + $current_rank = mycred_get_users_current_rank_id( $user_id, $point_type ); - if (!$current_rank || $current_rank != $rank_id ) { - - global $mycred_current_account; + if ( !$current_rank || $current_rank != $rank_id ) { + + global $mycred_current_account; - //Divest Old Rank - if (! empty($current_rank) ) { - $old_rank = new myCRED_Rank($current_rank); + //Divest Old Rank + if ( ! empty( $current_rank ) ) + { + $old_rank = new myCRED_Rank( $current_rank ); - $old_rank->divest($user_id); - } + $old_rank->divest( $user_id ); + } - mycred_update_user_rank_id($user_id, $rank_id); + mycred_update_user_rank_id( $user_id, $rank_id ); - $new_rank = new myCRED_Rank($rank_id); - $new_rank->assign($user_id); + $new_rank = new myCRED_Rank( $rank_id ); + $new_rank->assign( $user_id ); - if (isset($mycred_current_account->user_id) - && $mycred_current_account->user_id == $user_id - && isset($mycred_current_account->ranks) - && $mycred_current_account->balance[ $point_type ] !== false - ) { - $mycred_current_account->balance[ $point_type ]->rank = $new_rank; - } + if ( + isset( $mycred_current_account->user_id ) && + $mycred_current_account->user_id == $user_id && + isset( $mycred_current_account->ranks ) && + $mycred_current_account->balance[ $point_type ] !== false + ) + $mycred_current_account->balance[ $point_type ]->rank = $new_rank; - } + } - return true; + return true; - } + } endif; /** * Get My Rank * Returns the current users rank - * - * @since 1.1 + * @since 1.1 * @version 1.2 */ -if (! function_exists('mycred_get_my_rank') ) : - function mycred_get_my_rank( $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_get_my_rank' ) ) : + function mycred_get_my_rank( $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - if (! is_user_logged_in() ) { return; - } + if ( ! is_user_logged_in() ) return; - $account = mycred_get_current_account(); - if ($account !== false ) { - return $account->balance[ $point_type ]->rank; - } + $account = mycred_get_current_account(); + if ( $account !== false ) + return $account->balance[ $point_type ]->rank; - return mycred_get_users_rank(get_current_user_id(), $point_type); + return mycred_get_users_rank( get_current_user_id(), $point_type ); - } + } endif; /** * Get Users Rank * Retreaves the users current saved rank or if rank is missing * finds the appropriate rank and saves it. - * - * @since 1.1 + * @since 1.1 * @version 1.7 */ -if (! function_exists('mycred_get_users_rank') ) : - function mycred_get_users_rank( $user_id = null, $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_get_users_rank' ) ) : + function mycred_get_users_rank( $user_id = NULL, $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $rank = false; + $rank = false; - // User ID is required - if ($user_id === null || ! is_numeric($user_id) ) { return $rank; - } + // User ID is required + if ( $user_id === NULL || ! is_numeric( $user_id ) ) return $rank; - $user_id = absint($user_id); - $account_object = mycred_get_account($user_id); - if (isset($account_object->ranks) && $account_object->balance[ $point_type ] !== false ) { - return $account_object->balance[ $point_type ]->rank; - } + $user_id = absint( $user_id ); + $account_object = mycred_get_account( $user_id ); + if ( isset( $account_object->ranks ) && $account_object->balance[ $point_type ] !== false ) + return $account_object->balance[ $point_type ]->rank; - // Get users rank - $rank_id = mycred_get_user_meta($user_id, MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' ), true); + // Get users rank + $rank_id = mycred_get_user_meta( $user_id, MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' ), true ); - // No rank, try to assign one - if ($rank_id == '' ) { + // No rank, try to assign one + if ( $rank_id == '' ) { - $rank = mycred_find_users_rank($user_id, $point_type); + $rank = mycred_find_users_rank( $user_id, $point_type ); - // Found a rank, save it - if ($rank !== false ) { - mycred_save_users_rank($user_id, $rank->rank_id, $point_type); - $rank_id = $rank->rank_id; - } + // Found a rank, save it + if ( $rank !== false ) { + mycred_save_users_rank( $user_id, $rank->rank_id, $point_type ); + $rank_id = $rank->rank_id; + } - } + } - // Get Rank object - if ($rank_id != '' ) { - $rank = mycred_get_rank($rank_id); - } + // Get Rank object + if ( $rank_id != '' ) + $rank = mycred_get_rank( $rank_id ); - return apply_filters('mycred_get_users_rank', $rank, $user_id, $rank_id, $point_type); + return apply_filters( 'mycred_get_users_rank', $rank, $user_id, $rank_id, $point_type ); - } + } endif; /** * Find Users Rank * Attenots to find a particular users rank for a particular point type. - * - * @uses mycred_user_got_demoted if user got demoted to a lower rank. - * @uses mycred_user_got_promoted if user got promoted to a higher rank. - * @since 1.1 + * @uses mycred_user_got_demoted if user got demoted to a lower rank. + * @uses mycred_user_got_promoted if user got promoted to a higher rank. + * @since 1.1 * @version 1.7 */ -if (! function_exists('mycred_find_users_rank') ) : - function mycred_find_users_rank( $user_id = null, $point_type = MYCRED_DEFAULT_TYPE_KEY, $act = true ) - { +if ( ! function_exists( 'mycred_find_users_rank' ) ) : + function mycred_find_users_rank( $user_id = NULL, $point_type = MYCRED_DEFAULT_TYPE_KEY, $act = true ) { - if (mycred_manual_ranks() ) { return false; - } + if ( mycred_manual_ranks() ) return false; - if ($user_id === null ) { $user_id = get_current_user_id(); - } + if ( $user_id === NULL ) $user_id = get_current_user_id(); - // Non logged in users have ID 0. - if (absint($user_id) === 0 ) { return false; - } + // Non logged in users have ID 0. + if ( absint( $user_id ) === 0 ) return false; - $user_id = absint($user_id); - $account_object = mycred_get_account($user_id); - $balance_object = $account_object->balance[ $point_type ]; + $user_id = absint( $user_id ); + $account_object = mycred_get_account( $user_id ); + $balance_object = $account_object->balance[ $point_type ]; - if ($balance_object === false ) { return false; - } + if ( $balance_object === false ) return false; - if (isset($account_object->ranks) ) { - $current_rank_id = ( ! empty($balance_object->rank) ) ? $balance_object->rank->post_id : false; - $current_rank = ( ! empty($balance_object->rank) ) ? $balance_object->rank : false; - } + if ( isset( $account_object->ranks ) ) { + $current_rank_id = ( ! empty( $balance_object->rank ) ) ? $balance_object->rank->post_id : false; + $current_rank = ( ! empty( $balance_object->rank ) ) ? $balance_object->rank : false; + } - else { - $current_rank_id = mycred_get_user_meta($user_id, MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' ), true); - $current_rank = ( $current_rank_id != '' ) ? mycred_get_rank($current_rank_id) : false; - } + else { + $current_rank_id = mycred_get_user_meta( $user_id, MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' ), true ); + $current_rank = ( $current_rank_id != '' ) ? mycred_get_rank( $current_rank_id ) : false; + } - $balance = $balance_object->current; - if (mycred_rank_based_on_total($point_type) ) { - $balance = $balance_object->accumulated; - } + $balance = $balance_object->current; + if ( mycred_rank_based_on_total( $point_type ) ) + $balance = $balance_object->accumulated; - // We are still within the set requirements - if ($current_rank !== false && $balance >= $current_rank->minimum && $balance <= $current_rank->maximum ) { - return false; - } + // We are still within the set requirements + if ( $current_rank !== false && $balance >= $current_rank->minimum && $balance <= $current_rank->maximum ) + return false; - global $wpdb; + global $wpdb; - // Prep format for the db query - $balance_format = ( isset($balance_object->point_type->sql_format) ) ? $balance_object->point_type->sql_format : '%d'; + // Prep format for the db query + $balance_format = ( isset( $balance_object->point_type->sql_format ) ) ? $balance_object->point_type->sql_format : '%d'; - // Get the appropriate post tables - $posts = mycred_get_db_column('posts'); - $postmeta = mycred_get_db_column('postmeta'); + // Get the appropriate post tables + $posts = mycred_get_db_column( 'posts' ); + $postmeta = mycred_get_db_column( 'postmeta' ); - // See where the users balance fits in - $results = $wpdb->get_row( - $wpdb->prepare( - " + // See where the users balance fits in + $results = $wpdb->get_row( $wpdb->prepare( " SELECT ranks.ID AS rank_id, min.meta_value AS minimum, max.meta_value AS maximum FROM {$posts} ranks INNER JOIN {$postmeta} ctype ON ( ranks.ID = ctype.post_id AND ctype.meta_key = 'ctype' AND ctype.meta_value = %s ) @@ -502,139 +448,121 @@ function mycred_find_users_rank( $user_id = null, $point_type = MYCRED_DEFAULT_T WHERE ranks.post_type = %s AND ranks.post_status = 'publish' AND {$balance_format} BETWEEN min.meta_value AND max.meta_value - LIMIT 0,1;", $point_type, MYCRED_RANK_KEY, $balance - ) - ); + LIMIT 0,1;", $point_type, MYCRED_RANK_KEY, $balance ) ); - if (isset($results->rank_id) ) { - $results->current_id = $current_rank_id; - } + if ( isset( $results->rank_id ) ) + $results->current_id = $current_rank_id; - // Found a new rank - if ($act === true && isset($results->rank_id) ) { + // Found a new rank + if ( $act === true && isset( $results->rank_id ) ) { - // Demotions - if ($results->current_id !== false && $current_rank !== false && $current_rank->maximum > $results->maximum ) { - do_action('mycred_user_got_demoted', $user_id, $current_rank_id, $current_rank, $point_type); - } + // Demotions + if ( $results->current_id !== false && $current_rank !== false && $current_rank->maximum > $results->maximum ) + do_action( 'mycred_user_got_demoted', $user_id, $current_rank_id, $current_rank, $point_type ); - // Promotions - else { + // Promotions + else { - do_action('mycred_user_got_promoted', $user_id, $results->rank_id, $results, $point_type); + do_action( 'mycred_user_got_promoted', $user_id, $results->rank_id, $results, $point_type ); - } + } - // Reset counters - if ($current_rank !== false ) { - mycred_delete_post_meta($current_rank->post_id, 'mycred_rank_users'); - } + // Reset counters + if ( $current_rank !== false ) + mycred_delete_post_meta( $current_rank->post_id, 'mycred_rank_users' ); - mycred_delete_post_meta($results->rank_id, 'mycred_rank_users'); + mycred_delete_post_meta( $results->rank_id, 'mycred_rank_users' ); - } + } - if ($results === null ) { - $results = false; - } + if ( $results === NULL ) + $results = false; - return apply_filters('mycred_find_users_rank', $results, $user_id, $point_type); + return apply_filters( 'mycred_find_users_rank', $results, $user_id, $point_type ); - } + } endif; /** * Assign Ranks * Runs though all user balances and assigns each users their * appropriate ranks. - * * @returns count - * @since 1.3.2 + * @since 1.3.2 * @version 1.7 */ -if (! function_exists('mycred_assign_ranks') ) : - function mycred_assign_ranks( $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_assign_ranks' ) ) : + function mycred_assign_ranks( $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - if (mycred_manual_ranks() ) { return 0; - } + if ( mycred_manual_ranks() ) return 0; - global $wpdb; - $type_object = new myCRED_Point_Type($point_type); - $rank_key = mycred_get_meta_key(MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' )); + global $wpdb; + $type_object = new myCRED_Point_Type( $point_type ); + $rank_key = mycred_get_meta_key( MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' ) ); - $balance_key = mycred_get_meta_key($point_type); - $mycred = mycred($point_type); - if (isset($mycred->rank['base']) && $mycred->rank['base'] == 'total' ) { - $balance_key = mycred_get_meta_key($point_type, '_total'); - } + $balance_key = mycred_get_meta_key( $point_type ); + $mycred = mycred( $point_type ); + if ( isset( $mycred->rank['base'] ) && $mycred->rank['base'] == 'total' ) + $balance_key = mycred_get_meta_key( $point_type, '_total' ); - $ranks = mycred_get_ranks('publish', '-1', 'ASC', $point_type); - $balance_format = ( isset($type_object->sql_format) ) ? $type_object->sql_format : '%d'; + $ranks = mycred_get_ranks( 'publish', '-1', 'ASC', $point_type ); + $balance_format = ( isset( $type_object->sql_format ) ) ? $type_object->sql_format : '%d'; - do_action('mycred_assign_ranks_start'); + do_action( 'mycred_assign_ranks_start' ); - $count = 0; - if (! empty($ranks) ) { - foreach ( $ranks as $rank ) { + $count = 0; + if ( ! empty( $ranks ) ) { + foreach ( $ranks as $rank ) { - $count += $wpdb->query( - $wpdb->prepare( - " + $count += $wpdb->query( $wpdb->prepare( " UPDATE {$wpdb->usermeta} ranks INNER JOIN {$wpdb->usermeta} balance ON ( ranks.user_id = balance.user_id AND balance.meta_key = %s ) SET ranks.meta_value = %d WHERE ranks.meta_key = %s - AND balance.meta_value BETWEEN {$balance_format} AND {$balance_format};", $balance_key, $rank->post_id, $rank_key, $rank->minimum, $rank->maximum - ) - ); + AND balance.meta_value BETWEEN {$balance_format} AND {$balance_format};", $balance_key, $rank->post_id, $rank_key, $rank->minimum, $rank->maximum ) ); - mycred_delete_post_meta($rank->post_id, 'mycred_rank_users'); + mycred_delete_post_meta( $rank->post_id, 'mycred_rank_users' ); - } - } + } + } - do_action('mycred_assign_ranks_end'); + do_action( 'mycred_assign_ranks_end' ); - return $count; + return $count; - } + } endif; /** * Get Ranks * Returns an associative array of ranks with the given status. - * - * @param $status (string) post status, defaults to 'publish' - * @param $number (int|string) number of ranks to return, defaults to all - * @param $order (string) option to return ranks ordered Ascending or Descending - * @param $type (string) optional point type + * @param $status (string) post status, defaults to 'publish' + * @param $number (int|string) number of ranks to return, defaults to all + * @param $order (string) option to return ranks ordered Ascending or Descending + * @param $type (string) optional point type * @returns (array) empty if no ranks are found or associative array with post ID as key and title as value - * @since 1.1 + * @since 1.1 * @version 1.6 */ -if (! function_exists('mycred_get_ranks') ) : - function mycred_get_ranks( $status = 'publish', $number = '-1', $order = 'DESC', $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_get_ranks' ) ) : + function mycred_get_ranks( $status = 'publish', $number = '-1', $order = 'DESC', $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $cache_key = 'ranks-published-' . $point_type; - $ranks = wp_cache_get($cache_key, MYCRED_SLUG); - $results = array(); + $cache_key = 'ranks-published-' . $point_type; + $ranks = wp_cache_get( $cache_key, MYCRED_SLUG ); + $results = array(); - if ($ranks === false ) { + if ( $ranks === false ) { - global $wpdb; + global $wpdb; - $order = ( ! in_array($order, array( 'ASC', 'DESC' )) ) ? 'DESC' : $order; - $limit = ( $number != '-1' ) ? 'LIMIT 0,' . absint($number) : ''; + $order = ( ! in_array( $order, array( 'ASC', 'DESC' ) ) ) ? 'DESC' : $order; + $limit = ( $number != '-1' ) ? 'LIMIT 0,' . absint( $number ) : ''; - $posts = mycred_get_db_column('posts'); - $postmeta = mycred_get_db_column('postmeta'); + $posts = mycred_get_db_column( 'posts' ); + $postmeta = mycred_get_db_column( 'postmeta' ); - $rank_ids = $wpdb->get_col( - $wpdb->prepare( - " + $rank_ids = $wpdb->get_col( $wpdb->prepare( " SELECT ranks.ID FROM {$posts} ranks LEFT JOIN {$postmeta} ctype ON ( ranks.ID = ctype.post_id AND ctype.meta_key = 'ctype' ) @@ -642,154 +570,134 @@ function mycred_get_ranks( $status = 'publish', $number = '-1', $order = 'DESC', WHERE ranks.post_type = %s AND ranks.post_status = %s AND ctype.meta_value = %s - ORDER BY min.meta_value+0 {$order} {$limit};", MYCRED_RANK_KEY, $status, $point_type - ) - ); + ORDER BY min.meta_value+0 {$order} {$limit};", MYCRED_RANK_KEY, $status, $point_type ) ); - if (! empty($rank_ids) ) { + if ( ! empty( $rank_ids ) ) { - foreach ( $rank_ids as $rank_id ) { - $results[] = mycred_get_rank($rank_id); - } + foreach ( $rank_ids as $rank_id ) + $results[] = mycred_get_rank( $rank_id ); - } + } - wp_cache_set($cache_key, $results, MYCRED_SLUG); + wp_cache_set( $cache_key, $results, MYCRED_SLUG ); - } else { - $results = $ranks; - } + } else { + $results = $ranks; + } - return apply_filters('mycred_get_ranks', $results, $status, $number, $order); + return apply_filters( 'mycred_get_ranks', $results, $status, $number, $order ); - } + } endif; /** * Get Users of Rank * Returns an associative array of user IDs and display names of users for a given * rank. - * - * @param $rank (int|string) either a rank id or rank name - * @param $number (int) number of users to return + * @param $rank (int|string) either a rank id or rank name + * @param $number (int) number of users to return * @returns (array) empty if no users were found or associative array with user ID as key and display name as value - * @since 1.1 + * @since 1.1 * @version 1.6 */ -if (! function_exists('mycred_get_users_of_rank') ) : - function mycred_get_users_of_rank( $rank_identifier = null, $number = 25, $order = 'DESC', $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_get_users_of_rank' ) ) : + function mycred_get_users_of_rank( $rank_identifier = NULL, $number = 25, $order = 'DESC', $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $rank_id = mycred_get_rank_object_id($rank_identifier); - if ($rank_id === false || ! mycred_point_type_exists($point_type) ) { return false; - } + $rank_id = mycred_get_rank_object_id( $rank_identifier ); + if ( $rank_id === false || ! mycred_point_type_exists( $point_type ) ) return false; - $number = ( $number > 25 || $number < 0 ) ? 25 : absint($number); - $order = ( ! in_array($order, array( 'ASC', 'DESC' )) ) ? 'DESC' : $order; - $cache_key = 'ranks-users-' . $rank_id; - $users = wp_cache_get($cache_key, MYCRED_SLUG); + $number = ( $number > 25 || $number < 0 ) ? 25 : absint( $number ); + $order = ( ! in_array( $order, array( 'ASC', 'DESC' ) ) ) ? 'DESC' : $order; + $cache_key = 'ranks-users-' . $rank_id; + $users = wp_cache_get( $cache_key, MYCRED_SLUG ); - if ($users === false ) { + if ( $users === false ) { - global $wpdb; + global $wpdb; - $rank_meta_key = mycred_get_meta_key(MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' )); - $balance_key = mycred_get_meta_key($point_type); + $rank_meta_key = mycred_get_meta_key( MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' ) ); + $balance_key = mycred_get_meta_key( $point_type ); - $posts = mycred_get_db_column('posts'); - $postmeta = mycred_get_db_column('postmeta'); + $posts = mycred_get_db_column( 'posts' ); + $postmeta = mycred_get_db_column( 'postmeta' ); - $users = $wpdb->get_results( - $wpdb->prepare( - " + $users = $wpdb->get_results( $wpdb->prepare( " SELECT users.*, creds.meta_value AS balance FROM {$wpdb->users} users LEFT JOIN {$wpdb->usermeta} mycredrank ON ( users.ID = mycredrank.user_id AND mycredrank.meta_key = %s ) LEFT JOIN {$wpdb->usermeta} creds ON ( users.ID = creds.user_id AND creds.meta_key = %s ) WHERE mycredrank.meta_value = %d - ORDER BY creds.meta_value+0 DESC LIMIT 25;", $rank_meta_key, $balance_key, $rank_id - ) - ); + ORDER BY creds.meta_value+0 DESC LIMIT 25;", $rank_meta_key, $balance_key, $rank_id ) ); - wp_cache_set($cache_key, $users, MYCRED_SLUG); + wp_cache_set( $cache_key, $users, MYCRED_SLUG ); - } + } - $users = array_slice($users, 0, $number, true); + $users = array_slice( $users, 0, $number, true ); - if ($order == 'ASC' ) { $users = array_reverse($users, true); - } + if ( $order == 'ASC' ) $users = array_reverse( $users, true ); - return apply_filters('mycred_get_users_of_rank', $users, $rank_id, $number, $order, $point_type); + return apply_filters( 'mycred_get_users_of_rank', $users, $rank_id, $number, $order, $point_type ); - } + } endif; /** * Manual Ranks - * - * @since 1.8 + * @since 1.8 * @version 1.0 */ -if (! function_exists('mycred_manual_ranks') ) : - function mycred_manual_ranks( $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_manual_ranks' ) ) : + function mycred_manual_ranks( $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $prefs = mycred_get_addon_settings('rank', $point_type); + $prefs = mycred_get_addon_settings( 'rank', $point_type ); - $result = false; - if (! empty($prefs) && $prefs['base'] == 'manual' ) { - $result = true; - } + $result = false; + if ( ! empty( $prefs ) && $prefs['base'] == 'manual' ) + $result = true; - return $result; + return $result; - } + } endif; /** * Rank Based on Total * Checks if ranks for a given point type are based in total * balance. - * - * @since 1.6 + * @since 1.6 * @version 1.2 */ -if (! function_exists('mycred_rank_based_on_total') ) : - function mycred_rank_based_on_total( $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_rank_based_on_total' ) ) : + function mycred_rank_based_on_total( $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $prefs = mycred_get_addon_settings('rank', $point_type); + $prefs = mycred_get_addon_settings( 'rank', $point_type ); - $result = false; - if (! empty($prefs) && $prefs['base'] == 'total' ) { - $result = true; - } + $result = false; + if ( ! empty( $prefs ) && $prefs['base'] == 'total' ) + $result = true; - return $result; + return $result; - } + } endif; /** * Rank Based on Total * Checks if ranks for a given point type are based on current balance. - * - * @since 2.1 + * @since 2.1 * @version 1.0 */ -if (! function_exists('mycred_rank_based_on_current') ) : - function mycred_rank_based_on_current( $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_rank_based_on_current' ) ) : + function mycred_rank_based_on_current( $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $prefs = mycred_get_addon_settings('rank', $point_type); + $prefs = mycred_get_addon_settings( 'rank', $point_type ); $result = false; - if (! empty($prefs) && $prefs['base'] == 'current' ) { + if ( ! empty( $prefs ) && $prefs['base'] == 'current' ) $result = true; - } return $result; @@ -799,135 +707,128 @@ function mycred_rank_based_on_current( $point_type = MYCRED_DEFAULT_TYPE_KEY ) /** * Rank Shown in BuddyPress * Returns either false or the location where the rank is to be shown in BuddyPress. - * - * @since 1.6 + * @since 1.6 * @version 1.2 */ -if (! function_exists('mycred_show_rank_in_buddypress') ) : - function mycred_show_rank_in_buddypress( $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_show_rank_in_buddypress' ) ) : + function mycred_show_rank_in_buddypress( $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $prefs = mycred_get_addon_settings('rank', $point_type); + $prefs = mycred_get_addon_settings( 'rank', $point_type ); - $result = false; - if ($prefs['rank']['bb_location'] != '' ) { - $result = $prefs['rank']['bb_location']; - } + $result = false; + if ( $prefs['rank']['bb_location'] != '' ) + $result = $prefs['rank']['bb_location']; - return $result; + return $result; - } + } endif; /** * Rank Shown in bbPress * Returns either false or the location where the rank is to be shown in bbPress. - * - * @since 1.6 + * @since 1.6 * @version 1.2 */ -if (! function_exists('mycred_show_rank_in_bbpress') ) : - function mycred_show_rank_in_bbpress( $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_show_rank_in_bbpress' ) ) : + function mycred_show_rank_in_bbpress( $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - $prefs = mycred_get_addon_settings('rank', $point_type); + $prefs = mycred_get_addon_settings( 'rank', $point_type ); - $result = false; - if ($prefs['rank']['bp_location'] != '' ) { - $result = $prefs['rank']['bp_location']; - } + $result = false; + if ( $prefs['rank']['bp_location'] != '' ) + $result = $prefs['rank']['bp_location']; - return $result; + return $result; - } + } endif; /** * Update User Ranks IDs - * - * @since 2.3 + * @since 2.3 * @version 1.0 */ -if(!function_exists('mycred_update_user_rank_id') ) : - function mycred_update_user_rank_id( $user_id, $rank_id ) - { - $current_rank_id = $rank_id; - - $rank_ids = mycred_get_user_meta($user_id, 'mycred_rank_ids', '', true); - - $promoted_ids = mycred_get_user_meta($user_id, 'mycred_promoted_rank_ids', '', true); - - $demoted_ids = mycred_get_user_meta($user_id, 'mycred_demoted_rank_ids', '', true); - - if(!empty($rank_ids) ) { - end($rank_ids); - $previous_rank_id = key($rank_ids); - - $previous_rank_id = $rank_ids[$previous_rank_id]; - - array_push($rank_ids, $current_rank_id); - - $prev_maximum = mycred_get_rank($previous_rank_id)->maximum; - - $current_minimum = mycred_get_rank($current_rank_id)->minimum; - - //Update for next time - mycred_update_user_meta($user_id, 'mycred_rank_ids', '', $rank_ids); - - //If Demoted - if($current_minimum < $prev_maximum ) { - //If already exists just update - if(!empty($demoted_ids) ) { - array_push($demoted_ids, $current_rank_id); - - mycred_update_user_meta($user_id, 'mycred_demoted_rank_ids', '', $demoted_ids); - - } - else { - mycred_update_user_meta($user_id, 'mycred_demoted_rank_ids', '', array( $current_rank_id )); - } - - } - //If Promoted - else - { - //If already exists just update - if(!empty($promoted_ids) ) { - array_push($promoted_ids, $current_rank_id); - - mycred_update_user_meta($user_id, 'mycred_promoted_rank_ids', '', $promoted_ids); - - } - else { - mycred_update_user_meta($user_id, 'mycred_promoted_rank_ids', '', array( $current_rank_id )); - } - } - } - else - { - mycred_update_user_meta($user_id, 'mycred_rank_ids', '', array( $current_rank_id )); - mycred_update_user_meta($user_id, 'mycred_promoted_rank_ids', '', array( $current_rank_id )); - } - } +if( !function_exists( 'mycred_update_user_rank_id' ) ): + function mycred_update_user_rank_id( $user_id, $rank_id ) + { + $current_rank_id = $rank_id; + + $rank_ids = mycred_get_user_meta( $user_id, 'mycred_rank_ids', '', true ); + + $promoted_ids = mycred_get_user_meta( $user_id, 'mycred_promoted_rank_ids', '', true ); + + $demoted_ids = mycred_get_user_meta( $user_id, 'mycred_demoted_rank_ids', '', true ); + + if( !empty( $rank_ids ) ) + { + end($rank_ids); + $previous_rank_id = key($rank_ids); + + $previous_rank_id = $rank_ids[$previous_rank_id]; + + array_push( $rank_ids, $current_rank_id ); + + $prev_maximum = mycred_get_rank( $previous_rank_id )->maximum; + + $current_minimum = mycred_get_rank( $current_rank_id )->minimum; + + //Update for next time + mycred_update_user_meta( $user_id, 'mycred_rank_ids', '', $rank_ids ); + + //If Demoted + if( $current_minimum < $prev_maximum ) + { + //If already exists just update + if( !empty( $demoted_ids ) ) + { + array_push( $demoted_ids, $current_rank_id ); + + mycred_update_user_meta( $user_id, 'mycred_demoted_rank_ids', '', $demoted_ids ); + + } + else + mycred_update_user_meta( $user_id, 'mycred_demoted_rank_ids', '', array( $current_rank_id ) ); + + } + //If Promoted + else + { + //If already exists just update + if( !empty( $promoted_ids ) ) + { + array_push( $promoted_ids, $current_rank_id ); + + mycred_update_user_meta( $user_id, 'mycred_promoted_rank_ids', '', $promoted_ids ); + + } + else + mycred_update_user_meta( $user_id, 'mycred_promoted_rank_ids', '', array( $current_rank_id ) ); + } + } + else + { + mycred_update_user_meta( $user_id, 'mycred_rank_ids', '', array( $current_rank_id ) ); + mycred_update_user_meta( $user_id, 'mycred_promoted_rank_ids', '', array( $current_rank_id ) ); + } + } endif; /** * Returns users current rank id - * - * @since 2.3 + * @since 2.3 * @version 1.0 */ -if(!function_exists('mycred_get_users_current_rank_id') ) : - function mycred_get_users_current_rank_id( $user_id, $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { - $point_type = $point_type == MYCRED_DEFAULT_TYPE_KEY ? '' : $point_type; +if( !function_exists( 'mycred_get_users_current_rank_id' ) ): +function mycred_get_users_current_rank_id( $user_id, $point_type = MYCRED_DEFAULT_TYPE_KEY ) +{ + $point_type = $point_type == MYCRED_DEFAULT_TYPE_KEY ? '' : $point_type; - $rank_id = mycred_get_user_meta($user_id, MYCRED_RANK_KEY, $point_type, true); + $rank_id = mycred_get_user_meta( $user_id, MYCRED_RANK_KEY, $point_type, true ); - if(!empty($rank_id) ) { - return $rank_id; - } + if( !empty ( $rank_id ) ) + return $rank_id; - return false; - } -endif; + return false; +} +endif; \ No newline at end of file diff --git a/addons/ranks/includes/mycred-rank-object.php b/addons/ranks/includes/mycred-rank-object.php index 2b7a494..4cc3e10 100644 --- a/addons/ranks/includes/mycred-rank-object.php +++ b/addons/ranks/includes/mycred-rank-object.php @@ -1,343 +1,305 @@ image_width = MYCRED_RANK_WIDTH; - $this->image_height = MYCRED_RANK_HEIGHT; - - $this->populate($rank_id); - - } - - /** - * Populate - * - * @since 1.0 - * @version 1.0 - */ - protected function populate( $rank_id = null ) - { - - $this->post_id = absint($rank_id); - $this->post = mycred_get_post($this->post_id); - $this->title = mycred_get_the_title($this->post); - $this->minimum = mycred_get_post_meta($this->post_id, 'mycred_rank_min', true); - $this->maximum = mycred_get_post_meta($this->post_id, 'mycred_rank_max', true); - $this->count = mycred_count_users_with_rank($this->post_id); + /** + * Indicates if the rank has a logo + */ + public $has_logo = false; - $this->has_logo = mycred_rank_has_logo($this->post_id); - $this->logo_id = get_post_thumbnail_id($this->post); - $this->logo_url = wp_get_attachment_url($this->logo_id); + /** + * The ranks logo attachment id + */ + public $logo_id = false; - $point_type = mycred_get_post_meta($this->post_id, 'ctype', true); - if (! mycred_point_type_exists($point_type) ) { - $point_type = MYCRED_DEFAULT_TYPE_KEY; - } + /** + * The ranks logo attachment url + */ + public $logo_url = false; - $this->point_type = new myCRED_Point_Type($point_type); + /** + * The rank image width + */ + public $image_width = false; - $this->is_manual = mycred_manual_ranks($point_type); + /** + * The rank image height + */ + public $image_height = false; - } + /** + * The point type object associated with this rank + */ + public $point_type = false; - /** - * Checks if a user has this rank - * - * @since 1.8 - * @version 1.0 - */ - public function user_has_rank( $user_id = false ) - { + /** + * Indicates if this rank is manually assigned or not + */ + public $is_manual = false; - if ($user_id === false || absint($user_id) === 0 ) { return false; - } + /** + * Construct + */ + public function __construct( $rank_id = NULL ) { - $user_id = absint($user_id); - $post_type = $this->point_type->cred_id; + parent::__construct(); - $users_rank = mycred_get_user_meta($user_id, MYCRED_RANK_KEY, ( ( $post_type != MYCRED_DEFAULT_TYPE_KEY ) ? $post_type : '' ), true); + $rank_id = absint( $rank_id ); + if ( $rank_id === 0 ) return; - $has_rank = false; - if ($users_rank != '' && absint($users_rank) === $this->post_id ) { - $has_rank = true; - } + if ( mycred_get_post_type( $rank_id ) != MYCRED_RANK_KEY ) return; - return apply_filters('mycred_user_has_rank', $has_rank, $user_id, $this); + $this->image_width = MYCRED_RANK_WIDTH; + $this->image_height = MYCRED_RANK_HEIGHT; - } + $this->populate( $rank_id ); - /** - * Assign Rank to User - * - * @since 1.8 - * @since 2.3 Added `mycred_count_users_with_rank` for better counting - * @version 1.0 - */ - public function assign( $user_id = false ) - { + } - if ($user_id === false || absint($user_id) === 0 ) { return false; - } + /** + * Populate + * @since 1.0 + * @version 1.0 + */ + protected function populate( $rank_id = NULL ) { - $user_id = absint($user_id); - $post_type = $this->point_type->cred_id; + $this->post_id = absint( $rank_id ); + $this->post = mycred_get_post( $this->post_id ); + $this->title = mycred_get_the_title( $this->post ); + $this->minimum = mycred_get_post_meta( $this->post_id, 'mycred_rank_min', true ); + $this->maximum = mycred_get_post_meta( $this->post_id, 'mycred_rank_max', true ); + $this->count = mycred_count_users_with_rank( $this->post_id ); - // User already has this rank - if ($this->user_has_rank($user_id) ) { return true; - } + $this->has_logo = mycred_rank_has_logo( $this->post_id ); + $this->logo_id = get_post_thumbnail_id( $this->post ); + $this->logo_url = wp_get_attachment_url( $this->logo_id ); - $value = apply_filters('mycred_rank_user_value', $this->post_id, $user_id, $this); + $point_type = mycred_get_post_meta( $this->post_id, 'ctype', true ); + if ( ! mycred_point_type_exists( $point_type ) ) + $point_type = MYCRED_DEFAULT_TYPE_KEY; - $this->count = mycred_count_users_with_rank($this->post_id); + $this->point_type = new myCRED_Point_Type( $point_type ); - $this->count++; + $this->is_manual = mycred_manual_ranks( $point_type ); - mycred_update_post_meta($this->post_id, 'mycred_rank_users', $this->count); + } - return mycred_update_user_meta($user_id, MYCRED_RANK_KEY, ( ( $post_type != MYCRED_DEFAULT_TYPE_KEY ) ? $post_type : '' ), $value); + /** + * Checks if a user has this rank + * @since 1.8 + * @version 1.0 + */ + public function user_has_rank( $user_id = false ) { - } + if ( $user_id === false || absint( $user_id ) === 0 ) return false; - /** - * Assign All - * Assigns all users that meet the requirements for this rank. - * - * @since 1.8 - * @version 1.0 - */ - public function assign_all() - { + $user_id = absint( $user_id ); + $post_type = $this->point_type->cred_id; - if ($this->is_manual ) { return false; - } + $users_rank = mycred_get_user_meta( $user_id, MYCRED_RANK_KEY, ( ( $post_type != MYCRED_DEFAULT_TYPE_KEY ) ? $post_type : '' ), true ); - global $wpdb; + $has_rank = false; + if ( $users_rank != '' && absint( $users_rank ) === $this->post_id ) + $has_rank = true; - $post_type = $this->point_type->cred_id; - $balance_format = esc_sql($this->point_type->sql_format); - $rank_key = mycred_get_meta_key(MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' )); + return apply_filters( 'mycred_user_has_rank', $has_rank, $user_id, $this ); - $balance_key = mycred_get_meta_key($point_type); - if (mycred_rank_based_on_total($point_type) ) { - $balance_key = mycred_get_meta_key($point_type, '_total'); - } + } - do_action('mycred_assign_rank_start', $this); + /** + * Assign Rank to User + * @since 1.8 + * @since 2.3 Added `mycred_count_users_with_rank` for better counting + * @version 1.0 + */ + public function assign( $user_id = false ) { - $count = $wpdb->query( - $wpdb->prepare( - " + if ( $user_id === false || absint( $user_id ) === 0 ) return false; + + $user_id = absint( $user_id ); + $post_type = $this->point_type->cred_id; + + // User already has this rank + if ( $this->user_has_rank( $user_id ) ) return true; + + $value = apply_filters( 'mycred_rank_user_value', $this->post_id, $user_id, $this ); + + $this->count = mycred_count_users_with_rank( $this->post_id ); + + $this->count++; + + mycred_update_post_meta( $this->post_id, 'mycred_rank_users', $this->count ); + + return mycred_update_user_meta( $user_id, MYCRED_RANK_KEY, ( ( $post_type != MYCRED_DEFAULT_TYPE_KEY ) ? $post_type : '' ), $value ); + + } + + /** + * Assign All + * Assigns all users that meet the requirements for this rank. + * @since 1.8 + * @version 1.0 + */ + public function assign_all() { + + if ( $this->is_manual ) return false; + + global $wpdb; + + $post_type = $this->point_type->cred_id; + $balance_format = esc_sql( $this->point_type->sql_format ); + $rank_key = mycred_get_meta_key( MYCRED_RANK_KEY, ( ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? $point_type : '' ) ); + + $balance_key = mycred_get_meta_key( $point_type ); + if ( mycred_rank_based_on_total( $point_type ) ) + $balance_key = mycred_get_meta_key( $point_type, '_total' ); + + do_action( 'mycred_assign_rank_start', $this ); + + $count = $wpdb->query( $wpdb->prepare( " UPDATE {$wpdb->usermeta} ranks INNER JOIN {$wpdb->usermeta} balance ON ( ranks.user_id = balance.user_id AND balance.meta_key = %s ) SET ranks.meta_value = %d WHERE ranks.meta_key = %s - AND balance.meta_value BETWEEN {$balance_format} AND {$balance_format};", $balance_key, $this->post_id, $rank_key, $this->minimum, $this->maximum - ) - ); + AND balance.meta_value BETWEEN {$balance_format} AND {$balance_format};", $balance_key, $this->post_id, $rank_key, $this->minimum, $this->maximum ) ); - do_action('mycred_assign_rank_end', $this); + do_action( 'mycred_assign_rank_end', $this ); - $this->count = ( $count === null ) ? 0 : absint($count); + $this->count = ( $count === NULL ) ? 0 : absint( $count ); - mycred_update_post_meta($this->post_id, 'mycred_rank_users', $this->count); + mycred_update_post_meta( $this->post_id, 'mycred_rank_users', $this->count ); - } + } - /** - * Divest User - * - * @since 1.8 - * @since 2.3 Added `mycred_count_users_with_rank` for better counting - * @version 1.0 - */ - public function divest( $user_id = false ) - { + /** + * Divest User + * @since 1.8 + * @since 2.3 Added `mycred_count_users_with_rank` for better counting + * @version 1.0 + */ + public function divest( $user_id = false ) { - if ($user_id === false || absint($user_id) === 0 ) { return false; - } + if ( $user_id === false || absint( $user_id ) === 0 ) return false; - $user_id = absint($user_id); - $post_type = $this->point_type->cred_id; + $user_id = absint( $user_id ); + $post_type = $this->point_type->cred_id; - $results = true; - $users_rank = mycred_get_user_meta($user_id, MYCRED_RANK_KEY, ( ( $post_type != MYCRED_DEFAULT_TYPE_KEY ) ? $post_type : '' ), true); + $results = true; + $users_rank = mycred_get_user_meta( $user_id, MYCRED_RANK_KEY, ( ( $post_type != MYCRED_DEFAULT_TYPE_KEY ) ? $post_type : '' ), true ); - if ($users_rank != '' ) { + if ( $users_rank != '' ) { - $results = mycred_delete_user_meta($user_id, MYCRED_RANK_KEY, ( ( $post_type != MYCRED_DEFAULT_TYPE_KEY ) ? $post_type : '' )); + $results = mycred_delete_user_meta( $user_id, MYCRED_RANK_KEY, ( ( $post_type != MYCRED_DEFAULT_TYPE_KEY ) ? $post_type : '' ) ); - $this->count = mycred_count_users_with_rank($this->post_id); + $this->count = mycred_count_users_with_rank( $this->post_id ); - $this->count--; + $this->count--; - mycred_update_post_meta($this->post_id, 'mycred_rank_users', $this->count); + mycred_update_post_meta( $this->post_id, 'mycred_rank_users', $this->count ); - } + } - return $results; + return $results; - } + } - /** - * Divest All Users - * - * @since 1.8 - * @version 1.0 - */ - public function divest_all() - { + /** + * Divest All Users + * @since 1.8 + * @version 1.0 + */ + public function divest_all() { - if ($this->post_id === false ) { return false; - } + if ( $this->post_id === false ) return false; - global $wpdb; + global $wpdb; - $post_type = $this->point_type->cred_id; + $post_type = $this->point_type->cred_id; - // Delete connections - $wpdb->delete( - $wpdb->usermeta, - array( 'meta_key' => mycred_get_meta_key(MYCRED_RANK_KEY, ( ( $post_type != MYCRED_DEFAULT_TYPE_KEY ) ? $post_type : '' )), 'meta_value' => $this->post_id ), - array( '%s', '%d' ) - ); + // Delete connections + $wpdb->delete( + $wpdb->usermeta, + array( 'meta_key' => mycred_get_meta_key( MYCRED_RANK_KEY, ( ( $post_type != MYCRED_DEFAULT_TYPE_KEY ) ? $post_type : '' ) ), 'meta_value' => $this->post_id ), + array( '%s', '%d' ) + ); - $this->count = 0; + $this->count = 0; - mycred_update_post_meta($this->post_id, 'mycred_rank_users', 0); + mycred_update_post_meta( $this->post_id, 'mycred_rank_users', 0 ); - return true; + return true; - } + } - /** - * Delete Rank - * - * @since 1.8 - * @version 1.0 - */ - public function delete( $delete_post = true ) - { + /** + * Delete Rank + * @since 1.8 + * @version 1.0 + */ + public function delete( $delete_post = true ) { - if ($this->post_id === false ) { return false; - } + if ( $this->post_id === false ) return false; - $this->divest_all(); + $this->divest_all(); - if ($delete_post ) { - mycred_delete_post($this->post_id, true); - } + if ( $delete_post ) + mycred_delete_post( $this->post_id, true ); - return true; + return true; - } + } - /** - * Get Image - * - * @since 1.0 - * @version 1.0 - */ - public function get_image( $image = 'logo' ) - { + /** + * Get Image + * @since 1.0 + * @version 1.0 + */ + public function get_image( $image = 'logo' ) { - if ($image === 'logo' && $this->has_logo ) { - return ''; - } + if ( $image === 'logo' && $this->has_logo ) + return ''; - return ''; + return ''; - } + } - } + } endif; diff --git a/addons/ranks/includes/mycred-rank-shortcodes.php b/addons/ranks/includes/mycred-rank-shortcodes.php index 336b608..e6d92fe 100644 --- a/addons/ranks/includes/mycred-rank-shortcodes.php +++ b/addons/ranks/includes/mycred-rank-shortcodes.php @@ -1,390 +1,331 @@ 'current', - 'ctype' => MYCRED_DEFAULT_TYPE_KEY, - 'show_title' => 1, - 'show_logo' => 0, - 'logo_size' => 'post-thumbnail', - 'first' => 'logo' - ), $atts, MYCRED_SLUG . '_my_rank' - ) - ); - - if ($user_id == '' && ! is_user_logged_in() ) { return; - } - - if (! mycred_point_type_exists($ctype) ) { - $ctype = MYCRED_DEFAULT_TYPE_KEY; - } - - $show = array(); - $user_id = mycred_get_user_id($user_id); - if ($user_id === false ) { return; - } - - $account_object = mycred_get_account($user_id); - - if(empty($account_object->balance[ $ctype ]->rank) ) { return; - } - - $rank_object = $account_object->balance[ $ctype ]->rank; - - if ($rank_object !== false ) { - - if ($show_logo == 1 && $rank_object->has_logo ) { - $show[] = mycred_get_rank_logo($rank_object->post_id, $logo_size); - } - - if ($show_title == 1 ) { - $show[] = $rank_object->title; - } - - if ($first != 'logo' ) { - $show = array_reverse($show); - } - - } - - if (! empty($show) ) { - $content = '
    ' . implode(' ', $show) . '
    '; - } - - return apply_filters('mycred_my_rank', $content, $user_id, $rank_object); - - } +if ( ! function_exists( 'mycred_render_my_rank' ) ) : + function mycred_render_my_rank( $atts, $content = '' ) { + + extract( shortcode_atts( array( + 'user_id' => 'current', + 'ctype' => MYCRED_DEFAULT_TYPE_KEY, + 'show_title' => 1, + 'show_logo' => 0, + 'logo_size' => 'post-thumbnail', + 'first' => 'logo' + ), $atts, MYCRED_SLUG . '_my_rank' ) ); + + if ( $user_id == '' && ! is_user_logged_in() ) return; + + if ( ! mycred_point_type_exists( $ctype ) ) + $ctype = MYCRED_DEFAULT_TYPE_KEY; + + $show = array(); + $user_id = mycred_get_user_id( $user_id ); + if ( $user_id === false ) return; + + $account_object = mycred_get_account( $user_id ); + + if( empty( $account_object->balance[ $ctype ]->rank ) ) return; + + $rank_object = $account_object->balance[ $ctype ]->rank; + + if ( $rank_object !== false ) { + + if ( $show_logo == 1 && $rank_object->has_logo ) + $show[] = mycred_get_rank_logo( $rank_object->post_id, $logo_size ); + + if ( $show_title == 1 ) + $show[] = $rank_object->title; + + if ( $first != 'logo' ) + $show = array_reverse( $show ); + + } + + if ( ! empty( $show ) ) + $content = '
    ' . implode( ' ', $show ) . '
    '; + + return apply_filters( 'mycred_my_rank', $content, $user_id, $rank_object ); + + } endif; /** * myCRED Shortcode: mycred_my_ranks * Returns the given users ranks. - * - * @see http://codex.mycred.me/shortcodes/mycred_my_ranks/ - * @since 1.6 + * @see http://codex.mycred.me/shortcodes/mycred_my_ranks/ + * @since 1.6 * @version 1.3 */ -if (! function_exists('mycred_render_my_ranks') ) : - function mycred_render_my_ranks( $atts, $content = '' ) - { - - $ranks = new stdClass(); +if ( ! function_exists( 'mycred_render_my_ranks' ) ) : + function mycred_render_my_ranks( $atts, $content = '' ) { + + $ranks = new stdClass(); - extract( - shortcode_atts( - array( - 'user_id' => 'current', - 'show_title' => 1, - 'show_logo' => 0, - 'logo_size' => 'post-thumbnail', - 'first' => 'logo' - ), $atts, MYCRED_SLUG . '_my_ranks' - ) - ); + extract( shortcode_atts( array( + 'user_id' => 'current', + 'show_title' => 1, + 'show_logo' => 0, + 'logo_size' => 'post-thumbnail', + 'first' => 'logo' + ), $atts, MYCRED_SLUG . '_my_ranks' ) ); - if ($user_id == '' && ! is_user_logged_in() ) { return; - } + if ( $user_id == '' && ! is_user_logged_in() ) return; - $user_id = mycred_get_user_id($user_id); - if ($user_id == false ) { return; - } + $user_id = mycred_get_user_id( $user_id ); + if ( $user_id == false ) return; - $account_object = mycred_get_account($user_id); - $show = array(); + $account_object = mycred_get_account( $user_id ); + $show = array(); - // Get the rank for each type - foreach ( $account_object->balance as $type_id => $balance ) { + // Get the rank for each type + foreach ( $account_object->balance as $type_id => $balance ) { - $row = array(); - $rank_object = $balance->rank; + $row = array(); + $rank_object = $balance->rank; - if ($rank_object !== false ) { + if ( $rank_object !== false ) { - if ($show_logo == 1 && $rank_object->has_logo ) { - $row[] = mycred_get_rank_logo($rank_object->post_id, $logo_size); - } + if ( $show_logo == 1 && $rank_object->has_logo ) + $row[] = mycred_get_rank_logo( $rank_object->post_id, $logo_size ); - if ($show_title == 1 ) { - $row[] = $rank_object->title; - } - - if ($first != 'logo' ) { - $row = array_reverse($row); - } + if ( $show_title == 1 ) + $row[] = $rank_object->title; + + if ( $first != 'logo' ) + $row = array_reverse( $row ); - } + } - if (! empty($row) ) { - $show[] = '
    ' . implode(' ', $row) . '
    '; - } + if ( ! empty( $row ) ) + $show[] = '
    ' . implode( ' ', $row ) . '
    '; - } + } - if (! empty($show) ) { - $content = '
    ' . implode(' ', $show) . '
    '; - } + if ( ! empty( $show ) ) + $content = '
    ' . implode( ' ', $show ) . '
    '; - if(! empty($rank_object) ) { - $ranks = $rank_object; - } + if( ! empty($rank_object) ) + $ranks = $rank_object; - return apply_filters('mycred_my_ranks', $content, $user_id, $ranks); + return apply_filters( 'mycred_my_ranks', $content, $user_id, $ranks ); - } + } endif; /** * myCRED Shortcode: mycred_users_of_rank * Returns all users who have the given rank with the option to show the rank logo and optional content. - * - * @see http://codex.mycred.me/shortcodes/mycred_users_of_rank/ - * @since 1.1 + * @see http://codex.mycred.me/shortcodes/mycred_users_of_rank/ + * @since 1.1 * @version 1.2 */ -if (! function_exists('mycred_render_users_of_rank') ) : - function mycred_render_users_of_rank( $atts, $row_template = null ) - { - - extract( - shortcode_atts( - array( - 'rank_id' => null, - 'login' => '', - 'number' => 10, - 'wrap' => 'div', - 'col' => 1, - 'nothing' => 'No users found with this rank', - 'ctype' => MYCRED_DEFAULT_TYPE_KEY, - 'order' => 'DESC' - ), $atts, MYCRED_SLUG . '_users_of_rank' - ) - ); - - // Rank ID required - if ($rank_id === null ) { - return 'ERROR Rank ID is required!'; - } - - // User is not logged in - if (! is_user_logged_in() && $login != '' ) { - return $mycred->template_tags_general($login); - } - - if (! mycred_point_type_exists($ctype) ) { - $ctype = MYCRED_DEFAULT_TYPE_KEY; - } - - $mycred = mycred($ctype); - - $output = ''; - - if ($row_template === null || empty($row_template) ) { - $row_template = '

    %user_profile_link% with %balance% %_plural%

    '; - } - - // Let others play - $row_template = apply_filters('mycred_users_of_rank', $row_template, $atts, $mycred); - - // Get users of this rank if there are any - $users = mycred_get_users_of_rank($rank_id, $number, $order, $ctype); - if (! empty($users) ) { - - // Add support for table - if ($wrap != 'table' && ! empty($wrap) ) { - $output .= '<' . $wrap . ' class="mycred-users-of-rank-wrapper">'; - } - - // Loop - foreach ( $users as $user ) { - $output .= $mycred->template_tags_user($row_template, false, $user); - } - - // Add support for table - if ($wrap != 'table' && ! empty($wrap) ) { - $output .= '' . "\n"; - } - - } - - // No users found - else { - - // Add support for table - if ($wrap == 'table' ) { - $output .= ' 1 ) { $output .= ' colspan="' . $col . '"'; - } - $output .= '>' . $nothing . ''; - } - - else { - if (empty($wrap) ) { $wrap = 'p'; - } - $output .= '<' . $wrap . '>' . $nothing . '' . "\n"; - } - - } - - return do_shortcode($output); - - } +if ( ! function_exists( 'mycred_render_users_of_rank' ) ) : + function mycred_render_users_of_rank( $atts, $row_template = NULL ) { + + extract( shortcode_atts( array( + 'rank_id' => NULL, + 'login' => '', + 'number' => 10, + 'wrap' => 'div', + 'col' => 1, + 'nothing' => 'No users found with this rank', + 'ctype' => MYCRED_DEFAULT_TYPE_KEY, + 'order' => 'DESC' + ), $atts, MYCRED_SLUG . '_users_of_rank' ) ); + + // Rank ID required + if ( $rank_id === NULL ) + return 'ERROR Rank ID is required!'; + + // User is not logged in + if ( ! is_user_logged_in() && $login != '' ) + return $mycred->template_tags_general( $login ); + + if ( ! mycred_point_type_exists( $ctype ) ) + $ctype = MYCRED_DEFAULT_TYPE_KEY; + + $mycred = mycred( $ctype ); + + $output = ''; + + if ( $row_template === NULL || empty( $row_template ) ) + $row_template = '

    %user_profile_link% with %balance% %_plural%

    '; + + // Let others play + $row_template = apply_filters( 'mycred_users_of_rank', $row_template, $atts, $mycred ); + + // Get users of this rank if there are any + $users = mycred_get_users_of_rank( $rank_id, $number, $order, $ctype ); + if ( ! empty( $users ) ) { + + // Add support for table + if ( $wrap != 'table' && ! empty( $wrap ) ) + $output .= '<' . $wrap . ' class="mycred-users-of-rank-wrapper">'; + + // Loop + foreach ( $users as $user ) + $output .= $mycred->template_tags_user( $row_template, false, $user ); + + // Add support for table + if ( $wrap != 'table' && ! empty( $wrap ) ) + $output .= '' . "\n"; + + } + + // No users found + else { + + // Add support for table + if ( $wrap == 'table' ) { + $output .= ' 1 ) $output .= ' colspan="' . $col . '"'; + $output .= '>' . $nothing . ''; + } + + else { + if ( empty( $wrap ) ) $wrap = 'p'; + $output .= '<' . $wrap . '>' . $nothing . '' . "\n"; + } + + } + + return do_shortcode( $output ); + + } endif; /** * myCRED Shortcode: mycred_users_of_all_ranks * Returns all users fore every registered rank in order. - * - * @see http://codex.mycred.me/shortcodes/mycred_users_of_all_ranks/ - * @since 1.1 + * @see http://codex.mycred.me/shortcodes/mycred_users_of_all_ranks/ + * @since 1.1 * @version 1.2.1 */ -if (! function_exists('mycred_render_users_of_all_ranks') ) : - function mycred_render_users_of_all_ranks( $atts, $row_template = null ) - { +if ( ! function_exists( 'mycred_render_users_of_all_ranks' ) ) : + function mycred_render_users_of_all_ranks( $atts, $row_template = NULL ) { - extract( - shortcode_atts( - array( - 'login' => '', - 'number' => 10, - 'ctype' => MYCRED_DEFAULT_TYPE_KEY, - 'show_logo' => 1, - 'logo_size' => 'post-thumbnail', - 'wrap' => 'div', - 'nothing' => 'No users found with this rank' - ), $atts, MYCRED_SLUG . '_users_of_all_ranks' - ) - ); + extract( shortcode_atts( array( + 'login' => '', + 'number' => 10, + 'ctype' => MYCRED_DEFAULT_TYPE_KEY, + 'show_logo' => 1, + 'logo_size' => 'post-thumbnail', + 'wrap' => 'div', + 'nothing' => 'No users found with this rank' + ), $atts, MYCRED_SLUG . '_users_of_all_ranks' ) ); - // Prep - $mycred = mycred(); + // Prep + $mycred = mycred(); - // User is not logged in - if (! is_user_logged_in() && $login != '' ) { - return $mycred->template_tags_general($login); - } + // User is not logged in + if ( ! is_user_logged_in() && $login != '' ) + return $mycred->template_tags_general( $login ); - $output = ''; - $all_ranks = mycred_get_ranks('publish', '-1', 'DESC', $ctype); + $output = ''; + $all_ranks = mycred_get_ranks( 'publish', '-1', 'DESC', $ctype ); - // If we have ranks - if (! empty($all_ranks) ) { + // If we have ranks + if ( ! empty( $all_ranks ) ) { - $output .= '
    ' . "\n"; + $output .= '
    ' . "\n"; - // Loop though all ranks - foreach ( $all_ranks as $rank ) { + // Loop though all ranks + foreach ( $all_ranks as $rank ) { - // Prep Slug - $slug = str_replace(' ', '-', strtolower($rank->title)); + // Prep Slug + $slug = str_replace( ' ', '-', strtolower( $rank->title ) ); - // Rank wrapper - $output .= '

    '; + // Rank wrapper + $output .= '

    '; - // Insert Logo - if ($show_logo ) { - $output .= mycred_get_rank_logo($rank->post_id, $logo_size); - } + // Insert Logo + if ( $show_logo ) + $output .= mycred_get_rank_logo( $rank->post_id, $logo_size ); - // Rank title - $output .= $rank->title . '

    ' . "\n"; + // Rank title + $output .= $rank->title . '

    ' . "\n"; - $attr = array( - 'rank_id' => $rank->post_id, - 'number' => $number, - 'nothing' => $nothing, - 'wrap' => $wrap, - 'ctype' => $ctype - ); - $output .= mycred_render_users_of_rank($attr, $row_template); + $attr = array( + 'rank_id' => $rank->post_id, + 'number' => $number, + 'nothing' => $nothing, + 'wrap' => $wrap, + 'ctype' => $ctype + ); + $output .= mycred_render_users_of_rank( $attr, $row_template ); - $output .= '
    ' . "\n"; + $output .= '
    ' . "\n"; - } + } - $output .= '
    '; + $output .= ''; - } + } - return $output; + return $output; - } + } endif; /** * myCRED Shortcode: mycred_list_ranks * Returns a list of ranks with minimum and maximum point requirements. - * - * @see http://codex.mycred.me/shortcodes/mycred_list_ranks/ - * @since 1.1.1 + * @see http://codex.mycred.me/shortcodes/mycred_list_ranks/ + * @since 1.1.1 * @version 1.3 */ -if (! function_exists('mycred_render_rank_list') ) : - function mycred_render_rank_list( $atts, $row_template = null ) - { +if ( ! function_exists( 'mycred_render_rank_list' ) ) : + function mycred_render_rank_list( $atts, $row_template = NULL ) { - $atts = shortcode_atts( - array( - 'order' => 'DESC', - 'ctype' => MYCRED_DEFAULT_TYPE_KEY, - 'wrap' => 'div' - ), $atts, MYCRED_SLUG . '_list_ranks' - ); + $atts = shortcode_atts( array( + 'order' => 'DESC', + 'ctype' => MYCRED_DEFAULT_TYPE_KEY, + 'wrap' => 'div' + ), $atts, MYCRED_SLUG . '_list_ranks' ); - extract($atts); + extract( $atts ); - $output = ''; - $all_ranks = mycred_get_ranks('publish', '-1', $order, $ctype); + $output = ''; + $all_ranks = mycred_get_ranks( 'publish', '-1', $order, $ctype ); - if (! empty($all_ranks) ) { + if ( ! empty( $all_ranks ) ) { - if ($wrap != '' ) { - $output .= '<' . $wrap . ' class="mycred-rank-list">'; - } + if ( $wrap != '' ) + $output .= '<' . $wrap . ' class="mycred-rank-list">'; - if ($row_template === null || empty($row_template) ) { - $row_template = '

    %rank% %min% - %max%

    '; - } + if ( $row_template === NULL || empty( $row_template ) ) + $row_template = '

    %rank% %min% - %max%

    '; - foreach ( $all_ranks as $rank ) { + foreach ( $all_ranks as $rank ) { - $mycred = mycred($rank->point_type); - $row = apply_filters('mycred_rank_list', $row_template, $atts, $mycred); + $mycred = mycred( $rank->point_type ); + $row = apply_filters( 'mycred_rank_list', $row_template, $atts, $mycred ); - $row = str_replace('%rank%', $rank->title, $row); - $row = str_replace('%rank_logo%', mycred_get_rank_logo($rank->post_id), $row); - $row = str_replace('%min%', $mycred->format_creds($rank->minimum), $row); - $row = str_replace('%max%', $mycred->format_creds($rank->maximum), $row); - $row = str_replace('%count%', $rank->count, $row); + $row = str_replace( '%rank%', $rank->title, $row ); + $row = str_replace( '%rank_logo%', mycred_get_rank_logo( $rank->post_id ), $row ); + $row = str_replace( '%min%', $mycred->format_creds( $rank->minimum ), $row ); + $row = str_replace( '%max%', $mycred->format_creds( $rank->maximum ), $row ); + $row = str_replace( '%count%', $rank->count, $row ); - $row = $mycred->template_tags_general($row); + $row = $mycred->template_tags_general( $row ); - $output .= $row; + $output .= $row; - } + } - if ($wrap != '' ) { - $output .= ''; - } + if ( $wrap != '' ) + $output .= ''; - } + } - return $output; + return $output; - } + } endif; diff --git a/addons/ranks/index.php b/addons/ranks/index.php index 1580272..4e6c07c 100644 --- a/addons/ranks/index.php +++ b/addons/ranks/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/ranks/js/index.php b/addons/ranks/js/index.php index 1580272..4e6c07c 100644 --- a/addons/ranks/js/index.php +++ b/addons/ranks/js/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/ranks/js/management.js b/addons/ranks/js/management.js index 038f4d1..d237155 100644 --- a/addons/ranks/js/management.js +++ b/addons/ranks/js/management.js @@ -1,102 +1,91 @@ /** * myCRED Management Scripts - * - * @since 1.3 + * @since 1.3 * @version 1.0 */ -jQuery( - function ($) { - - var mycred_action_delete_ranks = function ( button ) { - var label = button.val(); - $.ajax( - { - type : "POST", - data : { - action : 'mycred-action-delete-ranks', - token : myCRED_Ranks.token - }, - dataType : "JSON", - url : myCRED_Ranks.ajaxurl, - beforeSend : function () { - button.attr('value', myCRED_Ranks.working); - button.attr('disabled', 'disabled'); - }, - success : function ( data ) { - console.log(data); - - if (data.status == 'OK' ) { - $('input#mycred-ranks-no-of-ranks').val(data.rows); - button.val(myCREDmanage.done); - button.removeClass('button-primary'); - } - else { - button.val(label); - button.removeAttr('disabled'); - } - }, - error : function ( jqXHR, textStatus, errorThrown ) { - // Debug - console.log(textStatus + ':' + errorThrown); - button.attr('value', label); - button.removeAttr('disabled'); - } - } - ); - }; - - $('input#mycred-manage-action-reset-ranks').click( - function () { - // Confirm action - if (confirm(myCRED_Ranks.confirm_del) ) { - mycred_action_delete_ranks($(this)); - } - } - ); - - var mycred_action_assign_ranks = function ( button ) { - var label = button.val(); - $.ajax( - { - type : "POST", - data : { - action : 'mycred-action-assign-ranks', - token : myCRED_Ranks.token - }, - dataType : "JSON", - url : myCRED_Ranks.ajaxurl, - beforeSend : function () { - button.attr('value', myCRED_Ranks.working); - button.attr('disabled', 'disabled'); - }, - success : function ( data ) { - console.log(data); - - if (data.status == 'OK' ) { - button.val(myCREDmanage.done); - } - else { - button.val(label); - button.removeAttr('disabled'); - } - }, - error : function ( jqXHR, textStatus, errorThrown ) { - // Debug - console.log(textStatus + ':' + errorThrown); - button.attr('value', label); - button.removeAttr('disabled'); - } - } - ); - }; - - $('input#mycred-manage-action-assign-ranks').click( - function () { - // Confirm action - if (confirm(myCRED_Ranks.confirm_assign) ) { - mycred_action_assign_ranks($(this)); - } - } - ); - } -); \ No newline at end of file +jQuery(function($) { + + var mycred_action_delete_ranks = function( button ) { + var label = button.val(); + $.ajax({ + type : "POST", + data : { + action : 'mycred-action-delete-ranks', + token : myCRED_Ranks.token + }, + dataType : "JSON", + url : myCRED_Ranks.ajaxurl, + beforeSend : function() { + button.attr( 'value', myCRED_Ranks.working ); + button.attr( 'disabled', 'disabled' ); + }, + success : function( data ) { + console.log( data ); + + if ( data.status == 'OK' ) { + $( 'input#mycred-ranks-no-of-ranks' ).val( data.rows ); + button.val( myCREDmanage.done ); + button.removeClass( 'button-primary' ); + } + else { + button.val( label ); + button.removeAttr( 'disabled' ); + } + }, + error : function( jqXHR, textStatus, errorThrown ) { + // Debug + console.log( textStatus + ':' + errorThrown ); + button.attr( 'value', label ); + button.removeAttr( 'disabled' ); + } + }); + }; + + $( 'input#mycred-manage-action-reset-ranks' ).click(function(){ + // Confirm action + if ( confirm( myCRED_Ranks.confirm_del ) ) { + mycred_action_delete_ranks( $(this) ); + } + }); + + var mycred_action_assign_ranks = function( button ) { + var label = button.val(); + $.ajax({ + type : "POST", + data : { + action : 'mycred-action-assign-ranks', + token : myCRED_Ranks.token + }, + dataType : "JSON", + url : myCRED_Ranks.ajaxurl, + beforeSend : function() { + button.attr( 'value', myCRED_Ranks.working ); + button.attr( 'disabled', 'disabled' ); + }, + success : function( data ) { + console.log( data ); + + if ( data.status == 'OK' ) { + button.val( myCREDmanage.done ); + } + else { + button.val( label ); + button.removeAttr( 'disabled' ); + } + }, + error : function( jqXHR, textStatus, errorThrown ) { + // Debug + console.log( textStatus + ':' + errorThrown ); + button.attr( 'value', label ); + button.removeAttr( 'disabled' ); + } + }); + }; + + $( 'input#mycred-manage-action-assign-ranks' ).click(function(){ + // Confirm action + if ( confirm( myCRED_Ranks.confirm_assign ) ) { + mycred_action_assign_ranks( $(this) ); + } + }); +}); \ No newline at end of file diff --git a/addons/ranks/myCRED-addon-ranks.php b/addons/ranks/myCRED-addon-ranks.php index d251460..9a952f0 100644 --- a/addons/ranks/myCRED-addon-ranks.php +++ b/addons/ranks/myCRED-addon-ranks.php @@ -166,7 +166,7 @@ public function module_admin_init() { add_filter( 'manage_' . MYCRED_RANK_KEY . '_posts_columns', array( $this, 'adjust_column_headers' ), 50 ); add_action( 'manage_' . MYCRED_RANK_KEY . '_posts_custom_column', array( $this, 'adjust_column_content' ), 10, 2 ); add_action( 'save_post_' . MYCRED_RANK_KEY, array( $this, 'save_rank' ), 10, 2 ); - add_filter( 'views_edit-mycred_rank', array( $this, 'modify_ranks_views_links' ) ); + add_filter( 'views_edit-mycred_rank', array( $this, 'modify_ranks_views_links' ) ); add_action( 'delete_user', array( $this, 'delete_user_rank_data' ) ); } @@ -1989,12 +1989,13 @@ public function action_assign_ranks() { * @since 2.2 * @version 1.0 */ - public function active_current_view( $view ) - { - $post_status = isset( $_GET['post_status'] ) ? $_GET['post_status'] : ''; + public function active_current_view( $view ) { + + $post_status = isset( $_GET['post_status'] ) ? sanitize_key( $_GET['post_status'] ) : ''; if( $post_status == $view ) return 'class="current" aria-current="page"'; + } /** @@ -2002,13 +2003,13 @@ public function active_current_view( $view ) * @since 2.2 * @version 1.0 */ - public function modify_ranks_views_links( $view ) - { - $post_status = isset( $_GET['post_status'] ) ? $_GET['post_status'] : ''; + public function modify_ranks_views_links( $view ) { + + $post_status = isset( $_GET['post_status'] ) ? sanitize_key( $_GET['post_status'] ) : ''; $current = 'class="current" aria-current="page"'; - $current_point_type = isset( $_GET['ctype'] ) ? $_GET['ctype'] : MYCRED_DEFAULT_TYPE_KEY; + $current_point_type = isset( $_GET['ctype'] ) ? sanitize_key( $_GET['ctype'] ) : MYCRED_DEFAULT_TYPE_KEY; $view['all'] = 'active_current_view( '' ).'>All'; @@ -2021,12 +2022,14 @@ public function modify_ranks_views_links( $view ) $view['draft'] = 'active_current_view( 'draft' ).'>Drafts'; return $view; + } - public function delete_user_rank_data( $user_id ) - { + public function delete_user_rank_data( $user_id ) { + $current_assign_rank = mycred_get_users_rank($user_id); mycred_update_post_meta( $current_assign_rank->post_id, 'mycred_rank_users', mycred_count_users_with_rank( $current_assign_rank->post_id ) - 1 ); + } } diff --git a/addons/sell-content/assets/index.php b/addons/sell-content/assets/index.php index 1580272..4e6c07c 100644 --- a/addons/sell-content/assets/index.php +++ b/addons/sell-content/assets/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/sell-content/assets/js/admin.js b/addons/sell-content/assets/js/admin.js index fc761d2..131960d 100644 --- a/addons/sell-content/assets/js/admin.js +++ b/addons/sell-content/assets/js/admin.js @@ -1,23 +1,19 @@ -(function ($) { - $(document).on( - 'click', '#update-sales-count', function ( e ) { - e.preventDefault(); - $.ajax( - { - url: ajaxurl, - type: 'POST', - data:{ - action: 'mycred_ajax_update_sell_count' - }, - beforeSend: function () { - jQuery('.mycred-update-sells-count').css("display", "inherit"); - }, - success:function (data) { - alert(data); - jQuery('.mycred-update-sells-count').hide(); - } - } - ) - } - ) -})(jQuery); \ No newline at end of file +(function($) { + $( document ).on( 'click', '#update-sales-count', function( e ){ + e.preventDefault(); + $.ajax({ + url: ajaxurl, + type: 'POST', + data:{ + action: 'mycred_ajax_update_sell_count' + }, + beforeSend: function() { + jQuery('.mycred-update-sells-count').css("display", "inherit"); + }, + success:function(data) { + alert( data ); + jQuery('.mycred-update-sells-count').hide(); + } + }) + } ) +})( jQuery ); \ No newline at end of file diff --git a/addons/sell-content/assets/js/buy-content.js b/addons/sell-content/assets/js/buy-content.js index 8677f4e..43a2617 100644 --- a/addons/sell-content/assets/js/buy-content.js +++ b/addons/sell-content/assets/js/buy-content.js @@ -1,82 +1,73 @@ /** * myCRED Sell Content - * - * @since 1.1 + * @since 1.1 * @version 1.2 */ -(function ($) { +(function($) { - var buying = false; + var buying = false; - $('.mycred-sell-this-wrapper').on( - 'click', '.mycred-buy-this-content-button', function () { + $( '.mycred-sell-this-wrapper' ).on( 'click', '.mycred-buy-this-content-button', function(){ - if (buying === true ) { return false; - } + if ( buying === true ) return false; - buying = true; + buying = true; - var button = $(this); - var post_id = button.data('pid'); - var point_type = button.data('type'); - var buttonlabel = button.html(); - var content_for_sale = $('#mycred-buy-content' + post_id); + var button = $(this); + var post_id = button.data( 'pid' ); + var point_type = button.data( 'type' ); + var buttonlabel = button.html(); + var content_for_sale = $( '#mycred-buy-content' + post_id ); - $.ajax( - { - type : "POST", - data : { - action : 'mycred-buy-content', - token : myCREDBuyContent.token, - postid : post_id, - ctype : point_type - }, - dataType : "JSON", - url : myCREDBuyContent.ajaxurl, - beforeSend : function () { + $.ajax({ + type : "POST", + data : { + action : 'mycred-buy-content', + token : myCREDBuyContent.token, + postid : post_id, + ctype : point_type + }, + dataType : "JSON", + url : myCREDBuyContent.ajaxurl, + beforeSend : function() { - button.attr('disabled', 'disabled').html(myCREDBuyContent.working); + button.attr( 'disabled', 'disabled' ).html( myCREDBuyContent.working ); - }, - success : function ( response ) { + }, + success : function( response ) { - if (response.success === undefined || ( response.success === true && myCREDBuyContent.reload === '1' ) ) { - location.reload(); + if ( response.success === undefined || ( response.success === true && myCREDBuyContent.reload === '1' ) ) + location.reload(); - } else { + else { - if (response.success ) { - content_for_sale.fadeOut( - function () { - content_for_sale.removeClass('mycred-sell-this-wrapper mycred-sell-entire-content mycred-sell-partial-content').empty().append(response.data).fadeIn(); - } - ); - } + if ( response.success ) { + content_for_sale.fadeOut(function(){ + content_for_sale.removeClass( 'mycred-sell-this-wrapper mycred-sell-entire-content mycred-sell-partial-content' ).empty().append( response.data ).fadeIn(); + }); + } - else { + else { - button.removeAttr('disabled').html(buttonlabel); + button.removeAttr( 'disabled' ).html( buttonlabel ); - if (response.data != '' ) { - alert(response.data); - } + if ( response.data != '' ) + alert( response.data ); - } + } - } + } - console.log(response); + console.log( response ); - }, - complete : function () { + }, + complete : function(){ - buying = false; + buying = false; - } - } - ); + } + }); - } - ); + }); -})(jQuery); \ No newline at end of file +})( jQuery ); \ No newline at end of file diff --git a/addons/sell-content/assets/js/index.php b/addons/sell-content/assets/js/index.php index 1580272..4e6c07c 100644 --- a/addons/sell-content/assets/js/index.php +++ b/addons/sell-content/assets/js/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/sell-content/css/index.php b/addons/sell-content/css/index.php index 1580272..4e6c07c 100644 --- a/addons/sell-content/css/index.php +++ b/addons/sell-content/css/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/sell-content/includes/index.php b/addons/sell-content/includes/index.php index 1580272..4e6c07c 100644 --- a/addons/sell-content/includes/index.php +++ b/addons/sell-content/includes/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/sell-content/includes/mycred-sell-functions.php b/addons/sell-content/includes/mycred-sell-functions.php index 10b4d18..4284257 100644 --- a/addons/sell-content/includes/mycred-sell-functions.php +++ b/addons/sell-content/includes/mycred-sell-functions.php @@ -1,74 +1,67 @@ sell_content) ) { - $settings = $mycred->sell_content; + $mycred = mycred(); + if ( isset( $mycred->sell_content ) ) + $settings = $mycred->sell_content; - } else { + else { - global $mycred_modules; + global $mycred_modules; - $settings = $mycred_modules['solo']['content']->sell_content; + $settings = $mycred_modules['solo']['content']->sell_content; - } + } - return $settings; + return $settings; - } + } endif; /** * Get Post Types * Returns an array of sellable post types. In order for a post type to be * considered "usable", it must be public. - * - * @since 1.7 + * @since 1.7 * @version 1.0.1 */ -if (! function_exists('mycred_sell_content_post_types') ) : - function mycred_sell_content_post_types() - { +if ( ! function_exists( 'mycred_sell_content_post_types' ) ) : + function mycred_sell_content_post_types() { - $args = array( - 'public' => true, - '_builtin' => false - ); + $args = array( + 'public' => true, + '_builtin' => false + ); - $post_types = get_post_types($args, 'objects', 'OR'); + $post_types = get_post_types( $args, 'objects', 'OR' ); - $eligeble_types = array(); - $mycred_post_types = get_mycred_post_types(); + $eligeble_types = array(); + $mycred_post_types = get_mycred_post_types(); - if (! empty($post_types) ) { - foreach ( $post_types as $post_type => $setup ) { + if ( ! empty( $post_types ) ) { + foreach ( $post_types as $post_type => $setup ) { - if ($setup->public != 1 ) { continue; - } + if ( $setup->public != 1 ) continue; - if (in_array($post_type, $mycred_post_types) || $post_type == 'attachment' ) { continue; - } + if ( in_array( $post_type, $mycred_post_types ) || $post_type == 'attachment' ) continue; - $eligeble_types[ $post_type ] = $setup->labels->name; + $eligeble_types[ $post_type ] = $setup->labels->name; - } - } + } + } - return $eligeble_types; + return $eligeble_types; - } + } endif; /** @@ -76,966 +69,877 @@ function mycred_sell_content_post_types() * Will attempt to get the current posts ID. Also supports bbPress * where it will return either the form ID (if viewing a forum), the topic ID * (if viewing a topic) or the reply ID (if viewing a reply). - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_sell_content_post_id') ) : - function mycred_sell_content_post_id() - { +if ( ! function_exists( 'mycred_sell_content_post_id' ) ) : + function mycred_sell_content_post_id() { - $post_id = $bbp_topic_id = $bbp_reply_id = false; + $post_id = $bbp_topic_id = $bbp_reply_id = false; - // Check if we are selling access to bbPress forum, topic or reply - if (function_exists('bbpress') ) { + // Check if we are selling access to bbPress forum, topic or reply + if ( function_exists( 'bbpress' ) ) { - global $wp_query; + global $wp_query; - $bbp = bbpress(); + $bbp = bbpress(); - // Currently inside a topic loop - if (! empty($bbp->topic_query->in_the_loop) && isset($bbp->topic_query->post->ID) ) { - $bbp_topic_id = $bbp->topic_query->post->ID; - } + // Currently inside a topic loop + if ( ! empty( $bbp->topic_query->in_the_loop ) && isset( $bbp->topic_query->post->ID ) ) + $bbp_topic_id = $bbp->topic_query->post->ID; - // Currently inside a search loop - elseif (! empty($bbp->search_query->in_the_loop) && isset($bbp->search_query->post->ID) && bbp_is_topic($bbp->search_query->post->ID) ) { - $bbp_topic_id = $bbp->search_query->post->ID; - } + // Currently inside a search loop + elseif ( ! empty( $bbp->search_query->in_the_loop ) && isset( $bbp->search_query->post->ID ) && bbp_is_topic( $bbp->search_query->post->ID ) ) + $bbp_topic_id = $bbp->search_query->post->ID; - // Currently viewing/editing a topic, likely alone - elseif (( bbp_is_single_topic() || bbp_is_topic_edit() ) && ! empty($bbp->current_topic_id) ) { - $bbp_topic_id = $bbp->current_topic_id; - } + // Currently viewing/editing a topic, likely alone + elseif ( ( bbp_is_single_topic() || bbp_is_topic_edit() ) && ! empty( $bbp->current_topic_id ) ) + $bbp_topic_id = $bbp->current_topic_id; - // Currently viewing/editing a topic, likely in a loop - elseif (( bbp_is_single_topic() || bbp_is_topic_edit() ) && isset($wp_query->post->ID) ) { - $bbp_topic_id = $wp_query->post->ID; - } - - // So far, no topic found, check if we are in a reply - if ($bbp_topic_id === false ) { + // Currently viewing/editing a topic, likely in a loop + elseif ( ( bbp_is_single_topic() || bbp_is_topic_edit() ) && isset( $wp_query->post->ID ) ) + $bbp_topic_id = $wp_query->post->ID; + + // So far, no topic found, check if we are in a reply + if ( $bbp_topic_id === false ) { - // Currently inside a replies loop - if (! empty($bbp->reply_query->in_the_loop) && isset($bbp->reply_query->post->ID) ) { - $bbp_reply_id = $bbp->reply_query->post->ID; - } + // Currently inside a replies loop + if ( ! empty( $bbp->reply_query->in_the_loop ) && isset( $bbp->reply_query->post->ID ) ) + $bbp_reply_id = $bbp->reply_query->post->ID; - // Currently inside a search loop - elseif (! empty($bbp->search_query->in_the_loop) && isset($bbp->search_query->post->ID) && bbp_is_reply($bbp->search_query->post->ID) ) { - $bbp_reply_id = $bbp->search_query->post->ID; - } + // Currently inside a search loop + elseif ( ! empty( $bbp->search_query->in_the_loop ) && isset( $bbp->search_query->post->ID ) && bbp_is_reply( $bbp->search_query->post->ID ) ) + $bbp_reply_id = $bbp->search_query->post->ID; - // Currently viewing a forum - elseif (( bbp_is_single_reply() || bbp_is_reply_edit() ) && ! empty($bbp->current_reply_id) ) { - $bbp_reply_id = $bbp->current_reply_id; - } + // Currently viewing a forum + elseif ( ( bbp_is_single_reply() || bbp_is_reply_edit() ) && ! empty( $bbp->current_reply_id ) ) + $bbp_reply_id = $bbp->current_reply_id; - // Currently viewing a reply - elseif (( bbp_is_single_reply() || bbp_is_reply_edit() ) && isset($wp_query->post->ID) ) { - $bbp_reply_id = $wp_query->post->ID; - } - - if ($bbp_reply_id !== false ) { - $post_id = $bbp_reply_id; - } + // Currently viewing a reply + elseif ( ( bbp_is_single_reply() || bbp_is_reply_edit() ) && isset( $wp_query->post->ID ) ) + $bbp_reply_id = $wp_query->post->ID; + + if ( $bbp_reply_id !== false ) + $post_id = $bbp_reply_id; - } - - // Else we are in a topic - else { $post_id = $bbp_topic_id; - } + } + + // Else we are in a topic + else $post_id = $bbp_topic_id; - } + } - if ($post_id === false ) { + if ( $post_id === false ) { - global $post; + global $post; - if (isset($post->ID) ) { - $post_id = $post->ID; - } + if ( isset( $post->ID ) ) + $post_id = $post->ID; - } + } - return apply_filters('mycred_sell_this_get_post_ID', $post_id); + return apply_filters( 'mycred_sell_this_get_post_ID', $post_id ); - } + } endif; /** * Post Type for Sale * Returns either true (post type is for sale) or false (post type not for sale). - * - * @since 1.7 + * @since 1.7 * @version 1.0.1 */ -if (! function_exists('mycred_post_type_for_sale') ) : - function mycred_post_type_for_sale( $post_type = null ) - { +if ( ! function_exists( 'mycred_post_type_for_sale' ) ) : + function mycred_post_type_for_sale( $post_type = NULL ) { - $settings = mycred_sell_content_settings(); - $for_sale = false; + $settings = mycred_sell_content_settings(); + $for_sale = false; - if (array_key_exists('post_types', $settings) && ! empty($settings['post_types']) ) { + if ( array_key_exists( 'post_types', $settings ) && ! empty( $settings['post_types'] ) ) { - $post_types = explode(',', $settings['post_types']); - if (in_array($post_type, $post_types) ) { - $for_sale = true; - } + $post_types = explode( ',', $settings['post_types'] ); + if ( in_array( $post_type, $post_types ) ) + $for_sale = true; - } + } - // BuddyPress support to prevent issues when we select to sell access to all pages. - if (function_exists('bp_current_component') && bp_current_component() !== false ) { - $for_sale = false; - } + // BuddyPress support to prevent issues when we select to sell access to all pages. + if ( function_exists( 'bp_current_component' ) && bp_current_component() !== false ) + $for_sale = false; - return apply_filters('mycred_post_type_for_sale', $for_sale, $post_type); + return apply_filters( 'mycred_post_type_for_sale', $for_sale, $post_type ); - } + } endif; /** * Post is for Sale * Returns true (post is for sale) or false (post is not for sale). - * - * @since 1.7 + * @since 1.7 * @version 1.0.1 */ -if (! function_exists('mycred_post_is_for_sale') ) : - function mycred_post_is_for_sale( $post = null ) - { +if ( ! function_exists( 'mycred_post_is_for_sale' ) ) : + function mycred_post_is_for_sale( $post = NULL ) { - if (! is_object($post) ) { - $post = mycred_get_post($post); - } + if ( ! is_object( $post ) ) + $post = mycred_get_post( $post ); - // Invalid post - not for sale - if (! isset($post->ID) ) { return false; - } + // Invalid post - not for sale + if ( ! isset( $post->ID ) ) return false; - $settings = mycred_sell_content_settings(); - $point_types = $settings['type']; - $for_sale = false; + $settings = mycred_sell_content_settings(); + $point_types = $settings['type']; + $for_sale = false; - // We start with checking the post type. - if (mycred_post_type_for_sale($post->post_type) && array_key_exists($post->post_type, $settings['filters']) ) { + // We start with checking the post type. + if ( mycred_post_type_for_sale( $post->post_type ) && array_key_exists( $post->post_type, $settings['filters'] ) ) { - $filter = $settings['filters'][ $post->post_type ]['by']; - $list = explode(',', $settings['filters'][ $post->post_type ]['list']); + $filter = $settings['filters'][ $post->post_type ]['by']; + $list = explode( ',', $settings['filters'][ $post->post_type ]['list'] ); - // Manual filter - check saved settings - if ($filter === 'manual' ) { + // Manual filter - check saved settings + if ( $filter === 'manual' ) { - // Loop through each point type we allow and check the settings to see if anyone is enabled - foreach ( $point_types as $type_id ) { + // Loop through each point type we allow and check the settings to see if anyone is enabled + foreach ( $point_types as $type_id ) { - $suffix = '_' . $type_id; - if ($type_id == MYCRED_DEFAULT_TYPE_KEY ) { - $suffix = ''; - } + $suffix = '_' . $type_id; + if ( $type_id == MYCRED_DEFAULT_TYPE_KEY ) + $suffix = ''; - $sale_setup = (array) mycred_get_post_meta($post->ID, 'myCRED_sell_content' . $suffix, true); - if (array_key_exists('status', $sale_setup) && $sale_setup['status'] === 'enabled' ) { - $for_sale = true; - } + $sale_setup = (array) mycred_get_post_meta( $post->ID, 'myCRED_sell_content' . $suffix, true ); + if ( array_key_exists( 'status', $sale_setup ) && $sale_setup['status'] === 'enabled' ) + $for_sale = true; - } + } - } + } - // All posts for sale - elseif ($filter === 'all' ) { + // All posts for sale + elseif ( $filter === 'all' ) { - $for_sale = true; + $for_sale = true; - } + } - // Posts are set for sale but some are excluded - elseif ($filter === 'exclude' ) { + // Posts are set for sale but some are excluded + elseif ( $filter === 'exclude' ) { - // If post is not excluded, it is for sale - if (! in_array($post->ID, $list) ) { - $for_sale = true; - } + // If post is not excluded, it is for sale + if ( ! in_array( $post->ID, $list ) ) + $for_sale = true; - } + } - // Posts are not for sale but some are - elseif ($filter === 'include' ) { + // Posts are not for sale but some are + elseif ( $filter === 'include' ) { - // If post is included, it is for sale - if (in_array($post->ID, $list) ) { - $for_sale = true; - } + // If post is included, it is for sale + if ( in_array( $post->ID, $list ) ) + $for_sale = true; - } + } - // Taxonomy check - else { + // Taxonomy check + else { - $check = 'include'; - $taxonomy = $filter; + $check = 'include'; + $taxonomy = $filter; - if (substr($taxonomy, 0, 1) === '-' ) { - $check = 'exclude'; - $taxonomy = ltrim($taxonomy); - } + if ( substr( $taxonomy, 0, 1 ) === '-' ) { + $check = 'exclude'; + $taxonomy = ltrim( $taxonomy ); + } - // Get post terms - $terms = wp_get_post_terms($post->ID, $taxonomy); + // Get post terms + $terms = wp_get_post_terms( $post->ID, $taxonomy ); - // Taxonomy exclude check - if ($check === 'exclude' ) { + // Taxonomy exclude check + if ( $check === 'exclude' ) { - if (! empty($terms) ) { - foreach ( $terms as $term ) { + if ( ! empty( $terms ) ) { + foreach ( $terms as $term ) { - if (in_array($term->slug, $list) ) { continue; - } - $for_sale = true; + if ( in_array( $term->slug, $list ) ) continue; + $for_sale = true; - } - } + } + } - // No terms - not excluded - else { - $for_sale = true; - } + // No terms - not excluded + else { + $for_sale = true; + } - } + } - // Taxonomy include check - else { + // Taxonomy include check + else { - if (! empty($terms) ) { - foreach ( $terms as $term ) { + if ( ! empty( $terms ) ) { + foreach ( $terms as $term ) { - if (! in_array($term->slug, $list) ) { continue; - } - $for_sale = true; + if ( ! in_array( $term->slug, $list ) ) continue; + $for_sale = true; - } - } + } + } - } + } - } + } - } + } - return apply_filters('mycred_post_is_for_sale', $for_sale, $post, $settings); + return apply_filters( 'mycred_post_is_for_sale', $for_sale, $post, $settings ); - } + } endif; /** * User Has Paid * Checks if a user has paid for the given post. Will also take into account * if a purchase has expired (if used). - * - * @since 1.7 + * @since 1.7 * @version 1.1 */ -if (! function_exists('mycred_user_paid_for_content') ) : - function mycred_user_paid_for_content( $user_id = null, $post_id = null, $point_type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_user_paid_for_content' ) ) : + function mycred_user_paid_for_content( $user_id = NULL, $post_id = NULL, $point_type = MYCRED_DEFAULT_TYPE_KEY ) { - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - $has_paid = false; - $user_id = absint($user_id); - $post_id = absint($post_id); - $account = mycred_get_account($user_id); - $expires = mycred_sell_content_get_expiration_length($post_id, $point_type); + $has_paid = false; + $user_id = absint( $user_id ); + $post_id = absint( $post_id ); + $account = mycred_get_account( $user_id ); + $expires = mycred_sell_content_get_expiration_length( $post_id, $point_type ); - // No expirations - if ($expires == 0 ) { + // No expirations + if ( $expires == 0 ) { - // The history object should have a record of our payment for a quick check without the need to run the below db query - if (! empty($account->point_types) && in_array($point_type, $account->point_types) && isset($account->balance[ $point_type ]->history) ) { + // The history object should have a record of our payment for a quick check without the need to run the below db query + if ( ! empty( $account->point_types ) && in_array( $point_type, $account->point_types ) && isset( $account->balance[ $point_type ]->history ) ) { - $data = $account->balance[ $point_type ]->history->get('data'); - if (array_key_exists('buy_content', $data) && ! empty($data['buy_content']->reference_ids) && in_array($post_id, $data['buy_content']->reference_ids) ) { - $has_paid = true; - } + $data = $account->balance[ $point_type ]->history->get( 'data' ); + if ( array_key_exists( 'buy_content', $data ) && ! empty( $data['buy_content']->reference_ids ) && in_array( $post_id, $data['buy_content']->reference_ids ) ) + $has_paid = true; - } + } - } + } - $last_payment = ''; - - if (! $has_paid ) { + $last_payment = ''; + + if ( ! $has_paid ) { - $last_payment = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$mycred_log_table} WHERE user_id = %d AND ref = 'buy_content' AND ref_id = %d ORDER BY time DESC LIMIT 1;", $user_id, $post_id)); + $last_payment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$mycred_log_table} WHERE user_id = %d AND ref = 'buy_content' AND ref_id = %d ORDER BY time DESC LIMIT 1;", $user_id, $post_id ) ); - // Found a payment - if ($last_payment !== null ) { + // Found a payment + if ( $last_payment !== NULL ) { - $has_paid = true; + $has_paid = true; - // Check for expirations - if (mycred_content_purchase_has_expired($last_payment) ) { - $has_paid = false; - } + // Check for expirations + if ( mycred_content_purchase_has_expired( $last_payment ) ) + $has_paid = false; - } + } - } + } - // All else there are no purchases - return apply_filters('mycred_user_has_paid_for_content', $has_paid, $user_id, $post_id, $last_payment); + // All else there are no purchases + return apply_filters( 'mycred_user_has_paid_for_content', $has_paid, $user_id, $post_id, $last_payment ); - } + } endif; /** * Sale Expired * Checks if a given purchase has expired. Left this in place from the old version * for backwards comp. - * - * @since 1.7 + * @since 1.7 * @version 1.1 */ -if (! function_exists('mycred_content_purchase_has_expired') ) : - function mycred_content_purchase_has_expired( $payment = null ) - { +if ( ! function_exists( 'mycred_content_purchase_has_expired' ) ) : + function mycred_content_purchase_has_expired( $payment = NULL ) { - $has_expired = false; - if (! is_object($payment) ) { return $has_expired; - } + $has_expired = false; + if ( ! is_object( $payment ) ) return $has_expired; - $length = mycred_sell_content_get_expiration_length($payment->ref_id, $payment->ctype); + $length = mycred_sell_content_get_expiration_length( $payment->ref_id, $payment->ctype ); - // If expiration is set - if ($length > 0 ) { + // If expiration is set + if ( $length > 0 ) { - $expiration = apply_filters('mycred_sell_expire_calc', absint($length * HOUR_IN_SECONDS), $length, $payment->user_id, $payment->ref_id); + $expiration = apply_filters( 'mycred_sell_expire_calc', absint( $length * HOUR_IN_SECONDS ), $length, $payment->user_id, $payment->ref_id ); - $expiration = $expiration + $payment->time; + $expiration = $expiration + $payment->time; - if ($expiration <= current_time('timestamp') ) { - $has_expired = true; - } + if ( $expiration <= current_time( 'timestamp' ) ) + $has_expired = true; - } + } - return apply_filters('mycred_sell_content_sale_expired', $has_expired, $payment->user_id, $payment->ref_id, $payment->time, $length); + return apply_filters( 'mycred_sell_content_sale_expired', $has_expired, $payment->user_id, $payment->ref_id, $payment->time, $length ); - } + } endif; /** * Get Expiration Length - * - * @since 1.7.9.1 + * @since 1.7.9.1 * @version 1.0 */ -if (! function_exists('mycred_sell_content_get_expiration_length') ) : - function mycred_sell_content_get_expiration_length( $post_id = null, $type = MYCRED_DEFAULT_TYPE_KEY ) - { +if ( ! function_exists( 'mycred_sell_content_get_expiration_length' ) ) : + function mycred_sell_content_get_expiration_length( $post_id = NULL, $type = MYCRED_DEFAULT_TYPE_KEY ) { - $length = 0; - if ($post_id === null ) { return $length; - } + $length = 0; + if ( $post_id === NULL ) return $length; - $settings = mycred_sell_content_settings(); - $post = mycred_get_post($post_id); - $point_types = $settings['type']; - $has_expired = false; + $settings = mycred_sell_content_settings(); + $post = mycred_get_post( $post_id ); + $point_types = $settings['type']; + $has_expired = false; - // Invalid post - if (! isset($post->ID) ) { return $length; - } + // Invalid post + if ( ! isset( $post->ID ) ) return $length; - $filter = $settings['filters'][ $post->post_type ]['by']; + $filter = $settings['filters'][ $post->post_type ]['by']; - // Manual mode - expiration settings are found in the post setting - if ($filter === 'manual' ) { + // Manual mode - expiration settings are found in the post setting + if ( $filter === 'manual' ) { - $suffix = '_' . $type; - if ($type == MYCRED_DEFAULT_TYPE_KEY ) { - $suffix = ''; - } + $suffix = '_' . $type; + if ( $type == MYCRED_DEFAULT_TYPE_KEY ) + $suffix = ''; - $sale_setup = (array) mycred_get_post_meta($post->ID, 'myCRED_sell_content' . $suffix, true); - if (! empty($sale_setup) && array_key_exists('expire', $sale_setup) && $sale_setup['expire'] > 0 ) { - $length = $sale_setup['expire']; - } + $sale_setup = (array) mycred_get_post_meta( $post->ID, 'myCRED_sell_content' . $suffix, true ); + if ( ! empty( $sale_setup ) && array_key_exists( 'expire', $sale_setup ) && $sale_setup['expire'] > 0 ) + $length = $sale_setup['expire']; - } + } - // Else we need to check the point type setup in our add-on settings. - else { + // Else we need to check the point type setup in our add-on settings. + else { - $point_type_setup = (array) mycred_get_option('mycred_sell_this_' . $type); - if (! empty($point_type_setup) && array_key_exists('expire', $point_type_setup) && $point_type_setup['expire'] > 0 ) { - $length = $point_type_setup['expire']; - } + $point_type_setup = (array) mycred_get_option( 'mycred_sell_this_' . $type ); + if ( ! empty( $point_type_setup ) && array_key_exists( 'expire', $point_type_setup ) && $point_type_setup['expire'] > 0 ) + $length = $point_type_setup['expire']; - } + } - return apply_filters('mycred_sell_content_expiration', $length, $post); + return apply_filters( 'mycred_sell_content_expiration', $length, $post ); - } + } endif; /** * Get Payment Buttons * Returns all payment buttons a user can use to pay for a given post. - * - * @since 1.7 + * @since 1.7 * @version 1.1 */ -if (! function_exists('mycred_sell_content_payment_buttons') ) : - function mycred_sell_content_payment_buttons( $user_id = null, $post_id = null ) - { +if ( ! function_exists( 'mycred_sell_content_payment_buttons' ) ) : + function mycred_sell_content_payment_buttons( $user_id = NULL, $post_id = NULL ) { - if ($user_id === null || $post_id === null ) { return false; - } + if ( $user_id === NULL || $post_id === NULL ) return false; - $settings = mycred_sell_content_settings(); - $post = mycred_get_post($post_id); - $result = false; + $settings = mycred_sell_content_settings(); + $post = mycred_get_post( $post_id ); + $result = false; - if (! empty($settings['type']) ) { + if ( ! empty( $settings['type'] ) ) { - $buttons = array(); + $buttons = array(); - foreach ( $settings['type'] as $point_type ) { - - // Load point type - $mycred = mycred($point_type); - $setup = mycred_get_option('mycred_sell_this_' . $point_type); - $price = mycred_get_content_price($post_id, $point_type, $user_id); - $status = $setup['status']; - - // Manual mode - if ($settings['filters'][ $post->post_type ]['by'] == 'manual' ) { + foreach ( $settings['type'] as $point_type ) { + + // Load point type + $mycred = mycred( $point_type ); + $setup = mycred_get_option( 'mycred_sell_this_' . $point_type ); + $price = mycred_get_content_price( $post_id, $point_type, $user_id ); + $status = $setup['status']; + + // Manual mode + if ( $settings['filters'][ $post->post_type ]['by'] == 'manual' ) { - $suffix = ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? '_' . $point_type : ''; - $manual_setup = (array) mycred_get_post_meta($post_id, 'myCRED_sell_content' . $suffix, true); - if (! empty($manual_setup) && array_key_exists('status', $manual_setup) ) { - $status = $manual_setup['status']; - } + $suffix = ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? '_' . $point_type : ''; + $manual_setup = (array) mycred_get_post_meta( $post_id, 'myCRED_sell_content' . $suffix, true ); + if ( ! empty( $manual_setup ) && array_key_exists( 'status', $manual_setup ) ) + $status = $manual_setup['status']; - } + } - // Point type not enabled - if ($status == 'disabled' ) { continue; - } + // Point type not enabled + if ( $status == 'disabled' ) continue; - // Make sure we are not excluded from this type - if ($mycred->exclude_user($user_id) ) { continue; - } + // Make sure we are not excluded from this type + if ( $mycred->exclude_user( $user_id ) ) continue; - // Make sure we can afford to pay - if ($mycred->get_users_balance($user_id, $point_type) < $price ) { continue; - } + // Make sure we can afford to pay + if ( $mycred->get_users_balance( $user_id, $point_type ) < $price ) continue; - $button_label = str_replace('%price%', $mycred->format_creds($price), $setup['button_label']); + $button_label = str_replace( '%price%', $mycred->format_creds( $price ), $setup['button_label'] ); - $button = ''; - $buttons[] = apply_filters('mycred_sell_this_button', $button, $post, $setup, $mycred); + $button = ''; + $buttons[] = apply_filters( 'mycred_sell_this_button', $button, $post, $setup, $mycred ); - } + } - if (! empty($buttons) ) { - $result = implode(' ', $buttons); - } + if ( ! empty( $buttons ) ) + $result = implode( ' ', $buttons ); - } - - // Return a string of buttons or false if user can not afford - return apply_filters('mycred_sellcontent_buttons', $result, $user_id, $post_id); + } + + // Return a string of buttons or false if user can not afford + return apply_filters( 'mycred_sellcontent_buttons', $result, $user_id, $post_id ); - } + } endif; /** * Sell Content Template * Parses a particular template. - * - * @since 1.7 + * @since 1.7 * @version 1.0.2 */ -if (! function_exists('mycred_sell_content_template') ) : - function mycred_sell_content_template( $template = '', $post = null, $type = 'mycred-sell-partial-content', $status = 'visitor' ) - { +if ( ! function_exists( 'mycred_sell_content_template' ) ) : + function mycred_sell_content_template( $template = '', $post = NULL, $type = 'mycred-sell-partial-content', $status = 'visitor' ) { - if (! is_object($post) || strlen($template) === 0 ) { return $template; - } + if ( ! is_object( $post ) || strlen( $template ) === 0 ) return $template; - $post_type = get_post_type_object($post->post_type); - $url = mycred_get_permalink($post->ID); - - if ($status == 'mycred-sell-insufficient' ) { - $post = mycred_get_post($post->ID); - $settings = mycred_sell_content_settings(); - $prices = array(); + $post_type = get_post_type_object( $post->post_type ); + $url = mycred_get_permalink( $post->ID ); + + if ( $status == 'mycred-sell-insufficient' ) { + $post = mycred_get_post( $post->ID ); + $settings = mycred_sell_content_settings(); + $prices = array(); - foreach ( $settings['type'] as $point_type ) { + foreach ( $settings['type'] as $point_type ) { - $setup = mycred_get_option('mycred_sell_this_' . $point_type); - $status = $setup['status']; + $setup = mycred_get_option( 'mycred_sell_this_' . $point_type ); + $status = $setup['status']; - // Point type not enabled - if ($status == 'disabled' ) { continue; - } - - $mycred = mycred($point_type); - $price = mycred_get_content_price($post->ID, $point_type, get_current_user_id()); + // Point type not enabled + if ( $status == 'disabled' ) continue; + + $mycred = mycred( $point_type ); + $price = mycred_get_content_price( $post->ID, $point_type, get_current_user_id() ); - // Manual mode - if ($settings['filters'][ $post->post_type ]['by'] == 'manual' ) { + // Manual mode + if ( $settings['filters'][ $post->post_type ]['by'] == 'manual' ) { - $suffix = ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? '_' . $point_type : ''; - - $manual_setup = (array) mycred_get_post_meta($post->ID, 'myCRED_sell_content' . $suffix, true); - - if (! empty($manual_setup) && array_key_exists('status', $manual_setup) ) { - $status = $manual_setup['status']; - } + $suffix = ( $point_type != MYCRED_DEFAULT_TYPE_KEY ) ? '_' . $point_type : ''; + + $manual_setup = (array) mycred_get_post_meta( $post->ID, 'myCRED_sell_content' . $suffix, true ); + + if ( ! empty( $manual_setup ) && array_key_exists( 'status', $manual_setup ) ) + $status = $manual_setup['status']; - } + } - $prices[] = $mycred->format_creds($price); - } + $prices[] = $mycred->format_creds( $price ); + } - $template = str_replace('%price%', implode(', ', $prices), $template); - } - - // Remove old tags that are no longer supported - $template = str_replace(array( '%price%', '%expires%', ), '', $template); + $template = str_replace( '%price%',implode(', ',$prices), $template ); + } + + // Remove old tags that are no longer supported + $template = str_replace( array( '%price%', '%expires%', ), '', $template ); - $template = str_replace('%post_title%', mycred_get_the_title($post->ID), $template); - $template = str_replace('%post_type%', $post_type->labels->singular_name, $template); - $template = str_replace('%post_url%', $url, $template); - $template = str_replace('%link_with_title%', '' . $post->post_title . '', $template); + $template = str_replace( '%post_title%', mycred_get_the_title( $post->ID ), $template ); + $template = str_replace( '%post_type%', $post_type->labels->singular_name, $template ); + $template = str_replace( '%post_url%', $url, $template ); + $template = str_replace( '%link_with_title%', '' . $post->post_title . '', $template ); - $template = apply_filters('mycred_sell_content_template', $template, $post, $type); - $template = do_shortcode($template); + $template = apply_filters( 'mycred_sell_content_template', $template, $post, $type ); + $template = do_shortcode( $template ); - $wrapper_classes = array(); - $wrapper_classes[] = 'mycred-sell-this-wrapper'; - $wrapper_classes[] = esc_attr($type); - $wrapper_classes[] = esc_attr($status); + $wrapper_classes = array(); + $wrapper_classes[] = 'mycred-sell-this-wrapper'; + $wrapper_classes[] = esc_attr( $type ); + $wrapper_classes[] = esc_attr( $status ); - $wrapper_classes = apply_filters('mycred_sell_template_class', $wrapper_classes, $post); + $wrapper_classes = apply_filters( 'mycred_sell_template_class', $wrapper_classes, $post ); - return '
    ' . $template . '
    '; + return '
    ' . $template . '
    '; - } + } endif; /** * New Purchase * Handles the purchase of a particular post by a given user. - * * @returns true (bool) on success or an error message (string) - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_sell_content_new_purchase') ) : - function mycred_sell_content_new_purchase( $post = null, $user_id = null, $point_type = null ) - { +if ( ! function_exists( 'mycred_sell_content_new_purchase' ) ) : + function mycred_sell_content_new_purchase( $post = NULL, $user_id = NULL, $point_type = NULL ) { - if (! is_object($post) ) { - $post = mycred_get_post($post); - } + if ( ! is_object( $post ) ) + $post = mycred_get_post( $post ); - if (! isset($post->ID) ) { return false; - } + if ( ! isset( $post->ID ) ) return false; - $mycred = mycred($point_type); - $settings = mycred_sell_content_settings(); - $setup = mycred_get_option('mycred_sell_this_' . $point_type); - $result = apply_filters('mycred_before_content_purchase', false, $post->ID, $user_id, $point_type); + $mycred = mycred( $point_type ); + $settings = mycred_sell_content_settings(); + $setup = mycred_get_option( 'mycred_sell_this_' . $point_type ); + $result = apply_filters( 'mycred_before_content_purchase', false, $post->ID, $user_id, $point_type ); - // We handle payment - if ($result === false ) { + // We handle payment + if ( $result === false ) { - // Disabled point type or user is excluded. - if ($setup['status'] === 'disabled' || $mycred->exclude_user($user_id) ) { - $result = sprintf(_x('You can not pay using %s', 'Point type name', 'mycred'), $mycred->plural()); + // Disabled point type or user is excluded. + if ( $setup['status'] === 'disabled' || $mycred->exclude_user( $user_id ) ) + $result = sprintf( _x( 'You can not pay using %s', 'Point type name', 'mycred' ), $mycred->plural() ); - } else { + else { - $balance = $mycred->get_users_balance($user_id, $point_type); - $price = mycred_get_content_price($post->ID, $point_type, $user_id); + $balance = $mycred->get_users_balance( $user_id, $point_type ); + $price = mycred_get_content_price( $post->ID, $point_type, $user_id ); - // Insufficient funds (not free) - if ($price > 0 && $balance < $price ) { - $result = __('Insufficient funds.', 'mycred'); - } + // Insufficient funds (not free) + if ( $price > 0 && $balance < $price ) + $result = __( 'Insufficient funds.', 'mycred' ); - // Content is not free - elseif ($price > 0 ) { + // Content is not free + elseif ( $price > 0 ) { - // Need a unqiue transaction id - $transaction_id = 'TXID' . $user_id . current_time('timestamp') . $post->ID; + // Need a unqiue transaction id + $transaction_id = 'TXID' . $user_id . current_time( 'timestamp' ) . $post->ID; - // Charge buyer - $mycred->add_creds( - 'buy_content', - $user_id, - 0 - $price, - $setup['log_payment'], - $post->ID, - array( - 'ref_type' => 'post', - 'purchase_id' => $transaction_id, - 'seller' => $post->post_author - ), - $point_type - ); + // Charge buyer + $mycred->add_creds( + 'buy_content', + $user_id, + 0 - $price, + $setup['log_payment'], + $post->ID, + array( + 'ref_type' => 'post', + 'purchase_id' => $transaction_id, + 'seller' => $post->post_author + ), + $point_type + ); - // Profit Sharing - if ($setup['profit_share'] > 0 ) { + // Profit Sharing + if ( $setup['profit_share'] > 0 ) { - // Let others play with the users profit share - $percentage = mycred_get_authors_profit_share($post->post_author, $point_type, $setup['profit_share']); - if ($percentage !== false ) { + // Let others play with the users profit share + $percentage = mycred_get_authors_profit_share( $post->post_author, $point_type, $setup['profit_share'] ); + if ( $percentage !== false ) { - // Convert percentage to a share amount - $share = ( $percentage / 100 ) * $price; + // Convert percentage to a share amount + $share = ( $percentage / 100 ) * $price; - // Pay the author - $mycred->add_creds( - 'sell_content', - $post->post_author, - $share, - $setup['log_sale'], - $post->ID, - array( - 'ref_type' => 'post', - 'purchase_id' => $transaction_id, - 'buyer' => $user_id - ), - $point_type - ); + // Pay the author + $mycred->add_creds( + 'sell_content', + $post->post_author, + $share, + $setup['log_sale'], + $post->ID, + array( + 'ref_type' => 'post', + 'purchase_id' => $transaction_id, + 'buyer' => $user_id + ), + $point_type + ); - } + } - } + } - $result = true; + $result = true; - // Delete counters to trigger new db query - mycred_delete_post_meta($post->ID, '_mycred_content_sales'); - mycred_delete_post_meta($post->ID, '_mycred_content_buyers'); + // Delete counters to trigger new db query + mycred_delete_post_meta( $post->ID, '_mycred_content_sales' ); + mycred_delete_post_meta( $post->ID, '_mycred_content_buyers' ); - } + } - // Free - else { - $result = true; - } + // Free + else { + $result = true; + } - } + } - } + } - return apply_filters('mycred_after_content_purchase', $result, $post, $user_id, $point_type); + return apply_filters( 'mycred_after_content_purchase', $result, $post, $user_id, $point_type ); - } + } endif; /** * Get Content Price * Returns the contents price. - * - * @since 1.7 + * @since 1.7 * @version 1.0.1 */ -if (! function_exists('mycred_get_content_price') ) : - function mycred_get_content_price( $post_id = null, $point_type = null, $user_id = null ) - { +if ( ! function_exists( 'mycred_get_content_price' ) ) : + function mycred_get_content_price( $post_id = NULL, $point_type = NULL, $user_id = NULL ) { - $mycred = mycred($point_type); - $settings = mycred_sell_content_settings(); + $mycred = mycred( $point_type ); + $settings = mycred_sell_content_settings(); - $setup = mycred_get_option('mycred_sell_this_' . $point_type); - $price = $mycred->number($setup['price']); - $post_type = mycred_get_post_type($post_id); + $setup = mycred_get_option( 'mycred_sell_this_' . $point_type ); + $price = $mycred->number( $setup['price'] ); + $post_type = mycred_get_post_type( $post_id ); - if (array_key_exists($post_type, $settings['filters']) && $settings['filters'][ $post_type ]['by'] === 'manual' ) { + if ( array_key_exists( $post_type, $settings['filters'] ) && $settings['filters'][ $post_type ]['by'] === 'manual' ) { - $suffix = '_' . $point_type; - if ($point_type == MYCRED_DEFAULT_TYPE_KEY ) { - $suffix = ''; - } + $suffix = '_' . $point_type; + if ( $point_type == MYCRED_DEFAULT_TYPE_KEY ) + $suffix = ''; - $sale_setup = (array) mycred_get_post_meta($post_id, 'myCRED_sell_content' . $suffix, true); - if (array_key_exists('price', $sale_setup) ) { - $price = $mycred->number($sale_setup['price']); - } + $sale_setup = (array) mycred_get_post_meta( $post_id, 'myCRED_sell_content' . $suffix, true ); + if ( array_key_exists( 'price', $sale_setup ) ) + $price = $mycred->number( $sale_setup['price'] ); - } + } - return apply_filters('mycred_get_content_price', $price, $post_id, $point_type, $user_id); + return apply_filters( 'mycred_get_content_price', $price, $post_id, $point_type, $user_id ); - } + } endif; /** * Get Users Purchased Content * Returns an array of log entries for content purchases. - * - * @since 1.7 + * @since 1.7 * @version 1.0.1 */ -if (! function_exists('mycred_get_users_purchased_content') ) : - function mycred_get_users_purchased_content( $user_id = null, $number = 25, $order = 'DESC', $point_type = null ) - { +if ( ! function_exists( 'mycred_get_users_purchased_content' ) ) : + function mycred_get_users_purchased_content( $user_id = NULL, $number = 25, $order = 'DESC', $point_type = NULL ) { - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - $limit = ''; - if (absint($number) > 0 ) { - $limit = $wpdb->prepare("LIMIT 0,%d", $number); - } + $limit = ''; + if ( absint( $number ) > 0 ) + $limit = $wpdb->prepare( "LIMIT 0,%d", $number ); - $wheres = array(); - $wheres[] = "ref = 'buy_content'"; - $wheres[] = $wpdb->prepare("user_id = %d", $user_id); + $wheres = array(); + $wheres[] = "ref = 'buy_content'"; + $wheres[] = $wpdb->prepare( "user_id = %d", $user_id ); - if ($point_type !== null && mycred_point_type_exists($point_type) ) { - $wheres[] = $wpdb->prepare("ctype = %s", $point_type); - } + if ( $point_type !== NULL && mycred_point_type_exists( $point_type ) ) + $wheres[] = $wpdb->prepare( "ctype = %s", $point_type ); - $wheres = 'WHERE ' . implode(' AND ', $wheres); + $wheres = 'WHERE ' . implode( ' AND ', $wheres ); - if (! in_array($order, array( 'ASC', 'DESC' )) ) { - $order = 'DESC'; - } + if ( ! in_array( $order, array( 'ASC', 'DESC' ) ) ) + $order = 'DESC'; - $sql = apply_filters('mycred_get_users_purchased_content', "SELECT * FROM {$mycred_log_table} log INNER JOIN {$wpdb->posts} posts ON ( log.ref_id = posts.ID ) {$wheres} ORDER BY time {$order} {$limit};", $user_id, $number, $order, $point_type); + $sql = apply_filters( 'mycred_get_users_purchased_content', "SELECT * FROM {$mycred_log_table} log INNER JOIN {$wpdb->posts} posts ON ( log.ref_id = posts.ID ) {$wheres} ORDER BY time {$order} {$limit};", $user_id, $number, $order, $point_type ); - return $wpdb->get_results($sql); + return $wpdb->get_results( $sql ); - } + } endif; /** * Get Posts Buyers * Returns an array of User IDs of the user that has purchased * a given post. - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_get_posts_buyers') ) : - function mycred_get_posts_buyers( $post_id = null, $number = 25, $point_type = null ) - { +if ( ! function_exists( 'mycred_get_posts_buyers' ) ) : + function mycred_get_posts_buyers( $post_id = NULL, $number = 25, $point_type = NULL ) { - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - $limit = ''; - if (absint($number) > 0 ) { - $limit = $wpdb->prepare("LIMIT 0,%d", $number); - } + $limit = ''; + if ( absint( $number ) > 0 ) + $limit = $wpdb->prepare( "LIMIT 0,%d", $number ); - $wheres = array(); - $wheres[] = "ref = 'buy_content'"; - $wheres[] = $wpdb->prepare("ref_id = %d", $post_id); + $wheres = array(); + $wheres[] = "ref = 'buy_content'"; + $wheres[] = $wpdb->prepare( "ref_id = %d", $post_id ); - if ($point_type !== null && mycred_point_type_exists($point_type) ) { - $wheres[] = $wpdb->prepare("ctype = %s", $point_type); - } + if ( $point_type !== NULL && mycred_point_type_exists( $point_type ) ) + $wheres[] = $wpdb->prepare( "ctype = %s", $point_type ); - $wheres = 'WHERE ' . implode(' AND ', $wheres); + $wheres = 'WHERE ' . implode( ' AND ', $wheres ); - return $wpdb->get_col("SELECT user_id FROM {$mycred_log_table} {$wheres} ORDER BY time DESC {$limit};"); + return $wpdb->get_col( "SELECT user_id FROM {$mycred_log_table} {$wheres} ORDER BY time DESC {$limit};" ); - } + } endif; /** * Get Content Sales Count * Returns the number of times a content has been purchased. - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_get_content_sales_count') ) : - function mycred_get_content_sales_count( $post_id = null ) - { +if ( ! function_exists( 'mycred_get_content_sales_count' ) ) : + function mycred_get_content_sales_count( $post_id = NULL ) { - $count = mycred_get_post_meta($post_id, '_mycred_content_sales', true); - if (strlen($count) == 0 ) { + $count = mycred_get_post_meta( $post_id, '_mycred_content_sales', true ); + if ( strlen( $count ) == 0 ) { - $count = mycred_count_ref_id_instances('buy_content', $post_id); - mycred_add_post_meta($post_id, '_mycred_content_sales', $count, true); + $count = mycred_count_ref_id_instances( 'buy_content', $post_id ); + mycred_add_post_meta( $post_id, '_mycred_content_sales', $count, true ); - } + } - return apply_filters('mycred_content_sales_count', $count, $post_id); + return apply_filters( 'mycred_content_sales_count', $count, $post_id ); - } + } endif; /** * Get Content Buyer Count * Returns the number of buyers a particular content has. - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_get_content_buyers_count') ) : - function mycred_get_content_buyers_count( $post_id = null ) - { +if ( ! function_exists( 'mycred_get_content_buyers_count' ) ) : + function mycred_get_content_buyers_count( $post_id = NULL ) { - $count = mycred_get_post_meta($post_id, '_mycred_content_buyers', true); - if (strlen($count) == 0 ) { + $count = mycred_get_post_meta( $post_id, '_mycred_content_buyers', true ); + if ( strlen( $count ) == 0 ) { - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT( DISTINCT user_id ) FROM {$mycred_log_table} WHERE ref = 'buy_content' AND ref_id = %d;", $post_id)); - if ($count === null ) { $count = 0; - } + $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( DISTINCT user_id ) FROM {$mycred_log_table} WHERE ref = 'buy_content' AND ref_id = %d;", $post_id ) ); + if ( $count === NULL ) $count = 0; - mycred_add_post_meta($post_id, '_mycred_content_buyers', $count, true); + mycred_add_post_meta( $post_id, '_mycred_content_buyers', $count, true ); - } + } - return apply_filters('_mycred_content_buyers', $count, $post_id); + return apply_filters( '_mycred_content_buyers', $count, $post_id ); - } + } endif; /** * Get Authors Profit Share * Get a particular users profit share percentage. If not set, the general setup for the given * point type is returned instead. - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_get_authors_profit_share') ) : - function mycred_get_authors_profit_share( $user_id = null, $point_type = null, $default = false ) - { +if ( ! function_exists( 'mycred_get_authors_profit_share' ) ) : + function mycred_get_authors_profit_share( $user_id = NULL, $point_type = NULL, $default = false ) { - $users_share = mycred_get_user_meta($user_id, 'mycred_sell_content_share_' . $point_type, '', true); - if (strlen($users_share) == 0 ) { - $users_share = $default; - } + $users_share = mycred_get_user_meta( $user_id, 'mycred_sell_content_share_' . $point_type, '', true ); + if ( strlen( $users_share ) == 0 ) + $users_share = $default; - return apply_filters('mycred_sell_content_profit_share', $users_share, $user_id, $point_type, $default); + return apply_filters( 'mycred_sell_content_profit_share', $users_share, $user_id, $point_type, $default ); - } + } endif; /** * Get Post Type Options * Returns an array of filter options for post types. - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_get_post_type_options') ) : - function mycred_get_post_type_options( $post_type ) - { - - $type = get_post_type_object($post_type); - if (! is_object($type) ) { return; - } - - $options = array(); - $options['all'] = array( - 'label' => sprintf(_x('All %s', 'all post type name', 'mycred'), $type->labels->name), - 'data' => '' - ); - $options['manual'] = array( - 'label' => sprintf(_x('%s I manually select', 'all post type name', 'mycred'), $type->labels->name), - 'data' => '' - ); - $options['exclude'] = array( - 'label' => sprintf(_x('All %s except', '%s = post type name', 'mycred'), $type->labels->name), - 'data' => sprintf(_x('Comma separated list of %s IDs to exclude', '%s = post type name', 'mycred'), $type->labels->singular_name) - ); - $options['include'] = array( - 'label' => sprintf(_x('Only %s', '%s = post type name', 'mycred'), $type->labels->name), - 'data' => sprintf(_x('Comma separated list of %s IDs', '%s = post type name', 'mycred'), $type->labels->singular_name) - ); - - $taxonomies = get_object_taxonomies($post_type, 'objects'); - if (! empty($taxonomies) ) { - - foreach ( $taxonomies as $taxonomy_id => $term ) { - - if (! $term->public ) { continue; - } - - if ($term->hierarchical ) { - $options[ $taxonomy_id ] = array( - 'label' => sprintf(_x('Only %s in %s', 'e.g. Only "Posts" in "Categories"', 'mycred'), $type->labels->name, $term->labels->name), - 'data' => sprintf(_x('Comma separated list of %s slugs', '%s = taxonomy name', 'mycred'), $term->labels->singular_name) - ); - $options[ '_' . $taxonomy_id ] = array( - 'label' => sprintf(_x('Only %s not in %s', 'e.g. Only "Posts" not in "Categories"', 'mycred'), $type->labels->name, $term->labels->name), - 'data' => sprintf(_x('Comma separated list of %s slugs', '%s = taxonomy name', 'mycred'), $term->labels->singular_name) - ); - } - else { - $options[ $taxonomy_id ] = array( - 'label' => sprintf(_x('Only %s with %s', 'e.g. Only "Posts" with "Tags"', 'mycred'), $type->labels->name, $term->labels->name), - 'data' => sprintf(_x('Comma separated list of %s slugs', '%s = taxonomy name', 'mycred'), $term->labels->singular_name) - ); - $options[ '_' . $taxonomy_id ] = array( - 'label' => sprintf(_x('Only %s without %s', 'e.g. Only "Posts" without "Tags"', 'mycred'), $type->labels->name, $term->labels->name), - 'data' => sprintf(_x('Comma separated list of %s slugs', '%s = taxonomy name', 'mycred'), $term->labels->singular_name) - ); - } - - } - - } - - return apply_filters('mycred_sell_post_type_options', $options, $post_type); - - } +if ( ! function_exists( 'mycred_get_post_type_options' ) ) : + function mycred_get_post_type_options( $post_type ) { + + $type = get_post_type_object( $post_type ); + if ( ! is_object( $type ) ) return; + + $options = array(); + $options['all'] = array( + 'label' => sprintf( _x( 'All %s', 'all post type name', 'mycred' ), $type->labels->name ), + 'data' => '' + ); + $options['manual'] = array( + 'label' => sprintf( _x( '%s I manually select', 'all post type name', 'mycred' ), $type->labels->name ), + 'data' => '' + ); + $options['exclude'] = array( + 'label' => sprintf( _x( 'All %s except', '%s = post type name', 'mycred' ), $type->labels->name ), + 'data' => sprintf( _x( 'Comma separated list of %s IDs to exclude', '%s = post type name', 'mycred' ), $type->labels->singular_name ) + ); + $options['include'] = array( + 'label' => sprintf( _x( 'Only %s', '%s = post type name', 'mycred' ), $type->labels->name ), + 'data' => sprintf( _x( 'Comma separated list of %s IDs', '%s = post type name', 'mycred' ), $type->labels->singular_name ) + ); + + $taxonomies = get_object_taxonomies( $post_type, 'objects' ); + if ( ! empty( $taxonomies ) ) { + + foreach ( $taxonomies as $taxonomy_id => $term ) { + + if ( ! $term->public ) continue; + + if ( $term->hierarchical ) { + $options[ $taxonomy_id ] = array( + 'label' => sprintf( _x( 'Only %s in %s', 'e.g. Only "Posts" in "Categories"', 'mycred' ), $type->labels->name, $term->labels->name ), + 'data' => sprintf( _x( 'Comma separated list of %s slugs', '%s = taxonomy name', 'mycred' ), $term->labels->singular_name ) + ); + $options[ '_' . $taxonomy_id ] = array( + 'label' => sprintf( _x( 'Only %s not in %s', 'e.g. Only "Posts" not in "Categories"', 'mycred' ), $type->labels->name, $term->labels->name ), + 'data' => sprintf( _x( 'Comma separated list of %s slugs', '%s = taxonomy name', 'mycred' ), $term->labels->singular_name ) + ); + } + else { + $options[ $taxonomy_id ] = array( + 'label' => sprintf( _x( 'Only %s with %s', 'e.g. Only "Posts" with "Tags"', 'mycred' ), $type->labels->name, $term->labels->name ), + 'data' => sprintf( _x( 'Comma separated list of %s slugs', '%s = taxonomy name', 'mycred' ), $term->labels->singular_name ) + ); + $options[ '_' . $taxonomy_id ] = array( + 'label' => sprintf( _x( 'Only %s without %s', 'e.g. Only "Posts" without "Tags"', 'mycred' ), $type->labels->name, $term->labels->name ), + 'data' => sprintf( _x( 'Comma separated list of %s slugs', '%s = taxonomy name', 'mycred' ), $term->labels->singular_name ) + ); + } + + } + + } + + return apply_filters( 'mycred_sell_post_type_options', $options, $post_type ); + + } endif; /** * Render remaining time - * - * @since 2.1.1 + * @since 2.1.1 * @version 1.0 */ -if (! function_exists('mycred_seconds_to_time') ) : - function mycred_seconds_to_time( $seconds ) - { - $dtF = new \DateTime('@0'); - $dtT = new \DateTime("@$seconds"); - return $dtF->diff($dtT)->format('%a days, %h hours,%i minutes ,%s Seconds'); - } +if ( ! function_exists( 'mycred_seconds_to_time' ) ) : + function mycred_seconds_to_time( $seconds ) { + $dtF = new \DateTime('@0'); + $dtT = new \DateTime("@$seconds"); + return $dtF->diff($dtT)->format('%a days, %h hours,%i minutes ,%s Seconds'); + } endif; /** * Check if points enable - * - * @since 2.3 + * @since 2.3 * @version 1.0 */ -if (! function_exists('mycred_sc_is_point_enable') ) : - function mycred_sc_is_points_enable() - { - $point_types = mycred_get_types(); +if ( ! function_exists( 'mycred_sc_is_point_enable' ) ) : +function mycred_sc_is_points_enable() +{ + $point_types = mycred_get_types(); - foreach( array_keys($point_types) as $point_type ) - { - $settings = mycred_get_option("mycred_sell_this_{$point_type}"); + foreach( array_keys( $point_types ) as $point_type ) + { + $settings = mycred_get_option( "mycred_sell_this_{$point_type}" ); - if(!empty($settings) && $settings['status'] == 'enabled' ) { - return true; - } + if( !empty( $settings ) && $settings['status'] == 'enabled' ) + return true; - continue; - } + continue; + } - return false; - } -endif; + return false; +} +endif; \ No newline at end of file diff --git a/addons/sell-content/includes/mycred-sell-shortcodes.php b/addons/sell-content/includes/mycred-sell-shortcodes.php index 1fa27ca..dc1c50e 100644 --- a/addons/sell-content/includes/mycred-sell-shortcodes.php +++ b/addons/sell-content/includes/mycred-sell-shortcodes.php @@ -1,400 +1,355 @@ post_author === $user_id ) ? true : false; + $post_id = mycred_sell_content_post_id(); + $post = mycred_get_post( $post_id ); + $user_id = get_current_user_id(); + $is_admin = mycred_is_admin( $user_id ); + $is_owner = ( (int) $post->post_author === $user_id ) ? true : false; - $mycred_partial_content_sale = true; + $mycred_partial_content_sale = true; - // Logged in users - if (is_user_logged_in() ) { + // Logged in users + if ( is_user_logged_in() ) { - // Authors and admins do not pay - if (! $is_admin && ! $is_owner ) { + // Authors and admins do not pay + if ( ! $is_admin && ! $is_owner ) { - // In case we have not paid - if (! mycred_user_paid_for_content($user_id, $post_id) ) { + // In case we have not paid + if ( ! mycred_user_paid_for_content( $user_id, $post_id ) ) { - // Get Payment Options - $payment_options = mycred_sell_content_payment_buttons($user_id, $post_id); + // Get Payment Options + $payment_options = mycred_sell_content_payment_buttons( $user_id, $post_id ); - // User can buy - if ($payment_options !== false ) { + // User can buy + if ( $payment_options !== false ) { - $content = $mycred_modules['solo']['content']->sell_content['templates']['members']; - $content = str_replace('%buy_button%', $payment_options, $content); - $content = mycred_sell_content_template($content, $post, 'mycred-sell-partial-content', 'mycred-sell-unpaid'); + $content = $mycred_modules['solo']['content']->sell_content['templates']['members']; + $content = str_replace( '%buy_button%', $payment_options, $content ); + $content = mycred_sell_content_template( $content, $post, 'mycred-sell-partial-content', 'mycred-sell-unpaid' ); - } + } - // Can not afford to buy - else { + // Can not afford to buy + else { - $content = $mycred_modules['solo']['content']->sell_content['templates']['cantafford']; - $content = mycred_sell_content_template($content, $post, 'mycred-sell-partial-content', 'mycred-sell-insufficient'); + $content = $mycred_modules['solo']['content']->sell_content['templates']['cantafford']; + $content = mycred_sell_content_template( $content, $post, 'mycred-sell-partial-content', 'mycred-sell-insufficient' ); - } + } - } + } - } + } - /** - * Incase the shortcode is used incorrectly - * Since the shortcode is only used to indicate which part of the content that is for sale, we need to make sure it can only be used - * on content that has been set to be purchasable. In manual mode, this means we must have clicked to enable sale in the metabox. - * In auto modes, the particular post types setup must be enabled and the post must fit any filter criteria we might have set. - * Since the content might have monetary value, we do not want to just show it, but to warn admin/post author and appologize to the user. - * - * @since 1.7.8 - */ - elseif (! mycred_post_is_for_sale($post) ) { + /** + * Incase the shortcode is used incorrectly + * Since the shortcode is only used to indicate which part of the content that is for sale, we need to make sure it can only be used + * on content that has been set to be purchasable. In manual mode, this means we must have clicked to enable sale in the metabox. + * In auto modes, the particular post types setup must be enabled and the post must fit any filter criteria we might have set. + * Since the content might have monetary value, we do not want to just show it, but to warn admin/post author and appologize to the user. + * @since 1.7.8 + */ + elseif ( ! mycred_post_is_for_sale( $post ) ) { - if ($is_admin || $is_owner ) { - return '

    ' . sprintf('%s %s', __('This shortcode can not be used in content that has not been set for sale!', 'mycred'), '' . __('Edit', 'mycred') . '

    '; - } + if ( $is_admin || $is_owner ) + return '

    ' . sprintf( '%s %s', __( 'This shortcode can not be used in content that has not been set for sale!', 'mycred' ), '' . __( 'Edit', 'mycred' ) . '

    '; - return '

    ' . __('This content is currently unattainable. Apologies for the inconvenience.', 'mycred') . '

    '; + return '

    ' . __( 'This content is currently unattainable. Apologies for the inconvenience.', 'mycred' ) . '

    '; - } + } - } + } - // Visitors - else { + // Visitors + else { - $content = $mycred_modules['solo']['content']->sell_content['templates']['visitors']; - $content = mycred_sell_content_template($content, $post, 'mycred-sell-partial-content', 'mycred-sell-visitor'); + $content = $mycred_modules['solo']['content']->sell_content['templates']['visitors']; + $content = mycred_sell_content_template( $content, $post, 'mycred-sell-partial-content', 'mycred-sell-visitor' ); - } + } - return do_shortcode($content); + return do_shortcode( $content ); - } + } endif; /** * Shortcode: Sell This AJAX * Depreciated as of version 1.7 and will be removed in version 1.8 - * - * @since 1.3 + * @since 1.3 * @version 1.0 */ -if (! function_exists('mycred_render_sell_this_ajax') ) : - function mycred_render_sell_this_ajax( $atts, $content = '' ) - { +if ( ! function_exists( 'mycred_render_sell_this_ajax' ) ) : + function mycred_render_sell_this_ajax( $atts, $content = '' ) { - _doing_it_wrong('mycred_render_sell_this_ajax', 'The mycred_sell_this_ajax shortcode has been depreciated and will be removed in version 1.8.', '1.7'); + _doing_it_wrong( 'mycred_render_sell_this_ajax', 'The mycred_sell_this_ajax shortcode has been depreciated and will be removed in version 1.8.', '1.7' ); - return mycred_render_sell_this($atts, $content); + return mycred_render_sell_this( $atts, $content ); - } + } endif; /** * Shortcode: Sales Counter * Renders the total number of times this post has been purchased or the total number of * active sales right now, if sales expire. - * * @attribute wrapper (string) - optional html element to wrap around the value. * @attribute post_id (int) - option to get the count for the provided post ID. - * @since 1.7 - * @version 1.0 + * @since 1.7 + * @version 1.0 */ -if (! function_exists('mycred_render_sell_count') ) : - function mycred_render_sell_count( $atts, $content = '' ) - { +if ( ! function_exists( 'mycred_render_sell_count' ) ) : + function mycred_render_sell_count( $atts, $content = '' ) { - extract( - shortcode_atts( - array( - 'wrapper' => '', - 'post_id' => null - ), $atts, MYCRED_SLUG . '_content_sale_count' - ) - ); + extract( shortcode_atts( array( + 'wrapper' => '', + 'post_id' => NULL + ), $atts, MYCRED_SLUG . '_content_sale_count' ) ); - if ($post_id === null ) { - $post_id = mycred_sell_content_post_id(); - } + if ( $post_id === NULL ) + $post_id = mycred_sell_content_post_id(); - $content = ''; + $content = ''; - if ($wrapper != '' ) { - $content .= '<' . $wrapper . ' class="mycred-sell-this-sales-count">'; - } + if ( $wrapper != '' ) + $content .= '<' . $wrapper . ' class="mycred-sell-this-sales-count">'; - $content .= mycred_get_content_sales_count($post_id); + $content .= mycred_get_content_sales_count( $post_id ); - if ($wrapper != '' ) { - $content .= ''; - } + if ( $wrapper != '' ) + $content .= ''; - return $content; + return $content; - } + } endif; /** * Shortcode: Sales Buyer Counter * Renders the total number of unique users that has purchased this content. - * * @attribute wrapper (string) - optional html element to wrap around the value. * @attribute post_id (int) - option to get the count for the provided post ID. - * @since 1.7 - * @version 1.0 + * @since 1.7 + * @version 1.0 */ -if (! function_exists('mycred_render_sell_buyer_count') ) : - function mycred_render_sell_buyer_count( $atts, $content = '' ) - { +if ( ! function_exists( 'mycred_render_sell_buyer_count' ) ) : + function mycred_render_sell_buyer_count( $atts, $content = '' ) { - extract( - shortcode_atts( - array( - 'wrapper' => '', - 'post_id' => null - ), $atts, MYCRED_SLUG . '_content_buyer_count' - ) - ); + extract( shortcode_atts( array( + 'wrapper' => '', + 'post_id' => NULL + ), $atts, MYCRED_SLUG . '_content_buyer_count' ) ); - if ($post_id === null ) { - $post_id = mycred_sell_content_post_id(); - } + if ( $post_id === NULL ) + $post_id = mycred_sell_content_post_id(); - $content = ''; + $content = ''; - if ($wrapper != '' ) { - $content .= '<' . $wrapper . ' class="mycred-sell-this-author-count">'; - } + if ( $wrapper != '' ) + $content .= '<' . $wrapper . ' class="mycred-sell-this-author-count">'; - $content .= mycred_get_content_buyers_count($post_id); + $content .= mycred_get_content_buyers_count( $post_id ); - if ($wrapper != '' ) { - $content .= ''; - } + if ( $wrapper != '' ) + $content .= ''; - return $content; + return $content; - } + } endif; /** * Shortcode: Sales History * Will show a given users payment history with links to the posts * they have purchased. - * - * @since 1.7 + * @since 1.7 * @version 1.1 */ -if (! function_exists('mycred_render_sell_history') ) : - function mycred_render_sell_history( $atts, $content = '' ) - { - - extract( - shortcode_atts( - array( - 'user_id' => 'current', - 'number' => 25, - 'nothing' => 'No purchases found', - 'ctype' => null, - 'order' => 'DESC' - ), $atts, MYCRED_SLUG . '_sales_history' - ) - ); - - // Not logged in - if (! is_user_logged_in() && $user_id == 'current' ) { - return $content; - } - - $user_id = mycred_get_user_id($user_id); - $date_format = get_option('date_format'); - $expiration = apply_filters('mycred_sell_exp_title', __('Hour(s)', 'mycred')); - $purchases = mycred_get_users_purchased_content($user_id, $number, $order, $ctype); - - $columns = apply_filters( - 'mycred_sales_history_columns', array( - 'col-date' => __('Date', 'mycred'), - 'col-title' => __('Title', 'mycred'), - 'col-amount' => __('Cost', 'mycred'), - 'col-expires' => __('Expires', 'mycred') - ), $atts - ); - - if (empty($purchases) && $nothing == '' ) { return; - } - - ob_start(); - - ?> +if ( ! function_exists( 'mycred_render_sell_history' ) ) : + function mycred_render_sell_history( $atts, $content = '' ) { + + extract( shortcode_atts( array( + 'user_id' => 'current', + 'number' => 25, + 'nothing' => 'No purchases found', + 'ctype' => NULL, + 'order' => 'DESC' + ), $atts, MYCRED_SLUG . '_sales_history' ) ); + + // Not logged in + if ( ! is_user_logged_in() && $user_id == 'current' ) + return $content; + + $user_id = mycred_get_user_id( $user_id ); + $date_format = get_option( 'date_format' ); + $expiration = apply_filters( 'mycred_sell_exp_title', __( 'Hour(s)', 'mycred' ) ); + $purchases = mycred_get_users_purchased_content( $user_id, $number, $order, $ctype ); + + $columns = apply_filters( 'mycred_sales_history_columns', array( + 'col-date' => __( 'Date', 'mycred' ), + 'col-title' => __( 'Title', 'mycred' ), + 'col-amount' => __( 'Cost', 'mycred' ), + 'col-expires' => __( 'Expires', 'mycred' ) + ), $atts ); + + if ( empty( $purchases ) && $nothing == '' ) return; + + ob_start(); + +?>
    - - - - + + + $column_label ) { - echo ''; - } + foreach ( $columns as $column_id => $column_label ) + echo ''; - ?> - - - + + +ctype); - - $hours = mycred_sell_content_get_expiration_length($entry->ref_id, $entry->ctype); - - $expires_in = apply_filters('mycred_sell_content_expires_in', $hours); - - echo ''; + $mycred = mycred( $entry->ctype ); + + $hours = mycred_sell_content_get_expiration_length( $entry->ref_id, $entry->ctype ); + + $expires_in = apply_filters( 'mycred_sell_content_expires_in', $hours ); + + echo ''; - foreach ( $columns as $column_id => $column_label ) { - + foreach ( $columns as $column_id => $column_label ) { + - if ($column_id == 'col-date' ) { - echo ''; + if ( $column_id == 'col-date' ) + echo ''; - } elseif ($column_id == 'col-title' ) { - echo ''; + elseif ( $column_id == 'col-title' ) + echo ''; - } elseif ($column_id == 'col-amount' ) { - echo ''; + elseif ( $column_id == 'col-amount' ) + echo ''; - } elseif ($column_id == 'col-expires' ) { + elseif ( $column_id == 'col-expires' ) { - $expires = __('Never', 'mycred'); + $expires = __( 'Never', 'mycred' ); - if ($expires_in > 0 ) { - $days = $hours * 60 * 60; - $date = time()- $entry->time; - $time_change = $days - $date; - $expires_in = mycred_seconds_to_time($time_change); + if ( $expires_in > 0 ) { + $days = $hours * 60 * 60; + $date = time()- $entry->time; + $time_change = $days - $date; + $expires_in = mycred_seconds_to_time( $time_change ); - if($expires < $time_change ) { - - $expires = sprintf(_x('Purchase expires in %s', 'e.g. 10 hours', 'mycred'), $expires_in. ' '); - - } - else{ - - $expires = 'Expired'; - - } + if( $expires < $time_change ){ + + $expires = sprintf( _x( 'Purchase expires in %s', 'e.g. 10 hours', 'mycred' ), $expires_in. ' ' ); + + } + else{ + + $expires = 'Expired'; + + } - } - - echo ''; + } + + echo ''; - } - else { + } + else { - do_action('mycred_sales_history_column', $column_id, $entry); - do_action('mycred_sales_history_column_' . $column_id, $entry); + do_action( 'mycred_sales_history_column', $column_id, $entry ); + do_action( 'mycred_sales_history_column_' . $column_id, $entry ); - } + } - } + } - echo ''; + echo ''; - } - } - else { + } + } + else { - echo ''; + echo ''; - } + } - ?> - -
    ' . $column_label . '' . $column_label . '
    '.date($date_format, $entry->time).''.date( $date_format, $entry->time ).'' . mycred_get_the_title($entry->ref_id) . '' . mycred_get_the_title( $entry->ref_id ) . '' . $mycred->format_creds(abs($entry->creds)) . '' . $mycred->format_creds( abs( $entry->creds ) ) . '' . $expires . '' . $expires . '
    ' . $nothing . '
    ' . $nothing . '
    +?> + +
    - null, - 'number' => 10, - 'size' => 42, - 'ctype' => null, - 'use_email' => 0, - 'default' => '', - 'alt' => '' - ), $atts, MYCRED_SLUG . '_content_buyer_avatars' - ) - ); - - if ($post_id === null ) { - $post_id = mycred_sell_content_post_id(); - } - - $buyers = mycred_get_posts_buyers($post_id, $number, $ctype); - - $content = ''; - if (! empty($buyers) ) { - foreach ( $buyers as $buyer_id ) { - - $identification = $buyer_id; - if (absint($use_email) === 1 ) { - $buyer_object = get_userdata($buyer_id); - if (! isset($buyer_object->ID) ) { continue; - } - $identification = $buyer_object->user_email; - } - - $avatar = get_avatar($identification, $size, $default, $alt); - $avatar = apply_filters('mycred_sell_content_buyer_avatar', $avatar, $buyer_id, $post_id); - if ($avatar !== false ) { - $content .= $avatar; - } - - } - } - - return '
    ' . $content . '
    '; - - } +if ( ! function_exists( 'mycred_render_sell_buyer_avatars' ) ) : + function mycred_render_sell_buyer_avatars( $atts, $content = '' ) { + + extract( shortcode_atts( array( + 'post_id' => NULL, + 'number' => 10, + 'size' => 42, + 'ctype' => NULL, + 'use_email' => 0, + 'default' => '', + 'alt' => '' + ), $atts, MYCRED_SLUG . '_content_buyer_avatars' ) ); + + if ( $post_id === NULL ) + $post_id = mycred_sell_content_post_id(); + + $buyers = mycred_get_posts_buyers( $post_id, $number, $ctype ); + + $content = ''; + if ( ! empty( $buyers ) ) { + foreach ( $buyers as $buyer_id ) { + + $identification = $buyer_id; + if ( absint( $use_email ) === 1 ) { + $buyer_object = get_userdata( $buyer_id ); + if ( ! isset( $buyer_object->ID ) ) continue; + $identification = $buyer_object->user_email; + } + + $avatar = get_avatar( $identification, $size, $default, $alt ); + $avatar = apply_filters( 'mycred_sell_content_buyer_avatar', $avatar, $buyer_id, $post_id ); + if ( $avatar !== false ) + $content .= $avatar; + + } + } + + return '
    ' . $content . '
    '; + + } endif; diff --git a/addons/sell-content/index.php b/addons/sell-content/index.php index 1580272..4e6c07c 100644 --- a/addons/sell-content/index.php +++ b/addons/sell-content/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/sell-content/js/buy-content.js b/addons/sell-content/js/buy-content.js index a27e655..2ffb97e 100644 --- a/addons/sell-content/js/buy-content.js +++ b/addons/sell-content/js/buy-content.js @@ -1,53 +1,46 @@ /** * myCRED Sell Content - * - * @since 1.1 + * @since 1.1 * @version 1.0 */ -jQuery( - function ($) { - var mycred_buy_content = function ( button, label ) { - wrapper = button.parents('div.mycred-content-forsale'); - $.ajax( - { - type : "POST", - data : { - action : 'mycred-buy-content', - postid : button.attr('data-id'), - token : myCREDsell.token - }, - dataType : "HTML", - url : myCREDsell.ajaxurl, - // Before we start - beforeSend : function () { - button.attr('value', myCREDsell.working); - button.attr('disabled', 'disabled'); - wrapper.slideUp(); - }, - // On Successful Communication - success : function ( data ) { - wrapper.empty(); - wrapper.append(data); - wrapper.slideDown(); - }, - // Error (sent to console) - error : function ( jqXHR, textStatus, errorThrown ) { - button.attr('value', 'Upps!'); - button.removeAttr('disabled'); - wrapper.slideDown(); - // Debug - uncomment to use - console.log(jqXHR); - console.log(textStatus); - console.log(errorThrown); - } - } - ); - }; - - $('.mycred-sell-this-button').click( - function () { - mycred_buy_content($(this), $(this).attr('value')); - } - ); - } -); \ No newline at end of file +jQuery(function($) { + var mycred_buy_content = function( button, label ) { + wrapper = button.parents( 'div.mycred-content-forsale' ); + $.ajax({ + type : "POST", + data : { + action : 'mycred-buy-content', + postid : button.attr( 'data-id' ), + token : myCREDsell.token + }, + dataType : "HTML", + url : myCREDsell.ajaxurl, + // Before we start + beforeSend : function() { + button.attr( 'value', myCREDsell.working ); + button.attr( 'disabled', 'disabled' ); + wrapper.slideUp(); + }, + // On Successful Communication + success : function( data ) { + wrapper.empty(); + wrapper.append( data ); + wrapper.slideDown(); + }, + // Error (sent to console) + error : function( jqXHR, textStatus, errorThrown ) { + button.attr( 'value', 'Upps!' ); + button.removeAttr( 'disabled' ); + wrapper.slideDown(); + // Debug - uncomment to use + console.log( jqXHR ); + console.log( textStatus ); + console.log( errorThrown ); + } + }); + }; + + $('.mycred-sell-this-button').click(function(){ + mycred_buy_content( $(this), $(this).attr( 'value' ) ); + }); +}); \ No newline at end of file diff --git a/addons/sell-content/js/index.php b/addons/sell-content/js/index.php index 1580272..4e6c07c 100644 --- a/addons/sell-content/js/index.php +++ b/addons/sell-content/js/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/addons/sell-content/myCRED-addon-sell-content.php b/addons/sell-content/myCRED-addon-sell-content.php index 1d75387..0e8bd36 100644 --- a/addons/sell-content/myCRED-addon-sell-content.php +++ b/addons/sell-content/myCRED-addon-sell-content.php @@ -4,1343 +4,1256 @@ * Addon URI: http://codex.mycred.me/chapter-iii/sell-content/ * Version: 2.0.1 */ -if (! defined('myCRED_VERSION') ) { exit; -} +if ( ! defined( 'myCRED_VERSION' ) ) exit; -define('myCRED_SELL', __FILE__); -define('myCRED_SELL_VERSION', '1.5'); -define('MYCRED_SELL_DIR', myCRED_ADDONS_DIR . 'sell-content/'); -define('MYCRED_SELL_ASSETS_DIR', MYCRED_SELL_DIR . 'assets/'); -define('MYCRED_SELL_INCLUDES_DIR', MYCRED_SELL_DIR . 'includes/'); +define( 'myCRED_SELL', __FILE__ ); +define( 'myCRED_SELL_VERSION', '1.5' ); +define( 'MYCRED_SELL_DIR', myCRED_ADDONS_DIR . 'sell-content/' ); +define( 'MYCRED_SELL_ASSETS_DIR', MYCRED_SELL_DIR . 'assets/' ); +define( 'MYCRED_SELL_INCLUDES_DIR', MYCRED_SELL_DIR . 'includes/' ); require_once MYCRED_SELL_INCLUDES_DIR . 'mycred-sell-functions.php'; require_once MYCRED_SELL_INCLUDES_DIR . 'mycred-sell-shortcodes.php'; /** * myCRED_Sell_Content_Module class - * - * @since 0.1 + * @since 0.1 * @version 2.0.1 */ -if (! class_exists('myCRED_Sell_Content_Module') ) : - class myCRED_Sell_Content_Module extends myCRED_Module - { - - public $current_user_id = 0; - public $priority = 10; - public $bbp_content = ''; - - /** - * Construct - */ - function __construct() - { - - parent::__construct( - 'myCRED_Sell_Content_Module', array( - 'module_name' => 'sell_content', - 'register' => false, - 'defaults' => mycred_get_addon_defaults('sell_content'), - 'add_to_core' => true - ) - ); - - if (! is_array($this->sell_content['type']) ) { - $this->sell_content['type'] = array( $this->sell_content['type'] ); - } +if ( ! class_exists( 'myCRED_Sell_Content_Module' ) ) : + class myCRED_Sell_Content_Module extends myCRED_Module { + + public $current_user_id = 0; + public $priority = 10; + public $bbp_content = ''; + + /** + * Construct + */ + function __construct() { + + parent::__construct( 'myCRED_Sell_Content_Module', array( + 'module_name' => 'sell_content', + 'register' => false, + 'defaults' => mycred_get_addon_defaults( 'sell_content' ), + 'add_to_core' => true + ) ); + + if ( ! is_array( $this->sell_content['type'] ) ) + $this->sell_content['type'] = array( $this->sell_content['type'] ); + + } + + /** + * Module Init + * @since 0.1 + * @version 1.2.2 + */ + public function module_init() { + + $this->current_user_id = get_current_user_id(); + $this->priority = apply_filters( 'mycred_sell_content_priority', 25, $this ); + + // Email add-on support + add_filter( 'mycred_get_email_events', array( $this, 'email_notice_instance' ), 10, 2 ); + add_filter( 'mycred_email_before_send', array( $this, 'email_notices' ), 40, 2 ); + + // Setup Content Override + add_action( 'template_redirect', array( $this, 'template_redirect' ), 99990 ); + + // Register shortcodes + add_shortcode( MYCRED_SLUG . '_sell_this', 'mycred_render_sell_this' ); + add_shortcode( MYCRED_SLUG . '_sell_this_ajax', 'mycred_render_sell_this_ajax' ); + add_shortcode( MYCRED_SLUG . '_sales_history', 'mycred_render_sell_history' ); + add_shortcode( MYCRED_SLUG . '_content_sale_count', 'mycred_render_sell_count' ); + add_shortcode( MYCRED_SLUG . '_content_buyer_count', 'mycred_render_sell_buyer_count' ); + add_shortcode( MYCRED_SLUG . '_content_buyer_avatars', 'mycred_render_sell_buyer_avatars' ); + + // Setup Script + add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) ); + add_action( 'mycred_register_assets', array( $this, 'register_assets' ) ); + add_action( 'mycred_front_enqueue_footer', array( $this, 'enqueue_footer' ) ); + add_action( 'bbp_template_redirect', array( $this, 'bbp_content' ), 10 ); + add_action( 'mycred_delete_log_entry', array( $this, 'sale_content_count_ajax' ), 10, 2 ); + add_action( 'wp_ajax_mycred_ajax_update_sell_count', array( $this, 'ajax_update_sell_count' ) ); + add_action( 'wp_ajax_nopriv_mycred_ajax_update_sell_count', array( $this, 'ajax_update_sell_count' ) ); + + } + + /** + * Module Admin Init + * @since 1.7 + * @version 1.0 + */ + public function module_admin_init() { + + // Setup the "Sell This" Metaboxes + $post_types = explode( ',', $this->sell_content['post_types'] ); + if ( ! empty( $post_types ) ) { + + foreach ( $post_types as $type ) { + add_action( "add_meta_boxes_{$type}", array( $this, 'add_metabox' ) ); + add_action( "save_post_{$type}", array( $this, 'save_metabox' ) ); + } + + } + + // User Override + add_action( 'mycred_user_edit_after_balances', array( $this, 'sell_content_user_screen' ), 50 ); + + add_action( 'personal_options_update', array( $this, 'save_manual_profit_share' ), 50 ); + add_action( 'edit_user_profile_update', array( $this, 'save_manual_profit_share' ), 50 ); + + } + + + /** + * Enqueue Admin Script + * @since 2.0.1 + * @version 1.0 + */ + public function admin_enqueue_scripts() + { + wp_enqueue_script( + 'mycred-admin-sell-content', + plugins_url( 'assets/js/admin.js', myCRED_SELL ), + array( 'jquery' ), + myCRED_SELL_VERSION, + true + ); + } + + /** + * Register Assets + * @since 1.7 + * @version 1.0 + */ + public function register_assets() { + + wp_register_script( + 'mycred-sell-this', + plugins_url( 'assets/js/buy-content.js', myCRED_SELL ), + array( 'jquery' ), + myCRED_SELL_VERSION, + true + ); + + } + + /** + * Load Script + * @since 1.7 + * @version 1.0.2 + */ + public function enqueue_footer() { + + global $mycred_sell_this; + + // Only enqueue our script if it's needed + if ( $mycred_sell_this === true ) { + + global $post; + + wp_localize_script( + 'mycred-sell-this', + 'myCREDBuyContent', + array( + 'ajaxurl' => esc_url( ( isset( $post->ID ) ) ? mycred_get_permalink( $post->ID ) : home_url( '/' ) ), + 'token' => wp_create_nonce( 'mycred-buy-this-content' ), + 'working' => esc_js( $this->sell_content['working'] ), + 'reload' => $this->sell_content['reload'], + 'sweeterror' => __( 'Error', 'mycred' ) + ) + ); + + wp_enqueue_script( 'mycred-sell-this' ); + + } + + } + + /** + * Fires when user deletes single log entry ref = buy_content + * @since 2.2 + * @version 1.0 + */ + public function sale_content_count_ajax( $row_id, $point_type ) + { + $log = new myCRED_Query_Log( "entry_id = $row_id" ); + + $logs = $log->results; - } + foreach( $logs as $log ) + { + $content_id = ''; - /** - * Module Init - * - * @since 0.1 - * @version 1.2.2 - */ - public function module_init() - { - - $this->current_user_id = get_current_user_id(); - $this->priority = apply_filters('mycred_sell_content_priority', 25, $this); - - // Email add-on support - add_filter('mycred_get_email_events', array( $this, 'email_notice_instance' ), 10, 2); - add_filter('mycred_email_before_send', array( $this, 'email_notices' ), 40, 2); - - // Setup Content Override - add_action('template_redirect', array( $this, 'template_redirect' ), 99990); - - // Register shortcodes - add_shortcode(MYCRED_SLUG . '_sell_this', 'mycred_render_sell_this'); - add_shortcode(MYCRED_SLUG . '_sell_this_ajax', 'mycred_render_sell_this_ajax'); - add_shortcode(MYCRED_SLUG . '_sales_history', 'mycred_render_sell_history'); - add_shortcode(MYCRED_SLUG . '_content_sale_count', 'mycred_render_sell_count'); - add_shortcode(MYCRED_SLUG . '_content_buyer_count', 'mycred_render_sell_buyer_count'); - add_shortcode(MYCRED_SLUG . '_content_buyer_avatars', 'mycred_render_sell_buyer_avatars'); - - // Setup Script - add_action('admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' )); - add_action('mycred_register_assets', array( $this, 'register_assets' )); - add_action('mycred_front_enqueue_footer', array( $this, 'enqueue_footer' )); - add_action('bbp_template_redirect', array( $this, 'bbp_content' ), 10); - add_action('mycred_delete_log_entry', array( $this, 'sale_content_count_ajax' ), 10, 2); - add_action('wp_ajax_mycred_ajax_update_sell_count', array( $this, 'ajax_update_sell_count' )); - add_action('wp_ajax_nopriv_mycred_ajax_update_sell_count', array( $this, 'ajax_update_sell_count' )); + if( $log->ref == 'buy_content' && $log->id == $row_id ) + { + + $content_id = (int) $log->ref_id; + + $sold_content = mycred_get_post_meta( $content_id, '_mycred_content_sales', true ); - } + if ( ! empty( $sold_content ) ) { - /** - * Module Admin Init - * - * @since 1.7 - * @version 1.0 - */ - public function module_admin_init() - { + $sold_content = (int) $sold_content; + $sold_content--; - // Setup the "Sell This" Metaboxes - $post_types = explode(',', $this->sell_content['post_types']); - if (! empty($post_types) ) { + mycred_update_post_meta( $content_id, '_mycred_content_sales', $sold_content ); + + } + + } - foreach ( $post_types as $type ) { - add_action("add_meta_boxes_{$type}", array( $this, 'add_metabox' )); - add_action("save_post_{$type}", array( $this, 'save_metabox' )); - } + } + } - } - // User Override - add_action('mycred_user_edit_after_balances', array( $this, 'sell_content_user_screen' ), 50); + /** + * Setup Content Filter + * We are using the template_redirect action to prevent this add-on having to run anywhere else but + * in the front-end of our website, since the the_content filter is used in soooo many places. + * As of 1.7.6, purchases are made via front-end submissions and not via admin-ajax.php + * @since 1.7 + * @version 1.0.1 + */ + public function template_redirect() { - add_action('personal_options_update', array( $this, 'save_manual_profit_share' ), 50); - add_action('edit_user_profile_update', array( $this, 'save_manual_profit_share' ), 50); + global $mycred_partial_content_sale; - } + $mycred_partial_content_sale = false; + // Handle purhchase requests + $this->maybe_buy_content(); - /** - * Enqueue Admin Script - * - * @since 2.0.1 - * @version 1.0 - */ - public function admin_enqueue_scripts() - { - wp_enqueue_script( - 'mycred-admin-sell-content', - plugins_url('assets/js/admin.js', myCRED_SELL), - array( 'jquery' ), - myCRED_SELL_VERSION, - true - ); - } + // Unless we successfully bought the content, filter it + add_filter( 'the_content', array( $this, 'the_content' ), $this->priority ); - /** - * Register Assets - * - * @since 1.7 - * @version 1.0 - */ - public function register_assets() - { - - wp_register_script( - 'mycred-sell-this', - plugins_url('assets/js/buy-content.js', myCRED_SELL), - array( 'jquery' ), - myCRED_SELL_VERSION, - true - ); + } - } + /** + * Maybe Buy Content + * Check if a purchase request has been made either via an AJAX submission. + * @since 1.7.6 + * @version 1.0 + */ + public function maybe_buy_content() { - /** - * Load Script - * - * @since 1.7 - * @version 1.0.2 - */ - public function enqueue_footer() - { + if ( is_user_logged_in() && ! mycred_is_admin() ) { - global $mycred_sell_this; + if ( isset( $_POST['action'] ) && $_POST['action'] == 'mycred-buy-content' && isset( $_POST['postid'] ) && isset( $_POST['token'] ) && wp_verify_nonce( $_POST['token'], 'mycred-buy-this-content' ) ) { - // Only enqueue our script if it's needed - if ($mycred_sell_this === true ) { + $post_id = absint( $_POST['postid'] ); + $point_type = sanitize_key( $_POST['ctype'] ); + $buying_cred = $this->sell_content['type']; + $point_types = mycred_get_types( true ); + global $mycred_types; - global $post; + if ( ! array_key_exists( $point_type, $mycred_types ) || mycred_force_singular_session( $this->current_user_id, 'mycred-last-content-purchase' ) || !in_array($point_type, $buying_cred) ) + wp_send_json( 'ERROR' ); - wp_localize_script( - 'mycred-sell-this', - 'myCREDBuyContent', - array( - 'ajaxurl' => esc_url(( isset($post->ID) ) ? mycred_get_permalink($post->ID) : home_url('/')), - 'token' => wp_create_nonce('mycred-buy-this-content'), - 'working' => esc_js($this->sell_content['working']), - 'reload' => $this->sell_content['reload'], - 'sweeterror' => __('Error', 'mycred') - ) - ); + // If the content is for sale and we have not paid for it + if ( mycred_post_is_for_sale( $post_id ) && ! mycred_user_paid_for_content( $this->current_user_id, $post_id ) ) { - wp_enqueue_script('mycred-sell-this'); + $content = ''; + $post = mycred_get_post( $post_id ); + $purchase = mycred_sell_content_new_purchase( $post, $this->current_user_id, $point_type ); - } + // Successfull purchase + if ( $purchase === true ) { - } + preg_match('/\[mycred_sell_this[^\]]*](.*)\[\/mycred_sell_this[^\]]*]/uis', $post->post_content , $match ); - /** - * Fires when user deletes single log entry ref = buy_content - * - * @since 2.2 - * @version 1.0 - */ - public function sale_content_count_ajax( $row_id, $point_type ) - { - $log = new myCRED_Query_Log("entry_id = $row_id"); + $content = $post->post_content; + if ( is_array( $match ) && array_key_exists( 1, $match ) ) + $content = $match[1]; - $logs = $log->results; + do_action( 'mycred_sell_before_content_render' ); - foreach( $logs as $log ) - { - $content_id = ''; + remove_filter( 'the_content', array( $this, 'the_content' ), $this->priority ); + $content = apply_filters( 'the_content', $content ); + $content = str_replace( ']]>', ']]>', $content ); + $content = do_shortcode( $content ); + add_filter( 'the_content', array( $this, 'the_content' ), $this->priority ); - if($log->ref == 'buy_content' && $log->id == $row_id ) { - - $content_id = (int) $log->ref_id; - - $sold_content = mycred_get_post_meta($content_id, '_mycred_content_sales', true); + } - if (! empty($sold_content) ) { + // Something went wrong + else { - $sold_content = (int) $sold_content; - $sold_content--; + $content = $purchase; - mycred_update_post_meta($content_id, '_mycred_content_sales', $sold_content); - - } - - } + } - } - } + // Let others play + $content = apply_filters( 'mycred_content_purchase_ajax', $content, $purchase ); + if ( $purchase !== true ) + wp_send_json_error( $content ); - /** - * Setup Content Filter - * We are using the template_redirect action to prevent this add-on having to run anywhere else but - * in the front-end of our website, since the the_content filter is used in soooo many places. - * As of 1.7.6, purchases are made via front-end submissions and not via admin-ajax.php - * - * @since 1.7 - * @version 1.0.1 - */ - public function template_redirect() - { + wp_send_json_success( $content ); - global $mycred_partial_content_sale; + } - $mycred_partial_content_sale = false; + wp_send_json( 'ERROR' ); - // Handle purhchase requests - $this->maybe_buy_content(); + } - // Unless we successfully bought the content, filter it - add_filter('the_content', array( $this, 'the_content' ), $this->priority); + } - } + } - /** - * Maybe Buy Content - * Check if a purchase request has been made either via an AJAX submission. - * - * @since 1.7.6 - * @version 1.0 - */ - public function maybe_buy_content() - { + /** + * AXAJ Updates sell count + * @since 2.0.1 + * @version 1.0 + */ + public function ajax_update_sell_count() + { + global $wpdb; - if (is_user_logged_in() && ! mycred_is_admin() ) { + $wpdb->delete( + $wpdb->postmeta, + array( + 'meta_key' => '_mycred_content_sales' + ) + ); - if (isset($_POST['action']) && $_POST['action'] == 'mycred-buy-content' && isset($_POST['postid']) && isset($_POST['token']) && wp_verify_nonce($_POST['token'], 'mycred-buy-this-content') ) { + $logs = new myCRED_Query_Log( 'ref=buy_content' ); - $post_id = absint($_POST['postid']); - $point_type = sanitize_key($_POST['ctype']); - $buying_cred = $this->sell_content['type']; - $point_types = mycred_get_types(true); - global $mycred_types; + $logs = $logs->results; - if (! array_key_exists($point_type, $mycred_types) || mycred_force_singular_session($this->current_user_id, 'mycred-last-content-purchase') || !in_array($point_type, $buying_cred) ) { - wp_send_json('ERROR'); - } + $ref_counts = array(); - // If the content is for sale and we have not paid for it - if (mycred_post_is_for_sale($post_id) && ! mycred_user_paid_for_content($this->current_user_id, $post_id) ) { + foreach( $logs as $log ) + $ref_counts[] = $log->ref_id; + + $sell_counts = array_count_values( $ref_counts ); - $content = ''; - $post = mycred_get_post($post_id); - $purchase = mycred_sell_content_new_purchase($post, $this->current_user_id, $point_type); + foreach( $sell_counts as $post_id => $sell_count ) + update_post_meta( $post_id, '_mycred_content_sales', $sell_count ); - // Successfull purchase - if ($purchase === true ) { + echo 'Sell Counts Updated'; + die; + } - preg_match('/\[mycred_sell_this[^\]]*](.*)\[\/mycred_sell_this[^\]]*]/uis', $post->post_content, $match); + /** + * The Content Overwrite + * Handles content sales by replacing the posts content with the appropriate template + * for those who have not paid. Admins and authors are excluded. + * @since 0.1 + * @since 2.3 Added function `mycred_sc_is_points_enable` If points are disabled just return the content + * @version 1.2.3 + */ + public function the_content( $content ) { - $content = $post->post_content; - if (is_array($match) && array_key_exists(1, $match) ) { - $content = $match[1]; - } + if( !mycred_sc_is_points_enable() ) + return $content; - do_action('mycred_sell_before_content_render'); + global $mycred_partial_content_sale, $mycred_sell_this; - remove_filter('the_content', array( $this, 'the_content' ), $this->priority); - $content = apply_filters('the_content', $content); - $content = str_replace(']]>', ']]>', $content); - $content = do_shortcode($content); - add_filter('the_content', array( $this, 'the_content' ), $this->priority); + $post_id = mycred_sell_content_post_id(); + $post = mycred_get_post( $post_id ); - } + // If content is for sale + if ( mycred_post_is_for_sale( $post_id ) ) { - // Something went wrong - else { + $mycred_sell_this = true; - $content = $purchase; + // Parse shortcodes now just in case it has not been done already + $_content = do_shortcode( $content ); - } + // Partial Content Sale - We have already done the work in the shortcode + if ( $mycred_partial_content_sale === true ) + return $_content; - // Let others play - $content = apply_filters('mycred_content_purchase_ajax', $content, $purchase); + // Logged in users + if ( is_user_logged_in() ) { - if ($purchase !== true ) { - wp_send_json_error($content); - } + // Authors and admins do not pay + if ( ! mycred_is_admin() && $post->post_author != $this->current_user_id ) { - wp_send_json_success($content); + // In case we have not paid + if ( ! mycred_user_paid_for_content( $this->current_user_id, $post_id ) ) { - } + // Get Payment Options + $payment_options = mycred_sell_content_payment_buttons( $this->current_user_id, $post_id ); - wp_send_json('ERROR'); + // User can buy + if ( $payment_options !== false ) { - } + $content = $this->sell_content['templates']['members']; + $content = str_replace( '%buy_button%', $payment_options, $content ); + $content = mycred_sell_content_template( $content, $post, 'mycred-sell-entire-content', 'mycred-sell-unpaid' ); - } + } - } + // Can not afford to buy + else { - /** - * AXAJ Updates sell count - * - * @since 2.0.1 - * @version 1.0 - */ - public function ajax_update_sell_count() - { - global $wpdb; - - $wpdb->delete( - $wpdb->postmeta, - array( - 'meta_key' => '_mycred_content_sales' - ) - ); - - $logs = new myCRED_Query_Log('ref=buy_content'); - - $logs = $logs->results; - - $ref_counts = array(); - - foreach( $logs as $log ) { - $ref_counts[] = $log->ref_id; - } - - $sell_counts = array_count_values($ref_counts); - - foreach( $sell_counts as $post_id => $sell_count ) { - update_post_meta($post_id, '_mycred_content_sales', $sell_count); - } - - echo 'Sell Counts Updated'; - die; - } + $content = $this->sell_content['templates']['cantafford']; + $content = mycred_sell_content_template( $content, $post, 'mycred-sell-entire-content', 'mycred-sell-insufficient' ); - /** - * The Content Overwrite - * Handles content sales by replacing the posts content with the appropriate template - * for those who have not paid. Admins and authors are excluded. - * - * @since 0.1 - * @since 2.3 Added function `mycred_sc_is_points_enable` If points are disabled just return the content - * @version 1.2.3 - */ - public function the_content( $content ) - { + } - if(!mycred_sc_is_points_enable() ) { - return $content; - } + } - global $mycred_partial_content_sale, $mycred_sell_this; + } - $post_id = mycred_sell_content_post_id(); - $post = mycred_get_post($post_id); + } - // If content is for sale - if (mycred_post_is_for_sale($post_id) ) { + // Visitors + else { - $mycred_sell_this = true; + $content = $this->sell_content['templates']['visitors']; + $content = mycred_sell_content_template( $content, $post, 'mycred-sell-entire-content', 'mycred-sell-visitor' ); - // Parse shortcodes now just in case it has not been done already - $_content = do_shortcode($content); + } - // Partial Content Sale - We have already done the work in the shortcode - if ($mycred_partial_content_sale === true ) { - return $_content; - } + } - // Logged in users - if (is_user_logged_in() ) { + return $content; - // Authors and admins do not pay - if (! mycred_is_admin() && $post->post_author != $this->current_user_id ) { + } - // In case we have not paid - if (! mycred_user_paid_for_content($this->current_user_id, $post_id) ) { - // Get Payment Options - $payment_options = mycred_sell_content_payment_buttons($this->current_user_id, $post_id); - // User can buy - if ($payment_options !== false ) { + public function bbp_content() { - $content = $this->sell_content['templates']['members']; - $content = str_replace('%buy_button%', $payment_options, $content); - $content = mycred_sell_content_template($content, $post, 'mycred-sell-entire-content', 'mycred-sell-unpaid'); + global $mycred_partial_content_sale, $mycred_sell_this; - } + $post_id = mycred_sell_content_post_id(); - // Can not afford to buy - else { - $content = $this->sell_content['templates']['cantafford']; - $content = mycred_sell_content_template($content, $post, 'mycred-sell-entire-content', 'mycred-sell-insufficient'); + $post = mycred_get_post( $post_id ); - } + $content = ''; - } - } - } + // If content is for sale + if ( mycred_post_is_for_sale( $post_id ) && ( bbp_is_single_forum() || bbp_is_single_topic() || bbp_is_single_reply() ) ) { - // Visitors - else { + $mycred_sell_this = true; - $content = $this->sell_content['templates']['visitors']; - $content = mycred_sell_content_template($content, $post, 'mycred-sell-entire-content', 'mycred-sell-visitor'); - } + // Partial Content Sale - We have already done the work in the shortcode + if ( $mycred_partial_content_sale === true ) return; - } + // Logged in users + if ( is_user_logged_in() ) { - return $content; + // Authors and admins do not pay + if ( ! mycred_is_admin() && $post->post_author != $this->current_user_id ) { - } + // In case we have not paid + if ( ! mycred_user_paid_for_content( $this->current_user_id, $post_id ) ) { + // Get Payment Options + $payment_options = mycred_sell_content_payment_buttons( $this->current_user_id, $post_id ); + // User can buy + if ( $payment_options !== false ) { - public function bbp_content() - { + $content = $this->sell_content['templates']['members']; + + $content = str_replace( '%buy_button%', $payment_options, $content ); + $content = mycred_sell_content_template( $content, $post, 'mycred-sell-entire-content', 'mycred-sell-unpaid' ); + + $this->mycred_bbp_sell_forum_actions(); - global $mycred_partial_content_sale, $mycred_sell_this; + } - $post_id = mycred_sell_content_post_id(); + // Can not afford to buy + else { + $content = $this->sell_content['templates']['cantafford']; + $content = mycred_sell_content_template( $content, $post, 'mycred-sell-entire-content', 'mycred-sell-insufficient' ); + $this->mycred_bbp_sell_forum_actions(); - $post = mycred_get_post($post_id); + } - $content = ''; + } + } + } - // If content is for sale - if (mycred_post_is_for_sale($post_id) && ( bbp_is_single_forum() || bbp_is_single_topic() || bbp_is_single_reply() ) ) { + // Visitors + else { - $mycred_sell_this = true; + $content = $this->sell_content['templates']['visitors']; + $content = mycred_sell_content_template( $content, $post, 'mycred-sell-entire-content', 'mycred-sell-visitor' ); - // Partial Content Sale - We have already done the work in the shortcode - if ($mycred_partial_content_sale === true ) { return; - } + $this->mycred_bbp_sell_forum_actions(); - // Logged in users - if (is_user_logged_in() ) { + } - // Authors and admins do not pay - if (! mycred_is_admin() && $post->post_author != $this->current_user_id ) { + } - // In case we have not paid - if (! mycred_user_paid_for_content($this->current_user_id, $post_id) ) { + $this->bbp_content = $content; - // Get Payment Options - $payment_options = mycred_sell_content_payment_buttons($this->current_user_id, $post_id); + } - // User can buy - if ($payment_options !== false ) { - $content = $this->sell_content['templates']['members']; - - $content = str_replace('%buy_button%', $payment_options, $content); - $content = mycred_sell_content_template($content, $post, 'mycred-sell-entire-content', 'mycred-sell-unpaid'); - - $this->mycred_bbp_sell_forum_actions(); - } - // Can not afford to buy - else { + public function mycred_bbp_sell_forum_actions() { - $content = $this->sell_content['templates']['cantafford']; - $content = mycred_sell_content_template($content, $post, 'mycred-sell-entire-content', 'mycred-sell-insufficient'); - $this->mycred_bbp_sell_forum_actions(); + add_action( 'bbp_template_before_single_forum', array( $this, 'bbp_template_before_single' ) ); + add_action( 'bbp_template_before_single_topic', array( $this, 'bbp_template_before_single' ) ); + add_filter( 'bbp_no_breadcrumb', array( $this, 'bbp_remove_breadcrumb' ), 10 ); + add_filter( 'bbp_is_single_topic', array( $this, 'bbp_is_topic' ), 10 ); + add_filter( 'bbp_get_forum_subscribe_link', array( $this, 'bbp_remove_subscribe_link' ), 10 , 3 ); + add_filter( 'bbp_get_topic_subscribe_link', array( $this, 'bbp_remove_subscribe_link' ), 10 , 3 ); + add_filter( 'bbp_get_topic_favorite_link', array( $this, 'bbp_remove_subscribe_link' ), 10 , 3 ); + add_filter( 'bbp_get_template_part', array( $this, 'bbp_remove_templates' ), 10 , 3 ); + add_filter( 'bbp_get_single_forum_description', array( $this, 'bbp_get_single_description' ), 10 , 3 ); + add_filter( 'bbp_get_single_topic_description', array( $this, 'bbp_get_single_description' ), 10 , 3 ); - } + } - } + public function bbp_template_before_single() { + + echo $this->bbp_content; - } + } - } + public function bbp_remove_breadcrumb( $is_front ) { + return true; + } - // Visitors - else { + public function bbp_is_topic( $post_id = 0 ) { - $content = $this->sell_content['templates']['visitors']; - $content = mycred_sell_content_template($content, $post, 'mycred-sell-entire-content', 'mycred-sell-visitor'); + // Assume false + $retval = false; + // Supplied ID is a topic + if ( ! empty( $post_id ) && ( bbp_get_topic_post_type() === get_post_type( $post_id ) ) ) { + $retval = true; + } - $this->mycred_bbp_sell_forum_actions(); + // Filter & return + return (bool) apply_filters( 'bbp_is_topic', $retval, $post_id ); + } - } + public function bbp_remove_subscribe_link( $retval, $r, $args ) { + return ''; + } - } + public function bbp_remove_templates( $templates, $slug, $name ) { - $this->bbp_content = $content; + if ( $slug == 'content' ) return $templates; - } + return array(''); + } + public function bbp_get_single_description( $retstr, $r, $args ) { + return ''; + } + /** + * User Level Override + * @since 1.5 + * @version 1.3.1 + */ + public function sell_content_user_screen( $user ) { + // Only visible to admins + if ( ! mycred_is_admin() ) return; - public function mycred_bbp_sell_forum_actions() - { + $mycred_types = mycred_get_types( true ); + $available_options = array(); - add_action('bbp_template_before_single_forum', array( $this, 'bbp_template_before_single' )); - add_action('bbp_template_before_single_topic', array( $this, 'bbp_template_before_single' )); - add_filter('bbp_no_breadcrumb', array( $this, 'bbp_remove_breadcrumb' ), 10); - add_filter('bbp_is_single_topic', array( $this, 'bbp_is_topic' ), 10); - add_filter('bbp_get_forum_subscribe_link', array( $this, 'bbp_remove_subscribe_link' ), 10, 3); - add_filter('bbp_get_topic_subscribe_link', array( $this, 'bbp_remove_subscribe_link' ), 10, 3); - add_filter('bbp_get_topic_favorite_link', array( $this, 'bbp_remove_subscribe_link' ), 10, 3); - add_filter('bbp_get_template_part', array( $this, 'bbp_remove_templates' ), 10, 3); - add_filter('bbp_get_single_forum_description', array( $this, 'bbp_get_single_description' ), 10, 3); - add_filter('bbp_get_single_topic_description', array( $this, 'bbp_get_single_description' ), 10, 3); + foreach ( $mycred_types as $point_type_key => $label ) { - } + $setup = array( 'name' => $label, 'enabled' => false, 'default' => 0, 'excluded' => true, 'override' => false, 'custom' => 0 ); - public function bbp_template_before_single() - { - - echo $this->bbp_content; + if ( ! empty( $this->sell_content['type'] ) && in_array( $point_type_key, $this->sell_content['type'] ) ) { - } + $setup['enabled'] = true; + $mycred = mycred( $point_type_key ); - public function bbp_remove_breadcrumb( $is_front ) - { - return true; - } + if ( ! $mycred->exclude_user( $user->ID ) ) { - public function bbp_is_topic( $post_id = 0 ) - { + $setup['excluded'] = false; - // Assume false - $retval = false; + $settings = mycred_get_option( 'mycred_sell_this_' . $point_type_key ); - // Supplied ID is a topic - if (! empty($post_id) && ( bbp_get_topic_post_type() === get_post_type($post_id) ) ) { - $retval = true; - } + $setup['default'] = $settings['profit_share']; - // Filter & return - return (bool) apply_filters('bbp_is_topic', $retval, $post_id); - } + $users_share = mycred_get_user_meta( $user->ID, 'mycred_sell_content_share_' . $point_type_key, '', true ); + if ( strlen( $users_share ) > 0 ) { - public function bbp_remove_subscribe_link( $retval, $r, $args ) - { - return ''; - } + $setup['override'] = true; + $setup['custom'] = $users_share; - public function bbp_remove_templates( $templates, $slug, $name ) - { + } - if ($slug == 'content' ) { return $templates; - } + } - return array(''); - } + } - public function bbp_get_single_description( $retstr, $r, $args ) - { - return ''; - } + $available_options[ $point_type_key ] = $setup; - /** - * User Level Override - * - * @since 1.5 - * @version 1.3.1 - */ - public function sell_content_user_screen( $user ) - { + } - // Only visible to admins - if (! mycred_is_admin() ) { return; - } + if ( empty( $available_options ) ) return; - $mycred_types = mycred_get_types(true); - $available_options = array(); +?> +

    + + + + + +
    +
    + + $label ) { + foreach ( $available_options as $point_type => $data ) { - $setup = array( 'name' => $label, 'enabled' => false, 'default' => 0, 'excluded' => true, 'override' => false, 'custom' => 0 ); + // This point type is not for sale + if ( ! $data['enabled'] ) { - if (! empty($this->sell_content['type']) && in_array($point_type_key, $this->sell_content['type']) ) { +?> +
    +
    +
    +
    +
    +
    +
    +exclude_user($user->ID) ) { + // This user is excluded from this point type + elseif ( $data['excluded'] ) { - $setup['excluded'] = false; +?> +
    +
    +
    +
    +
    +
    +
    +ID, 'mycred_sell_content_share_' . $point_type_key, '', true); - if (strlen($users_share) > 0 ) { +?> +
    +
    +
    +
    %
    +
    +
    +
    + +
    +
    +
    + -

    - - - - - -
    -
    - - $data ) { - - // This point type is not for sale - if (! $data['enabled'] ) { - - ?> -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    %
    -
    -
    -
    - -
    -
    -
    - $share ) { - } + $share = sanitize_text_field( $share ); - /** - * Save Override - * - * @since 1.5 - * @version 1.2 - */ - function save_manual_profit_share( $user_id ) - { + mycred_delete_user_meta( $user_id, 'mycred_sell_content_share_' . $point_type ); + if ( $share != '' && is_numeric( $share ) ) + mycred_update_user_meta( $user_id, 'mycred_sell_content_share_' . $point_type, '', $share ); - // Only visible to admins - if (! mycred_is_admin() ) { return; - } + } - if (isset($_POST['mycred_sell_this']) && ! empty($_POST['mycred_sell_this']) ) { + } - foreach ( $_POST['mycred_sell_this'] as $point_type => $share ) { + } - $share = sanitize_text_field($share); + /** + * Enabled / Disabled Select Options + * @since 1.7 + * @version 1.0 + */ + protected function enabled_options( $selected = '' ) { - mycred_delete_user_meta($user_id, 'mycred_sell_content_share_' . $point_type); - if ($share != '' && is_numeric($share) ) { - mycred_update_user_meta($user_id, 'mycred_sell_content_share_' . $point_type, '', $share); - } + $options = array( + 'disabled' => __( 'Disabled', 'mycred' ), + 'enabled' => __( 'Enabled', 'mycred' ) + ); - } + $output = ''; + foreach ( $options as $value => $label ) { + $output .= '
    + \ No newline at end of file diff --git a/freemius/templates/sticky-admin-notice-js.php b/freemius/templates/sticky-admin-notice-js.php index 83a03bc..d6d7ebe 100644 --- a/freemius/templates/sticky-admin-notice-js.php +++ b/freemius/templates/sticky-admin-notice-js.php @@ -1,41 +1,41 @@ diff --git a/freemius/templates/tabs-capture-js.php b/freemius/templates/tabs-capture-js.php index b50dcf1..236be3b 100644 --- a/freemius/templates/tabs-capture-js.php +++ b/freemius/templates/tabs-capture-js.php @@ -1,63 +1,63 @@ get_slug(); + /** + * @package Freemius + * @copyright Copyright (c) 2015, Freemius, Inc. + * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License Version 3 + * @since 1.2.2.7 + */ + + if ( ! defined( 'ABSPATH' ) ) { + exit; + } + + /** + * @var array $VARS + * @var Freemius $fs + */ + $fs = freemius( $VARS['id'] ); + $slug = $fs->get_slug(); ?> + var + settingHtml = $wrap.html(), + tabsPosition = settingHtml.indexOf('nav-tab-wrapper'), + aboveTabsHtml = ''; + + if (-1 < tabsPosition) { + // Find the tabs HTML beginning exact position. + while ('<' !== settingHtml[tabsPosition] && 0 < tabsPosition) { + tabsPosition--; + } + + if (-1 < tabsPosition) { + aboveTabsHtml = settingHtml.substr(0, tabsPosition); + + var tabsHtml = $('.wrap .nav-tab-wrapper').clone().wrap('
    ').parent().html(); + + $.ajax({ + url : ajaxurl + '?' + $.param({ + action : 'get_ajax_action( 'store_tabs' ) ?>', + security : 'get_ajax_security( 'store_tabs' ) ?>', + module_id: 'get_id() ?>' + }), + method : 'POST', + data : aboveTabsHtml + "\n" + tabsHtml + '
    ', + dataType : 'html', + // Avoid escaping the HTML. + processData: false + }); + } + } + }); + })(jQuery); + \ No newline at end of file diff --git a/freemius/templates/tabs.php b/freemius/templates/tabs.php index 0777194..2a20b70 100644 --- a/freemius/templates/tabs.php +++ b/freemius/templates/tabs.php @@ -1,20 +1,20 @@ get_slug(); @@ -23,38 +23,38 @@ $show_settings_with_tabs = $fs->show_settings_with_tabs(); $tabs = array(); -foreach ( $menu_items as $priority => $items ) { - foreach ( $items as $item ) { - if (! $item['show_submenu'] ) { - $submenu_name = ('wp-support-forum' === $item['menu_slug']) ? - 'support' : - $item['menu_slug']; - - if ('pricing' === $submenu_name && ! $fs->is_pricing_page_visible() ) { - continue; - } + foreach ( $menu_items as $priority => $items ) { + foreach ( $items as $item ) { + if ( ! $item['show_submenu'] ) { + $submenu_name = ('wp-support-forum' === $item['menu_slug']) ? + 'support' : + $item['menu_slug']; + + if ( 'pricing' === $submenu_name && ! $fs->is_pricing_page_visible() ) { + continue; + } - if (! $show_settings_with_tabs || ! $fs->is_submenu_item_visible($submenu_name, true) ) { - continue; + if ( ! $show_settings_with_tabs || ! $fs->is_submenu_item_visible( $submenu_name, true ) ) { + continue; + } } - } - $url = $fs->_get_admin_page_url($item['menu_slug']); - $title = $item['menu_title']; + $url = $fs->_get_admin_page_url( $item['menu_slug'] ); + $title = $item['menu_title']; - $tab = array( - 'label' => $title, - 'href' => $url, - 'slug' => $item['menu_slug'], - ); + $tab = array( + 'label' => $title, + 'href' => $url, + 'slug' => $item['menu_slug'], + ); - if ('pricing' === $item['menu_slug'] && $fs->is_in_trial_promotion() ) { - $tab['href'] .= '&trial=true'; - } + if ( 'pricing' === $item['menu_slug'] && $fs->is_in_trial_promotion() ) { + $tab['href'] .= '&trial=true'; + } - $tabs[] = $tab; + $tabs[] = $tab; + } } -} ?> + \ No newline at end of file diff --git a/includes/classes/class.mycred-license.php b/includes/classes/class.mycred-license.php index 0a07ea5..3b8b7d8 100644 --- a/includes/classes/class.mycred-license.php +++ b/includes/classes/class.mycred-license.php @@ -1,268 +1,247 @@ version = $data['version']; - $this->slug = $data['slug']; - $this->base = $data['base']; - $this->filename = plugin_basename($this->base); - $this->license_key_name = 'mycred_membership_key'; - $this->transient_key = 'mcl_' . md5($this->slug); - $this->api_endpoint = 'https://license.mycred.me/wp-json/license/get-plugins'; + $this->version = $data['version']; + $this->slug = $data['slug']; + $this->base = $data['base']; + $this->filename = plugin_basename( $this->base ); + $this->license_key_name = 'mycred_membership_key'; + $this->transient_key = 'mcl_' . md5( $this->slug ); + $this->api_endpoint = 'https://license.mycred.me/wp-json/license/get-plugins'; - $this->init(); + $this->init(); - } + } - public function get_plugin_detail( $force = false ) - { + public function get_plugin_detail( $force = false ) { - $plugin_info = get_site_transient($this->transient_key); + $plugin_info = get_site_transient( $this->transient_key ); - if (false === $plugin_info || $force ) { - - $plugins_info_remote = $this->get_api_data(); + if ( false === $plugin_info || $force ) { + + $plugins_info_remote = $this->get_api_data(); - foreach ( $plugins_info_remote as $plugin ) { - - if (! empty($plugin->package) ) { - - $plugin->package = add_query_arg( - array( - 'license_key' => $this->get_license_key(), - 'site' => site_url(), - 'api-key' => md5(get_bloginfo('url')), - 'slug' => $plugin->slug - ), - $plugin->package - ); + foreach ( $plugins_info_remote as $plugin ) { + + if ( ! empty( $plugin->package ) ) { + + $plugin->package = add_query_arg( + array( + 'license_key' => $this->get_license_key(), + 'site' => site_url(), + 'api-key' => md5( get_bloginfo( 'url' ) ), + 'slug' => $plugin->slug + ), + $plugin->package + ); - } + } - $transient_key = 'mcl_' . md5($plugin->slug); - set_site_transient($transient_key, $plugin, 5 * HOUR_IN_SECONDS); + $transient_key = 'mcl_' . md5( $plugin->slug ); + set_site_transient( $transient_key, $plugin, 5 * HOUR_IN_SECONDS ); - if ($plugin->slug == $this->slug ) { - $plugin_info = $plugin; - } - - } + if ( $plugin->slug == $this->slug ) + $plugin_info = $plugin; + + } - } + } - return $plugin_info; + return $plugin_info; - } + } - public function init() - { + public function init() { - add_filter('mycred_license_addons', array( $this, 'register_addon_for_license' )); - add_filter('pre_set_site_transient_update_plugins', array( $this, 'check_update' ), 80); - add_filter('plugins_api', array( $this, 'plugin_api_call' ), 80, 3); - add_filter('plugin_row_meta', array( $this, 'plugin_view_info' ), 80, 3); + add_filter( 'mycred_license_addons', array( $this, 'register_addon_for_license' ) ); + add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'check_update' ), 80 ); + add_filter( 'plugins_api', array( $this, 'plugin_api_call' ), 80, 3 ); + add_filter( 'plugin_row_meta', array( $this, 'plugin_view_info' ), 80, 3 ); - } + } - public function register_addon_for_license( $addons ) - { - - array_push($addons, $this->slug); + public function register_addon_for_license( $addons ) { + + array_push( $addons, $this->slug ); - return $addons; + return $addons; - } + } - public function check_update( $data ) - { + public function check_update( $data ) { - $plugin_info = $this->get_plugin_detail(); + $plugin_info = $this->get_plugin_detail(); - if (! empty($plugin_info) && ! empty($plugin_info->new_version) ) { - - if (version_compare($this->version, $plugin_info->new_version, '<') ) { - $data->response[ $this->filename ] = $plugin_info; - } else { - $data->no_update[ $this->filename ] = $plugin_info; - } + if ( ! empty( $plugin_info ) && ! empty( $plugin_info->new_version ) ) { + + if ( version_compare( $this->version, $plugin_info->new_version, '<' ) ) { + $data->response[ $this->filename ] = $plugin_info; + } else { + $data->no_update[ $this->filename ] = $plugin_info; + } - } + } - $data->last_checked = time(); - $data->checked[ $this->filename ] = $this->version; + $data->last_checked = time(); + $data->checked[ $this->filename ] = $this->version; - return $data; + return $data; - } + } - public function plugin_api_call( $result, $action, $args ) - { + public function plugin_api_call( $result, $action, $args ) { - if (empty($args->slug) || $args->slug != $this->slug ) { - return $result; - } + if ( empty( $args->slug ) || $args->slug != $this->slug ) + return $result; - $data = $this->get_plugin_detail(); + $data = $this->get_plugin_detail(); - if (isset($data->banners) ) { - $data->banners = (array) $data->banners; - } + if ( isset( $data->banners ) ) + $data->banners = (array) $data->banners; - if (isset($data->sections) ) { - - if (! empty($data->sections->description) ) { - $data->sections->description = html_entity_decode($data->sections->description); - } - - if (! empty($data->sections->change_log) ) { - $data->sections->change_log = html_entity_decode($data->sections->change_log); - } - - if (! empty($data->sections->installation) ) { - $data->sections->installation = html_entity_decode($data->sections->installation); - } + if ( isset( $data->sections ) ) { + + if ( ! empty( $data->sections->description ) ) + $data->sections->description = html_entity_decode( $data->sections->description ); + + if ( ! empty( $data->sections->change_log ) ) + $data->sections->change_log = html_entity_decode( $data->sections->change_log ); + + if ( ! empty( $data->sections->installation ) ) + $data->sections->installation = html_entity_decode( $data->sections->installation ); - $data->sections = (array) $data->sections; + $data->sections = (array) $data->sections; - } + } - return $data; + return $data; - } + } - public function plugin_view_info( $plugin_meta, $file, $plugin_data ) - { + public function plugin_view_info( $plugin_meta, $file, $plugin_data ) { - if ($file != plugin_basename($this->base) ) { return $plugin_meta; - } + if ( $file != plugin_basename( $this->base ) ) return $plugin_meta; - $plugin_info = $this->get_plugin_detail(); + $plugin_info = $this->get_plugin_detail(); - if (empty($plugin_info->package) && ( empty($plugin_info->expiry) || empty($plugin_info->expiry->expiration_date) ) ) { - - $message = 'License not found.'; + if ( empty( $plugin_info->package ) && ( empty( $plugin_info->expiry ) || empty( $plugin_info->expiry->expiration_date ) ) ) { + + $message = 'License not found.'; - if (! empty($plugin_info->message) ) { - $message = $plugin_info->message; - } - - $plugin_meta[] = '' . $message . ''; + if ( ! empty( $plugin_info->message ) ) { + $message = $plugin_info->message; + } + + $plugin_meta[] = '' . $message . ''; - } - else { + } + else { - $plugin_meta[] = 'Expires in ' . $this->calculate_license_expiry($plugin_info->expiry->expiration_date) . ''; + $plugin_meta[] = 'Expires in ' . $this->calculate_license_expiry( $plugin_info->expiry->expiration_date ) . ''; - } + } - return $plugin_meta; + return $plugin_meta; - } + } - public function get_mycred_addons() - { + public function get_mycred_addons() { - return apply_filters('mycred_license_addons', array()); + return apply_filters( 'mycred_license_addons', array() ); - } + } - public function get_license_key() - { + public function get_license_key() { - return get_option($this->license_key_name); + return get_option( $this->license_key_name ); - } + } - public function get_api_data() - { + public function get_api_data() { - $cache_key = 'mycred_license_remote_data'; - $plugins_data = wp_cache_get($cache_key); - - if (false === $plugins_data ) { + $cache_key = 'mycred_license_remote_data'; + $plugins_data = wp_cache_get( $cache_key ); + + if ( false === $plugins_data ) { - $plugins_data = new stdClass(); - $license_key = $this->get_license_key(); - $addons = $this->get_mycred_addons(); - $request_args = array( - 'body' => array( - 'license_key' => $license_key, - 'site' => site_url(), - 'api-key' => md5(get_bloginfo('url')), - 'addons' => $addons - ), - 'timeout' => 12 - ); + $plugins_data = new stdClass(); + $license_key = $this->get_license_key(); + $addons = $this->get_mycred_addons(); + $request_args = array( + 'body' => array( + 'license_key' => $license_key, + 'site' => site_url(), + 'api-key' => md5( get_bloginfo( 'url' ) ), + 'addons' => $addons + ), + 'timeout' => 12 + ); - // Start checking for an update - $response = wp_remote_post($this->api_endpoint, $request_args); + // Start checking for an update + $response = wp_remote_post( $this->api_endpoint, $request_args ); - if (! is_wp_error($response) ) { + if ( ! is_wp_error( $response ) ) { - $response_data = json_decode($response['body']); + $response_data = json_decode( $response['body'] ); - if (! empty($response_data->status) && $response_data->status == 'success' ) { - - $plugins_data = $response_data->data; + if ( ! empty( $response_data->status ) && $response_data->status == 'success' ) { + + $plugins_data = $response_data->data; - } + } - } - - } + } + + } - wp_cache_set($cache_key, $plugins_data); - return $plugins_data; - - } + wp_cache_set( $cache_key, $plugins_data ); + return $plugins_data; + + } - public function calculate_license_expiry( $expire_date ) - { + public function calculate_license_expiry( $expire_date ) { - $interval = date_create('now')->diff(date_create($expire_date)); + $interval = date_create('now')->diff( date_create( $expire_date ) ); - $label_y = $interval->y > 1 ? "{$interval->y} years " : ( $interval->y == 1 ? "{$interval->y} year " : '' ); - $label_m = $interval->m > 1 ? "{$interval->m} months " : ( $interval->m == 1 ? "{$interval->m} month " : '' ); - $label_d = $interval->d > 1 ? "{$interval->d} days " : ( $interval->d == 1 ? "{$interval->d} day " : '' ); + $label_y = $interval->y > 1 ? "{$interval->y} years " : ( $interval->y == 1 ? "{$interval->y} year " : '' ); + $label_m = $interval->m > 1 ? "{$interval->m} months " : ( $interval->m == 1 ? "{$interval->m} month " : '' ); + $label_d = $interval->d > 1 ? "{$interval->d} days " : ( $interval->d == 1 ? "{$interval->d} day " : '' ); - return "{$label_y}{$label_m}{$label_d}"; + return "{$label_y}{$label_m}{$label_d}"; - } - + } + - } -endif; + } +endif; \ No newline at end of file diff --git a/includes/classes/class.query-export.php b/includes/classes/class.query-export.php index acc7db1..3965a28 100644 --- a/includes/classes/class.query-export.php +++ b/includes/classes/class.query-export.php @@ -1,662 +1,589 @@ args = apply_filters( - 'mycred_export_args', shortcode_atts( - array( - 'raw' => false, - 'number' => -1, - 'order' => 'time', - 'orderby' => 'DESC', - 'date_format' => get_option('date_format') - ), $args - ), $args - ); + public $args = array(); + public $headers = array(); + public $raw = false; + public $file_name = ''; + public $references = array(); + public $orderby = ''; + public $limit = ''; + public $user_id = false; - $this->db = $mycred_log_table; - $this->raw = $this->args['raw']; - $this->references = mycred_get_all_references(); + protected $data = array(); + protected $types = array(); - $this->set_orderby(); - $this->set_limit(); - $this->set_column_headers($headers); + /** + * Construct + */ + public function __construct( $args = array(), $headers = array() ) { - } + global $mycred_log_table; - /** - * Set Export File Name - * Sets the file name we will use when we export. - * - * @version 1.0 - */ - public function set_export_file_name( $name = '' ) - { + $this->args = apply_filters( 'mycred_export_args', shortcode_atts( array( + 'raw' => false, + 'number' => -1, + 'order' => 'time', + 'orderby' => 'DESC', + 'date_format' => get_option( 'date_format' ) + ), $args ), $args ); - $file = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $name); - $file = mb_ereg_replace("([\.]{2,})", '', $name); + $this->db = $mycred_log_table; + $this->raw = $this->args['raw']; + $this->references = mycred_get_all_references(); - if ($file === null || $file === false || strlen($file) == 0 ) { - $file = 'mycred-export-' . date($this->args['date_format'], current_time('timestamp')) . '.csv'; - } + $this->set_orderby(); + $this->set_limit(); + $this->set_column_headers( $headers ); - $username = ''; - $point_type = 'default'; + } - if ($this->user_id !== false ) { + /** + * Set Export File Name + * Sets the file name we will use when we export. + * @version 1.0 + */ + public function set_export_file_name( $name = '' ) { - $user = get_userdata($this->user_id); - if (isset($user->user_login) ) { - $username = $user->user_login; - } + $file = mb_ereg_replace( "([^\w\s\d\-_~,;\[\]\(\).])", '', $name ); + $file = mb_ereg_replace( "([\.]{2,})", '', $name ); - } + if ( $file === NULL || $file === false || strlen( $file ) == 0 ) + $file = 'mycred-export-' . date( $this->args['date_format'], current_time( 'timestamp' ) ) . '.csv'; - if (! empty($this->types) && count($this->types) == 1 ) { - foreach ( $this->types as $type_id => $mycred ) { - $point_type = $type_id; - } - } + $username = ''; + $point_type = 'default'; - $file = str_replace('%username%', $username, $file); - $file = str_replace('%point_type%', $point_type, $file); + if ( $this->user_id !== false ) { - $this->file_name = apply_filters('mycred_export_file_name', $file, $name, $this); + $user = get_userdata( $this->user_id ); + if ( isset( $user->user_login ) ) + $username = $user->user_login; - } + } - /** - * Get Data by IDs - * Retreaves log entries based on a set of entry ids. - * - * @version 1.0 - */ - public function get_data_by_ids( $ids = array() ) - { + if ( ! empty( $this->types ) && count( $this->types ) == 1 ) { + foreach ( $this->types as $type_id => $mycred ) + $point_type = $type_id; + } - $ids = $this->clean_ids($ids); - if ($ids === true || empty($ids) || empty($this->headers) ) { return false; - } + $file = str_replace( '%username%', $username, $file ); + $file = str_replace( '%point_type%', $point_type, $file ); - global $wpdb; + $this->file_name = apply_filters( 'mycred_export_file_name', $file, $name, $this ); - $id_list = implode(', ', $ids); - $data = $wpdb->get_results("SELECT * FROM {$this->db} WHERE id IN ({$id_list}) ORDER BY {$this->orderby} {$this->limit};"); + } - $exportable_data = array(); - if (! empty($data) ) { + /** + * Get Data by IDs + * Retreaves log entries based on a set of entry ids. + * @version 1.0 + */ + public function get_data_by_ids( $ids = array() ) { - $this->set_point_types($data); + $ids = $this->clean_ids( $ids ); + if ( $ids === true || empty( $ids ) || empty( $this->headers ) ) return false; - foreach ( $data as $entry ) { + global $wpdb; - if ($this->raw ) { - $exportable_data[] = $this->get_raw_entry($entry); - } else { - $exportable_data[] = $this->get_rendered_entry($entry); - } + $id_list = implode( ', ', $ids ); + $data = $wpdb->get_results( "SELECT * FROM {$this->db} WHERE id IN ({$id_list}) ORDER BY {$this->orderby} {$this->limit};" ); - } + $exportable_data = array(); + if ( ! empty( $data ) ) { - } - $this->data = $exportable_data; + $this->set_point_types( $data ); - return $exportable_data; + foreach ( $data as $entry ) { - } + if ( $this->raw ) + $exportable_data[] = $this->get_raw_entry( $entry ); + else + $exportable_data[] = $this->get_rendered_entry( $entry ); - /** - * Get Data by User - * Retreaves log entries based on a given user ID. - * - * @version 1.0 - */ - public function get_data_by_user( $user_id = null ) - { + } - $user_id = absint($user_id); - if ($user_id === 0 ) { return false; - } + } + $this->data = $exportable_data; - global $wpdb; + return $exportable_data; - $this->user_id = $user_id; - $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$this->db} WHERE user_id = %d ORDER BY {$this->orderby} {$this->limit};", $user_id)); + } - $exportable_data = array(); - if (! empty($data) ) { + /** + * Get Data by User + * Retreaves log entries based on a given user ID. + * @version 1.0 + */ + public function get_data_by_user( $user_id = NULL ) { - $this->set_point_types($data); + $user_id = absint( $user_id ); + if ( $user_id === 0 ) return false; - foreach ( $data as $entry ) { + global $wpdb; - if ($this->raw ) { - $exportable_data[] = $this->get_raw_entry($entry); - } else { - $exportable_data[] = $this->get_rendered_entry($entry); - } + $this->user_id = $user_id; + $data = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$this->db} WHERE user_id = %d ORDER BY {$this->orderby} {$this->limit};", $user_id ) ); - } + $exportable_data = array(); + if ( ! empty( $data ) ) { - } - $this->data = $exportable_data; + $this->set_point_types( $data ); - return $exportable_data; + foreach ( $data as $entry ) { - } + if ( $this->raw ) + $exportable_data[] = $this->get_raw_entry( $entry ); + else + $exportable_data[] = $this->get_rendered_entry( $entry ); - /** - * Get Data by Type - * Retreaves log entries based on a given point type. - * - * @version 1.0 - */ - public function get_data_by_type( $point_type = null ) - { + } - $point_type = sanitize_key($point_type); - if (! mycred_point_type_exists($point_type) ) { return false; - } + } + $this->data = $exportable_data; - global $wpdb; + return $exportable_data; - $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$this->db} WHERE ctype = %s ORDER BY {$this->orderby} {$this->limit};", $point_type)); + } - $exportable_data = array(); - if (! empty($data) ) { + /** + * Get Data by Type + * Retreaves log entries based on a given point type. + * @version 1.0 + */ + public function get_data_by_type( $point_type = NULL ) { - $types = array(); - $types[ $point_type ] = mycred($point_type); - $this->types = $types; + $point_type = sanitize_key( $point_type ); + if ( ! mycred_point_type_exists( $point_type ) ) return false; - foreach ( $data as $entry ) { + global $wpdb; - if ($this->raw ) { - $exportable_data[] = $this->get_raw_entry($entry); - } else { - $exportable_data[] = $this->get_rendered_entry($entry); - } + $data = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$this->db} WHERE ctype = %s ORDER BY {$this->orderby} {$this->limit};", $point_type ) ); - } + $exportable_data = array(); + if ( ! empty( $data ) ) { - } - $this->data = $exportable_data; + $types = array(); + $types[ $point_type ] = mycred( $point_type ); + $this->types = $types; - return $exportable_data; + foreach ( $data as $entry ) { - } + if ( $this->raw ) + $exportable_data[] = $this->get_raw_entry( $entry ); + else + $exportable_data[] = $this->get_rendered_entry( $entry ); - /** - * Get Data by Query - * Retreaves log entries based on an array of query arguments. - * - * @version 1.0 - */ - public function get_data_by_query( $args = array() ) - { + } - $log = new myCRED_Query_Log($args); + } + $this->data = $exportable_data; - if ($log->have_entries() ) { - $this->data = $log->results; - } + return $exportable_data; - $log->reset_query(); + } - } + /** + * Get Data by Query + * Retreaves log entries based on an array of query arguments. + * @version 1.0 + */ + public function get_data_by_query( $args = array() ) { - /** - * Set Orderby - * Converts a valid set of order arguments into the order arguments the export - * db queries will use. - * - * @version 1.0 - */ - protected function set_orderby() - { + $log = new myCRED_Query_Log( $args ); - $default = 'time DESC'; - $order = sanitize_key($this->args['order']); - $by = sanitize_text_field($this->args['orderby']); + if ( $log->have_entries() ) + $this->data = $log->results; - if (! in_array($order, array( 'id', 'time', 'user_id', 'creds', 'ctype', 'entry', 'data', 'ref', 'ref_id' )) ) { - $order = 'time'; - } + $log->reset_query(); - if (! in_array($by, array( 'ASC', 'DESC' )) ) { - $by = 'DESC'; - } + } - $orderby = $order . ' ' . $by; - if (strlen($orderby) === 1 ) { - $orderby = $default; - } + /** + * Set Orderby + * Converts a valid set of order arguments into the order arguments the export + * db queries will use. + * @version 1.0 + */ + protected function set_orderby() { - $this->orderby = apply_filters('mycred_export_orderby', $orderby, $this->args); + $default = 'time DESC'; + $order = sanitize_key( $this->args['order'] ); + $by = sanitize_text_field( $this->args['orderby'] ); - } + if ( ! in_array( $order, array( 'id', 'time', 'user_id', 'creds', 'ctype', 'entry', 'data', 'ref', 'ref_id' ) ) ) + $order = 'time'; - /** - * Set Limit - * Sets the limit argument to be used in the db queries based on the argument we gave. - * - * @version 1.0 - */ - protected function set_limit() - { - - $number = (int) sanitize_text_field($this->args['number']); - if ($number > 0 ) { - $number = absint($number); - } - - if ($number > 0 ) { - $this->limit = 'LIMIT 0,' . $number; - } + if ( ! in_array( $by, array( 'ASC', 'DESC' ) ) ) + $by = 'DESC'; - } + $orderby = $order . ' ' . $by; + if ( strlen( $orderby ) === 1 ) + $orderby = $default; - /** - * Set Column Headers - * Sets a valid set of column headers for the export. - * - * @version 1.0 - */ - protected function set_column_headers( $headers = array() ) - { - - if (empty($headers) || ! is_array($headers) ) { - $headers = array( 'ref' => __('Reference', 'mycred'), 'ref_id' => __('Reference ID', 'mycred'), 'user_id' => __('User', 'mycred'), 'creds' => __('Amount', 'mycred'), 'ctype' => __('Point Type', 'mycred'), 'time' => __('Date', 'mycred'), 'entry' => __('Entry', 'mycred'), 'data' => __('Data', 'mycred') ); - } - - if (! $this->raw ) { - unset($headers['ref_id']); - unset($headers['data']); - } - - $headers = apply_filters('mycred_export_headers', $headers, $this->raw); + $this->orderby = apply_filters( 'mycred_export_orderby', $orderby, $this->args ); - if ($this->raw ) { - $this->headers = array_keys($headers); + } - } else { - $this->headers = array_values($headers); - } - - } - - /** - * Clean IDs - * Sanitization function for array of entry ids. Also eliminates duplicates. - * - * @returns array of intregers or false - * @version 1.0 - */ - protected function clean_ids( $data = array() ) - { + /** + * Set Limit + * Sets the limit argument to be used in the db queries based on the argument we gave. + * @version 1.0 + */ + protected function set_limit() { - if (empty($data) ) { return false; - } - - $clean_ids = array(); - foreach ( $data as $unknown_id ) { - $abs_int = absint($unknown_id); - if ($abs_int === 0 || in_array($abs_int, $clean_ids) ) { continue; - } - $clean_ids[] = $abs_int; - } - - return $clean_ids; + $number = (int) sanitize_text_field( $this->args['number'] ); + if ( $number > 0 ) + $number = absint( $number ); - } + if ( $number > 0 ) + $this->limit = 'LIMIT 0,' . $number; - /** - * Set Point Types - * Populates $this->types with all the point types found int the data. - * - * @version 1.0 - */ - protected function set_point_types( $data ) - { + } - $types = array(); - foreach ( $data as $entry ) { + /** + * Set Column Headers + * Sets a valid set of column headers for the export. + * @version 1.0 + */ + protected function set_column_headers( $headers = array() ) { - if (isset($entry->ctype) && sanitize_text_field($entry->ctype) !== '' && ! array_key_exists($entry->ctype, $types) ) { - $types[ $entry->ctype ] = mycred($entry->ctype); - } + if ( empty( $headers ) || ! is_array( $headers ) ) + $headers = array( 'ref' => __( 'Reference', 'mycred' ), 'ref_id' => __( 'Reference ID', 'mycred' ), 'user_id' => __( 'User', 'mycred' ), 'creds' => __( 'Amount', 'mycred' ), 'ctype' => __( 'Point Type', 'mycred' ), 'time' => __( 'Date', 'mycred' ), 'entry' => __( 'Entry', 'mycred' ), 'data' => __( 'Data', 'mycred' ) ); - } + if ( ! $this->raw ) { + unset( $headers['ref_id'] ); + unset( $headers['data'] ); + } - $this->types = $types; + $headers = apply_filters( 'mycred_export_headers', $headers, $this->raw ); - } + if ( $this->raw ) + $this->headers = array_keys( $headers ); - /** - * Get Raw Entry - * Returns the values for all columns in the current export row in raw format. - * - * @version 1.0 - */ - protected function get_raw_entry( $entry ) - { + else + $this->headers = array_values( $headers ); - $row = array(); - if (! empty($this->headers) ) { - foreach ( $this->headers as $header_id ) { + } - $value = ''; - if (isset($entry->$header_id) ) { - $value = $entry->$header_id; - } + /** + * Clean IDs + * Sanitization function for array of entry ids. Also eliminates duplicates. + * @returns array of intregers or false + * @version 1.0 + */ + protected function clean_ids( $data = array() ) { - $row[ $header_id ] = $value; + if ( empty( $data ) ) return false; - } - } + $clean_ids = array(); + foreach ( $data as $unknown_id ) { + $abs_int = absint( $unknown_id ); + if ( $abs_int === 0 || in_array( $abs_int, $clean_ids ) ) continue; + $clean_ids[] = $abs_int; + } - return $row; + return $clean_ids; - } + } - /** - * Get Rendered Entry - * Returns the values for all columns in the current export row formatted. - * - * @version 1.0 - */ - protected function get_rendered_entry( $entry ) - { + /** + * Set Point Types + * Populates $this->types with all the point types found int the data. + * @version 1.0 + */ + protected function set_point_types( $data ) { - $row = array(); - $type = $entry->ctype; + $types = array(); + foreach ( $data as $entry ) { - if (! empty($this->headers) ) { - foreach ( $this->headers as $header_id ) { + if ( isset( $entry->ctype ) && sanitize_text_field( $entry->ctype ) !== '' && ! array_key_exists( $entry->ctype, $types ) ) + $types[ $entry->ctype ] = mycred( $entry->ctype ); - switch ( $header_id ) { + } - case 'ref' : - case __('Reference', 'mycred') : + $this->types = $types; - $content = ''; - if (array_key_exists($entry->ref, $this->references) ) { - $content = $this->references[ $entry->ref ]; - } + } - $content = apply_filters('mycred_log_ref', $content, $entry->ref, $entry); + /** + * Get Raw Entry + * Returns the values for all columns in the current export row in raw format. + * @version 1.0 + */ + protected function get_raw_entry( $entry ) { - break; + $row = array(); + if ( ! empty( $this->headers ) ) { + foreach ( $this->headers as $header_id ) { - case 'user_id' : - case __('User', 'mycred') : + $value = ''; + if ( isset( $entry->$header_id ) ) + $value = $entry->$header_id; - $user = get_userdata($entry->user_id); - $display_name = '' . __('User Missing', 'mycred') . ' (ID: ' . $entry->user_id . ')'; - if (isset($user->display_name) ) { - $display_name = $user->display_name; - } + $row[ $header_id ] = $value; - $content = apply_filters('mycred_log_username', $display_name, $entry->user_id, $entry); + } + } - break; + return $row; - case 'creds' : - case __('Amount', 'mycred') : + } - $content = $this->types[ $type ]->format_creds($entry->creds); - $content = apply_filters('mycred_log_creds', $content, $entry->creds, $entry); + /** + * Get Rendered Entry + * Returns the values for all columns in the current export row formatted. + * @version 1.0 + */ + protected function get_rendered_entry( $entry ) { - break; + $row = array(); + $type = $entry->ctype; - case 'ctype' : - case __('Point Type', 'mycred') : + if ( ! empty( $this->headers ) ) { + foreach ( $this->headers as $header_id ) { - $content = $this->types[ $type ]->plural(); - $content = apply_filters('mycred_log_ctype', $content, $entry->ctype, $entry); + switch ( $header_id ) { - break; + case 'ref' : + case __( 'Reference', 'mycred' ) : - case 'time' : - case __('Date', 'mycred') : + $content = ''; + if ( array_key_exists( $entry->ref, $this->references ) ) + $content = $this->references[ $entry->ref ]; - $content = apply_filters('mycred_log_date', date($this->args['date_format'], $entry->time), $entry->time, $entry); + $content = apply_filters( 'mycred_log_ref', $content, $entry->ref, $entry ); - break; + break; - case 'entry' : - case __('Entry', 'mycred') : + case 'user_id' : + case __( 'User', 'mycred' ) : - $content = $this->types[ $type ]->parse_template_tags($entry->entry, $entry); - $content = apply_filters('mycred_log_entry', $content, $entry->entry, $entry); + $user = get_userdata( $entry->user_id ); + $display_name = '' . __( 'User Missing', 'mycred' ) . ' (ID: ' . $entry->user_id . ')'; + if ( isset( $user->display_name ) ) + $display_name = $user->display_name; - break; + $content = apply_filters( 'mycred_log_username', $display_name, $entry->user_id, $entry ); - // Let others play - default : + break; - $content = apply_filters('mycred_log_' . $header_id, '', $entry); + case 'creds' : + case __( 'Amount', 'mycred' ) : - break; + $content = $this->types[ $type ]->format_creds( $entry->creds ); + $content = apply_filters( 'mycred_log_creds', $content, $entry->creds, $entry ); - } + break; - $row[ $header_id ] = $content; + case 'ctype' : + case __( 'Point Type', 'mycred' ) : - } - } + $content = $this->types[ $type ]->plural(); + $content = apply_filters( 'mycred_log_ctype', $content, $entry->ctype, $entry ); - return $row; + break; - } + case 'time' : + case __( 'Date', 'mycred' ) : - /** - * Do Export - * If data is available for export, we run the export tool. - * - * @version 1.0.1 - */ - public function do_export() - { + $content = apply_filters( 'mycred_log_date', date( $this->args['date_format'], $entry->time ), $entry->time, $entry ); - if (empty($this->data) ) { return false; - } + break; - // Load parseCSV - if (! class_exists('parseCSV') ) { - include_once myCRED_ASSETS_DIR . 'libs/parsecsv.lib.php'; - } + case 'entry' : + case __( 'Entry', 'mycred' ) : - $csv = new parseCSV(); - $csv->output(true, $this->file_name, $this->data, $this->headers); + $content = $this->types[ $type ]->parse_template_tags( $entry->entry, $entry ); + $content = apply_filters( 'mycred_log_entry', $content, $entry->entry, $entry ); - exit; + break; - } + // Let others play + default : - } + $content = apply_filters( 'mycred_log_' . $header_id, '', $entry ); + + break; + + } + + $row[ $header_id ] = $content; + + } + } + + return $row; + + } + + /** + * Do Export + * If data is available for export, we run the export tool. + * @version 1.0.1 + */ + public function do_export() { + + if ( empty( $this->data ) ) return false; + + // Load parseCSV + if ( ! class_exists( 'parseCSV' ) ) + require_once myCRED_ASSETS_DIR . 'libs/parsecsv.lib.php'; + + $csv = new parseCSV(); + $csv->output( true, $this->file_name, $this->data, $this->headers ); + + exit; + + } + + } endif; /** * Get Export Formats * Returns an arry of supported formats. - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_get_export_formats') ) : - function mycred_get_export_formats() - { - - return apply_filters( - 'mycred_export_formats', array( - 'raw' => __('Export log entries raw', 'mycred'), - 'formatted' => __('Export log entries formatted', 'mycred') - ) - ); - - } +if ( ! function_exists( 'mycred_get_export_formats' ) ) : + function mycred_get_export_formats() { + + return apply_filters( 'mycred_export_formats', array( + 'raw' => __( 'Export log entries raw', 'mycred' ), + 'formatted' => __( 'Export log entries formatted', 'mycred' ) + ) ); + + } endif; /** * Get Log Exports * Returns an associative array of log export options. - * - * @since 1.4 + * @since 1.4 * @version 1.2 */ -if (! function_exists('mycred_get_log_exports') ) : - function mycred_get_log_exports() - { - - $defaults = array( - 'all' => array( - 'label' => __('All Log Entries', 'mycred'), - 'my_label' => null, - 'class' => 'btn btn-primary button button-primary' - ), - 'search' => array( - 'label' => __('Search Results', 'mycred'), - 'my_label' => null, - 'class' => 'btn btn-primary button button-secondary' - ), - 'user' => array( - 'label' => __('Users Log Entries', 'mycred'), - 'my_label' => __('Export History', 'mycred'), - 'class' => 'btn btn-primary button button-secondary' - ) - ); - - return apply_filters('mycred_log_exports', $defaults); - - } +if ( ! function_exists( 'mycred_get_log_exports' ) ) : + function mycred_get_log_exports() { + + $defaults = array( + 'all' => array( + 'label' => __( 'All Log Entries', 'mycred' ), + 'my_label' => NULL, + 'class' => 'btn btn-primary button button-primary' + ), + 'search' => array( + 'label' => __( 'Search Results', 'mycred' ), + 'my_label' => NULL, + 'class' => 'btn btn-primary button button-secondary' + ), + 'user' => array( + 'label' => __( 'Users Log Entries', 'mycred' ), + 'my_label' => __( 'Export History', 'mycred' ), + 'class' => 'btn btn-primary button button-secondary' + ) + ); + + return apply_filters( 'mycred_log_exports', $defaults ); + + } endif; /** * Get Export URL * Returns the URL for triggering an export (if allowed). - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_get_export_url') ) : - function mycred_get_export_url( $set = 'all', $raw = false ) - { +if ( ! function_exists( 'mycred_get_export_url' ) ) : + function mycred_get_export_url( $set = 'all', $raw = false ) { - $export_url = false; - $is_admin = ( ( function_exists('is_admin') && is_admin() ) ? true : false ); + $export_url = false; + $is_admin = ( ( function_exists( 'is_admin' ) && is_admin() ) ? true : false ); - if (! $is_admin ) { + if ( ! $is_admin ) { - global $wp; - $current_url = add_query_arg($wp->query_string, '', home_url($wp->request . '/')); + global $wp; + $current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request . '/' ) ); - } - else { + } + else { - $current_url = admin_url('admin.php'); + $current_url = admin_url( 'admin.php' ); - } + } - if (is_user_logged_in() ) { + if ( is_user_logged_in() ) { - $args = array(); + $args = array(); - if ($is_admin ) { + if ( $is_admin ) { - if (isset($_GET['page']) ) { - $args['page'] = $_GET['page']; - } + if ( isset( $_GET['page'] ) ) + $args['page'] = $_GET['page']; - $args['mycred-action'] = 'export'; - $args['_token'] = wp_create_nonce('mycred-export-request-admin'); + $args['mycred-action'] = 'export'; + $args['_token'] = wp_create_nonce( 'mycred-export-request-admin' ); - } - else { + } + else { - $args['mycred-action'] = 'export'; - $args['_token'] = wp_create_nonce('mycred-export-request'); + $args['mycred-action'] = 'export'; + $args['_token'] = wp_create_nonce( 'mycred-export-request' ); - } + } - $args['set'] = sanitize_key($set); + $args['set'] = sanitize_key( $set ); - if ($raw ) { - $args['raw'] = 'export-raw'; - } + if ( $raw ) + $args['raw'] = 'export-raw'; - $export_url = add_query_arg($args, $current_url); + $export_url = add_query_arg( $args, $current_url ); - } + } - return apply_filters('mycred_get_export_url', $export_url, $set, $is_admin); + return apply_filters( 'mycred_get_export_url', $export_url, $set, $is_admin ); - } + } endif; /** * Is Valid Export URL * Checks if a valid export URL is present. - * - * @since 1.7 + * @since 1.7 * @version 1.0 */ -if (! function_exists('mycred_is_valid_export_url') ) : - function mycred_is_valid_export_url( $admin = false ) - { +if ( ! function_exists( 'mycred_is_valid_export_url' ) ) : + function mycred_is_valid_export_url( $admin = false ) { - $valid = false; - $token = 'mycred-export-request'; - if ($admin ) { - $token = 'mycred-export-request-admin'; - } + $valid = false; + $token = 'mycred-export-request'; + if ( $admin ) + $token = 'mycred-export-request-admin'; - if (is_user_logged_in() ) { + if ( is_user_logged_in() ) { - if (isset($_REQUEST['mycred-action']) && isset($_REQUEST['_token']) && substr($_REQUEST['mycred-action'], 0, 6) === 'export' ) { + if ( isset( $_REQUEST['mycred-action'] ) && isset( $_REQUEST['_token'] ) && substr( $_REQUEST['mycred-action'], 0, 6 ) === 'export' ) { - if (wp_verify_nonce($_REQUEST['_token'], $token) ) { - $valid = true; - } + if ( wp_verify_nonce( $_REQUEST['_token'], $token ) ) + $valid = true; - } + } - } + } - return apply_filters('mycred_is_valid_export_url', $valid, $admin); + return apply_filters( 'mycred_is_valid_export_url', $valid, $admin ); - } + } endif; diff --git a/includes/classes/class.query-leaderboard.php b/includes/classes/class.query-leaderboard.php index 2d84e25..b9d5ba6 100644 --- a/includes/classes/class.query-leaderboard.php +++ b/includes/classes/class.query-leaderboard.php @@ -1,376 +1,340 @@ now = current_time('timestamp'); - $this->user_id = get_current_user_id(); - $this->max_size = apply_filters('mycred_max_leaderboard_size', 250, $this); - - // Parse and validate the given args - $this->parse_args($args); - - // What is the leaderboard based on - $this->based_on = ( MYCRED_ENABLE_LOGGING ) ? $this->args['based_on'] : 'balance'; - $this->order = $this->args['order']; - - // Setup limit - if ($this->args['number'] > 0 ) { - - $this->limit = 'LIMIT ' . $this->args['number']; - if ($this->args['offset'] != 0 ) { - $this->limit = 'LIMIT ' . $this->args['offset'] . ', ' . $this->args['number']; - } - - } - - } - - /** - * Apply Defaults - * - * @since 1.0 - * @version 1.0 - */ - public function apply_defaults( $data = array() ) - { - - $defaults = array( - 'based_on' => 'balance', - 'number' => 25, - 'offset' => 0, - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'timeframe' => '', - 'to' => '', - 'now' => $this->now, - 'order' => 'DESC', - 'total' => 0, - 'exclude_zero' => 1, - 'forced' => 0, - 'exclude' => '' - ); - - return apply_filters('mycred_query_leaderboard_args', shortcode_atts($defaults, $data), $data, $this); - - } - - /** - * Parse Arguments - * We have two jobs: Make sure we provide arguments we can understand and - * that the arguments we provided are valid. - * - * @since 1.0 - * @version 1.1 - */ - public function parse_args( $args = array() ) - { - - /** - * Populate Query Arguments - * - * @uses mycred_query_leaderboard_args - * @see http://codex.mycred.me/filters/mycred_query_leaderboard_args/ - */ - $args = $this->apply_defaults($args); - - // Generate a unique ID that identifies the leaderboard we are trying to build - $this->cache_key = $this->get_cache_key($args); - - // Based on - $based_on = sanitize_text_field($args['based_on']); - if (! MYCRED_ENABLE_LOGGING ) { $based_on = 'balance'; - } - - if ($based_on != 'balance' ) { - - $references = array(); - if (! empty($args['based_on']) ) { - foreach ( explode(',', $based_on) as $ref ) { - - $ref = sanitize_key($ref); - if (strlen($ref) == 0 ) { continue; - } - $references[] = $ref; - - } - } - $this->references = $references; - - $based_on = 'references'; - - } - - $this->args['based_on'] = $based_on; +if ( ! class_exists( 'myCRED_Query_Leaderboard' ) ) : + class myCRED_Query_Leaderboard { + + public $cache_key = false; + public $now = 0; + public $core = NULL; + public $user_id = 0; + private $max_size = 250; + public $args = array(); + public $based_on = 'balance'; + public $references = array(); + public $point_types = array(); + public $multitype_query = false; + public $order = ''; + public $limit = ''; + + public $leaderboard = false; + + /** + * Construct + * Preps the class for getting a leaderboard based on the + * given arguments. Validates these arguments. + * @since 1.0 + * @version 1.1.1 + */ + public function __construct( $args = array() ) { + + $this->now = current_time( 'timestamp' ); + $this->user_id = get_current_user_id(); + $this->max_size = apply_filters( 'mycred_max_leaderboard_size', 250, $this ); + + // Parse and validate the given args + $this->parse_args( $args ); + + // What is the leaderboard based on + $this->based_on = ( MYCRED_ENABLE_LOGGING ) ? $this->args['based_on'] : 'balance'; + $this->order = $this->args['order']; + + // Setup limit + if ( $this->args['number'] > 0 ) { + + $this->limit = 'LIMIT ' . $this->args['number']; + if ( $this->args['offset'] != 0 ) + $this->limit = 'LIMIT ' . $this->args['offset'] . ', ' . $this->args['number']; + + } + + } + + /** + * Apply Defaults + * @since 1.0 + * @version 1.0 + */ + public function apply_defaults( $data = array() ) { + + $defaults = array( + 'based_on' => 'balance', + 'number' => 25, + 'offset' => 0, + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'timeframe' => '', + 'to' => '', + 'now' => $this->now, + 'order' => 'DESC', + 'total' => 0, + 'exclude_zero' => 1, + 'forced' => 0, + 'exclude' => '' + ); + + return apply_filters( 'mycred_query_leaderboard_args', shortcode_atts( $defaults, $data ), $data, $this ); + + } + + /** + * Parse Arguments + * We have two jobs: Make sure we provide arguments we can understand and + * that the arguments we provided are valid. + * @since 1.0 + * @version 1.1 + */ + public function parse_args( $args = array() ) { + + /** + * Populate Query Arguments + * @uses mycred_query_leaderboard_args + * @see http://codex.mycred.me/filters/mycred_query_leaderboard_args/ + */ + $args = $this->apply_defaults( $args ); + + // Generate a unique ID that identifies the leaderboard we are trying to build + $this->cache_key = $this->get_cache_key( $args ); + + // Based on + $based_on = sanitize_text_field( $args['based_on'] ); + if ( ! MYCRED_ENABLE_LOGGING ) $based_on = 'balance'; + + if ( $based_on != 'balance' ) { + + $references = array(); + if ( ! empty( $args['based_on'] ) ) { + foreach ( explode( ',', $based_on ) as $ref ) { + + $ref = sanitize_key( $ref ); + if ( strlen( $ref ) == 0 ) continue; + $references[] = $ref; - // Number or leaderboard size - $number = (int) sanitize_key($args['number']); - if ($number < -1 ) { - $number = -1; + } + } + $this->references = $references; - } elseif (! is_numeric($number) ) { - $number = 25; + $based_on = 'references'; - } elseif ($number > $this->max_size ) { - $number = $this->max_size; - } + } - $this->args['number'] = $number; - - // Option to offset - $offset = (int) sanitize_key($args['offset']); - if (! is_numeric($offset) ) { - $offset = 0; - } - - $this->args['offset'] = $offset; - - // Point Type - $point_types = explode(',', $args['type']); - $list_of_types = array(); - if (! empty($point_types) ) { - foreach ( $point_types as $potential_key ) { - - $type_key = sanitize_key($potential_key); - if (mycred_point_type_exists($type_key) || ! in_array($type_key, $list_of_types) ) { - $list_of_types[] = $type_key; - } - - } - } - if (empty($list_of_types) ) { - $list_of_types[] = MYCRED_DEFAULT_TYPE_KEY; - } + $this->args['based_on'] = $based_on; - $this->point_types = $list_of_types; - $this->multitype_query = ( count($list_of_types) > 1 ) ? true : false; + // Number or leaderboard size + $number = (int) sanitize_key( $args['number'] ); + if ( $number < -1 ) + $number = -1; - $this->core = mycred($this->point_types[0]); + elseif ( ! is_numeric( $number ) ) + $number = 25; - // Timeframe - $this->args['timeframe'] = ( MYCRED_ENABLE_LOGGING ) ? sanitize_text_field($args['timeframe']) : ''; - // To + elseif ( $number > $this->max_size ) + $number = $this->max_size; - $this->args['to'] = ( MYCRED_ENABLE_LOGGING ) ? sanitize_text_field($args['to']) : ''; - $this->args['now'] = ( $args['now'] != '' ) ? absint($args['now']) : $this->now; + $this->args['number'] = $number; - // Order - $order = strtoupper(sanitize_text_field($args['order'])); - if (! in_array($order, array( 'ASC', 'DESC' )) ) { - $order = 'DESC'; - } + // Option to offset + $offset = (int) sanitize_key( $args['offset'] ); + if ( ! is_numeric( $offset ) ) + $offset = 0; - $this->args['order'] = $order; + $this->args['offset'] = $offset; - // Show total balance - $this->args['total'] = ( MYCRED_ENABLE_TOTAL_BALANCE ) ? (bool) $args['total'] : false; + // Point Type + $point_types = explode( ',', $args['type'] ); + $list_of_types = array(); + if ( ! empty( $point_types ) ) { + foreach ( $point_types as $potential_key ) { - // Exclude zero balances - $this->args['exclude_zero'] = (bool) $args['exclude_zero']; + $type_key = sanitize_key( $potential_key ); + if ( mycred_point_type_exists( $type_key ) || ! in_array( $type_key, $list_of_types ) ) + $list_of_types[] = $type_key; - // Force a new leaderboard instead of a cached one (if used) - $this->args['forced'] = (bool) $args['forced']; - $this->args['exclude'] = ( $args['exclude'] != '' ) ? sanitize_text_field($args['exclude']) : ''; + } + } + if ( empty( $list_of_types ) ) + $list_of_types[] = MYCRED_DEFAULT_TYPE_KEY; - } + $this->point_types = $list_of_types; + $this->multitype_query = ( count( $list_of_types ) > 1 ) ? true : false; - /** - * Get Leaderboard Results - * Returns the leaderboard data in an array form or false if the query results in no data. - * - * @since 1.0 - * @version 1.0 - */ - public function get_leaderboard_results( $append_current_user = false ) - { + $this->core = mycred( $this->point_types[0] ); - $results = $this->get_cache(); - if ($results === false ) { + // Timeframe + $this->args['timeframe'] = ( MYCRED_ENABLE_LOGGING ) ? sanitize_text_field( $args['timeframe'] ) : ''; + // To - global $wpdb; + $this->args['to'] = ( MYCRED_ENABLE_LOGGING ) ? sanitize_text_field( $args['to'] ) : ''; + $this->args['now'] = ( $args['now'] != '' ) ? absint( $args['now'] ) : $this->now; - $results = $wpdb->get_results($this->get_db_query(), 'ARRAY_A'); - if (empty($results) ) { - $results = false; - } + // Order + $order = strtoupper( sanitize_text_field( $args['order'] ) ); + if ( ! in_array( $order, array( 'ASC', 'DESC' ) ) ) + $order = 'DESC'; - if ($results !== false ) { - $this->cache_result($results); - } + $this->args['order'] = $order; - } + // Show total balance + $this->args['total'] = ( MYCRED_ENABLE_TOTAL_BALANCE ) ? (bool) $args['total'] : false; - $this->leaderboard = $results; + // Exclude zero balances + $this->args['exclude_zero'] = (bool) $args['exclude_zero']; + // Force a new leaderboard instead of a cached one (if used) + $this->args['forced'] = (bool) $args['forced']; + $this->args['exclude'] = ( $args['exclude'] != '' ) ? sanitize_text_field( $args['exclude'] ) : ''; - if ($append_current_user ) { - $this->append_current_user(); - } + } - $results = $this->leaderboard; - $this->leaderboard = apply_filters('mycred_get_leaderboard_results', $results, $append_current_user, $this); + /** + * Get Leaderboard Results + * Returns the leaderboard data in an array form or false if the query results in no data. + * @since 1.0 + * @version 1.0 + */ + public function get_leaderboard_results( $append_current_user = false ) { - } + $results = $this->get_cache(); + if ( $results === false ) { - /** - * Append Current User - * Appends the current logged in user to the end of the leaderboard if the user is not in the results. - * This is done separatelly since we can not cache a leaderboard for each user that might view the board. - * - * @since 1.0 - * @version 1.0 - */ - public function append_current_user( $return = false ) - { + global $wpdb; - if (! is_user_logged_in() || $this->leaderboard === false || $this->core->exclude_user($this->user_id) ) { return; - } + $results = $wpdb->get_results( $this->get_db_query(), 'ARRAY_A' ); + if ( empty( $results ) ) + $results = false; - // First we need to check if the user is already in the leaderboard - if ($this->user_in_leaderboard() ) { return; - } + if ( $results !== false ) + $this->cache_result( $results ); - // User is not in the leaderboard so we need to append him/her to the end of the leaderboard array. - $new_row = array( 'ID' => $this->user_id ); - $new_row['position'] = $this->get_users_current_position(); - $new_row['cred'] = $this->get_users_current_value(); + } - if ($return ) { - return $new_row; - } + $this->leaderboard = $results; - $this->leaderboard[] = $new_row; - } + if ( $append_current_user ) + $this->append_current_user(); - /** - * User In Leaderboard - * Checks if a given user or the current user is in the leaderboard. - * - * @since 1.0 - * @version 1.0 - */ - public function user_in_leaderboard( $user_id = null ) - { + $results = $this->leaderboard; + $this->leaderboard = apply_filters( 'mycred_get_leaderboard_results', $results, $append_current_user, $this ); - $in_leaderboard = false; - if ($this->leaderboard !== false && ! empty($this->leaderboard) ) { + } - if ($user_id === null || absint($user_id) === 0 ) { - $user_id = $this->user_id; - } + /** + * Append Current User + * Appends the current logged in user to the end of the leaderboard if the user is not in the results. + * This is done separatelly since we can not cache a leaderboard for each user that might view the board. + * @since 1.0 + * @version 1.0 + */ + public function append_current_user( $return = false ) { - $user_id = absint($user_id); + if ( ! is_user_logged_in() || $this->leaderboard === false || $this->core->exclude_user( $this->user_id ) ) return; - foreach ( $this->leaderboard as $position => $user ) { - if (absint($user['ID']) === $user_id ) { - $in_leaderboard = true; - break; - } - } + // First we need to check if the user is already in the leaderboard + if ( $this->user_in_leaderboard() ) return; - } + // User is not in the leaderboard so we need to append him/her to the end of the leaderboard array. + $new_row = array( 'ID' => $this->user_id ); + $new_row['position'] = $this->get_users_current_position(); + $new_row['cred'] = $this->get_users_current_value(); - return apply_filters('mycred_user_in_leaderboard', $in_leaderboard, $user_id, $this); + if ( $return ) + return $new_row; - } + $this->leaderboard[] = $new_row; - /** - * Get Database Query - * Returns the SQL query required for generating a leaderboard. - * - * @since 1.0 - * @version 1.0 - */ - public function get_db_query() - { + } + /** + * User In Leaderboard + * Checks if a given user or the current user is in the leaderboard. + * @since 1.0 + * @version 1.0 + */ + public function user_in_leaderboard( $user_id = NULL ) { - if ($this->based_on == 'balance' ) { - $query = $this->get_balance_db_query(); - } - else { - $query = $this->get_reference_db_query(); - } + $in_leaderboard = false; + if ( $this->leaderboard !== false && ! empty( $this->leaderboard ) ) { - + if ( $user_id === NULL || absint( $user_id ) === 0 ) + $user_id = $this->user_id; - return $query; + $user_id = absint( $user_id ); - } + foreach ( $this->leaderboard as $position => $user ) { + if ( absint( $user['ID'] ) === $user_id ) { + $in_leaderboard = true; + break; + } + } - /** - * Get Balance Database Query - * Returns the SQL query required for generating a leaderboard that is based on balances. - * - * @since 1.0 - * @version 1.1 - */ - public function get_balance_db_query() - { - - global $wpdb, $mycred_log_table; - - $query = ''; - $exclude_filter = $this->get_excludefilter(); - $exclude_user_filter = $this->get_exclude_userfilter(); - $multisite_check = $this->get_multisitefilter(); - - /** - * Total balance with timeframe - * For this, we need to query the myCRED log so we can apply the timeframe. - */ - if (MYCRED_ENABLE_LOGGING && $this->args['total'] && $this->args['timeframe'] != '' ) { + } - $time_filter = $this->get_timefilter(); - $point_type_is = 'l.ctype = %s'; - $point_type_values = $this->point_types[0]; + return apply_filters( 'mycred_user_in_leaderboard', $in_leaderboard, $user_id, $this ); - // For multiple point types - if (count($this->point_types) > 1 ) { + } - $point_type_is = 'l.ctype IN ( %s' . str_repeat(', %s', ( count($this->point_types) - 1 )) . ' )'; - $point_type_values = $this->point_types; + /** + * Get Database Query + * Returns the SQL query required for generating a leaderboard. + * @since 1.0 + * @version 1.0 + */ + public function get_db_query() { - } - $query = $wpdb->prepare( - " + if ( $this->based_on == 'balance' ) { + $query = $this->get_balance_db_query(); + } + else { + $query = $this->get_reference_db_query(); + } + + + + return $query; + + } + + /** + * Get Balance Database Query + * Returns the SQL query required for generating a leaderboard that is based on balances. + * @since 1.0 + * @version 1.1 + */ + public function get_balance_db_query() { + + global $wpdb, $mycred_log_table; + + $query = ''; + $exclude_filter = $this->get_excludefilter(); + $exclude_user_filter = $this->get_exclude_userfilter(); + $multisite_check = $this->get_multisitefilter(); + + /** + * Total balance with timeframe + * For this, we need to query the myCRED log so we can apply the timeframe. + */ + if ( MYCRED_ENABLE_LOGGING && $this->args['total'] && $this->args['timeframe'] != '' ) { + + $time_filter = $this->get_timefilter(); + $point_type_is = 'l.ctype = %s'; + $point_type_values = $this->point_types[0]; + + // For multiple point types + if ( count( $this->point_types ) > 1 ) { + + $point_type_is = 'l.ctype IN ( %s' . str_repeat( ', %s', ( count( $this->point_types ) - 1 ) ) . ' )'; + $point_type_values = $this->point_types; + + } + + $query = $wpdb->prepare( " SELECT l.user_id AS ID, SUM( l.creds ) AS cred FROM {$mycred_log_table} l {$multisite_check} @@ -380,34 +344,31 @@ public function get_balance_db_query() {$exclude_user_filter} GROUP BY l.user_id ORDER BY SUM( l.creds ) {$this->order}, l.user_id ASC - {$this->limit};", $point_type_values - ); + {$this->limit};", $point_type_values ); - } + } - /** - * Current or Total Balance - * For this, we will query the usermeta table for the meta_key's. - */ - else { + /** + * Current or Total Balance + * For this, we will query the usermeta table for the meta_key's. + */ + else { - $point_type_is = 'l.meta_key = %s'; - $point_type_values = mycred_get_meta_key($this->point_types[0], ( ( $this->args['total'] ) ? '_total' : '' )); + $point_type_is = 'l.meta_key = %s'; + $point_type_values = mycred_get_meta_key( $this->point_types[0], ( ( $this->args['total'] ) ? '_total' : '' ) ); - // For multiple point types - if (count($this->point_types) > 1 ) { + // For multiple point types + if ( count( $this->point_types ) > 1 ) { - $point_type_is = 'l.meta_key IN ( %s' . str_repeat(', %s', ( count($this->point_types) - 1 )) . ' )'; - $point_type_values = array(); + $point_type_is = 'l.meta_key IN ( %s' . str_repeat( ', %s', ( count( $this->point_types ) - 1 ) ) . ' )'; + $point_type_values = array(); - foreach ( $this->point_types as $type_key ) { - $point_type_values[] = mycred_get_meta_key($type_key, ( ( $this->args['total'] ) ? '_total' : '' )); - } + foreach ( $this->point_types as $type_key ) + $point_type_values[] = mycred_get_meta_key( $type_key, ( ( $this->args['total'] ) ? '_total' : '' ) ); - } + } - $query = $wpdb->prepare( - " + $query = $wpdb->prepare( " SELECT DISTINCT u.ID, l.meta_value AS cred FROM {$wpdb->users} u INNER JOIN {$wpdb->usermeta} l ON ( u.ID = l.user_id ) @@ -416,60 +377,56 @@ public function get_balance_db_query() {$exclude_filter} {$exclude_user_filter} ORDER BY l.meta_value+0 {$this->order}, l.user_id ASC - {$this->limit};", $point_type_values - ); + {$this->limit};", $point_type_values ); - } + } - return apply_filters('mycred_get_balance_leaderboard_sql', $query, $this); + return apply_filters( 'mycred_get_balance_leaderboard_sql', $query, $this ); - } + } - /** - * Get Reference Database Query - * Returns the SQL query required for generating a leaderboard that is based on references. - * - * @since 1.0 - * @version 1.1 - */ - public function get_reference_db_query() - { + /** + * Get Reference Database Query + * Returns the SQL query required for generating a leaderboard that is based on references. + * @since 1.0 + * @version 1.1 + */ + public function get_reference_db_query() { - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - $query = ''; - $time_filter = $this->get_timefilter(); - $multisite_check = $this->get_multisitefilter(); - $exclude_user_filter = $this->get_exclude_userfilter(); + $query = ''; + $time_filter = $this->get_timefilter(); + $multisite_check = $this->get_multisitefilter(); + $exclude_user_filter = $this->get_exclude_userfilter(); - $reference_is = 'l.ref = %s'; - $reference_values = $this->references[0]; + $reference_is = 'l.ref = %s'; + $reference_values = $this->references[0]; - if (count($this->references) > 1 ) { + if ( count( $this->references ) > 1 ) { - $reference_is = 'l.ref IN ( %s' . str_repeat(', %s', ( count($this->references) - 1 )) . ' )'; - $reference_values = $this->references; + $reference_is = 'l.ref IN ( %s' . str_repeat( ', %s', ( count( $this->references ) - 1 ) ) . ' )'; + $reference_values = $this->references; - } + } - $point_type_is = 'l.ctype = %s'; - $point_type_values = $this->point_types[0]; + $point_type_is = 'l.ctype = %s'; + $point_type_values = $this->point_types[0]; - if (count($this->point_types) > 1 ) { + if ( count( $this->point_types ) > 1 ) { - $point_type_is = 'l.ctype IN ( %s' . str_repeat(', %s', ( count($this->point_types) - 1 )) . ' )'; - $point_type_values = $this->point_types; + $point_type_is = 'l.ctype IN ( %s' . str_repeat( ', %s', ( count( $this->point_types ) - 1 ) ) . ' )'; + $point_type_values = $this->point_types; - } + } - /** - * Central Logging - * When we are not using Multisite or if we do, but enabled "Central Loggign". - */ - if (mycred_centralize_log() ) { + /** + * Central Logging + * When we are not using Multisite or if we do, but enabled "Central Loggign". + */ + if ( mycred_centralize_log() ) { - $query = $wpdb->prepare( - " + $query = $wpdb->prepare( " SELECT DISTINCT l.user_id AS ID, SUM( l.creds ) AS cred FROM {$mycred_log_table} l WHERE {$reference_is} AND {$point_type_is} @@ -477,19 +434,17 @@ public function get_reference_db_query() {$exclude_user_filter} GROUP BY l.user_id ORDER BY SUM( l.creds ) {$this->order}, l.user_id ASC - {$this->limit};", $reference_values, $point_type_values - ); + {$this->limit};", $reference_values, $point_type_values ); - } + } - /** - * Multisites - * When we are on a multisite, we need to query based on our local users. - */ - else { + /** + * Multisites + * When we are on a multisite, we need to query based on our local users. + */ + else { - $query = $wpdb->prepare( - " + $query = $wpdb->prepare( " SELECT DISTINCT l.user_id AS ID, SUM( l.creds ) AS cred FROM {$mycred_log_table} l {$multisite_check} @@ -498,65 +453,58 @@ public function get_reference_db_query() {$exclude_user_filter} GROUP BY l.user_id ORDER BY SUM( l.creds ) {$this->order}, l.user_id ASC - {$this->limit};", $reference_values, $point_type_values - ); + {$this->limit};", $reference_values, $point_type_values ); - } + } - return apply_filters('mycred_get_reference_leaderboard_sql', $query, $this); + return apply_filters( 'mycred_get_reference_leaderboard_sql', $query, $this ); - } + } - /** - * Get Users Leaderboard Position - * - * @since 1.0 - * @version 1.1 - */ - public function get_users_current_position( $user_id = null, $no_position = '' ) - { + /** + * Get Users Leaderboard Position + * @since 1.0 + * @version 1.1 + */ + public function get_users_current_position( $user_id = NULL, $no_position = '' ) { - $position = false; + $position = false; - // Better safe than sorry - if ($user_id === null && ! is_user_logged_in() ) { return $position; - } + // Better safe than sorry + if ( $user_id === NULL && ! is_user_logged_in() ) return $position; - if ($user_id === null || absint($user_id) === 0 ) { - $user_id = $this->user_id; - } + if ( $user_id === NULL || absint( $user_id ) === 0 ) + $user_id = $this->user_id; - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - $time_filter = $this->get_timefilter(); - $exclude_filter = $this->get_excludefilter(); - $exclude_user_filter = $this->get_exclude_userfilter(); - $multisite_check = $this->get_multisitefilter(); + $time_filter = $this->get_timefilter(); + $exclude_filter = $this->get_excludefilter(); + $exclude_user_filter = $this->get_exclude_userfilter(); + $multisite_check = $this->get_multisitefilter(); - $point_type_is = 'l.ctype = %s'; - $point_type_values = $this->point_types[0]; + $point_type_is = 'l.ctype = %s'; + $point_type_values = $this->point_types[0]; - if (count($this->point_types) > 1 ) { + if ( count( $this->point_types ) > 1 ) { - $point_type_is = 'l.ctype IN ( %s' . str_repeat(', %s', ( count($this->point_types) - 1 )) . ' )'; - $point_type_values = $this->point_types; + $point_type_is = 'l.ctype IN ( %s' . str_repeat( ', %s', ( count( $this->point_types ) - 1 ) ) . ' )'; + $point_type_values = $this->point_types; - } + } - /** - * Balance Query - */ - if ($this->based_on == 'balance' ) { + /** + * Balance Query + */ + if ( $this->based_on == 'balance' ) { - /** - * Total balance with timeframe - * For this, we need to query the myCRED log so we can apply the timeframe. - */ - if (MYCRED_ENABLE_LOGGING && $this->args['total'] && $this->args['timeframe'] != '' ) { + /** + * Total balance with timeframe + * For this, we need to query the myCRED log so we can apply the timeframe. + */ + if ( MYCRED_ENABLE_LOGGING && $this->args['total'] && $this->args['timeframe'] != '' ) { - $position = $wpdb->get_var( - $wpdb->prepare( - " + $position = $wpdb->get_var( $wpdb->prepare( " SELECT position FROM ( SELECT s.*, @position := @position + 1 position FROM ( SELECT l.user_id, sum( l.creds ) TotalPoints FROM {$mycred_log_table} l @@ -569,36 +517,31 @@ public function get_users_current_position( $user_id = null, $no_position = '' ) ) s, (SELECT @position := 0) init ORDER BY TotalPoints DESC, s.user_id ASC ) r - WHERE user_id = %d", $point_type_values, $user_id - ) - ); + WHERE user_id = %d", $point_type_values, $user_id ) ); - } + } - /** - * Current or Total Balance - * For this, we will query the usermeta table for the meta_key's. - */ - else { + /** + * Current or Total Balance + * For this, we will query the usermeta table for the meta_key's. + */ + else { - $point_type_is = 'l.meta_key = %s'; - $point_type_values = mycred_get_meta_key($this->point_types[0], ( ( $this->args['total'] ) ? '_total' : '' )); + $point_type_is = 'l.meta_key = %s'; + $point_type_values = mycred_get_meta_key( $this->point_types[0], ( ( $this->args['total'] ) ? '_total' : '' ) ); - // For multiple point types - if (count($this->point_types) > 1 ) { + // For multiple point types + if ( count( $this->point_types ) > 1 ) { - $point_type_is = 'l.meta_key IN ( %s' . str_repeat(', %s', ( count($this->point_types) - 1 )) . ' )'; - $point_type_values = array(); + $point_type_is = 'l.meta_key IN ( %s' . str_repeat( ', %s', ( count( $this->point_types ) - 1 ) ) . ' )'; + $point_type_values = array(); - foreach ( $this->point_types as $type_key ) { - $point_type_values[] = mycred_get_meta_key($type_key, ( ( $this->args['total'] ) ? '_total' : '' )); - } + foreach ( $this->point_types as $type_key ) + $point_type_values[] = mycred_get_meta_key( $type_key, ( ( $this->args['total'] ) ? '_total' : '' ) ); - } + } - $position = $wpdb->get_var( - $wpdb->prepare( - " + $position = $wpdb->get_var( $wpdb->prepare( " SELECT position FROM ( SELECT s.*, @position := @position + 1 position FROM ( SELECT l.user_id, l.meta_value AS Balance FROM {$wpdb->usermeta} l @@ -609,29 +552,25 @@ public function get_users_current_position( $user_id = null, $no_position = '' ) ) s, (SELECT @position := 0) init ORDER BY Balance+0 DESC, s.user_id ASC ) r - WHERE user_id = %d", $point_type_values, $user_id - ) - ); + WHERE user_id = %d", $point_type_values, $user_id ) ); - } + } - } + } - /** - * Reference Query - */ - elseif (MYCRED_ENABLE_LOGGING ) { + /** + * Reference Query + */ + elseif ( MYCRED_ENABLE_LOGGING ) { - $reference_is = 'AND l.ref = %s'; - $reference_values = $this->references[0]; - if (count($this->references) > 1 ) { - $reference_is = 'AND l.ref IN ( %s' . str_repeat(', %s', ( count($this->references) - 1 )) . ' )'; - $reference_values = $this->references; - } + $reference_is = 'AND l.ref = %s'; + $reference_values = $this->references[0]; + if ( count( $this->references ) > 1 ) { + $reference_is = 'AND l.ref IN ( %s' . str_repeat( ', %s', ( count( $this->references ) - 1 ) ) . ' )'; + $reference_values = $this->references; + } - $position = $wpdb->get_var( - $wpdb->prepare( - " + $position = $wpdb->get_var( $wpdb->prepare( " SELECT position FROM ( SELECT s.*, @position := @position + 1 position FROM ( SELECT l.user_id, sum( l.creds ) TotalPoints FROM {$mycred_log_table} l @@ -645,70 +584,61 @@ public function get_users_current_position( $user_id = null, $no_position = '' ) ) s, (SELECT @position := 0) init ORDER BY TotalPoints DESC, s.user_id ASC ) r - WHERE user_id = %d", $point_type_values, $reference_values, $user_id - ) - ); + WHERE user_id = %d", $point_type_values, $reference_values, $user_id ) ); - } + } - if ($position === null ) { - $position = $no_position; - } + if ( $position === NULL ) + $position = $no_position; - return apply_filters('mycred_get_leaderboard_position', $position, $user_id, $no_position, $this); + return apply_filters( 'mycred_get_leaderboard_position', $position, $user_id, $no_position, $this ); - } + } - /** - * Get Users Leaderboard Value - * - * @since 1.0 - * @version 1.1 - */ - public function get_users_current_value( $user_id = null ) - { + /** + * Get Users Leaderboard Value + * @since 1.0 + * @version 1.1 + */ + public function get_users_current_value( $user_id = NULL ) { - $value = 0; + $value = 0; - // Better safe than sorry - if ($user_id === null && ! is_user_logged_in() ) { return $value; - } + // Better safe than sorry + if ( $user_id === NULL && ! is_user_logged_in() ) return $value; - if ($user_id === null || absint($user_id) === 0 ) { - $user_id = $this->user_id; - } + if ( $user_id === NULL || absint( $user_id ) === 0 ) + $user_id = $this->user_id; - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - $time_filter = $this->get_timefilter(); - $exclude_filter = $this->get_excludefilter(); - $exclude_user_filter = $this->get_exclude_userfilter(); - $multisite_check = $this->get_multisitefilter(); + $time_filter = $this->get_timefilter(); + $exclude_filter = $this->get_excludefilter(); + $exclude_user_filter = $this->get_exclude_userfilter(); + $multisite_check = $this->get_multisitefilter(); - $point_type_is = 'l.ctype = %s'; - $point_type_values = $this->point_types[0]; + $point_type_is = 'l.ctype = %s'; + $point_type_values = $this->point_types[0]; - if (count($this->point_types) > 1 ) { + if ( count( $this->point_types ) > 1 ) { - $point_type_is = 'l.ctype IN ( %s' . str_repeat(', %s', ( count($this->point_types) - 1 )) . ' )'; - $point_type_values = $this->point_types; + $point_type_is = 'l.ctype IN ( %s' . str_repeat( ', %s', ( count( $this->point_types ) - 1 ) ) . ' )'; + $point_type_values = $this->point_types; - } + } - /** - * Balance Query - */ - if ($this->based_on == 'balance' ) { + /** + * Balance Query + */ + if ( $this->based_on == 'balance' ) { - /** - * Total balance with timeframe - * For this, we need to query the myCRED log so we can apply the timeframe. - */ - if (MYCRED_ENABLE_LOGGING && $this->args['total'] && $this->args['timeframe'] != '' ) { + /** + * Total balance with timeframe + * For this, we need to query the myCRED log so we can apply the timeframe. + */ + if ( MYCRED_ENABLE_LOGGING && $this->args['total'] && $this->args['timeframe'] != '' ) { - $value = $wpdb->get_var( - $wpdb->prepare( - " + $value = $wpdb->get_var( $wpdb->prepare( " SELECT TotalPoints FROM ( SELECT s.*, @position := @position + 1 position FROM ( SELECT l.user_id, sum( l.creds ) TotalPoints FROM {$mycred_log_table} l @@ -721,36 +651,31 @@ public function get_users_current_value( $user_id = null ) ) s, (SELECT @position := 0) init ORDER BY TotalPoints DESC, s.user_id ASC ) r - WHERE user_id = %d", $point_type_values, $user_id - ) - ); + WHERE user_id = %d", $point_type_values, $user_id ) ); - } + } - /** - * Current or Total Balance - * For this, we will query the usermeta table for the meta_key's. - */ - else { + /** + * Current or Total Balance + * For this, we will query the usermeta table for the meta_key's. + */ + else { - $point_type_is = 'l.meta_key = %s'; - $point_type_values = mycred_get_meta_key($this->point_types[0], ( ( $this->args['total'] ) ? '_total' : '' )); + $point_type_is = 'l.meta_key = %s'; + $point_type_values = mycred_get_meta_key( $this->point_types[0], ( ( $this->args['total'] ) ? '_total' : '' ) ); - // For multiple point types - if (count($this->point_types) > 1 ) { + // For multiple point types + if ( count( $this->point_types ) > 1 ) { - $point_type_is = 'l.meta_key IN ( %s' . str_repeat(', %s', ( count($this->point_types) - 1 )) . ' )'; - $point_type_values = array(); + $point_type_is = 'l.meta_key IN ( %s' . str_repeat( ', %s', ( count( $this->point_types ) - 1 ) ) . ' )'; + $point_type_values = array(); - foreach ( $this->point_types as $type_key ) { - $point_type_values[] = mycred_get_meta_key($type_key, ( ( $this->args['total'] ) ? '_total' : '' )); - } + foreach ( $this->point_types as $type_key ) + $point_type_values[] = mycred_get_meta_key( $type_key, ( ( $this->args['total'] ) ? '_total' : '' ) ); - } + } - $value = $wpdb->get_var( - $wpdb->prepare( - " + $value = $wpdb->get_var( $wpdb->prepare( " SELECT Balance FROM ( SELECT s.*, @position := @position + 1 position FROM ( SELECT l.user_id, l.meta_value AS Balance FROM {$wpdb->usermeta} l @@ -761,29 +686,25 @@ public function get_users_current_value( $user_id = null ) ) s, (SELECT @position := 0) init ORDER BY Balance+0 DESC, s.user_id ASC ) r - WHERE user_id = %d", $point_type_values, $user_id - ) - ); + WHERE user_id = %d", $point_type_values, $user_id ) ); - } + } - } + } - /** - * Reference Query - */ - elseif (MYCRED_ENABLE_LOGGING ) { + /** + * Reference Query + */ + elseif ( MYCRED_ENABLE_LOGGING ) { - $reference_is = 'AND l.ref = %s'; - $reference_values = $this->references[0]; - if (count($this->references) > 1 ) { - $reference_is = 'AND l.ref IN ( %s' . str_repeat(', %s', ( count($this->references) - 1 )) . ' )'; - $reference_values = $this->references; - } + $reference_is = 'AND l.ref = %s'; + $reference_values = $this->references[0]; + if ( count( $this->references ) > 1 ) { + $reference_is = 'AND l.ref IN ( %s' . str_repeat( ', %s', ( count( $this->references ) - 1 ) ) . ' )'; + $reference_values = $this->references; + } - $value = $wpdb->get_var( - $wpdb->prepare( - " + $value = $wpdb->get_var( $wpdb->prepare( " SELECT TotalPoints FROM ( SELECT s.*, @position := @position + 1 position FROM ( SELECT l.user_id, sum( l.creds ) TotalPoints FROM {$mycred_log_table} l @@ -797,413 +718,371 @@ public function get_users_current_value( $user_id = null ) ) s, (SELECT @position := 0) init ORDER BY TotalPoints DESC, s.user_id ASC ) r - WHERE user_id = %d", $point_type_values, $reference_values, $user_id - ) - ); - - } + WHERE user_id = %d", $point_type_values, $reference_values, $user_id ) ); + + } + + return apply_filters( 'mycred_get_users_leaderboard_value', $value, $user_id, $this ); + + } - return apply_filters('mycred_get_users_leaderboard_value', $value, $user_id, $this); - - } + /** + * Get Time Filter + * Generates the required SQL query for filtering results based on time. + * Can only be used when the leaderboard is based either on total balance or based on references. + * @since 1.0 + * @version 1.0 + */ + public function get_timefilter() { - /** - * Get Time Filter - * Generates the required SQL query for filtering results based on time. - * Can only be used when the leaderboard is based either on total balance or based on references. - * - * @since 1.0 - * @version 1.0 - */ - public function get_timefilter() - { + $query = ''; + if ( $this->args['timeframe'] === NULL || strlen( $this->args['timeframe'] ) == 0 ) return $query; - $query = ''; - if ($this->args['timeframe'] === null || strlen($this->args['timeframe']) == 0 ) { return $query; - } - - global $wpdb; + global $wpdb; - + - // Filter: Daily - if ($this->args['timeframe'] == 'today' ) { - $query = $wpdb->prepare("AND l.time BETWEEN %d AND %d", strtotime('today midnight', $this->now), $this->args['now']); - } + // Filter: Daily + if ( $this->args['timeframe'] == 'today' ) { + $query = $wpdb->prepare( "AND l.time BETWEEN %d AND %d", strtotime( 'today midnight', $this->now ), $this->args['now'] ); + } - // Filter: Yesterday - elseif ($this->args['timeframe'] == 'yesterday' ) { - $query = $wpdb->prepare("AND l.time BETWEEN %d AND %d", strtotime('-1 day midnight', $this->now), strtotime('today midnight', $this->now)); - - } + // Filter: Yesterday + elseif ( $this->args['timeframe'] == 'yesterday' ) { + $query = $wpdb->prepare( "AND l.time BETWEEN %d AND %d", strtotime( '-1 day midnight', $this->now ), strtotime( 'today midnight', $this->now )); + + } - // Filter: Weekly - elseif ($this->args['timeframe'] == 'this-week' ) { + // Filter: Weekly + elseif ( $this->args['timeframe'] == 'this-week' ) { - // Start of the week based of our settings - $days = array( 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ); + // Start of the week based of our settings + $days = array( 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ); - $week_starts = get_option('start_of_week'); + $week_starts = get_option( 'start_of_week' ); - if ($days[ $week_starts ] == date('l') ) { - $week_starts = 'today midnight'; - } else { - $week_starts = 'last ' . $days[ $week_starts ]; - } + if ( $days[ $week_starts ] == date('l') ) + $week_starts = 'today midnight'; + else + $week_starts = 'last ' . $days[ $week_starts ]; - $query = $wpdb->prepare("AND l.time BETWEEN %d AND %d", strtotime($week_starts, $this->now), $this->args['now']); - } - // Filter: Monthly - elseif ($this->args['timeframe'] == 'this-month' ) { - $query = $wpdb->prepare("AND l.time BETWEEN %d AND %d", strtotime(date('Y-m-01', $this->now)), $this->args['now']); - } - else { + $query = $wpdb->prepare( "AND l.time BETWEEN %d AND %d", strtotime( $week_starts, $this->now ), $this->args['now'] ); + } + // Filter: Monthly + elseif ( $this->args['timeframe'] == 'this-month' ) { + $query = $wpdb->prepare( "AND l.time BETWEEN %d AND %d", strtotime( date( 'Y-m-01', $this->now ) ), $this->args['now'] ); + } + else { - $start_from = strtotime($this->args['timeframe'], $this->now); - - if ($start_from !== false && $start_from > 0 ) { - $end_to = $this->args['to'] != '' ? strtotime(date($this->args['to']." 23:59:59")) : 0; - if ($end_to === false || $end_to <= 0 ) { - $end_to = $this->args['now']; - } - $query = $wpdb->prepare("AND l.time BETWEEN %d AND %d", $start_from, $end_to); - } + $start_from = strtotime( $this->args['timeframe'], $this->now ); + + if ( $start_from !== false && $start_from > 0 ) { + $end_to = $this->args['to'] != '' ? strtotime(date($this->args['to']." 23:59:59")) : 0; + if ($end_to === false || $end_to <= 0 ) { + $end_to = $this->args['now']; + } + $query = $wpdb->prepare( "AND l.time BETWEEN %d AND %d", $start_from, $end_to ); + } - } + } - return apply_filters('mycred_leaderboard_time_filter', $query, $this); + return apply_filters( 'mycred_leaderboard_time_filter', $query, $this ); - } + } - /** - * Get Exclude Filter - * Generates the required SQL query for filtering results based on if zero balances should - * be part of the leaderboard or not. By default, myCRED will not give a user a balance until they - * gain or lose points. A user that has no balance and is not excluded, is considered to have zero balance. - * - * @since 1.0 - * @version 1.0 - */ - public function get_excludefilter() - { + /** + * Get Exclude Filter + * Generates the required SQL query for filtering results based on if zero balances should + * be part of the leaderboard or not. By default, myCRED will not give a user a balance until they + * gain or lose points. A user that has no balance and is not excluded, is considered to have zero balance. + * @since 1.0 + * @version 1.0 + */ + public function get_excludefilter() { - global $wpdb; + global $wpdb; - // Option to exclude zero balances - $query = ''; - if ($this->args['exclude_zero'] ) { + // Option to exclude zero balances + $query = ''; + if ( $this->args['exclude_zero'] ) { - $balance_format = '%d'; - if (isset($this->core->format['decimals']) && $this->core->format['decimals'] > 0 ) { - $length = absint(65 - $this->core->format['decimals']); - $balance_format = 'CAST( %f AS DECIMAL( ' . $length . ', ' . $this->core->format['decimals'] . ' ) )'; - } + $balance_format = '%d'; + if ( isset( $this->core->format['decimals'] ) && $this->core->format['decimals'] > 0 ) { + $length = absint( 65 - $this->core->format['decimals'] ); + $balance_format = 'CAST( %f AS DECIMAL( ' . $length . ', ' . $this->core->format['decimals'] . ' ) )'; + } - if (! $this->args['total'] ) { - $query = $wpdb->prepare("AND l.meta_value != {$balance_format}", $this->core->zero()); - } + if ( ! $this->args['total'] ) + $query = $wpdb->prepare( "AND l.meta_value != {$balance_format}", $this->core->zero() ); - } + } - return apply_filters('mycred_leaderboard_exclude_filter', $query, $this); + return apply_filters( 'mycred_leaderboard_exclude_filter', $query, $this ); - } + } - /** - * Get Exclude User Filter - * Generates the required SQL query for filtering results based on user ids or roles that should - * be part of the leaderboard or not. By default, myCRED will not exclude any user. - * - * @since 1.0 - * @version 1.0 - */ - public function get_exclude_userfilter() - { + /** + * Get Exclude User Filter + * Generates the required SQL query for filtering results based on user ids or roles that should + * be part of the leaderboard or not. By default, myCRED will not exclude any user. + * @since 1.0 + * @version 1.0 + */ + public function get_exclude_userfilter() { - global $wpdb; + global $wpdb; - // Option to exclude zero balances - $query = ''; - $checkIDs='~^\d+(,\d+)*$~'; - $exclude=$this->args['exclude']; + // Option to exclude zero balances + $query = ''; + $checkIDs='~^\d+(,\d+)*$~'; + $exclude=$this->args['exclude']; - if (!empty($exclude)) { + if (!empty($exclude)) { - if(preg_match($checkIDs, $exclude)) { + if(preg_match($checkIDs,$exclude)){ - $exclude=$this->args['exclude']; + $exclude=$this->args['exclude']; - } - elseif(!preg_match($checkIDs, $exclude)) { - - $exclude=mycred_leaderboard_exclude_role($exclude); + } + elseif(!preg_match($checkIDs,$exclude)){ + + $exclude=mycred_leaderboard_exclude_role($exclude); - } - $query = $wpdb->prepare("AND l.user_id NOT IN ($exclude)"); + } + $query = $wpdb->prepare( "AND l.user_id NOT IN ($exclude)"); - } - return apply_filters('mycred_leaderboard_exclude_user_filter', $query, $this); - } + } + return apply_filters( 'mycred_leaderboard_exclude_user_filter', $query, $this ); + } - /** - * Get Multisite Filter - * Generates the required SQL query for filtering results based on our multisite setup. - * Will return an empty string if we are not using multisites or if we have centralized the log. - * - * @since 1.0 - * @version 1.0 - */ - public function get_multisitefilter() - { + /** + * Get Multisite Filter + * Generates the required SQL query for filtering results based on our multisite setup. + * Will return an empty string if we are not using multisites or if we have centralized the log. + * @since 1.0 + * @version 1.0 + */ + public function get_multisitefilter() { - global $wpdb; + global $wpdb; - $multisite_check = ""; - if (! mycred_centralize_log() ) { + $multisite_check = ""; + if ( ! mycred_centralize_log() ) { - $blog_id = absint($GLOBALS['blog_id']); - $multisite_check = "LEFT JOIN {$wpdb->usermeta} cap ON ( l.user_id = cap.user_id AND cap.meta_key = 'cap.wp_{$blog_id}_capabilities' )"; + $blog_id = absint( $GLOBALS['blog_id'] ); + $multisite_check = "LEFT JOIN {$wpdb->usermeta} cap ON ( l.user_id = cap.user_id AND cap.meta_key = 'cap.wp_{$blog_id}_capabilities' )"; - } + } - return apply_filters('mycred_leaderboard_musite_filter', $multisite_check, $this); + return apply_filters( 'mycred_leaderboard_musite_filter', $multisite_check, $this ); - } + } - /** - * Get Cache Key - * - * @since 1.0 - * @version 1.0 - */ - public function get_cache_key( $args = array() ) - { + /** + * Get Cache Key + * @since 1.0 + * @version 1.0 + */ + public function get_cache_key( $args = array() ) { - if (empty($args) ) { $args = $this->args; - } else { $args = $this->apply_defaults($args); - } + if ( empty( $args ) ) $args = $this->args; + else $args = $this->apply_defaults( $args ); - unset($args['now']); + unset( $args['now'] ); - return 'leaderboard-' . md5(serialize($args)); + return 'leaderboard-' . md5( serialize( $args ) ); - } + } - /** - * Get Cached Leaderboard - * - * @since 1.0 - * @version 1.1 - */ - public function get_cache() - { + /** + * Get Cached Leaderboard + * @since 1.0 + * @version 1.1 + */ + public function get_cache() { - $data = false; - $key = $this->get_cache_key(); + $data = false; + $key = $this->get_cache_key(); - // Object caching we will always do - $object_cache = wp_cache_get($key, MYCRED_SLUG); - if ($object_cache !== false && is_array($object_cache) ) { + // Object caching we will always do + $object_cache = wp_cache_get( $key, MYCRED_SLUG ); + if ( $object_cache !== false && is_array( $object_cache ) ) { - if ($this->args['forced'] ) { - wp_cache_delete($key, MYCRED_SLUG); + if ( $this->args['forced'] ) + wp_cache_delete( $key, MYCRED_SLUG ); - } else { $data = $object_cache; - } + else $data = $object_cache; - } + } - return apply_filters('mycred_get_cached_leaderboard', $data, $this); + return apply_filters( 'mycred_get_cached_leaderboard', $data, $this ); - } + } - /** - * Cache Results - * - * @since 1.0 - * @version 1.1 - */ - public function cache_result( $data = array() ) - { + /** + * Cache Results + * @since 1.0 + * @version 1.1 + */ + public function cache_result( $data = array() ) { - if ($this->args['forced'] ) { return; - } + if ( $this->args['forced'] ) return; - $key = $this->get_cache_key(); - $cache_keys = mycred_get_option(MYCRED_SLUG . '-cache-leaderboard-keys', array()); + $key = $this->get_cache_key(); + $cache_keys = mycred_get_option( MYCRED_SLUG . '-cache-leaderboard-keys', array() ); - if (empty($cache_keys) || ( ! empty($cache_keys) && ! in_array($key, $cache_keys) ) ) { + if ( empty( $cache_keys ) || ( ! empty( $cache_keys ) && ! in_array( $key, $cache_keys ) ) ) { - $cache_keys[] = $key; + $cache_keys[] = $key; - mycred_update_option(MYCRED_SLUG . '-cache-leaderboard-keys', $cache_keys); + mycred_update_option( MYCRED_SLUG . '-cache-leaderboard-keys', $cache_keys ); - } + } - wp_cache_set($key, $data, MYCRED_SLUG); + wp_cache_set( $key, $data, MYCRED_SLUG ); - do_action('mycred_cache_leaderboard', $data, $this); + do_action( 'mycred_cache_leaderboard', $data, $this ); - } + } - /** - * Is Leaderboard - * - * @since 1.0 - * @version 1.0 - */ - public function is_leaderboard( $args = array() ) - { + /** + * Is Leaderboard + * @since 1.0 + * @version 1.0 + */ + public function is_leaderboard( $args = array() ) { - if ($this->cache_key === false ) { return false; - } + if ( $this->cache_key === false ) return false; - return ( $this->cache_key == $this->get_cache_key($args) ); + return ( $this->cache_key == $this->get_cache_key( $args ) ); - } + } - /** - * Render Leaderboard - * - * @since 1.0 - * @version 1.0 - */ - public function render( $args = array(), $content = '' ) - { + /** + * Render Leaderboard + * @since 1.0 + * @version 1.0 + */ + public function render( $args = array(), $content = '' ) { - extract( - shortcode_atts( - array( - 'wrap' => 'li', - 'template' => '#%position% %user_profile_link% %cred_f%', - 'nothing' => 'Leaderboard is empty', - ), $args - ) - ); + extract( shortcode_atts( array( + 'wrap' => 'li', + 'template' => '#%position% %user_profile_link% %cred_f%', + 'nothing' => 'Leaderboard is empty', + ), $args ) ); - $mycred = mycred($args['type']); - - $output = ''; + $mycred = mycred( $args['type'] ); + + $output = ''; - // Leaderboard is empty - if ($this->leaderboard === false || empty($this->leaderboard) ) { + // Leaderboard is empty + if ( $this->leaderboard === false || empty( $this->leaderboard ) ) { - $output .= '

    ' . $nothing . '

    '; + $output .= '

    ' . $nothing . '

    '; - } + } - // Got results to show - else { + // Got results to show + else { - // Wrapper - if ($wrap == 'li' ) { - $output .= '
      '; - } + // Wrapper + if ( $wrap == 'li' ) + $output .= '
        '; - // Loop - foreach ( $this->leaderboard as $position => $user ) { + // Loop + foreach ( $this->leaderboard as $position => $user ) { - // Prep - $class = array(); - $row = $position; + // Prep + $class = array(); + $row = $position; - if (array_key_exists('position', $user) ) { - $position = $user['position']; + if ( array_key_exists( 'position', $user ) ) + $position = $user['position']; - } else { + else { - if ($this->args['offset'] != '' && $this->args['offset'] > 0 ) { - $position = $position + $this->args['offset']; - } + if ( $this->args['offset'] != '' && $this->args['offset'] > 0 ) + $position = $position + $this->args['offset']; - $position++; + $position++; - } + } - // Classes - $class[] = 'item-' . $row; - if ($position == 0 ) { - $class[] = 'first-item'; - } + // Classes + $class[] = 'item-' . $row; + if ( $position == 0 ) + $class[] = 'first-item'; - if ($this->user_id > 0 && $user['ID'] == $this->user_id ) { - $class[] = 'current-user'; - } + if ( $this->user_id > 0 && $user['ID'] == $this->user_id ) + $class[] = 'current-user'; - if (is_numeric($position) && $position % 2 != 0 ) { - $class[] = 'alt'; - } + if ( is_numeric( $position ) && $position % 2 != 0 ) + $class[] = 'alt'; - $row_template = $template; - if (! empty($content) ) { - $row_template = $content; - } + $row_template = $template; + if ( ! empty( $content ) ) + $row_template = $content; - // Template Tags - $layout = str_replace(array( '%ranking%', '%position%' ), $position, $row_template); + // Template Tags + $layout = str_replace( array( '%ranking%', '%position%' ), $position, $row_template ); - $layout = $this->core->template_tags_amount($layout, $user['cred']); - $layout = $this->core->template_tags_user($layout, $user['ID']); + $layout = $this->core->template_tags_amount( $layout, $user['cred'] ); + $layout = $this->core->template_tags_user( $layout, $user['ID'] ); - //Point type Image - if($args['image'] && $mycred->image_url ) { - $layout = str_replace('%image%', "", $layout); - } else { - $layout = str_replace('%image%', '', $layout); - } - - // Wrapper - if (! empty($wrap) ) { - $layout = '<' . $wrap . ' class="%classes%">' . $layout . ''; - } + //Point type Image + if( $args['image'] && $mycred->image_url ) + $layout = str_replace( '%image%', "", $layout ); + else + $layout = str_replace( '%image%', '', $layout ); + + // Wrapper + if ( ! empty( $wrap ) ) + $layout = '<' . $wrap . ' class="%classes%">' . $layout . ''; - $layout = str_replace('%classes%', apply_filters('mycred_ranking_classes', implode(' ', $class), $this), $layout); - $layout = apply_filters('mycred_ranking_row', $layout, $template, $user, $position, $this); + $layout = str_replace( '%classes%', apply_filters( 'mycred_ranking_classes', implode( ' ', $class ), $this ), $layout ); + $layout = apply_filters( 'mycred_ranking_row', $layout, $template, $user, $position, $this ); - $output .= $layout . "\n"; + $output .= $layout . "\n"; - } + } - if ($wrap == 'li' ) { - $output .= '
      '; - } + if ( $wrap == 'li' ) + $output .= '
    '; - } + } - return apply_filters('mycred_leaderboard', $output, $args, $this); + return apply_filters( 'mycred_leaderboard', $output, $args, $this ); - } + } - } + } endif; /** * Get Leaderboard - * - * @since 1.7.9.1 + * @since 1.7.9.1 * @version 1.1 */ -if (! function_exists('mycred_get_leaderboard') ) : - function mycred_get_leaderboard( $args = array() ) - { +if ( ! function_exists( 'mycred_get_leaderboard' ) ) : + function mycred_get_leaderboard( $args = array() ) { - global $mycred_leaderboard; + global $mycred_leaderboard; - if (isset($mycred_leaderboard) - && ( $mycred_leaderboard instanceof myCRED_Query_Leaderboard ) - && ( $mycred_leaderboard->is_leaderboard($args) ) - ) { + if ( isset( $mycred_leaderboard ) + && ( $mycred_leaderboard instanceof myCRED_Query_Leaderboard ) + && ( $mycred_leaderboard->is_leaderboard( $args ) ) + ) { - return $mycred_leaderboard; + return $mycred_leaderboard; - } + } - $mycred_leaderboard = new myCRED_Query_Leaderboard($args); + $mycred_leaderboard = new myCRED_Query_Leaderboard( $args ); - return $mycred_leaderboard; + return $mycred_leaderboard; - } + } endif; diff --git a/includes/classes/class.query-log.php b/includes/classes/class.query-log.php index 7fa56a2..0c953d9 100644 --- a/includes/classes/class.query-log.php +++ b/includes/classes/class.query-log.php @@ -1286,7 +1286,7 @@ public function front_pagination( $pages_to_show = 5 ) { $removable_query_args = wp_removable_query_args(); - $current_url = set_url_scheme( sanitize_url('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) ); + $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); $current_url = remove_query_arg( $removable_query_args, $current_url ); $current_url = str_replace( '/' . $current . '/', '/', $current_url ); $current_url = apply_filters( 'mycred_log_front_nav_url', $current_url, $this ); @@ -1383,7 +1383,7 @@ public function pagination( $location = 'top', $id = '' ) { $output = ''; $total_pages = $this->max_num_pages; $current = $this->get_pagenum(); - $current_url = set_url_scheme( sanitize_url('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) ); + $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); if ( ! $this->is_admin ) $current_url = str_replace( '/page/' . $current . '/', '/', $current_url ); diff --git a/includes/classes/index.php b/includes/classes/index.php index 1580272..4e6c07c 100644 --- a/includes/classes/index.php +++ b/includes/classes/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/includes/hooks/external/index.php b/includes/hooks/external/index.php index 1580272..4e6c07c 100644 --- a/includes/hooks/external/index.php +++ b/includes/hooks/external/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/includes/hooks/external/mycred-hook-badgeOS.php b/includes/hooks/external/mycred-hook-badgeOS.php index 03c0df6..f126102 100644 --- a/includes/hooks/external/mycred-hook-badgeOS.php +++ b/includes/hooks/external/mycred-hook-badgeOS.php @@ -1,403 +1,360 @@ __('BadgeOS', 'mycred'), - 'description' => __('Default settings for each BadgeOS Achievement type. These settings may be overridden for individual achievement type.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/badgeos-achievements/', - 'callback' => array( 'myCRED_Hook_BadgeOS' ) - ); + $installed['badgeos'] = array( + 'title' => __( 'BadgeOS', 'mycred' ), + 'description' => __( 'Default settings for each BadgeOS Achievement type. These settings may be overridden for individual achievement type.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/badgeos-achievements/', + 'callback' => array( 'myCRED_Hook_BadgeOS' ) + ); - return $installed; + return $installed; } /** * BadgeOS Hook - * - * @since 1.0.8 + * @since 1.0.8 * @version 1.1.2 */ -add_action('mycred_load_hooks', 'mycred_load_badgeos_hook', 15); -function mycred_load_badgeos_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_Hook_BadgeOS') || ! class_exists('BadgeOS') ) { return; - } - - class myCRED_Hook_BadgeOS extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'badgeos', - 'defaults' => '' - ), $hook_prefs, $type - ); - - $key = '_mycred_values'; - if (! $this->is_main_type ) { - $key .= '_' . $this->mycred_type; - } - - $this->metakey = $key; - - } - - /** - * Run - * - * @since 1.0.8 - * @version 1.0 - */ - public function run() - { - - add_filter('mycred_post_type_excludes', array( $this, 'exclude_post_type' )); - - add_action('add_meta_boxes', array( $this, 'add_metaboxes' )); - add_action('save_post', array( $this, 'save_achivement_data' )); - - add_action('badgeos_award_achievement', array( $this, 'award_achievent' ), 10, 2); - add_action('badgeos_revoke_achievement', array( $this, 'revoke_achievement' ), 10, 2); - - } - - /** - * Exclude bbPress Post Types - * - * @since 1.0.8 - * @version 1.0 - */ - public function exclude_post_type( $excludes ) - { - - $excludes = array_merge($excludes, badgeos_get_achievement_types_slugs()); - - return $excludes; - - } - - /** - * Add Metaboxes - * - * @since 1.0.8 - * @version 1.0 - */ - public function add_metaboxes() - { - - // Get all Achievement Types - $badge_post_types = badgeos_get_achievement_types_slugs(); - foreach ( $badge_post_types as $post_type ) { - - add_meta_box( - 'mycred_badgeos_' . $post_type . '_' . $this->mycred_type, - $this->core->plural(), - array( $this, 'render_meta_box' ), - $post_type, - 'side', - 'core' - ); - - } - - } - - /** - * Render Meta Box - * - * @since 1.0.8 - * @version 1.1 - */ - public function render_meta_box( $post ) - { - - // Setup is needed - if (! isset($this->prefs[ $post->post_type ]) ) { - - $page = MYCRED_SLUG . '-hooks'; - if (! $this->is_main_type ) { - $page = MYCRED_SLUG . '_' . $this->mycred_type . '-hooks'; - } - - echo '

    ' . sprintf(__('Please setup your default settings before using this feature.', 'mycred'), admin_url('admin.php?page=' . $page)) . '

    '; - return; - - } - - $post_key = 'mycred_values' . $this->mycred_type; - - // Prep Achievement Data - $prefs = $this->prefs; - $achievement_data = mycred_get_post_meta($post->ID, $this->metakey, true); - if ($achievement_data == '' ) { - $achievement_data = $prefs[ $post->post_type ]; - } +add_action( 'mycred_load_hooks', 'mycred_load_badgeos_hook', 15 ); +function mycred_load_badgeos_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_Hook_BadgeOS' ) || ! class_exists( 'BadgeOS' ) ) return; + + class myCRED_Hook_BadgeOS extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'badgeos', + 'defaults' => '' + ), $hook_prefs, $type ); + + $key = '_mycred_values'; + if ( ! $this->is_main_type ) + $key .= '_' . $this->mycred_type; + + $this->metakey = $key; + + } + + /** + * Run + * @since 1.0.8 + * @version 1.0 + */ + public function run() { + + add_filter( 'mycred_post_type_excludes', array( $this, 'exclude_post_type' ) ); + + add_action( 'add_meta_boxes', array( $this, 'add_metaboxes' ) ); + add_action( 'save_post', array( $this, 'save_achivement_data' ) ); + + add_action( 'badgeos_award_achievement', array( $this, 'award_achievent' ), 10, 2 ); + add_action( 'badgeos_revoke_achievement', array( $this, 'revoke_achievement' ), 10, 2 ); + + } + + /** + * Exclude bbPress Post Types + * @since 1.0.8 + * @version 1.0 + */ + public function exclude_post_type( $excludes ) { + + $excludes = array_merge( $excludes, badgeos_get_achievement_types_slugs() ); + + return $excludes; + + } - ?> -

    core->template_tags_general(__('%plural% to Award', 'mycred')); ?>

    + /** + * Add Metaboxes + * @since 1.0.8 + * @version 1.0 + */ + public function add_metaboxes() { + + // Get all Achievement Types + $badge_post_types = badgeos_get_achievement_types_slugs(); + foreach ( $badge_post_types as $post_type ) { + + add_meta_box( + 'mycred_badgeos_' . $post_type . '_' . $this->mycred_type, + $this->core->plural(), + array( $this, 'render_meta_box' ), + $post_type, + 'side', + 'core' + ); + + } + + } + + /** + * Render Meta Box + * @since 1.0.8 + * @version 1.1 + */ + public function render_meta_box( $post ) { + + // Setup is needed + if ( ! isset( $this->prefs[ $post->post_type ] ) ) { + + $page = MYCRED_SLUG . '-hooks'; + if ( ! $this->is_main_type ) + $page = MYCRED_SLUG . '_' . $this->mycred_type . '-hooks'; + + echo '

    ' . sprintf( __( 'Please setup your default settings before using this feature.', 'mycred' ), admin_url( 'admin.php?page=' . $page ) ) . '

    '; + return; + + } + + $post_key = 'mycred_values' . $this->mycred_type; + + // Prep Achievement Data + $prefs = $this->prefs; + $achievement_data = mycred_get_post_meta( $post->ID, $this->metakey, true ); + if ( $achievement_data == '' ) + $achievement_data = $prefs[ $post->post_type ]; + +?> +

    core->template_tags_general( __( '%plural% to Award', 'mycred' ) ); ?>

    - - - + + +

    -

    +

    - - + +

    - prefs[ $post->post_type ]['deduct'] == 1 ) { + // If deduction is enabled + if ( $this->prefs[ $post->post_type ]['deduct'] == 1 ) { - ?> -

    +?> +

    - - + +

    - mycred_type; - - // Make sure preference is set - if (! isset($this->prefs[ $post_type ]) || ! isset($_POST[ $post_key ]['creds']) || ! isset($_POST[ $post_key ]['log']) ) { - return; - } - - // Only save if the settings differ, otherwise we default - if ($_POST[ $post_key ]['creds'] == $this->prefs[ $post_type ]['creds'] && $_POST[ $post_key ]['log'] == $this->prefs[ $post_type ]['log'] ) { - - mycred_delete_post_meta($post_id, $this->metakey); - return; - - } - - $data = array(); - - // Creds - if (! empty($_POST[ $post_key ]['creds']) && $_POST[ $post_key ]['creds'] != $this->prefs[ $post_type ]['creds'] ) { - $data['creds'] = $this->core->number($_POST[ $post_key ]['creds']); - } else { - $data['creds'] = $this->core->number($this->prefs[ $post_type ]['creds']); - } - - // Log template - if (! empty($_POST[ $post_key ]['log']) && $_POST[ $post_key ]['log'] != $this->prefs[ $post_type ]['log'] ) { - $data['log'] = sanitize_text_field($_POST[ $post_key ]['log']); - } else { - $data['log'] = sanitize_text_field($this->prefs[ $post_type ]['log']); - } - - // If deduction is enabled save log template - if ($this->prefs[ $post_type ]['deduct'] == 1 ) { - if (! empty($_POST[ $post_key ]['deduct_log']) && $_POST[ $post_key ]['deduct_log'] != $this->prefs[ $post_type ]['deduct_log'] ) { - $data['deduct_log'] = sanitize_text_field($_POST[ $post_key ]['deduct_log']); - } else { - $data['deduct_log'] = sanitize_text_field($this->prefs[ $post_type ]['deduct_log']); - } - } - - // Update sales values - mycred_update_post_meta($post_id, $this->metakey, $data); - - } - - /** - * Award Achievement - * Run by BadgeOS when ever needed, we make sure settings are not zero otherwise - * award points whenever this hook fires. - * - * @since 1.0.8 - * @version 1.1 - */ - public function award_achievent( $user_id, $achievement_id ) - { - - $post_type = mycred_get_post_type($achievement_id); - - // Settings are not set - if (! isset($this->prefs[ $post_type ]['creds']) ) { return; - } - - // Get achievemen data - $achievement_data = mycred_get_post_meta($achievement_id, $this->metakey, true); - if ($achievement_data == '' ) { - $achievement_data = $this->prefs[ $post_type ]; - } - - // Make sure its not disabled - if ($achievement_data['creds'] == 0 ) { return; - } - - // Execute - $post_type_object = get_post_type_object($post_type); - $this->core->add_creds( - $post_type_object->labels->name, - $user_id, - $achievement_data['creds'], - $achievement_data['log'], - $achievement_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - - } - - /** - * Revoke Achievement - * Run by BadgeOS when a users achievement is revoed. - * - * @since 1.0.8 - * @version 1.2 - */ - public function revoke_achievement( $user_id, $achievement_id ) - { - - $post_type = mycred_get_post_type($achievement_id); - - // Settings are not set - if (! isset($this->prefs[ $post_type ]['creds']) ) { return; - } - - // Get achievemen data - $achievement_data = mycred_get_post_meta($achievement_id, $this->metakey, true); - if ($achievement_data == '' ) { - $achievement_data = $this->prefs[ $post_type ]; - } - - // Make sure its not disabled - if ($achievement_data['creds'] == 0 ) { return; - } - - // Execute - $post_type_object = get_post_type_object($post_type); - $this->core->add_creds( - $post_type_object->labels->name, - $user_id, - 0 - $achievement_data['creds'], - $achievement_data['deduct_log'], - $achievement_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - - } - - /** - * Preferences for BadgeOS - * - * @since 1.0.8 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - $badge_post_types = badgeos_get_achievement_types_slugs(); - - foreach ( $badge_post_types as $post_type ) { - - if (in_array($post_type, apply_filters('mycred_badgeos_excludes', array( 'step' ))) ) { continue; - } - - if (! isset($prefs[ $post_type ]) ) { - $prefs[ $post_type ] = array( - 'creds' => 10, - 'log' => '', - 'deduct' => 1, - 'deduct_log' => '%plural% for revoked achievement' - ); - } - - $post_type_object = get_post_type_object($post_type); - - ?> +mycred_type; + + // Make sure preference is set + if ( ! isset( $this->prefs[ $post_type ] ) || ! isset( $_POST[ $post_key ]['creds'] ) || ! isset( $_POST[ $post_key ]['log'] ) ) + return; + + // Only save if the settings differ, otherwise we default + if ( $_POST[ $post_key ]['creds'] == $this->prefs[ $post_type ]['creds'] && $_POST[ $post_key ]['log'] == $this->prefs[ $post_type ]['log'] ) { + + mycred_delete_post_meta( $post_id, $this->metakey ); + return; + + } + + $data = array(); + + // Creds + if ( ! empty( $_POST[ $post_key ]['creds'] ) && $_POST[ $post_key ]['creds'] != $this->prefs[ $post_type ]['creds'] ) + $data['creds'] = $this->core->number( $_POST[ $post_key ]['creds'] ); + else + $data['creds'] = $this->core->number( $this->prefs[ $post_type ]['creds'] ); + + // Log template + if ( ! empty( $_POST[ $post_key ]['log'] ) && $_POST[ $post_key ]['log'] != $this->prefs[ $post_type ]['log'] ) + $data['log'] = sanitize_text_field( $_POST[ $post_key ]['log'] ); + else + $data['log'] = sanitize_text_field( $this->prefs[ $post_type ]['log'] ); + + // If deduction is enabled save log template + if ( $this->prefs[ $post_type ]['deduct'] == 1 ) { + if ( ! empty( $_POST[ $post_key ]['deduct_log'] ) && $_POST[ $post_key ]['deduct_log'] != $this->prefs[ $post_type ]['deduct_log'] ) + $data['deduct_log'] = sanitize_text_field( $_POST[ $post_key ]['deduct_log'] ); + else + $data['deduct_log'] = sanitize_text_field( $this->prefs[ $post_type ]['deduct_log'] ); + } + + // Update sales values + mycred_update_post_meta( $post_id, $this->metakey, $data ); + + } + + /** + * Award Achievement + * Run by BadgeOS when ever needed, we make sure settings are not zero otherwise + * award points whenever this hook fires. + * @since 1.0.8 + * @version 1.1 + */ + public function award_achievent( $user_id, $achievement_id ) { + + $post_type = mycred_get_post_type( $achievement_id ); + + // Settings are not set + if ( ! isset( $this->prefs[ $post_type ]['creds'] ) ) return; + + // Get achievemen data + $achievement_data = mycred_get_post_meta( $achievement_id, $this->metakey, true ); + if ( $achievement_data == '' ) + $achievement_data = $this->prefs[ $post_type ]; + + // Make sure its not disabled + if ( $achievement_data['creds'] == 0 ) return; + + // Execute + $post_type_object = get_post_type_object( $post_type ); + $this->core->add_creds( + $post_type_object->labels->name, + $user_id, + $achievement_data['creds'], + $achievement_data['log'], + $achievement_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + + } + + /** + * Revoke Achievement + * Run by BadgeOS when a users achievement is revoed. + * @since 1.0.8 + * @version 1.2 + */ + public function revoke_achievement( $user_id, $achievement_id ) { + + $post_type = mycred_get_post_type( $achievement_id ); + + // Settings are not set + if ( ! isset( $this->prefs[ $post_type ]['creds'] ) ) return; + + // Get achievemen data + $achievement_data = mycred_get_post_meta( $achievement_id, $this->metakey, true ); + if ( $achievement_data == '' ) + $achievement_data = $this->prefs[ $post_type ]; + + // Make sure its not disabled + if ( $achievement_data['creds'] == 0 ) return; + + // Execute + $post_type_object = get_post_type_object( $post_type ); + $this->core->add_creds( + $post_type_object->labels->name, + $user_id, + 0 - $achievement_data['creds'], + $achievement_data['deduct_log'], + $achievement_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + + } + + /** + * Preferences for BadgeOS + * @since 1.0.8 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + $badge_post_types = badgeos_get_achievement_types_slugs(); + + foreach ( $badge_post_types as $post_type ) { + + if ( in_array( $post_type, apply_filters( 'mycred_badgeos_excludes', array( 'step' ) ) ) ) continue; + + if ( ! isset( $prefs[ $post_type ] ) ) + $prefs[ $post_type ] = array( + 'creds' => 10, + 'log' => '', + 'deduct' => 1, + 'deduct_log' => '%plural% for revoked achievement' + ); + + $post_type_object = get_post_type_object( $post_type ); + +?>
    -

    labels->singular_name); ?>

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    labels->singular_name ); ?>

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    -

    labels->singular_name); ?>

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    labels->singular_name ); ?>

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - 'bbPress', - 'description' => __('Awards %_plural% for bbPress actions.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/bbpress-actions/', - 'callback' => array( 'myCRED_bbPress' ) - ); + $installed['hook_bbpress'] = array( + 'title' => 'bbPress', + 'description' => __( 'Awards %_plural% for bbPress actions.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/bbpress-actions/', + 'callback' => array( 'myCRED_bbPress' ) + ); - return $installed; + return $installed; } /** * bbPress Hook - * - * @since 0.1 + * @since 0.1 * @version 1.4.4 */ -add_action('mycred_load_hooks', 'mycred_load_bbpress_hook', 20); -function mycred_load_bbpress_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_bbPress') || ! class_exists('bbPress') ) { return; - } - - class myCRED_bbPress extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'hook_bbpress', - 'defaults' => array( - 'new_forum' => array( - 'creds' => 1, - 'log' => '%plural% for new forum', - 'limit' => '0/x' - ), - 'delete_forum' => array( - 'creds' => 0, - 'log' => '%singular% deduction for deleted forum' - ), - 'new_topic' => array( - 'creds' => 1, - 'log' => '%plural% for new forum topic', - 'author' => 0, - 'limit' => '0/x' - ), - 'delete_topic' => array( - 'creds' => 0, - 'log' => '%singular% deduction for deleted topic' - ), - 'fav_topic' => array( - 'creds' => 1, - 'log' => '%plural% for someone favorited your forum topic', - 'limit' => '0/x' - ), - 'new_reply' => array( - 'creds' => 1, - 'log' => '%plural% for new forum reply', - 'author' => 0, - 'limit' => '0/x' - ), - 'delete_reply' => array( - 'creds' => 0, - 'log' => '%singular% deduction for deleted reply' - ), - 'show_points_in_reply' => 0, - 'show_points_in_profile' => 0 - ) - ), $hook_prefs, $type - ); - - add_filter('mycred_post_type_excludes', array( $this, 'exclude_post_type' )); - - } - - /** - * Run - * - * @since 0.1 - * @version 1.2.1 - */ - public function run() - { - - // Insert Points balance in profile - if (isset($this->prefs['show_points_in_reply']) && $this->prefs['show_points_in_reply'] == 1 ) { - add_action('bbp_theme_after_reply_author_details', array( $this, 'insert_balance_reply' )); - } - - if (isset($this->prefs['show_points_in_profile']) && $this->prefs['show_points_in_profile'] == 1 ) { - add_action('bbp_template_after_user_profile', array( $this, 'insert_balance_profile' )); - } - - // New Forum - if ($this->prefs['new_forum']['creds'] != 0 ) { - add_action('bbp_new_forum', array( $this, 'new_forum' ), 20); - } - - // Delete Forum - if ($this->prefs['delete_forum']['creds'] != 0 ) { - add_action('bbp_delete_forum', array( $this, 'delete_forum' )); - } - - // New Topic - if ($this->prefs['new_topic']['creds'] != 0 ) { - add_action('bbp_new_topic', array( $this, 'new_topic' ), 20, 4); - } - - // Delete Topic - if ($this->prefs['delete_topic']['creds'] != 0 ) { - add_action('bbp_delete_topic', array( $this, 'delete_topic' )); - } - - // Fave Topic - if ($this->prefs['fav_topic']['creds'] != 0 ) { - add_action('bbp_add_user_favorite', array( $this, 'fav_topic' ), 10, 2); - } - - // New Reply - if ($this->prefs['new_reply']['creds'] != 0 ) { - add_action('bbp_new_reply', array( $this, 'new_reply' ), 20, 5); - } - - // Delete Reply - if ($this->prefs['delete_reply']['creds'] != 0 ) { - add_action('bbp_delete_reply', array( $this, 'delete_reply' )); - } - - } - - /** - * Exclude bbPress Post Types - * - * @since 0.1 - * @version 1.0 - */ - public function exclude_post_type( $excludes ) - { - - $excludes[] = bbp_get_forum_post_type(); - $excludes[] = bbp_get_topic_post_type(); - $excludes[] = bbp_get_reply_post_type(); - - return $excludes; - - } - - /** - * Insert Balance in bbPress Profiles - * - * @since 1.1.1 - * @version 1.2 - */ - public function insert_balance_profile() - { - - $user_id = bbp_get_displayed_user_id(); - - if ($this->core->exclude_user($user_id) || $user_id == 0 ) { return; - } - - $balance = $this->core->get_users_balance($user_id, $this->mycred_type); - $layout = $this->core->plural() . ': ' . $this->core->format_creds($balance); - - echo apply_filters('mycred_bbp_profile_balance', '
    ' . $layout . '
    ', $layout, $user_id, $this); - - } - - /** - * Insert Balance - * - * @since 0.1 - * @version 1.2.1 - */ - public function insert_balance_reply() - { - - $reply_id = bbp_get_reply_id(); - - // Skip Anonymous replies - if (bbp_is_reply_anonymous($reply_id) ) { return; - } - - // Get reply author - $user_id = bbp_get_reply_author_id($reply_id); - - // Check for exclusions and guests - if ($this->core->exclude_user($user_id) || $user_id == 0 ) { return; - } - - $balance = $this->core->get_users_balance($user_id, $this->mycred_type); - $layout = $this->core->plural() . ': ' . $this->core->format_creds($balance); - - echo apply_filters('mycred_bbp_reply_balance', '
    ' . $layout . '
    ', $layout, $user_id, $this); - - } - - /** - * New Forum - * - * @since 1.1.1 - * @version 1.2 - */ - public function new_forum( $forum ) - { - - // Forum id - $forum_id = $forum['forum_id']; - - // Forum author - $forum_author = $forum['forum_author']; - - // Check if user is excluded - if ($this->core->exclude_user($forum_author) ) { return; - } - - // Limit - if ($this->over_hook_limit('new_forum', 'new_forum', $forum_author) ) { return; - } - - // Make sure this is unique event - if ($this->bbpress_has_entry('new_forum', $forum_id, $forum_author) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_forum', - $forum_author, - $this->prefs['new_forum']['creds'], - $this->prefs['new_forum']['log'], - $forum_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - - } - - /** - * Delete Forum - * - * @since 1.2 - * @version 1.1 - */ - public function delete_forum( $forum_id ) - { - - // Get Author - $forum_author = bbp_get_forum_author_id($forum_id); - - // If gained, points, deduct - if ($this->bbpress_has_entry('new_forum', $forum_id, $forum_author) ) { - - // Execute - $this->core->add_creds( - 'deleted_forum', - $forum_author, - $this->prefs['delete_forum']['creds'], - $this->prefs['delete_forum']['log'], - $forum_id, - '', - $this->mycred_type - ); - - } - - } - - /** - * New Topic - * - * @since 0.1 - * @version 1.2 - */ - public function new_topic( $topic_id, $forum_id, $anonymous_data, $topic_author ) - { - - // Check if user is excluded - if ($this->core->exclude_user($topic_author) ) { return; - } - - // Check if forum author is allowed to get points for their own topics - if ((bool) $this->prefs['new_topic']['author'] == false ) { - if (bbp_get_forum_author_id($forum_id) == $topic_author ) { return; - } - } - - // Limit - if ($this->over_hook_limit('new_topic', 'new_forum_topic', $topic_author) ) { return; - } - - // Make sure this is unique event - if ($this->bbpress_has_entry('new_forum_topic', $topic_id, $topic_author) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_forum_topic', - $topic_author, - $this->prefs['new_topic']['creds'], - $this->prefs['new_topic']['log'], - $topic_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - - } - - /** - * Delete Topic - * - * @since 1.2 - * @version 1.1 - */ - public function delete_topic( $topic_id ) - { - - // Get Author - $topic_author = bbp_get_topic_author_id($topic_id); - - // If gained, points, deduct - if ($this->bbpress_has_entry('new_forum_topic', $topic_id, $topic_author) ) { - - // Execute - $this->core->add_creds( - 'deleted_topic', - $topic_author, - $this->prefs['delete_topic']['creds'], - $this->prefs['delete_topic']['log'], - $topic_id, - '', - $this->mycred_type - ); - - } - - } - - /** - * Topic Added to Favorites - * - * @by Fee (http://wordpress.org/support/profile/wdfee) - * @since 1.1.1 - * @version 1.5 - */ - public function fav_topic( $user_id, $topic_id ) - { - - // $user_id is loggedin_user, not author, so get topic author - $topic_author = get_post_field('post_author', $topic_id); - - // Check if user is excluded (required) - if ($this->core->exclude_user($topic_author) || $topic_author == $user_id ) { return; - } - - // Limit - if ($this->over_hook_limit('fav_topic', 'topic_favorited', $topic_author) ) { return; - } - - // Make sure this is a unique event (favorite not from same user) - $data = array( 'ref_user' => $user_id, 'ref_type' => 'post' ); - if ($this->bbpress_has_entry('topic_favorited', $topic_id, $topic_author, $data) ) { return; - } - - // Execute - $this->core->add_creds( - 'topic_favorited', - $topic_author, - $this->prefs['fav_topic']['creds'], - $this->prefs['fav_topic']['log'], - $topic_id, - $data, - $this->mycred_type - ); - - } - - /** - * New Reply - * - * @since 0.1 - * @version 1.5 - */ - public function new_reply( $reply_id, $topic_id, $forum_id, $anonymous_data, $reply_author ) - { - - // Check if user is excluded - if ($this->core->exclude_user($reply_author) ) { return; - } - - // Check if topic author gets points for their own replies - if ((bool) $this->prefs['new_reply']['author'] === false && bbp_get_topic_author_id($topic_id) == $reply_author ) { return; - } - - // Limit - if ($this->over_hook_limit('new_reply', 'new_forum_reply', $reply_author) ) { return; - } - - // Make sure this is unique event - if ($this->bbpress_has_entry('new_forum_reply', $reply_id, $reply_author) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_forum_reply', - $reply_author, - $this->prefs['new_reply']['creds'], - $this->prefs['new_reply']['log'], - $reply_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - - } - - /** - * Delete Reply - * - * @since 1.2 - * @version 1.2.1 - */ - public function delete_reply( $reply_id ) - { - - // Get Author - $reply_author = bbp_get_reply_author_id($reply_id); - - // If gained, points, deduct - if ($this->bbpress_has_entry('new_forum_reply', $reply_id, $reply_author) ) { - - // Execute - $this->core->add_creds( - 'deleted_reply', - $reply_author, - $this->prefs['delete_reply']['creds'], - $this->prefs['delete_reply']['log'], - $reply_id, - '', - $this->mycred_type - ); - - } - - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.3 - */ - public function preferences() - { - - $prefs = $this->prefs; - - if (! isset($prefs['new_forum']['limit']) ) { - $prefs['new_forum']['limit'] = '0/x'; - } - - if (! isset($prefs['new_topic']['limit']) ) { - $prefs['new_topic']['limit'] = '0/x'; - } - - if (! isset($prefs['fav_topic']['limit']) ) { - $prefs['fav_topic']['limit'] = '0/x'; - } - - if (! isset($prefs['new_reply']['limit']) ) { - $prefs['new_reply']['limit'] = '0/x'; - } - - ?> +add_action( 'mycred_load_hooks', 'mycred_load_bbpress_hook', 20 ); +function mycred_load_bbpress_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_bbPress' ) || ! class_exists( 'bbPress' ) ) return; + + class myCRED_bbPress extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'hook_bbpress', + 'defaults' => array( + 'new_forum' => array( + 'creds' => 1, + 'log' => '%plural% for new forum', + 'limit' => '0/x' + ), + 'delete_forum' => array( + 'creds' => 0, + 'log' => '%singular% deduction for deleted forum' + ), + 'new_topic' => array( + 'creds' => 1, + 'log' => '%plural% for new forum topic', + 'author' => 0, + 'limit' => '0/x' + ), + 'delete_topic' => array( + 'creds' => 0, + 'log' => '%singular% deduction for deleted topic' + ), + 'fav_topic' => array( + 'creds' => 1, + 'log' => '%plural% for someone favorited your forum topic', + 'limit' => '0/x' + ), + 'new_reply' => array( + 'creds' => 1, + 'log' => '%plural% for new forum reply', + 'author' => 0, + 'limit' => '0/x' + ), + 'delete_reply' => array( + 'creds' => 0, + 'log' => '%singular% deduction for deleted reply' + ), + 'show_points_in_reply' => 0, + 'show_points_in_profile' => 0 + ) + ), $hook_prefs, $type ); + + add_filter( 'mycred_post_type_excludes', array( $this, 'exclude_post_type' ) ); + + } + + /** + * Run + * @since 0.1 + * @version 1.2.1 + */ + public function run() { + + // Insert Points balance in profile + if ( isset( $this->prefs['show_points_in_reply'] ) && $this->prefs['show_points_in_reply'] == 1 ) + add_action( 'bbp_theme_after_reply_author_details', array( $this, 'insert_balance_reply' ) ); + + if ( isset( $this->prefs['show_points_in_profile'] ) && $this->prefs['show_points_in_profile'] == 1 ) + add_action( 'bbp_template_after_user_profile', array( $this, 'insert_balance_profile' ) ); + + // New Forum + if ( $this->prefs['new_forum']['creds'] != 0 ) + add_action( 'bbp_new_forum', array( $this, 'new_forum' ), 20 ); + + // Delete Forum + if ( $this->prefs['delete_forum']['creds'] != 0 ) + add_action( 'bbp_delete_forum', array( $this, 'delete_forum' ) ); + + // New Topic + if ( $this->prefs['new_topic']['creds'] != 0 ) + add_action( 'bbp_new_topic', array( $this, 'new_topic' ), 20, 4 ); + + // Delete Topic + if ( $this->prefs['delete_topic']['creds'] != 0 ) + add_action( 'bbp_delete_topic', array( $this, 'delete_topic' ) ); + + // Fave Topic + if ( $this->prefs['fav_topic']['creds'] != 0 ) + add_action( 'bbp_add_user_favorite', array( $this, 'fav_topic' ), 10, 2 ); + + // New Reply + if ( $this->prefs['new_reply']['creds'] != 0 ) + add_action( 'bbp_new_reply', array( $this, 'new_reply' ), 20, 5 ); + + // Delete Reply + if ( $this->prefs['delete_reply']['creds'] != 0 ) + add_action( 'bbp_delete_reply', array( $this, 'delete_reply' ) ); + + } + + /** + * Exclude bbPress Post Types + * @since 0.1 + * @version 1.0 + */ + public function exclude_post_type( $excludes ) { + + $excludes[] = bbp_get_forum_post_type(); + $excludes[] = bbp_get_topic_post_type(); + $excludes[] = bbp_get_reply_post_type(); + + return $excludes; + + } + + /** + * Insert Balance in bbPress Profiles + * @since 1.1.1 + * @version 1.2 + */ + public function insert_balance_profile() { + + $user_id = bbp_get_displayed_user_id(); + + if ( $this->core->exclude_user( $user_id ) || $user_id == 0 ) return; + + $balance = $this->core->get_users_balance( $user_id, $this->mycred_type ); + $layout = $this->core->plural() . ': ' . $this->core->format_creds( $balance ); + + echo apply_filters( 'mycred_bbp_profile_balance', '
    ' . $layout . '
    ', $layout, $user_id, $this ); + + } + + /** + * Insert Balance + * @since 0.1 + * @version 1.2.1 + */ + public function insert_balance_reply() { + + $reply_id = bbp_get_reply_id(); + + // Skip Anonymous replies + if ( bbp_is_reply_anonymous( $reply_id ) ) return; + + // Get reply author + $user_id = bbp_get_reply_author_id( $reply_id ); + + // Check for exclusions and guests + if ( $this->core->exclude_user( $user_id ) || $user_id == 0 ) return; + + $balance = $this->core->get_users_balance( $user_id, $this->mycred_type ); + $layout = $this->core->plural() . ': ' . $this->core->format_creds( $balance ); + + echo apply_filters( 'mycred_bbp_reply_balance', '
    ' . $layout . '
    ', $layout, $user_id, $this ); + + } + + /** + * New Forum + * @since 1.1.1 + * @version 1.2 + */ + public function new_forum( $forum ) { + + // Forum id + $forum_id = $forum['forum_id']; + + // Forum author + $forum_author = $forum['forum_author']; + + // Check if user is excluded + if ( $this->core->exclude_user( $forum_author ) ) return; + + // Limit + if ( $this->over_hook_limit( 'new_forum', 'new_forum', $forum_author ) ) return; + + // Make sure this is unique event + if ( $this->bbpress_has_entry( 'new_forum', $forum_id, $forum_author ) ) return; + + // Execute + $this->core->add_creds( + 'new_forum', + $forum_author, + $this->prefs['new_forum']['creds'], + $this->prefs['new_forum']['log'], + $forum_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + + } + + /** + * Delete Forum + * @since 1.2 + * @version 1.1 + */ + public function delete_forum( $forum_id ) { + + // Get Author + $forum_author = bbp_get_forum_author_id( $forum_id ); + + // If gained, points, deduct + if ( $this->bbpress_has_entry( 'new_forum', $forum_id, $forum_author ) ) { + + // Execute + $this->core->add_creds( + 'deleted_forum', + $forum_author, + $this->prefs['delete_forum']['creds'], + $this->prefs['delete_forum']['log'], + $forum_id, + '', + $this->mycred_type + ); + + } + + } + + /** + * New Topic + * @since 0.1 + * @version 1.2 + */ + public function new_topic( $topic_id, $forum_id, $anonymous_data, $topic_author ) { + + // Check if user is excluded + if ( $this->core->exclude_user( $topic_author ) ) return; + + // Check if forum author is allowed to get points for their own topics + if ( (bool) $this->prefs['new_topic']['author'] == false ) { + if ( bbp_get_forum_author_id( $forum_id ) == $topic_author ) return; + } + + // Limit + if ( $this->over_hook_limit( 'new_topic', 'new_forum_topic', $topic_author ) ) return; + + // Make sure this is unique event + if ( $this->bbpress_has_entry( 'new_forum_topic', $topic_id, $topic_author ) ) return; + + // Execute + $this->core->add_creds( + 'new_forum_topic', + $topic_author, + $this->prefs['new_topic']['creds'], + $this->prefs['new_topic']['log'], + $topic_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + + } + + /** + * Delete Topic + * @since 1.2 + * @version 1.1 + */ + public function delete_topic( $topic_id ) { + + // Get Author + $topic_author = bbp_get_topic_author_id( $topic_id ); + + // If gained, points, deduct + if ( $this->bbpress_has_entry( 'new_forum_topic', $topic_id, $topic_author ) ) { + + // Execute + $this->core->add_creds( + 'deleted_topic', + $topic_author, + $this->prefs['delete_topic']['creds'], + $this->prefs['delete_topic']['log'], + $topic_id, + '', + $this->mycred_type + ); + + } + + } + + /** + * Topic Added to Favorites + * @by Fee (http://wordpress.org/support/profile/wdfee) + * @since 1.1.1 + * @version 1.5 + */ + public function fav_topic( $user_id, $topic_id ) { + + // $user_id is loggedin_user, not author, so get topic author + $topic_author = get_post_field( 'post_author', $topic_id ); + + // Check if user is excluded (required) + if ( $this->core->exclude_user( $topic_author ) || $topic_author == $user_id ) return; + + // Limit + if ( $this->over_hook_limit( 'fav_topic', 'topic_favorited', $topic_author ) ) return; + + // Make sure this is a unique event (favorite not from same user) + $data = array( 'ref_user' => $user_id, 'ref_type' => 'post' ); + if ( $this->bbpress_has_entry( 'topic_favorited', $topic_id, $topic_author, $data ) ) return; + + // Execute + $this->core->add_creds( + 'topic_favorited', + $topic_author, + $this->prefs['fav_topic']['creds'], + $this->prefs['fav_topic']['log'], + $topic_id, + $data, + $this->mycred_type + ); + + } + + /** + * New Reply + * @since 0.1 + * @version 1.5 + */ + public function new_reply( $reply_id, $topic_id, $forum_id, $anonymous_data, $reply_author ) { + + // Check if user is excluded + if ( $this->core->exclude_user( $reply_author ) ) return; + + // Check if topic author gets points for their own replies + if ( (bool) $this->prefs['new_reply']['author'] === false && bbp_get_topic_author_id( $topic_id ) == $reply_author ) return; + + // Limit + if ( $this->over_hook_limit( 'new_reply', 'new_forum_reply', $reply_author ) ) return; + + // Make sure this is unique event + if ( $this->bbpress_has_entry( 'new_forum_reply', $reply_id, $reply_author ) ) return; + + // Execute + $this->core->add_creds( + 'new_forum_reply', + $reply_author, + $this->prefs['new_reply']['creds'], + $this->prefs['new_reply']['log'], + $reply_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + + } + + /** + * Delete Reply + * @since 1.2 + * @version 1.2.1 + */ + public function delete_reply( $reply_id ) { + + // Get Author + $reply_author = bbp_get_reply_author_id( $reply_id ); + + // If gained, points, deduct + if ( $this->bbpress_has_entry( 'new_forum_reply', $reply_id, $reply_author ) ) { + + // Execute + $this->core->add_creds( + 'deleted_reply', + $reply_author, + $this->prefs['delete_reply']['creds'], + $this->prefs['delete_reply']['log'], + $reply_id, + '', + $this->mycred_type + ); + + } + + } + + /** + * Preferences + * @since 0.1 + * @version 1.3 + */ + public function preferences() { + + $prefs = $this->prefs; + + if ( ! isset( $prefs['new_forum']['limit'] ) ) + $prefs['new_forum']['limit'] = '0/x'; + + if ( ! isset( $prefs['new_topic']['limit'] ) ) + $prefs['new_topic']['limit'] = '0/x'; + + if ( ! isset( $prefs['fav_topic']['limit'] ) ) + $prefs['fav_topic']['limit'] = '0/x'; + + if ( ! isset( $prefs['new_reply']['limit'] ) ) + $prefs['new_reply']['limit'] = '0/x'; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_forum', 'limit' )), $this->field_id(array( 'new_forum', 'limit' )), $prefs['new_forum']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_forum', 'limit' ) ), $this->field_id( array( 'new_forum', 'limit' ) ), $prefs['new_forum']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_topic', 'limit' )), $this->field_id(array( 'new_topic', 'limit' )), $prefs['new_topic']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_topic', 'limit' ) ), $this->field_id( array( 'new_topic', 'limit' ) ), $prefs['new_topic']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'fav_topic', 'limit' )), $this->field_id(array( 'fav_topic', 'limit' )), $prefs['fav_topic']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'fav_topic', 'limit' ) ), $this->field_id( array( 'fav_topic', 'limit' ) ), $prefs['fav_topic']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_reply', 'limit' )), $this->field_id(array( 'new_reply', 'limit' )), $prefs['new_reply']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_reply', 'limit' ) ), $this->field_id( array( 'new_reply', 'limit' ) ), $prefs['new_reply']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -
    -
    -
    -
    - -
    -
    - -
    -
    -
    -
    +
    +
    +
    +
    + +
    +
    + +
    +
    +
    +
    - prepare("ref = %s", $reference); - } - - if ($ref_id !== null ) { - $wheres[] = $wpdb->prepare("ref_id = %d", $ref_id); - } - - if ($user_id !== null ) { - $wheres[] = $wpdb->prepare("user_id = %d", $user_id); - } - - // if ( $data !== NULL ) - // $wheres[] = $wpdb->prepare( "data = %s", maybe_serialize( $data ) ); - - if ($type === null ) { $type = $this->get_point_type_key(); - } - $wheres[] = $wpdb->prepare("ctype = %s", $type); - - $where = implode(' AND ', $wheres); - - if (! empty($wheres) ) { - - $check = $wpdb->get_var("SELECT id FROM {$wpdb->prefix}myCRED_log WHERE {$where};"); - if ($check !== null ) { - $has_entry = true; - } - - } - - } - - return $has_entry; - - - } - - } +prepare( "ref = %s", $reference ); + + if ( $ref_id !== NULL ) + $wheres[] = $wpdb->prepare( "ref_id = %d", $ref_id ); + + if ( $user_id !== NULL ) + $wheres[] = $wpdb->prepare( "user_id = %d", $user_id ); + + // if ( $data !== NULL ) + // $wheres[] = $wpdb->prepare( "data = %s", maybe_serialize( $data ) ); + + if ( $type === NULL ) $type = $this->get_point_type_key(); + $wheres[] = $wpdb->prepare( "ctype = %s", $type ); + + $where = implode( ' AND ', $wheres ); + + if ( ! empty( $wheres ) ) { + + $check = $wpdb->get_var( "SELECT id FROM {$wpdb->prefix}myCRED_log WHERE {$where};" ); + if ( $check !== NULL ) + $has_entry = true; + + } + + } + + return $has_entry; + + + } + + } } diff --git a/includes/hooks/external/mycred-hook-buddypress-media.php b/includes/hooks/external/mycred-hook-buddypress-media.php index e4beb75..9bd99be 100644 --- a/includes/hooks/external/mycred-hook-buddypress-media.php +++ b/includes/hooks/external/mycred-hook-buddypress-media.php @@ -1,503 +1,453 @@ __('rtMedia Galleries', 'mycred'), - 'description' => __('Award / Deduct %_plural% for users creating albums or uploading new photos.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/rtmedia-uploads/', - 'callback' => array( 'myCRED_rtMedia' ) - ); + $installed['rtmedia'] = array( + 'title' => __( 'rtMedia Galleries', 'mycred' ), + 'description' => __( 'Award / Deduct %_plural% for users creating albums or uploading new photos.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/rtmedia-uploads/', + 'callback' => array( 'myCRED_rtMedia' ) + ); - return $installed; + return $installed; } /** * rtMedia Hook - * - * @since 1.4 + * @since 1.4 * @version 1.1.1 */ -add_action('mycred_load_hooks', 'mycred_load_buddypress_media_hook', 35); -function mycred_load_buddypress_media_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_rtMedia') || ! function_exists('rtmedia_autoloader') ) { return; - } - - class myCRED_rtMedia extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'rtmedia', - 'defaults' => array( - 'new_media' => array( - 'photo' => 0, - 'photo_log' => '%plural% for new photo', - 'photo_limit' => '0/x', - 'video' => 0, - 'video_log' => '%plural% for new video', - 'video_limit' => '0/x', - 'music' => 0, - 'music_log' => '%plural% for new music', - 'music_limit' => '0/x', - ), - 'delete_media' => array( - 'photo' => 0, - 'photo_log' => '%plural% for deleting photo', - 'video' => 0, - 'video_log' => '%plural% for deleting video', - 'music' => 0, - 'music_log' => '%plural% for deleting music' - ) - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.4 - * @version 1.0.1 - */ - public function run() - { - - add_action('rtmedia_after_add_media', array( $this, 'new_media' )); - add_action('rtmedia_before_delete_media', array( $this, 'delete_media' )); - - } - - /** - * New Media - * - * @since 1.4 - * @version 1.2.2 - */ - public function new_media( $media_ids ) - { - - // Loop through all uploaded files - foreach ( $media_ids as $media_id ) { - - // Get media details from id - $model = new RTMediaModel(); - $media = $model->get_media(array( 'id' => $media_id )); - - if (! isset($media[0]->media_type) ) { continue; - } - - $reference = $media[0]->media_type . '_upload'; - $user_id = $media[0]->media_author; - - if ($this->core->exclude_user($user_id) ) { continue; - } - - $points = $this->prefs['new_media'][ $media[0]->media_type ]; - $log_entry = $this->prefs['new_media'][ $media[0]->media_type . '_log' ]; - $data = array( 'ref_type' => 'media', 'attachment_id' => $media_id ); - - // If this media type awards zero, bail - if ($points == $this->core->zero() ) { continue; - } - - // Limit - if ($this->over_hook_limit($media[0]->media_type . '_limit', $reference, $user_id) ) { continue; - } - - // Make sure this is unique - if (! $this->core->has_entry($reference, $media_id, $user_id) ) { - $this->core->add_creds( - $reference, - $user_id, - $points, - $log_entry, - $media_id, - $data, - $this->mycred_type - ); - } - - } - - } - - /** - * Delete Media - * - * @since 1.4 - * @version 1.1.2 - */ - public function delete_media( $media_id ) - { - - // Get media details from id - $model = new RTMediaModel(); - $media = $model->get_media(array( 'id' => $media_id )); - - if (! isset($media[0]->media_type) ) { return; - } - - $reference = $media[0]->media_type . '_deletion'; - $user_id = $media[0]->media_author; - $points = $this->prefs['delete_media'][ $media[0]->media_type ]; - $log_entry = $this->prefs['delete_media'][ $media[0]->media_type . '_log' ]; - $data = array( 'ref_type' => 'media', 'attachment_id' => $media_id ); - - // If this media type awards zero, bail - if ($points == $this->core->zero() ) { return; - } - - // Check for exclusion - if ($this->core->exclude_user($user_id) ) { return; - } - - // Only delete points once - if (! $this->core->has_entry($reference, $media_id, $user_id) ) { - $this->core->add_creds( - $reference, - $user_id, - $points, - $log_entry, - $media_id, - $data, - $this->mycred_type - ); - } - - } - - /** - * Check Limit - * - * @since 1.6 - * @version 1.1.1 - */ - function over_hook_limit( $instance = '', $reference = '', $user_id = null, $ref_id = null ) - { - - global $wpdb, $mycred_log_table; - - // Prep - $wheres = array(); - $now = current_time('timestamp'); - - // If hook uses multiple instances - if (isset($this->prefs['new_media'][ $instance ]) ) { - $prefs = $this->prefs['new_media'][ $instance ]; - } - - // no support for limits - else { return false; - } - - if (count(explode('/', $prefs)) != 2 ) { - $prefs = '0/x'; - } - - // Prep settings - list ( $amount, $period ) = explode('/', $prefs); - $amount = (int) $amount; - - // We start constructing the query. - $wheres[] = $wpdb->prepare("user_id = %d", $user_id); - $wheres[] = $wpdb->prepare("ref = %s", $reference); - $wheres[] = $wpdb->prepare("ctype = %s", $this->mycred_type); - - // If check is based on time - if (! in_array($period, array( 't', 'x' )) ) { - - // Per day - if ($period == 'd' ) { - $from = mktime(0, 0, 0, date('n', $now), date('j', $now), date('Y', $now)); - } - - // Per week - elseif ($period == 'w' ) { - $from = mktime(0, 0, 0, date("n", $now), date("j", $now) - date("N", $now) + 1); - } - - // Per Month - elseif ($period == 'm' ) { - $from = mktime(0, 0, 0, date("n", $now), 1, date('Y', $now)); - } - - $wheres[] = $wpdb->prepare("time BETWEEN %d AND %d", $from, $now); - - } - - // Put all wheres together into one string - $wheres = implode(" AND ", $wheres); - - // Count - $count = $wpdb->get_var("SELECT COUNT(*) FROM {$mycred_log_table} WHERE {$wheres};"); - if ($count === null ) { $count = 0; - } - - $over_limit = false; - if ($period != 'x' && $count >= $amount ) { - $over_limit = true; - } - - return $over_limit; - - } - - /** - * Adjust Limit Name - * - * @since 1.6 - * @version 1.0 - */ - public function hook_limit_name( $name ) - { - - $name = str_replace('[photo_limit]', '[photo_limit_by]', $name); - $name = str_replace('[video_limit]', '[video_limit_by]', $name); - $name = str_replace('[music_limit]', '[music_limit_by]', $name); - return $name; - - } - - /** - * Adjust Limit ID - * - * @since 1.6 - * @version 1.0 - */ - public function hook_limit_id( $id ) - { - - $id = str_replace('photo-limit', 'photo-limit-by', $id); - $id = str_replace('video-limit', 'video-limit-by', $id); - $id = str_replace('music-limit', 'music-limit-by', $id); - return $id; - - } - - /** - * Preferences for rtMedia Gallery Hook - * - * @since 1.4 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - global $rtmedia; - - $photos = ' readonly="readonly"'; - if (array_key_exists('allowedTypes_photo_enabled', $rtmedia->options) && $rtmedia->options['allowedTypes_photo_enabled'] == 1 ) { - $photos = ''; - } - - $videos = ' readonly="readonly"'; - if (array_key_exists('allowedTypes_video_enabled', $rtmedia->options) && $rtmedia->options['allowedTypes_video_enabled'] == 1 ) { - $videos = ''; - } - - $music = ' readonly="readonly"'; - if (array_key_exists('allowedTypes_music_enabled', $rtmedia->options) && $rtmedia->options['allowedTypes_music_enabled'] == 1 ) { - $music = ''; - } - - add_filter('mycred_hook_limit_name_by', array( $this, 'hook_limit_name' )); - add_filter('mycred_hook_limit_id_by', array( $this, 'hook_limit_id' )); - - ?> +add_action( 'mycred_load_hooks', 'mycred_load_buddypress_media_hook', 35 ); +function mycred_load_buddypress_media_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_rtMedia' ) || ! function_exists( 'rtmedia_autoloader' ) ) return; + + class myCRED_rtMedia extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'rtmedia', + 'defaults' => array( + 'new_media' => array( + 'photo' => 0, + 'photo_log' => '%plural% for new photo', + 'photo_limit' => '0/x', + 'video' => 0, + 'video_log' => '%plural% for new video', + 'video_limit' => '0/x', + 'music' => 0, + 'music_log' => '%plural% for new music', + 'music_limit' => '0/x', + ), + 'delete_media' => array( + 'photo' => 0, + 'photo_log' => '%plural% for deleting photo', + 'video' => 0, + 'video_log' => '%plural% for deleting video', + 'music' => 0, + 'music_log' => '%plural% for deleting music' + ) + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.4 + * @version 1.0.1 + */ + public function run() { + + add_action( 'rtmedia_after_add_media', array( $this, 'new_media' ) ); + add_action( 'rtmedia_before_delete_media', array( $this, 'delete_media' ) ); + + } + + /** + * New Media + * @since 1.4 + * @version 1.2.2 + */ + public function new_media( $media_ids ) { + + // Loop through all uploaded files + foreach ( $media_ids as $media_id ) { + + // Get media details from id + $model = new RTMediaModel(); + $media = $model->get_media( array( 'id' => $media_id ) ); + + if ( ! isset( $media[0]->media_type ) ) continue; + + $reference = $media[0]->media_type . '_upload'; + $user_id = $media[0]->media_author; + + if ( $this->core->exclude_user( $user_id ) ) continue; + + $points = $this->prefs['new_media'][ $media[0]->media_type ]; + $log_entry = $this->prefs['new_media'][ $media[0]->media_type . '_log' ]; + $data = array( 'ref_type' => 'media', 'attachment_id' => $media_id ); + + // If this media type awards zero, bail + if ( $points == $this->core->zero() ) continue; + + // Limit + if ( $this->over_hook_limit( $media[0]->media_type . '_limit', $reference, $user_id ) ) continue; + + // Make sure this is unique + if ( ! $this->core->has_entry( $reference, $media_id, $user_id ) ) + $this->core->add_creds( + $reference, + $user_id, + $points, + $log_entry, + $media_id, + $data, + $this->mycred_type + ); + + } + + } + + /** + * Delete Media + * @since 1.4 + * @version 1.1.2 + */ + public function delete_media( $media_id ) { + + // Get media details from id + $model = new RTMediaModel(); + $media = $model->get_media( array( 'id' => $media_id ) ); + + if ( ! isset( $media[0]->media_type ) ) return; + + $reference = $media[0]->media_type . '_deletion'; + $user_id = $media[0]->media_author; + $points = $this->prefs['delete_media'][ $media[0]->media_type ]; + $log_entry = $this->prefs['delete_media'][ $media[0]->media_type . '_log' ]; + $data = array( 'ref_type' => 'media', 'attachment_id' => $media_id ); + + // If this media type awards zero, bail + if ( $points == $this->core->zero() ) return; + + // Check for exclusion + if ( $this->core->exclude_user( $user_id ) ) return; + + // Only delete points once + if ( ! $this->core->has_entry( $reference, $media_id, $user_id ) ) + $this->core->add_creds( + $reference, + $user_id, + $points, + $log_entry, + $media_id, + $data, + $this->mycred_type + ); + + } + + /** + * Check Limit + * @since 1.6 + * @version 1.1.1 + */ + function over_hook_limit( $instance = '', $reference = '', $user_id = NULL, $ref_id = NULL ) { + + global $wpdb, $mycred_log_table; + + // Prep + $wheres = array(); + $now = current_time( 'timestamp' ); + + // If hook uses multiple instances + if ( isset( $this->prefs['new_media'][ $instance ] ) ) + $prefs = $this->prefs['new_media'][ $instance ]; + + // no support for limits + else return false; + + if ( count( explode( '/', $prefs ) ) != 2 ) + $prefs = '0/x'; + + // Prep settings + list ( $amount, $period ) = explode( '/', $prefs ); + $amount = (int) $amount; + + // We start constructing the query. + $wheres[] = $wpdb->prepare( "user_id = %d", $user_id ); + $wheres[] = $wpdb->prepare( "ref = %s", $reference ); + $wheres[] = $wpdb->prepare( "ctype = %s", $this->mycred_type ); + + // If check is based on time + if ( ! in_array( $period, array( 't', 'x' ) ) ) { + + // Per day + if ( $period == 'd' ) + $from = mktime( 0, 0, 0, date( 'n', $now ), date( 'j', $now ), date( 'Y', $now ) ); + + // Per week + elseif ( $period == 'w' ) + $from = mktime( 0, 0, 0, date( "n", $now ), date( "j", $now ) - date( "N", $now ) + 1 ); + + // Per Month + elseif ( $period == 'm' ) + $from = mktime( 0, 0, 0, date( "n", $now ), 1, date( 'Y', $now ) ); + + $wheres[] = $wpdb->prepare( "time BETWEEN %d AND %d", $from, $now ); + + } + + // Put all wheres together into one string + $wheres = implode( " AND ", $wheres ); + + // Count + $count = $wpdb->get_var( "SELECT COUNT(*) FROM {$mycred_log_table} WHERE {$wheres};" ); + if ( $count === NULL ) $count = 0; + + $over_limit = false; + if ( $period != 'x' && $count >= $amount ) + $over_limit = true; + + return $over_limit; + + } + + /** + * Adjust Limit Name + * @since 1.6 + * @version 1.0 + */ + public function hook_limit_name( $name ) { + + $name = str_replace( '[photo_limit]', '[photo_limit_by]', $name ); + $name = str_replace( '[video_limit]', '[video_limit_by]', $name ); + $name = str_replace( '[music_limit]', '[music_limit_by]', $name ); + return $name; + + } + + /** + * Adjust Limit ID + * @since 1.6 + * @version 1.0 + */ + public function hook_limit_id( $id ) { + + $id = str_replace( 'photo-limit', 'photo-limit-by', $id ); + $id = str_replace( 'video-limit', 'video-limit-by', $id ); + $id = str_replace( 'music-limit', 'music-limit-by', $id ); + return $id; + + } + + /** + * Preferences for rtMedia Gallery Hook + * @since 1.4 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + + global $rtmedia; + + $photos = ' readonly="readonly"'; + if ( array_key_exists( 'allowedTypes_photo_enabled', $rtmedia->options ) && $rtmedia->options['allowedTypes_photo_enabled'] == 1 ) + $photos = ''; + + $videos = ' readonly="readonly"'; + if ( array_key_exists( 'allowedTypes_video_enabled', $rtmedia->options ) && $rtmedia->options['allowedTypes_video_enabled'] == 1 ) + $videos = ''; + + $music = ' readonly="readonly"'; + if ( array_key_exists( 'allowedTypes_music_enabled', $rtmedia->options ) && $rtmedia->options['allowedTypes_music_enabled'] == 1 ) + $music = ''; + + add_filter( 'mycred_hook_limit_name_by', array( $this, 'hook_limit_name' ) ); + add_filter( 'mycred_hook_limit_id_by', array( $this, 'hook_limit_id' ) ); + +?>
    -

    -
    -
    -
    - - value="core->number($prefs['new_media']['photo']); ?>" class="form-control" /> -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_media', 'photo_limit' )), $this->field_id(array( 'new_media', 'photo_limit' )), $prefs['new_media']['photo_limit']); ?> -
    -
    -
    -
    - - placeholder="" value="" class="form-control" /> - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + value="core->number( $prefs['new_media']['photo'] ); ?>" class="form-control" /> +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_media', 'photo_limit' ) ), $this->field_id( array( 'new_media', 'photo_limit' ) ), $prefs['new_media']['photo_limit'] ); ?> +
    +
    +
    +
    + + placeholder="" value="" class="form-control" /> + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - value="core->number($prefs['new_media']['video']); ?>" class="form-control" /> -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_media', 'video_limit' )), $this->field_id(array( 'new_media', 'video_limit' )), $prefs['new_media']['video_limit']); ?> -
    -
    -
    -
    - - placeholder="" value="" class="form-control" /> - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + value="core->number( $prefs['new_media']['video'] ); ?>" class="form-control" /> +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_media', 'video_limit' ) ), $this->field_id( array( 'new_media', 'video_limit' ) ), $prefs['new_media']['video_limit'] ); ?> +
    +
    +
    +
    + + placeholder="" value="" class="form-control" /> + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - value="core->number($prefs['new_media']['music']); ?>" class="form-control" /> -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_media', 'music_limit' )), $this->field_id(array( 'new_media', 'music_limit' )), $prefs['new_media']['music_limit']); ?> -
    -
    -
    -
    - - placeholder="" value="" class="form-control" /> - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + value="core->number( $prefs['new_media']['music'] ); ?>" class="form-control" /> +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_media', 'music_limit' ) ), $this->field_id( array( 'new_media', 'music_limit' ) ), $prefs['new_media']['music_limit'] ); ?> +
    +
    +
    +
    + + placeholder="" value="" class="form-control" /> + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - value="core->number($prefs['delete_media']['photo']); ?>" class="form-control" /> -
    -
    -
    -
    - - placeholder="" value="" class="form-control" /> - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + value="core->number( $prefs['delete_media']['photo'] ); ?>" class="form-control" /> +
    +
    +
    +
    + + placeholder="" value="" class="form-control" /> + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - value="core->number($prefs['delete_media']['video']); ?>" class="form-control" /> -
    -
    -
    -
    - - placeholder="" value="" class="form-control" /> - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + value="core->number( $prefs['delete_media']['video'] ); ?>" class="form-control" /> +
    +
    +
    +
    + + placeholder="" value="" class="form-control" /> + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - value="core->number($prefs['delete_media']['music']); ?>" class="form-control" /> -
    -
    -
    -
    - - placeholder="" value="" class="form-control" /> - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + value="core->number( $prefs['delete_media']['music'] ); ?>" class="form-control" /> +
    +
    +
    +
    + + placeholder="" value="" class="form-control" /> + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - __('BuddyPress: Members', 'mycred'), - 'description' => __('Awards %_plural% for profile related actions.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/buddypress-profiles/', - 'callback' => array( 'myCRED_BuddyPress_Profile' ) - ); - } - - if (bp_is_active('groups') ) { - $installed['hook_bp_groups'] = array( - 'title' => __('BuddyPress: Groups', 'mycred'), - 'description' => __('Awards %_plural% for group related actions. Use minus to deduct %_plural% or zero to disable a specific hook.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/buddypress-groups/', - 'callback' => array( 'myCRED_BuddyPress_Groups' ) - ); - } - - return $installed; +add_filter( 'mycred_setup_hooks', 'mycred_register_buddypress_hook', 40 ); +function mycred_register_buddypress_hook( $installed ) { + + if ( ! class_exists( 'BuddyPress' ) ) return $installed; + + if ( bp_is_active( 'xprofile' ) ) { + $installed['hook_bp_profile'] = array( + 'title' => __( 'BuddyPress: Members', 'mycred' ), + 'description' => __( 'Awards %_plural% for profile related actions.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/buddypress-profiles/', + 'callback' => array( 'myCRED_BuddyPress_Profile' ) + ); + } + + if ( bp_is_active( 'groups' ) ) { + $installed['hook_bp_groups'] = array( + 'title' => __( 'BuddyPress: Groups', 'mycred' ), + 'description' => __( 'Awards %_plural% for group related actions. Use minus to deduct %_plural% or zero to disable a specific hook.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/buddypress-groups/', + 'callback' => array( 'myCRED_BuddyPress_Groups' ) + ); + } + + return $installed; } /** * myCRED_BuddyPress_Profile class * Creds for profile updates - * - * @since 0.1 + * @since 0.1 * @version 1.3 */ -add_action('mycred_load_hooks', 'mycred_load_buddypress_profile_hook', 40); -function mycred_load_buddypress_profile_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_BuddyPress_Profile') || ! class_exists('BuddyPress') ) { return; - } - - class myCRED_BuddyPress_Profile extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'hook_bp_profile', - 'defaults' => array( - 'update' => array( - 'creds' => 1, - 'log' => '%plural% for updating profile', - 'limit' => '0/x' - ), - 'removed_update' => array( - 'creds' => 1, - 'log' => '%plural% for removing profile update', - 'limit' => '0/x' - ), - 'avatar' => array( - 'creds' => 1, - 'log' => '%plural% for new avatar', - 'limit' => '0/x' - ), - 'cover' => array( - 'creds' => 1, - 'log' => '%plural% for new cover photo', - 'limit' => '0/x' - ), - 'new_friend' => array( - 'creds' => 1, - 'log' => '%plural% for new friendship', - 'block' => 0, - 'limit' => '0/x' - ), - 'leave_friend' => array( - 'creds' => '-1', - 'log' => '%singular% deduction for losing a friend', - 'limit' => '0/x' - ), - 'new_comment' => array( - 'creds' => 1, - 'log' => '%plural% for new comment', - 'limit' => '0/x' - ), - 'delete_comment' => array( - 'creds' => '-1', - 'log' => '%singular% deduction for comment removal' - ), - 'add_favorite' => array( - 'creds' => 1, - 'log' => '%plural% for adding an activity to favorites', - 'limit' => '0/x' - ), - 'remove_favorite' => array( - 'creds' => '-1', - 'log' => '%singular% deduction for removing favorite activity' - ), - 'message' => array( - 'creds' => 1, - 'log' => '%plural% for sending a message', - 'limit' => '0/x' - ), - 'send_gift' => array( - 'creds' => 1, - 'log' => '%plural% for sending a gift', - 'limit' => '0/x' - ) - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 0.1 - * @version 1.0 - */ - public function run() - { - - if ($this->prefs['update']['creds'] != 0 ) { - add_action('bp_activity_posted_update', array( $this, 'new_update' ), 10, 3); - } - - if ($this->prefs['removed_update']['creds'] != 0 ) { - add_action('bp_activity_delete', array( $this, 'remove_update' ), 10, 3); - } - - if ($this->prefs['avatar']['creds'] != 0 ) { - add_action('xprofile_avatar_uploaded', array( $this, 'avatar_upload' )); - } - - if ($this->prefs['cover']['creds'] != 0 ) { - add_action('xprofile_cover_image_uploaded', array( $this, 'cover_change' )); - } - - if ($this->prefs['new_friend']['creds'] < 0 && isset($this->prefs['new_friend']['block']) && $this->prefs['new_friend']['block'] == 1 ) { - add_action('wp_ajax_addremove_friend', array( $this, 'ajax_addremove_friend' ), 0); - add_filter('bp_get_add_friend_button', array( $this, 'disable_friendship' )); - } - - if ($this->prefs['new_friend']['creds'] != 0 ) { - add_action('friends_friendship_accepted', array( $this, 'friendship_join' ), 10, 3); - } - - if ($this->prefs['leave_friend']['creds'] != 0 ) { - add_action('friends_friendship_deleted', array( $this, 'friendship_leave' ), 10, 3); - } - - if ($this->prefs['new_comment']['creds'] != 0 ) { - add_action('bp_activity_comment_posted', array( $this, 'new_comment' ), 10, 2); - } - - if ($this->prefs['delete_comment']['creds'] != 0 ) { - add_action('bp_activity_before_action_delete_activity', array( $this, 'delete_comment' ), 10, 2); - } - - if ($this->prefs['add_favorite']['creds'] != 0 ) { - add_action('bp_activity_add_user_favorite', array( $this, 'add_to_favorites' ), 10, 2); - } - - if ($this->prefs['remove_favorite']['creds'] != 0 ) { - add_action('bp_activity_remove_user_favorite', array( $this, 'removed_from_favorites' ), 10, 2); - } - - if ($this->prefs['message']['creds'] != 0 ) { - add_action('messages_message_sent', array( $this, 'messages' )); - } - - if ($this->prefs['send_gift']['creds'] != 0 ) { - add_action('bp_gifts_send_gifts', array( $this, 'send_gifts' ), 10, 2); - } - - } - - /** - * New Profile Update - * - * @since 0.1 - * @version 1.2 - */ - public function new_update( $content, $user_id, $activity_id ) - { - - // Check if user is excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Limit - if ($this->over_hook_limit('update', 'new_profile_update', $user_id) ) { return; - } - - // Make sure this is unique event - if ($this->core->has_entry('new_profile_update', $activity_id, $user_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_profile_update', - $user_id, - $this->prefs['update']['creds'], - $this->prefs['update']['log'], - $activity_id, - 'bp_activity', - $this->mycred_type - ); - - } - - /** - * Removing Profile Update - * - * @since 1.6 - * @version 1.0 - */ - public function remove_update( $args ) - { - - if (! isset($args['user_id']) || $args['user_id'] === false ) { return; - } - - $user_id = absint($args['user_id']); - - // Check if user is excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Limit - if ($this->over_hook_limit('removed_update', 'deleted_profile_update', $user_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'deleted_profile_update', - $user_id, - $this->prefs['removed_update']['creds'], - $this->prefs['removed_update']['log'], - 0, - $args, - $this->mycred_type - ); - - } - - /** - * Avatar Upload - * - * @since 0.1 - * @version 1.2 - */ - public function avatar_upload() - { - - $user_id = apply_filters('bp_xprofile_new_avatar_user_id', bp_displayed_user_id()); - - // Check if user is excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Limit - if ($this->over_hook_limit('avatar', 'upload_avatar', $user_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'upload_avatar', - $user_id, - $this->prefs['avatar']['creds'], - $this->prefs['avatar']['log'], - 0, - '', - $this->mycred_type - ); - - } - - /** - * Cover Upload - * - * @since 1.7 - * @version 1.0 - */ - public function cover_change( $user_id = null ) - { - - // Check if user is excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Limit - if ($this->over_hook_limit('cover', 'upload_cover', $user_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'upload_cover', - $user_id, - $this->prefs['cover']['creds'], - $this->prefs['cover']['log'], - 0, - '', - $this->mycred_type - ); - - } - - /** - * AJAX: Add/Remove Friend - * Intercept addremovefriend ajax call and block - * action if the user can not afford new friendship. - * - * @since 1.5.4 - * @version 1.0 - */ - public function ajax_addremove_friend() - { - - // Bail if not a POST action - if ('POST' !== strtoupper($_SERVER['REQUEST_METHOD']) ) { - return; - } - - $user_id = bp_loggedin_user_id(); - $balance = $this->core->get_users_balance($user_id, $this->mycred_type); - $cost = abs($this->prefs['new_friend']['creds']); - - // Take into account any existing requests which will be charged when the new - // friend approves it. Prevents users from requesting more then they can afford. - $pending_requests = $this->count_pending_requests($user_id); - if ($pending_requests > 0 ) { - $cost = $cost + ( $cost * $pending_requests ); - } - - // Prevent BP from running this ajax call - if ($balance < $cost ) { - echo apply_filters('mycred_bp_declined_addfriend', __('Insufficient Funds', 'mycred'), $this); - exit; - } - - } - - /** - * Disable Friendship - * If we deduct points from a user for new friendships - * we disable the friendship button if the user ca not afford it. - * - * @since 1.5.4 - * @version 1.0 - */ - public function disable_friendship( $button ) - { - - // Only applicable for Add Friend button - if ($button['id'] == 'not_friends' ) { - - $user_id = bp_loggedin_user_id(); - $balance = $this->core->get_users_balance($user_id, $this->mycred_type); - $cost = abs($this->prefs['new_friend']['creds']); - - // Take into account any existing requests which will be charged when the new - // friend approves it. Prevents users from requesting more then they can afford. - $pending_requests = $this->count_pending_requests($user_id); - if ($pending_requests > 0 ) { - $cost = $cost + ( $cost * $pending_requests ); - } - - if ($balance < $cost ) { - return array(); - } - - } - - return $button; - - } - - /** - * Count Pending Friendship Requests - * Counts the given users pending friendship requests sent to - * other users. - * - * @since 1.5.4 - * @version 1.0 - */ - protected function count_pending_requests( $user_id ) - { - - global $wpdb, $bp; - - return $wpdb->get_var( - $wpdb->prepare( - " +add_action( 'mycred_load_hooks', 'mycred_load_buddypress_profile_hook', 40 ); +function mycred_load_buddypress_profile_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_BuddyPress_Profile' ) || ! class_exists( 'BuddyPress' ) ) return; + + class myCRED_BuddyPress_Profile extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'hook_bp_profile', + 'defaults' => array( + 'update' => array( + 'creds' => 1, + 'log' => '%plural% for updating profile', + 'limit' => '0/x' + ), + 'removed_update' => array( + 'creds' => 1, + 'log' => '%plural% for removing profile update', + 'limit' => '0/x' + ), + 'avatar' => array( + 'creds' => 1, + 'log' => '%plural% for new avatar', + 'limit' => '0/x' + ), + 'cover' => array( + 'creds' => 1, + 'log' => '%plural% for new cover photo', + 'limit' => '0/x' + ), + 'new_friend' => array( + 'creds' => 1, + 'log' => '%plural% for new friendship', + 'block' => 0, + 'limit' => '0/x' + ), + 'leave_friend' => array( + 'creds' => '-1', + 'log' => '%singular% deduction for losing a friend', + 'limit' => '0/x' + ), + 'new_comment' => array( + 'creds' => 1, + 'log' => '%plural% for new comment', + 'limit' => '0/x' + ), + 'delete_comment' => array( + 'creds' => '-1', + 'log' => '%singular% deduction for comment removal' + ), + 'add_favorite' => array( + 'creds' => 1, + 'log' => '%plural% for adding an activity to favorites', + 'limit' => '0/x' + ), + 'remove_favorite' => array( + 'creds' => '-1', + 'log' => '%singular% deduction for removing favorite activity' + ), + 'message' => array( + 'creds' => 1, + 'log' => '%plural% for sending a message', + 'limit' => '0/x' + ), + 'send_gift' => array( + 'creds' => 1, + 'log' => '%plural% for sending a gift', + 'limit' => '0/x' + ) + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 0.1 + * @version 1.0 + */ + public function run() { + + if ( $this->prefs['update']['creds'] != 0 ) + add_action( 'bp_activity_posted_update', array( $this, 'new_update' ), 10, 3 ); + + if ( $this->prefs['removed_update']['creds'] != 0 ) + add_action( 'bp_activity_delete', array( $this, 'remove_update' ), 10, 3 ); + + if ( $this->prefs['avatar']['creds'] != 0 ) + add_action( 'xprofile_avatar_uploaded', array( $this, 'avatar_upload' ) ); + + if ( $this->prefs['cover']['creds'] != 0 ) + add_action( 'xprofile_cover_image_uploaded', array( $this, 'cover_change' ) ); + + if ( $this->prefs['new_friend']['creds'] < 0 && isset( $this->prefs['new_friend']['block'] ) && $this->prefs['new_friend']['block'] == 1 ) { + add_action( 'wp_ajax_addremove_friend', array( $this, 'ajax_addremove_friend' ), 0 ); + add_filter( 'bp_get_add_friend_button', array( $this, 'disable_friendship' ) ); + } + + if ( $this->prefs['new_friend']['creds'] != 0 ) + add_action( 'friends_friendship_accepted', array( $this, 'friendship_join' ), 10, 3 ); + + if ( $this->prefs['leave_friend']['creds'] != 0 ) + add_action( 'friends_friendship_deleted', array( $this, 'friendship_leave' ), 10, 3 ); + + if ( $this->prefs['new_comment']['creds'] != 0 ) + add_action( 'bp_activity_comment_posted', array( $this, 'new_comment' ), 10, 2 ); + + if ( $this->prefs['delete_comment']['creds'] != 0 ) + add_action( 'bp_activity_before_action_delete_activity', array( $this, 'delete_comment' ), 10, 2 ); + + if ( $this->prefs['add_favorite']['creds'] != 0 ) + add_action( 'bp_activity_add_user_favorite', array( $this, 'add_to_favorites' ), 10, 2 ); + + if ( $this->prefs['remove_favorite']['creds'] != 0 ) + add_action( 'bp_activity_remove_user_favorite', array( $this, 'removed_from_favorites' ), 10, 2 ); + + if ( $this->prefs['message']['creds'] != 0 ) + add_action( 'messages_message_sent', array( $this, 'messages' ) ); + + if ( $this->prefs['send_gift']['creds'] != 0 ) + add_action( 'bp_gifts_send_gifts', array( $this, 'send_gifts' ), 10, 2 ); + + } + + /** + * New Profile Update + * @since 0.1 + * @version 1.2 + */ + public function new_update( $content, $user_id, $activity_id ) { + + // Check if user is excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'update', 'new_profile_update', $user_id ) ) return; + + // Make sure this is unique event + if ( $this->core->has_entry( 'new_profile_update', $activity_id, $user_id ) ) return; + + // Execute + $this->core->add_creds( + 'new_profile_update', + $user_id, + $this->prefs['update']['creds'], + $this->prefs['update']['log'], + $activity_id, + 'bp_activity', + $this->mycred_type + ); + + } + + /** + * Removing Profile Update + * @since 1.6 + * @version 1.0 + */ + public function remove_update( $args ) { + + if ( ! isset( $args['user_id'] ) || $args['user_id'] === false ) return; + + $user_id = absint( $args['user_id'] ); + + // Check if user is excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'removed_update', 'deleted_profile_update', $user_id ) ) return; + + // Execute + $this->core->add_creds( + 'deleted_profile_update', + $user_id, + $this->prefs['removed_update']['creds'], + $this->prefs['removed_update']['log'], + 0, + $args, + $this->mycred_type + ); + + } + + /** + * Avatar Upload + * @since 0.1 + * @version 1.2 + */ + public function avatar_upload() { + + $user_id = apply_filters( 'bp_xprofile_new_avatar_user_id', bp_displayed_user_id() ); + + // Check if user is excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'avatar', 'upload_avatar', $user_id ) ) return; + + // Execute + $this->core->add_creds( + 'upload_avatar', + $user_id, + $this->prefs['avatar']['creds'], + $this->prefs['avatar']['log'], + 0, + '', + $this->mycred_type + ); + + } + + /** + * Cover Upload + * @since 1.7 + * @version 1.0 + */ + public function cover_change( $user_id = NULL ) { + + // Check if user is excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'cover', 'upload_cover', $user_id ) ) return; + + // Execute + $this->core->add_creds( + 'upload_cover', + $user_id, + $this->prefs['cover']['creds'], + $this->prefs['cover']['log'], + 0, + '', + $this->mycred_type + ); + + } + + /** + * AJAX: Add/Remove Friend + * Intercept addremovefriend ajax call and block + * action if the user can not afford new friendship. + * @since 1.5.4 + * @version 1.0 + */ + public function ajax_addremove_friend() { + + // Bail if not a POST action + if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) + return; + + $user_id = bp_loggedin_user_id(); + $balance = $this->core->get_users_balance( $user_id, $this->mycred_type ); + $cost = abs( $this->prefs['new_friend']['creds'] ); + + // Take into account any existing requests which will be charged when the new + // friend approves it. Prevents users from requesting more then they can afford. + $pending_requests = $this->count_pending_requests( $user_id ); + if ( $pending_requests > 0 ) + $cost = $cost + ( $cost * $pending_requests ); + + // Prevent BP from running this ajax call + if ( $balance < $cost ) { + echo apply_filters( 'mycred_bp_declined_addfriend', __( 'Insufficient Funds', 'mycred' ), $this ); + exit; + } + + } + + /** + * Disable Friendship + * If we deduct points from a user for new friendships + * we disable the friendship button if the user ca not afford it. + * @since 1.5.4 + * @version 1.0 + */ + public function disable_friendship( $button ) { + + // Only applicable for Add Friend button + if ( $button['id'] == 'not_friends' ) { + + $user_id = bp_loggedin_user_id(); + $balance = $this->core->get_users_balance( $user_id, $this->mycred_type ); + $cost = abs( $this->prefs['new_friend']['creds'] ); + + // Take into account any existing requests which will be charged when the new + // friend approves it. Prevents users from requesting more then they can afford. + $pending_requests = $this->count_pending_requests( $user_id ); + if ( $pending_requests > 0 ) + $cost = $cost + ( $cost * $pending_requests ); + + if ( $balance < $cost ) + return array(); + + } + + return $button; + + } + + /** + * Count Pending Friendship Requests + * Counts the given users pending friendship requests sent to + * other users. + * @since 1.5.4 + * @version 1.0 + */ + protected function count_pending_requests( $user_id ) { + + global $wpdb, $bp; + + return $wpdb->get_var( $wpdb->prepare( " SELECT COUNT(*) FROM {$bp->friends->table_name} WHERE initiator_user_id = %d - AND is_confirmed = 0;", $user_id - ) - ); - - } - - /** - * New Friendship - * - * @since 0.1 - * @version 1.3.1 - */ - public function friendship_join( $friendship_id, $initiator_user_id, $friend_user_id ) - { - - // Make sure this is unique event - if (! $this->core->exclude_user($initiator_user_id) && ! $this->core->has_entry('new_friendship', $friend_user_id, $initiator_user_id) && ! $this->over_hook_limit('new_friend', 'new_friendship', $initiator_user_id) ) { - $this->core->add_creds( - 'new_friendship', - $initiator_user_id, - $this->prefs['new_friend']['creds'], - $this->prefs['new_friend']['log'], - $friend_user_id, - array( 'ref_type' => 'user' ), - $this->mycred_type - ); - } - - // Points to friend (ignored if we are deducting points for new friendships) - if ($this->prefs['new_friend']['creds'] > 0 && ! $this->core->exclude_user($friend_user_id) && ! $this->over_hook_limit('new_friend', 'new_friendship', $friend_user_id) ) { - $this->core->add_creds( - 'new_friendship', - $friend_user_id, - $this->prefs['new_friend']['creds'], - $this->prefs['new_friend']['log'], - $initiator_user_id, - array( 'ref_type' => 'user' ), - $this->mycred_type - ); - } - - } - - /** - * Ending Friendship - * - * @since 0.1 - * @version 1.2 - */ - public function friendship_leave( $friendship_id, $initiator_user_id, $friend_user_id ) - { - - if (! $this->core->exclude_user($initiator_user_id) && ! $this->core->has_entry('ended_friendship', $friend_user_id, $initiator_user_id) ) { - $this->core->add_creds( - 'ended_friendship', - $initiator_user_id, - $this->prefs['leave_friend']['creds'], - $this->prefs['leave_friend']['log'], - $friend_user_id, - array( 'ref_type' => 'user' ), - $this->mycred_type - ); - } - - if (! $this->core->exclude_user($friend_user_id) ) { - $this->core->add_creds( - 'ended_friendship', - $friend_user_id, - $this->prefs['leave_friend']['creds'], - $this->prefs['leave_friend']['log'], - $initiator_user_id, - array( 'ref_type' => 'user' ), - $this->mycred_type - ); - } - - } - - /** - * New Comment - * - * @since 0.1 - * @version 1.2 - */ - public function new_comment( $comment_id, $params ) - { - - $user_id = bp_loggedin_user_id(); - - // Check if user is excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Limit - if ($this->over_hook_limit('new_comment', 'new_comment') ) { return; - } - - // Make sure this is unique event - if ($this->core->has_entry('new_comment', $comment_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_comment', - $user_id, - $this->prefs['new_comment']['creds'], - $this->prefs['new_comment']['log'], - $comment_id, - 'bp_comment', - $this->mycred_type - ); - - } - - /** - * Comment Deletion - * - * @since 0.1 - * @version 1.0 - */ - public function delete_comment( $activity_id, $user_id ) - { - - global $wpdb, $bp; - - $activity_type = $wpdb->get_var($wpdb->prepare("SELECT type FROM {$bp->activity->table_name} WHERE id = %d", $activity_id)); + AND is_confirmed = 0;", $user_id ) ); + + } + + /** + * New Friendship + * @since 0.1 + * @version 1.3.1 + */ + public function friendship_join( $friendship_id, $initiator_user_id, $friend_user_id ) { + + // Make sure this is unique event + if ( ! $this->core->exclude_user( $initiator_user_id ) && ! $this->core->has_entry( 'new_friendship', $friend_user_id, $initiator_user_id ) && ! $this->over_hook_limit( 'new_friend', 'new_friendship', $initiator_user_id ) ) + $this->core->add_creds( + 'new_friendship', + $initiator_user_id, + $this->prefs['new_friend']['creds'], + $this->prefs['new_friend']['log'], + $friend_user_id, + array( 'ref_type' => 'user' ), + $this->mycred_type + ); + + // Points to friend (ignored if we are deducting points for new friendships) + if ( $this->prefs['new_friend']['creds'] > 0 && ! $this->core->exclude_user( $friend_user_id ) && ! $this->over_hook_limit( 'new_friend', 'new_friendship', $friend_user_id ) ) + $this->core->add_creds( + 'new_friendship', + $friend_user_id, + $this->prefs['new_friend']['creds'], + $this->prefs['new_friend']['log'], + $initiator_user_id, + array( 'ref_type' => 'user' ), + $this->mycred_type + ); + + } + + /** + * Ending Friendship + * @since 0.1 + * @version 1.2 + */ + public function friendship_leave( $friendship_id, $initiator_user_id, $friend_user_id ) { + + if ( ! $this->core->exclude_user( $initiator_user_id ) && ! $this->core->has_entry( 'ended_friendship', $friend_user_id, $initiator_user_id ) ) + $this->core->add_creds( + 'ended_friendship', + $initiator_user_id, + $this->prefs['leave_friend']['creds'], + $this->prefs['leave_friend']['log'], + $friend_user_id, + array( 'ref_type' => 'user' ), + $this->mycred_type + ); + + if ( ! $this->core->exclude_user( $friend_user_id ) ) + $this->core->add_creds( + 'ended_friendship', + $friend_user_id, + $this->prefs['leave_friend']['creds'], + $this->prefs['leave_friend']['log'], + $initiator_user_id, + array( 'ref_type' => 'user' ), + $this->mycred_type + ); + + } + + /** + * New Comment + * @since 0.1 + * @version 1.2 + */ + public function new_comment( $comment_id, $params ) { + + $user_id = bp_loggedin_user_id(); + + // Check if user is excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'new_comment', 'new_comment' ) ) return; + + // Make sure this is unique event + if ( $this->core->has_entry( 'new_comment', $comment_id ) ) return; + + // Execute + $this->core->add_creds( + 'new_comment', + $user_id, + $this->prefs['new_comment']['creds'], + $this->prefs['new_comment']['log'], + $comment_id, + 'bp_comment', + $this->mycred_type + ); + + } + + /** + * Comment Deletion + * @since 0.1 + * @version 1.0 + */ + public function delete_comment( $activity_id, $user_id ) { + + global $wpdb, $bp; + + $activity_type = $wpdb->get_var( $wpdb->prepare( "SELECT type FROM {$bp->activity->table_name} WHERE id = %d", $activity_id ) ); - if($activity_type == 'activity_comment' ) { + if( $activity_type == 'activity_comment' ) { - // Check if user is excluded - if ($this->core->exclude_user($user_id) ) { return; - } + // Check if user is excluded + if ( $this->core->exclude_user( $user_id ) ) return; - // Make sure this is unique event - if ($this->core->has_entry('comment_deletion', $activity_id) ) { return; - } + // Make sure this is unique event + if ( $this->core->has_entry( 'comment_deletion', $activity_id ) ) return; - // Execute - $this->core->add_creds( - 'comment_deletion', - $user_id, - $this->prefs['delete_comment']['creds'], - $this->prefs['delete_comment']['log'], - $activity_id, - 'bp_comment', - $this->mycred_type - ); - - } - - } - - /** - * Add to Favorites - * - * @since 1.7 - * @version 1.0 - */ - public function add_to_favorites( $activity_id, $user_id ) - { - - // Check if user is excluded - if ($this->core->exclude_user($user_id) ) { return; - } - //Limit - if ($this->over_hook_limit('add_favorite', 'fave_activity') ) { return; - } - // Make sure this is unique event - if ($this->core->has_entry('fave_activity', $activity_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'fave_activity', - $user_id, - $this->prefs['add_favorite']['creds'], - $this->prefs['add_favorite']['log'], - $activity_id, - 'bp_comment', - $this->mycred_type - ); - - } - - /** - * Remove from Favorites - * - * @since 1.7 - * @version 1.0 - */ - public function removed_from_favorites( $activity_id, $user_id ) - { - - // Check if user is excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Make sure this is unique event - if ($this->core->has_entry('unfave_activity', $activity_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'unfave_activity', - $user_id, - $this->prefs['remove_favorite']['creds'], - $this->prefs['remove_favorite']['log'], - $activity_id, - 'bp_comment', - $this->mycred_type - ); - - } - - /** - * New Message - * - * @since 0.1 - * @version 1.1 - */ - public function messages( $message ) - { - - // Check if user is excluded - if ($this->core->exclude_user($message->sender_id) ) { return; - } - - // Limit - if ($this->over_hook_limit('message', 'new_message', $message->sender_id) ) { return; - } - - // Make sure this is unique event - if ($this->core->has_entry('new_message', $message->thread_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_message', - $message->sender_id, - $this->prefs['message']['creds'], - $this->prefs['message']['log'], - $message->thread_id, - 'bp_message', - $this->mycred_type - ); - - } - - /** - * Send Gift - * - * @since 0.1 - * @version 1.1 - */ - public function send_gifts( $to_user_id, $from_user_id ) - { - - // Check if sender is excluded - if ($this->core->exclude_user($from_user_id) ) { return; - } - - // Check if recipient is excluded - if ($this->core->exclude_user($to_user_id) ) { return; - } - - // Limit - if (! $this->over_hook_limit('send_gift', 'sending_gift', $from_user_id) ) { - $this->core->add_creds( - 'sending_gift', - $from_user_id, - $this->prefs['send_gift']['creds'], - $this->prefs['send_gift']['log'], - $to_user_id, - 'bp_gifts', - $this->mycred_type - ); - } - - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.2 - */ - public function preferences() - { - - $prefs = $this->prefs; - - if (! isset($prefs['removed_update']) ) { - $prefs['removed_update'] = array( 'creds' => 0, 'limit' => '0/x', 'log' => '%plural% deduction for removing profile update' ); - } - - $friend_block = 0; - if (isset($prefs['new_friend']['block']) ) { - $friend_block = $prefs['new_friend']['block']; - } - - ?> + // Execute + $this->core->add_creds( + 'comment_deletion', + $user_id, + $this->prefs['delete_comment']['creds'], + $this->prefs['delete_comment']['log'], + $activity_id, + 'bp_comment', + $this->mycred_type + ); + + } + + } + + /** + * Add to Favorites + * @since 1.7 + * @version 1.0 + */ + public function add_to_favorites( $activity_id, $user_id ) { + + // Check if user is excluded + if ( $this->core->exclude_user( $user_id ) ) return; + //Limit + if ($this->over_hook_limit( 'add_favorite', 'fave_activity' ) ) return; + // Make sure this is unique event + if ( $this->core->has_entry( 'fave_activity', $activity_id ) ) return; + + // Execute + $this->core->add_creds( + 'fave_activity', + $user_id, + $this->prefs['add_favorite']['creds'], + $this->prefs['add_favorite']['log'], + $activity_id, + 'bp_comment', + $this->mycred_type + ); + + } + + /** + * Remove from Favorites + * @since 1.7 + * @version 1.0 + */ + public function removed_from_favorites( $activity_id, $user_id ) { + + // Check if user is excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Make sure this is unique event + if ( $this->core->has_entry( 'unfave_activity', $activity_id ) ) return; + + // Execute + $this->core->add_creds( + 'unfave_activity', + $user_id, + $this->prefs['remove_favorite']['creds'], + $this->prefs['remove_favorite']['log'], + $activity_id, + 'bp_comment', + $this->mycred_type + ); + + } + + /** + * New Message + * @since 0.1 + * @version 1.1 + */ + public function messages( $message ) { + + // Check if user is excluded + if ( $this->core->exclude_user( $message->sender_id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'message', 'new_message', $message->sender_id ) ) return; + + // Make sure this is unique event + if ( $this->core->has_entry( 'new_message', $message->thread_id ) ) return; + + // Execute + $this->core->add_creds( + 'new_message', + $message->sender_id, + $this->prefs['message']['creds'], + $this->prefs['message']['log'], + $message->thread_id, + 'bp_message', + $this->mycred_type + ); + + } + + /** + * Send Gift + * @since 0.1 + * @version 1.1 + */ + public function send_gifts( $to_user_id, $from_user_id ) { + + // Check if sender is excluded + if ( $this->core->exclude_user( $from_user_id ) ) return; + + // Check if recipient is excluded + if ( $this->core->exclude_user( $to_user_id ) ) return; + + // Limit + if ( ! $this->over_hook_limit( 'send_gift', 'sending_gift', $from_user_id ) ) + $this->core->add_creds( + 'sending_gift', + $from_user_id, + $this->prefs['send_gift']['creds'], + $this->prefs['send_gift']['log'], + $to_user_id, + 'bp_gifts', + $this->mycred_type + ); + + } + + /** + * Preferences + * @since 0.1 + * @version 1.2 + */ + public function preferences() { + + $prefs = $this->prefs; + + if ( ! isset( $prefs['removed_update'] ) ) + $prefs['removed_update'] = array( 'creds' => 0, 'limit' => '0/x', 'log' => '%plural% deduction for removing profile update' ); + + $friend_block = 0; + if ( isset( $prefs['new_friend']['block'] ) ) + $friend_block = $prefs['new_friend']['block']; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'update', 'limit' )), $this->field_id(array( 'update', 'limit' )), $prefs['update']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'update', 'limit' ) ), $this->field_id( array( 'update', 'limit' ) ), $prefs['update']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'removed_update', 'limit' )), $this->field_id(array( 'removed_update', 'limit' )), $prefs['removed_update']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'removed_update', 'limit' ) ), $this->field_id( array( 'removed_update', 'limit' ) ), $prefs['removed_update']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'avatar', 'limit' )), $this->field_id(array( 'avatar', 'limit' )), $prefs['avatar']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'avatar', 'limit' ) ), $this->field_id( array( 'avatar', 'limit' ) ), $prefs['avatar']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'cover', 'limit' )), $this->field_id(array( 'cover', 'limit' )), $prefs['cover']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'cover', 'limit' ) ), $this->field_id( array( 'cover', 'limit' ) ), $prefs['cover']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_friend', 'limit' )), $this->field_id(array( 'new_friend', 'limit' )), $prefs['new_friend']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_friend', 'limit' ) ), $this->field_id( array( 'new_friend', 'limit' ) ), $prefs['new_friend']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_comment', 'limit' )), $this->field_id(array( 'new_comment', 'limit' )), $prefs['new_comment']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_comment', 'limit' ) ), $this->field_id( array( 'new_comment', 'limit' ) ), $prefs['new_comment']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'add_favorite', 'limit' )), $this->field_id(array( 'add_favorite', 'limit' )), $prefs['add_favorite']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'add_favorite', 'limit' ) ), $this->field_id( array( 'add_favorite', 'limit' ) ), $prefs['add_favorite']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'message', 'limit' )), $this->field_id(array( 'message', 'limit' )), $prefs['message']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'message', 'limit' ) ), $this->field_id( array( 'message', 'limit' ) ), $prefs['message']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'send_gift', 'limit' )), $this->field_id(array( 'send_gift', 'limit' )), $prefs['send_gift']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'send_gift', 'limit' ) ), $this->field_id( array( 'send_gift', 'limit' ) ), $prefs['send_gift']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - 'hook_bp_groups', - 'defaults' => array( - 'create' => array( - 'creds' => 10, - 'log' => '%plural% for creating a new group', - 'min' => 0 - ), - 'delete' => array( - 'creds' => '-10', - 'log' => '%singular% deduction for deleting a group' - ), - 'new_topic' => array( - 'creds' => 1, - 'log' => '%plural% for new group topic', - 'limit' => '0/x' - ), - 'edit_topic' => array( - 'creds' => 1, - 'log' => '%plural% for updating group topic', - 'limit' => '0/x' - ), - 'new_post' => array( - 'creds' => 1, - 'log' => '%plural% for new group post', - 'limit' => '0/x' - ), - 'edit_post' => array( - 'creds' => 1, - 'log' => '%plural% for updating group post', - 'limit' => '0/x' - ), - 'join' => array( - 'creds' => 1, - 'log' => '%plural% for joining new group', - 'limit' => '0/x' - ), - 'leave' => array( - 'creds' => '-5', - 'log' => '%singular% deduction for leaving group' - ), - 'avatar' => array( - 'creds' => 1, - 'log' => '%plural% for new group avatar', - 'limit' => '0/x' - ), - 'cover' => array( - 'creds' => 1, - 'log' => '%plural% for new cover photo', - 'limit' => '0/x' - ), - 'comments' => array( - 'creds' => 1, - 'log' => '%plural% for new group post', - 'limit' => '0/x' - ) - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 0.1 - * @version 1.0 - */ - public function run() - { - - if ($this->prefs['create']['creds'] != 0 && $this->prefs['create']['min'] == 0 ) { - add_action('groups_group_create_complete', array( $this, 'create_group' )); - } - - if ($this->prefs['create']['creds'] < 0 ) { - add_filter('bp_user_can_create_groups', array( $this, 'restrict_group_creation' ), 99, 2); - } - - if ($this->prefs['delete']['creds'] != 0 ) { - add_action('groups_group_deleted', array( $this, 'delete_group' )); - } - - if ($this->prefs['new_topic']['creds'] != 0 ) { - add_action('bp_forums_new_topic', array( $this, 'new_topic' )); - } - - if ($this->prefs['edit_topic']['creds'] != 0 ) { - add_action('groups_edit_forum_topic', array( $this, 'edit_topic' )); - } - - if ($this->prefs['new_post']['creds'] != 0 ) { - add_action('bp_forums_new_post', array( $this, 'new_post' )); - } - - if ($this->prefs['edit_post']['creds'] != 0 ) { - add_action('groups_edit_forum_post', array( $this, 'edit_post' )); - } - - if ($this->prefs['join']['creds'] != 0 || ( $this->prefs['create']['creds'] != 0 && $this->prefs['create']['min'] != 0 ) ) { - add_action('groups_join_group', array( $this, 'join_group' ), 20, 2); - } - - if ($this->prefs['join']['creds'] < 0 ) { - add_filter('bp_get_group_join_button', array( $this, 'restrict_joining_group' )); - } - - if ($this->prefs['leave']['creds'] != 0 ) { - add_action('groups_leave_group', array( $this, 'leave_group' ), 20, 2); - } - - if ($this->prefs['avatar']['creds'] != 0 ) { - add_action('groups_screen_group_admin_avatar', array( $this, 'avatar_upload_group' )); - } - - if ($this->prefs['cover']['creds'] != 0 ) { - add_action('group_cover_image_uploaded', array( $this, 'cover_change' )); - } - - if ($this->prefs['comments']['creds'] != 0 ) { - add_action('bp_groups_posted_update', array( $this, 'new_group_comment' ), 20, 4); - } - - } - - /** - * Creating Group - * - * @since 0.1 - * @version 1.0 - */ - public function create_group( $group_id ) - { - - global $bp; - - // Check if user should be excluded - if ($this->core->exclude_user($bp->loggedin_user->id) ) { return; - } - - // Execute - $this->core->add_creds( - 'creation_of_new_group', - $bp->loggedin_user->id, - $this->prefs['create']['creds'], - $this->prefs['create']['log'], - $group_id, - 'bp_group', - $this->mycred_type - ); - - } - - /** - * Restrict Group Creation - * If creating a group costs and the user does not have enough points, we restrict creations. - * - * @since 0.1 - * @version 1.0 - */ - public function restrict_group_creation( $can_create, $restricted ) - { - - global $bp; - - // Check if user should be excluded - if ($this->core->exclude_user($bp->loggedin_user->id) ) { return $can_create; - } - - // Check if user has enough to create a group - $cost = abs($this->prefs['create']['creds']); - $balance = $this->core->get_users_balance($bp->loggedin_user->id, $this->mycred_type); - if ($cost > $balance ) { return false; - } - - return $can_create; - - } - - /** - * Restrict Group Join - * If joining a group costs and the user does not have enough points, we restrict joining of groups. - * - * @since 0.1 - * @version 1.0 - */ - public function restrict_joining_group( $button ) - { - - global $bp; - - // Check if user should be excluded - if ($this->core->exclude_user($bp->loggedin_user->id) ) { return $button; - } - - // Check if user has enough to join group - $cost = abs($this->prefs['join']['creds']); - $balance = $this->core->get_users_balance($bp->loggedin_user->id, $this->mycred_type); - if ($cost > $balance ) { return false; - } - - return $button; - - } - - /** - * Deleting Group - * - * @since 0.1 - * @version 1.0 - */ - public function delete_group( $group_id ) - { - - global $bp; - - // If admin is removing deduct from creator - if ($bp->loggedin_user->is_super_admin ) { - $user_id = $bp->groups->current_group->creator_id; - } - - // Else if admin but not the creator is removing - elseif ($bp->loggedin_user->id != $bp->groups->current_group->creator_id ) { - $user_id = $bp->groups->current_group->creator_id; - } - - // Else deduct from current user - else { - $user_id = $bp->loggedin_user->id; - } - - // Check if user should be excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'deletion_of_group', - $user_id, - $this->prefs['delete']['creds'], - $this->prefs['delete']['log'], - $group_id, - 'bp_group', - $this->mycred_type - ); - - } - - /** - * New Group Forum Topic - * - * @since 0.1 - * @version 1.1 - */ - public function new_topic( $topic_id ) - { - - global $bp; - - // Check if user should be excluded - if ($this->core->exclude_user($bp->loggedin_user->id) ) { return; - } - - // Limit - if ($this->over_hook_limit('new_topic', 'new_group_forum_topic') ) { return; - } - - // Make sure this is unique event - if ($this->core->has_entry('new_group_forum_topic', $topic_id, $bp->loggedin_user->id) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_group_forum_topic', - $bp->loggedin_user->id, - $this->prefs['new_topic']['creds'], - $this->prefs['new_topic']['log'], - $topic_id, - 'bp_ftopic', - $this->mycred_type - ); - - } - - /** - * Edit Group Forum Topic - * - * @since 0.1 - * @version 1.0 - */ - public function edit_topic( $topic_id ) - { - - global $bp; - - // Check if user should be excluded - if ($this->core->exclude_user($bp->loggedin_user->id) ) { return; - } - - // Limit - if ($this->over_hook_limit('edit_topic', 'edit_group_forum_topic') ) { return; - } - - // Execute - $this->core->add_creds( - 'edit_group_forum_topic', - $bp->loggedin_user->id, - $this->prefs['edit_topic']['creds'], - $this->prefs['edit_topic']['log'], - $topic_id, - 'bp_ftopic', - $this->mycred_type - ); - - } - - /** - * New Group Forum Post - * - * @since 0.1 - * @version 1.1 - */ - public function new_post( $post_id ) - { - - global $bp; - - // Check if user should be excluded - if ($this->core->exclude_user($bp->loggedin_user->id) ) { return; - } - - // Limit - if ($this->over_hook_limit('new_post', 'new_group_forum_post') ) { return; - } - - // Make sure this is unique event - if ($this->core->has_entry('new_group_forum_post', $post_id, $bp->loggedin_user->id) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_group_forum_post', - $bp->loggedin_user->id, - $this->prefs['new_post']['creds'], - $this->prefs['new_post']['log'], - $post_id, - 'bp_fpost', - $this->mycred_type - ); - - } - - /** - * Edit Group Forum Post - * - * @since 0.1 - * @version 1.0 - */ - public function edit_post( $post_id ) - { - - global $bp; - - // Check if user should be excluded - if ($this->core->exclude_user($bp->loggedin_user->id) ) { return; - } - - // Limit - if ($this->over_hook_limit('edit_post', 'edit_group_forum_post') ) { return; - } - - // Execute - $this->core->add_creds( - 'edit_group_forum_post', - $bp->loggedin_user->id, - $this->prefs['edit_post']['creds'], - $this->prefs['edit_post']['log'], - $post_id, - 'bp_fpost', - $this->mycred_type - ); - - } - - /** - * Joining Group - * - * @since 0.1 - * @version 1.1 - */ - public function join_group( $group_id, $user_id ) - { - - // Minimum members limit - if ($this->prefs['create']['min'] != 0 ) { - $group = groups_get_group(array( 'group_id' => $group_id )); - - // Award creator if we have reached the minimum number of members and we have not yet been awarded - if ($group->total_member_count >= (int) $this->prefs['create']['min'] && ! $this->core->has_entry('creation_of_new_group', $group_id, $group->creator_id) ) { - $this->core->add_creds( - 'creation_of_new_group', - $group->creator_id, - $this->prefs['create']['creds'], - $this->prefs['create']['log'], - $group_id, - 'bp_group', - $this->mycred_type - ); - } - - // Clean up - unset($group); - - } - - // Check if user should be excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Limit - if ($this->over_hook_limit('join', 'joining_group') ) { return; - } - - // Make sure this is unique event - if ($this->core->has_entry('joining_group', $group_id, $user_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'joining_group', - $user_id, - $this->prefs['join']['creds'], - $this->prefs['join']['log'], - $group_id, - 'bp_group', - $this->mycred_type - ); - - } - - /** - * Leaving Group - * - * @since 0.1 - * @version 1.0 - */ - public function leave_group( $group_id, $user_id ) - { - - // Check if user should be excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Make sure this is unique event - if ($this->core->has_entry('leaving_group', $group_id, $user_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'leaving_group', - $user_id, - $this->prefs['leave']['creds'], - $this->prefs['leave']['log'], - $group_id, - 'bp_group', - $this->mycred_type - ); - - } - - /** - * Avatar Upload for Group - * - * @since 0.1 - * @version 1.1 - */ - public function avatar_upload_group( $group_id ) - { - - global $bp; - - // Check if user should be excluded - if ($this->core->exclude_user($bp->loggedin_user->id) ) { return; - } - - // Limit - if ($this->over_hook_limit('avatar', 'upload_group_avatar') ) { return; - } - - // Make sure this is unique event - if ($this->core->has_entry('upload_group_avatar', $group_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'upload_group_avatar', - $bp->loggedin_user->id, - $this->prefs['avatar']['creds'], - $this->prefs['avatar']['log'], - $group_id, - 'bp_group', - $this->mycred_type - ); - - } - - /** - * Group Cover Upload - * - * @since 1.7 - * @version 1.0 - */ - public function cover_change( $group_id ) - { - - global $bp; - - // Check if user is excluded - if ($this->core->exclude_user($bp->loggedin_user->id) ) { return; - } - - // Limit - if ($this->over_hook_limit('cover', 'upload_group_cover', $bp->loggedin_user->id) ) { return; - } - - // Execute - $this->core->add_creds( - 'upload_group_cover', - $bp->loggedin_user->id, - $this->prefs['cover']['creds'], - $this->prefs['cover']['log'], - $group_id, - 'bp_group', - $this->mycred_type - ); - - } - - /** - * New Group Comment - * - * @since 0.1 - * @version 1.1 - */ - public function new_group_comment( $content, $user_id, $group_id, $activity_id ) - { - - // Check if user should be excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Limit - if ($this->over_hook_limit('comments', 'new_group_comment', $user_id) ) { return; - } - - // Make sure this is unique event - if ($this->core->has_entry('new_group_comment', $activity_id, $user_id) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_group_comment', - $user_id, - $this->prefs['comments']['creds'], - $this->prefs['comments']['log'], - $activity_id, - 'bp_activity', - $this->mycred_type - ); - - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.3 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +add_action( 'mycred_load_hooks', 'mycred_load_buddypress_groups_hook', 45 ); +function mycred_load_buddypress_groups_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_BuddyPress_Groups' ) || ! class_exists( 'BuddyPress' ) ) return; + + class myCRED_BuddyPress_Groups extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'hook_bp_groups', + 'defaults' => array( + 'create' => array( + 'creds' => 10, + 'log' => '%plural% for creating a new group', + 'min' => 0 + ), + 'delete' => array( + 'creds' => '-10', + 'log' => '%singular% deduction for deleting a group' + ), + 'new_topic' => array( + 'creds' => 1, + 'log' => '%plural% for new group topic', + 'limit' => '0/x' + ), + 'edit_topic' => array( + 'creds' => 1, + 'log' => '%plural% for updating group topic', + 'limit' => '0/x' + ), + 'new_post' => array( + 'creds' => 1, + 'log' => '%plural% for new group post', + 'limit' => '0/x' + ), + 'edit_post' => array( + 'creds' => 1, + 'log' => '%plural% for updating group post', + 'limit' => '0/x' + ), + 'join' => array( + 'creds' => 1, + 'log' => '%plural% for joining new group', + 'limit' => '0/x' + ), + 'leave' => array( + 'creds' => '-5', + 'log' => '%singular% deduction for leaving group' + ), + 'avatar' => array( + 'creds' => 1, + 'log' => '%plural% for new group avatar', + 'limit' => '0/x' + ), + 'cover' => array( + 'creds' => 1, + 'log' => '%plural% for new cover photo', + 'limit' => '0/x' + ), + 'comments' => array( + 'creds' => 1, + 'log' => '%plural% for new group post', + 'limit' => '0/x' + ) + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 0.1 + * @version 1.0 + */ + public function run() { + + if ( $this->prefs['create']['creds'] != 0 && $this->prefs['create']['min'] == 0 ) + add_action( 'groups_group_create_complete', array( $this, 'create_group' ) ); + + if ( $this->prefs['create']['creds'] < 0 ) + add_filter( 'bp_user_can_create_groups', array( $this, 'restrict_group_creation' ), 99, 2 ); + + if ( $this->prefs['delete']['creds'] != 0 ) + add_action( 'groups_group_deleted', array( $this, 'delete_group' ) ); + + if ( $this->prefs['new_topic']['creds'] != 0 ) + add_action( 'bp_forums_new_topic', array( $this, 'new_topic' ) ); + + if ( $this->prefs['edit_topic']['creds'] != 0 ) + add_action( 'groups_edit_forum_topic', array( $this, 'edit_topic' ) ); + + if ( $this->prefs['new_post']['creds'] != 0 ) + add_action( 'bp_forums_new_post', array( $this, 'new_post' ) ); + + if ( $this->prefs['edit_post']['creds'] != 0 ) + add_action( 'groups_edit_forum_post', array( $this, 'edit_post' ) ); + + if ( $this->prefs['join']['creds'] != 0 || ( $this->prefs['create']['creds'] != 0 && $this->prefs['create']['min'] != 0 ) ) + add_action( 'groups_join_group', array( $this, 'join_group' ), 20, 2 ); + + if ( $this->prefs['join']['creds'] < 0 ) + add_filter( 'bp_get_group_join_button', array( $this, 'restrict_joining_group' ) ); + + if ( $this->prefs['leave']['creds'] != 0 ) + add_action( 'groups_leave_group', array( $this, 'leave_group' ), 20, 2 ); + + if ( $this->prefs['avatar']['creds'] != 0 ) + add_action( 'groups_screen_group_admin_avatar', array( $this, 'avatar_upload_group' ) ); + + if ( $this->prefs['cover']['creds'] != 0 ) + add_action( 'group_cover_image_uploaded', array( $this, 'cover_change' ) ); + + if ( $this->prefs['comments']['creds'] != 0 ) + add_action( 'bp_groups_posted_update', array( $this, 'new_group_comment' ), 20, 4 ); + + } + + /** + * Creating Group + * @since 0.1 + * @version 1.0 + */ + public function create_group( $group_id ) { + + global $bp; + + // Check if user should be excluded + if ( $this->core->exclude_user( $bp->loggedin_user->id ) ) return; + + // Execute + $this->core->add_creds( + 'creation_of_new_group', + $bp->loggedin_user->id, + $this->prefs['create']['creds'], + $this->prefs['create']['log'], + $group_id, + 'bp_group', + $this->mycred_type + ); + + } + + /** + * Restrict Group Creation + * If creating a group costs and the user does not have enough points, we restrict creations. + * @since 0.1 + * @version 1.0 + */ + public function restrict_group_creation( $can_create, $restricted ) { + + global $bp; + + // Check if user should be excluded + if ( $this->core->exclude_user( $bp->loggedin_user->id ) ) return $can_create; + + // Check if user has enough to create a group + $cost = abs( $this->prefs['create']['creds'] ); + $balance = $this->core->get_users_balance( $bp->loggedin_user->id, $this->mycred_type ); + if ( $cost > $balance ) return false; + + return $can_create; + + } + + /** + * Restrict Group Join + * If joining a group costs and the user does not have enough points, we restrict joining of groups. + * @since 0.1 + * @version 1.0 + */ + public function restrict_joining_group( $button ) { + + global $bp; + + // Check if user should be excluded + if ( $this->core->exclude_user( $bp->loggedin_user->id ) ) return $button; + + // Check if user has enough to join group + $cost = abs( $this->prefs['join']['creds'] ); + $balance = $this->core->get_users_balance( $bp->loggedin_user->id, $this->mycred_type ); + if ( $cost > $balance ) return false; + + return $button; + + } + + /** + * Deleting Group + * @since 0.1 + * @version 1.0 + */ + public function delete_group( $group_id ) { + + global $bp; + + // If admin is removing deduct from creator + if ( $bp->loggedin_user->is_super_admin ) + $user_id = $bp->groups->current_group->creator_id; + + // Else if admin but not the creator is removing + elseif ( $bp->loggedin_user->id != $bp->groups->current_group->creator_id ) + $user_id = $bp->groups->current_group->creator_id; + + // Else deduct from current user + else + $user_id = $bp->loggedin_user->id; + + // Check if user should be excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Execute + $this->core->add_creds( + 'deletion_of_group', + $user_id, + $this->prefs['delete']['creds'], + $this->prefs['delete']['log'], + $group_id, + 'bp_group', + $this->mycred_type + ); + + } + + /** + * New Group Forum Topic + * @since 0.1 + * @version 1.1 + */ + public function new_topic( $topic_id ) { + + global $bp; + + // Check if user should be excluded + if ( $this->core->exclude_user( $bp->loggedin_user->id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'new_topic', 'new_group_forum_topic' ) ) return; + + // Make sure this is unique event + if ( $this->core->has_entry( 'new_group_forum_topic', $topic_id, $bp->loggedin_user->id ) ) return; + + // Execute + $this->core->add_creds( + 'new_group_forum_topic', + $bp->loggedin_user->id, + $this->prefs['new_topic']['creds'], + $this->prefs['new_topic']['log'], + $topic_id, + 'bp_ftopic', + $this->mycred_type + ); + + } + + /** + * Edit Group Forum Topic + * @since 0.1 + * @version 1.0 + */ + public function edit_topic( $topic_id ) { + + global $bp; + + // Check if user should be excluded + if ( $this->core->exclude_user( $bp->loggedin_user->id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'edit_topic', 'edit_group_forum_topic' ) ) return; + + // Execute + $this->core->add_creds( + 'edit_group_forum_topic', + $bp->loggedin_user->id, + $this->prefs['edit_topic']['creds'], + $this->prefs['edit_topic']['log'], + $topic_id, + 'bp_ftopic', + $this->mycred_type + ); + + } + + /** + * New Group Forum Post + * @since 0.1 + * @version 1.1 + */ + public function new_post( $post_id ) { + + global $bp; + + // Check if user should be excluded + if ( $this->core->exclude_user( $bp->loggedin_user->id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'new_post', 'new_group_forum_post' ) ) return; + + // Make sure this is unique event + if ( $this->core->has_entry( 'new_group_forum_post', $post_id, $bp->loggedin_user->id ) ) return; + + // Execute + $this->core->add_creds( + 'new_group_forum_post', + $bp->loggedin_user->id, + $this->prefs['new_post']['creds'], + $this->prefs['new_post']['log'], + $post_id, + 'bp_fpost', + $this->mycred_type + ); + + } + + /** + * Edit Group Forum Post + * @since 0.1 + * @version 1.0 + */ + public function edit_post( $post_id ) { + + global $bp; + + // Check if user should be excluded + if ( $this->core->exclude_user( $bp->loggedin_user->id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'edit_post', 'edit_group_forum_post' ) ) return; + + // Execute + $this->core->add_creds( + 'edit_group_forum_post', + $bp->loggedin_user->id, + $this->prefs['edit_post']['creds'], + $this->prefs['edit_post']['log'], + $post_id, + 'bp_fpost', + $this->mycred_type + ); + + } + + /** + * Joining Group + * @since 0.1 + * @version 1.1 + */ + public function join_group( $group_id, $user_id ) { + + // Minimum members limit + if ( $this->prefs['create']['min'] != 0 ) { + $group = groups_get_group( array( 'group_id' => $group_id ) ); + + // Award creator if we have reached the minimum number of members and we have not yet been awarded + if ( $group->total_member_count >= (int) $this->prefs['create']['min'] && ! $this->core->has_entry( 'creation_of_new_group', $group_id, $group->creator_id ) ) + $this->core->add_creds( + 'creation_of_new_group', + $group->creator_id, + $this->prefs['create']['creds'], + $this->prefs['create']['log'], + $group_id, + 'bp_group', + $this->mycred_type + ); + + // Clean up + unset( $group ); + + } + + // Check if user should be excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'join', 'joining_group' ) ) return; + + // Make sure this is unique event + if ( $this->core->has_entry( 'joining_group', $group_id, $user_id ) ) return; + + // Execute + $this->core->add_creds( + 'joining_group', + $user_id, + $this->prefs['join']['creds'], + $this->prefs['join']['log'], + $group_id, + 'bp_group', + $this->mycred_type + ); + + } + + /** + * Leaving Group + * @since 0.1 + * @version 1.0 + */ + public function leave_group( $group_id, $user_id ) { + + // Check if user should be excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Make sure this is unique event + if ( $this->core->has_entry( 'leaving_group', $group_id, $user_id ) ) return; + + // Execute + $this->core->add_creds( + 'leaving_group', + $user_id, + $this->prefs['leave']['creds'], + $this->prefs['leave']['log'], + $group_id, + 'bp_group', + $this->mycred_type + ); + + } + + /** + * Avatar Upload for Group + * @since 0.1 + * @version 1.1 + */ + public function avatar_upload_group( $group_id ) { + + global $bp; + + // Check if user should be excluded + if ( $this->core->exclude_user( $bp->loggedin_user->id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'avatar', 'upload_group_avatar' ) ) return; + + // Make sure this is unique event + if ( $this->core->has_entry( 'upload_group_avatar', $group_id ) ) return; + + // Execute + $this->core->add_creds( + 'upload_group_avatar', + $bp->loggedin_user->id, + $this->prefs['avatar']['creds'], + $this->prefs['avatar']['log'], + $group_id, + 'bp_group', + $this->mycred_type + ); + + } + + /** + * Group Cover Upload + * @since 1.7 + * @version 1.0 + */ + public function cover_change( $group_id ) { + + global $bp; + + // Check if user is excluded + if ( $this->core->exclude_user( $bp->loggedin_user->id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'cover', 'upload_group_cover', $bp->loggedin_user->id ) ) return; + + // Execute + $this->core->add_creds( + 'upload_group_cover', + $bp->loggedin_user->id, + $this->prefs['cover']['creds'], + $this->prefs['cover']['log'], + $group_id, + 'bp_group', + $this->mycred_type + ); + + } + + /** + * New Group Comment + * @since 0.1 + * @version 1.1 + */ + public function new_group_comment( $content, $user_id, $group_id, $activity_id ) { + + // Check if user should be excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'comments', 'new_group_comment', $user_id ) ) return; + + // Make sure this is unique event + if ( $this->core->has_entry( 'new_group_comment', $activity_id, $user_id ) ) return; + + // Execute + $this->core->add_creds( + 'new_group_comment', + $user_id, + $this->prefs['comments']['creds'], + $this->prefs['comments']['log'], + $activity_id, + 'bp_activity', + $this->mycred_type + ); + + } + + /** + * Preferences + * @since 0.1 + * @version 1.3 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -

    -
    -
    -
    - - - core->template_tags_general(__('If you use a negative value and the user does not have enough %_plural%, the "Create Group" button will be disabled.', 'mycred')); ?> -
    -
    -
    -
    - - - core->template_tags_general(__('The number of members a group must gain before awarding %_plural%. Use zero to award as soon as the group is created.', 'mycred')); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + + core->template_tags_general( __( 'If you use a negative value and the user does not have enough %_plural%, the "Create Group" button will be disabled.', 'mycred' ) ); ?> +
    +
    +
    +
    + + + core->template_tags_general( __( 'The number of members a group must gain before awarding %_plural%. Use zero to award as soon as the group is created.', 'mycred' ) ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'avatar', 'limit' )), $this->field_id(array( 'avatar', 'limit' )), $prefs['avatar']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'avatar', 'limit' ) ), $this->field_id( array( 'avatar', 'limit' ) ), $prefs['avatar']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'cover', 'limit' )), $this->field_id(array( 'cover', 'limit' )), $prefs['cover']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'cover', 'limit' ) ), $this->field_id( array( 'cover', 'limit' ) ), $prefs['cover']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_topic', 'limit' )), $this->field_id(array( 'new_topic', 'limit' )), $prefs['new_topic']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_topic', 'limit' ) ), $this->field_id( array( 'new_topic', 'limit' ) ), $prefs['new_topic']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'edit_topic', 'limit' )), $this->field_id(array( 'edit_topic', 'limit' )), $prefs['edit_topic']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'edit_topic', 'limit' ) ), $this->field_id( array( 'edit_topic', 'limit' ) ), $prefs['edit_topic']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_post', 'limit' )), $this->field_id(array( 'new_post', 'limit' )), $prefs['new_post']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_post', 'limit' ) ), $this->field_id( array( 'new_post', 'limit' ) ), $prefs['new_post']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'edit_post', 'limit' )), $this->field_id(array( 'edit_post', 'limit' )), $prefs['edit_post']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'edit_post', 'limit' ) ), $this->field_id( array( 'edit_post', 'limit' ) ), $prefs['edit_post']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'join', 'limit' )), $this->field_id(array( 'join', 'limit' )), $prefs['join']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'join', 'limit' ) ), $this->field_id( array( 'join', 'limit' ) ), $prefs['join']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'comments', 'limit' )), $this->field_id(array( 'comments', 'limit' )), $prefs['comments']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'comments', 'limit' ) ), $this->field_id( array( 'comments', 'limit' ) ), $prefs['comments']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - __('Contact Form 7 Form Submissions', 'mycred'), - 'description' => __('Awards %_plural% for successful form submissions (by logged in users).', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/submitting-contact-form-7-forms/', - 'callback' => array( 'myCRED_Contact_Form7' ) - ); + $installed['contact_form7'] = array( + 'title' => __( 'Contact Form 7 Form Submissions', 'mycred' ), + 'description' => __( 'Awards %_plural% for successful form submissions (by logged in users).', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/submitting-contact-form-7-forms/', + 'callback' => array( 'myCRED_Contact_Form7' ) + ); - return $installed; + return $installed; } /** * Contact Form 7 Hook - * - * @since 0.1 + * @since 0.1 * @version 1.1 */ -add_action('mycred_load_hooks', 'mycred_load_contact_form_seven_hook', 50); -function mycred_load_contact_form_seven_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_Contact_Form7') || ! function_exists('wpcf7') ) { return; - } - - class myCRED_Contact_Form7 extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'contact_form7', - 'defaults' => array() - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 0.1 - * @version 1.0 - */ - public function run() - { - - add_action('wpcf7_mail_sent', array( $this, 'form_submission' )); - - } - - /** - * Get Forms - * Queries all Contact Form 7 forms. - * - * @since 0.1 - * @version 1.3 - */ - public function get_forms() - { - - global $wpdb; - - $restuls = array(); - $posts_table = mycred_get_db_column('posts'); - $forms = $wpdb->get_results( - $wpdb->prepare( - " +add_action( 'mycred_load_hooks', 'mycred_load_contact_form_seven_hook', 50 ); +function mycred_load_contact_form_seven_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_Contact_Form7' ) || ! function_exists( 'wpcf7' ) ) return; + + class myCRED_Contact_Form7 extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'contact_form7', + 'defaults' => array() + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 0.1 + * @version 1.0 + */ + public function run() { + + add_action( 'wpcf7_mail_sent', array( $this, 'form_submission' ) ); + + } + + /** + * Get Forms + * Queries all Contact Form 7 forms. + * @since 0.1 + * @version 1.3 + */ + public function get_forms() { + + global $wpdb; + + $restuls = array(); + $posts_table = mycred_get_db_column( 'posts' ); + $forms = $wpdb->get_results( $wpdb->prepare( " SELECT ID, post_title FROM {$posts_table} WHERE post_type = %s - ORDER BY ID ASC;", 'wpcf7_contact_form' - ) - ); - - if ($forms ) { - foreach ( $forms as $form ) { - $restuls[ $form->ID ] = $form->post_title; - } - } - - return $restuls; - - } - - /** - * Successful Form Submission - * - * @since 0.1 - * @version 1.4.1 - */ - public function form_submission( $form_object ) - { - - // Login is required - if (! is_user_logged_in() ) { return; - } - - $form_id = ( version_compare(WPCF7_VERSION, '4.8', '<') ) ? $form_object->id : $form_object->id(); - - if (! isset($this->prefs[ $form_id ]) || ! $this->prefs[ $form_id ]['creds'] != 0 ) { return; - } - - // Check for exclusions - $user_id = get_current_user_id(); - if ($this->core->exclude_user($user_id) ) { return; - } - - // Limit - if ($this->over_hook_limit($form_id, 'contact_form_submission') ) { return; - } - - $this->core->add_creds( - 'contact_form_submission', - $user_id, - $this->prefs[ $form_id ]['creds'], - $this->prefs[ $form_id ]['log'], - $form_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - - } - - /** - * Preferences for Contact Form 7 Hook - * - * @since 0.1 - * @version 1.2.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - if ($prefs === false ) { $prefs = array(); - } - - $forms = $this->get_forms(); - - // No forms found - if (empty($forms) ) { - echo '

    ' . __('No forms found.', 'mycred') . '

    '; - return; - } - - // Loop though prefs to make sure we always have a default settings (happens when a new form has been created) - foreach ( $forms as $form_id => $form_title ) { - - if (! array_key_exists($form_id, $prefs) ) { - $prefs[ $form_id ] = array( - 'creds' => 0, - 'log' => '%plural% for submitting form', - 'limit' => '0/x' - ); - } - - if (! isset($prefs[ $form_id ]['limit']) ) { - $prefs[ $form_id ]['limit'] = '0/x'; - } - - } - - // Set pref if empty - if (empty($prefs) ) { $this->prefs = $prefs; - } - - // Loop for settings - foreach ( $forms as $form_id => $form_title ) { - - ?> + ORDER BY ID ASC;", 'wpcf7_contact_form' ) ); + + if ( $forms ) { + foreach ( $forms as $form ) + $restuls[ $form->ID ] = $form->post_title; + } + + return $restuls; + + } + + /** + * Successful Form Submission + * @since 0.1 + * @version 1.4.1 + */ + public function form_submission( $form_object ) { + + // Login is required + if ( ! is_user_logged_in() ) return; + + $form_id = ( version_compare( WPCF7_VERSION, '4.8', '<' ) ) ? $form_object->id : $form_object->id(); + + if ( ! isset( $this->prefs[ $form_id ] ) || ! $this->prefs[ $form_id ]['creds'] != 0 ) return; + + // Check for exclusions + $user_id = get_current_user_id(); + if ( $this->core->exclude_user( $user_id ) ) return; + + // Limit + if ( $this->over_hook_limit( $form_id, 'contact_form_submission' ) ) return; + + $this->core->add_creds( + 'contact_form_submission', + $user_id, + $this->prefs[ $form_id ]['creds'], + $this->prefs[ $form_id ]['log'], + $form_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + + } + + /** + * Preferences for Contact Form 7 Hook + * @since 0.1 + * @version 1.2.1 + */ + public function preferences() { + + $prefs = $this->prefs; + if ( $prefs === false ) $prefs = array(); + + $forms = $this->get_forms(); + + // No forms found + if ( empty( $forms ) ) { + echo '

    ' . __( 'No forms found.', 'mycred' ) . '

    '; + return; + } + + // Loop though prefs to make sure we always have a default settings (happens when a new form has been created) + foreach ( $forms as $form_id => $form_title ) { + + if ( ! array_key_exists( $form_id, $prefs ) ) { + $prefs[ $form_id ] = array( + 'creds' => 0, + 'log' => '%plural% for submitting form', + 'limit' => '0/x' + ); + } + + if ( ! isset( $prefs[ $form_id ]['limit'] ) ) + $prefs[ $form_id ]['limit'] = '0/x'; + + } + + // Set pref if empty + if ( empty( $prefs ) ) $this->prefs = $prefs; + + // Loop for settings + foreach ( $forms as $form_id => $form_title ) { + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( $form_id, 'limit' )), $this->field_id(array( $form_id, 'limit' )), $prefs[ $form_id ]['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( $form_id, 'limit' ) ), $this->field_id( array( $form_id, 'limit' ) ), $prefs[ $form_id ]['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - get_forms(); - foreach ( $forms as $form_id => $form_title ) { + $forms = $this->get_forms(); + foreach ( $forms as $form_id => $form_title ) { - if (isset($data[ $form_id ]['limit']) && isset($data[ $form_id ]['limit_by']) ) { - $limit = sanitize_text_field($data[ $form_id ]['limit']); - if ($limit == '' ) { $limit = 0; - } - $data[ $form_id ]['limit'] = $limit . '/' . $data[ $form_id ]['limit_by']; - unset($data[ $form_id ]['limit_by']); - } + if ( isset( $data[ $form_id ]['limit'] ) && isset( $data[ $form_id ]['limit_by'] ) ) { + $limit = sanitize_text_field( $data[ $form_id ]['limit'] ); + if ( $limit == '' ) $limit = 0; + $data[ $form_id ]['limit'] = $limit . '/' . $data[ $form_id ]['limit_by']; + unset( $data[ $form_id ]['limit_by'] ); + } - } + } - return $data; + return $data; - } + } - } + } } diff --git a/includes/hooks/external/mycred-hook-events-manager-light.php b/includes/hooks/external/mycred-hook-events-manager-light.php index 0be8fe3..0c8c1bd 100644 --- a/includes/hooks/external/mycred-hook-events-manager-light.php +++ b/includes/hooks/external/mycred-hook-events-manager-light.php @@ -1,299 +1,266 @@ __('Events Manager', 'mycred'), - 'description' => __('Awards %_plural% for users attending events.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/event-attendance/', - 'callback' => array( 'myCRED_Hook_Events_Manager' ) - ); + $installed['eventsmanager'] = array( + 'title' => __( 'Events Manager', 'mycred' ), + 'description' => __( 'Awards %_plural% for users attending events.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/event-attendance/', + 'callback' => array( 'myCRED_Hook_Events_Manager' ) + ); - return $installed; + return $installed; } /** * Events Manager Hook - * - * @since 1.1 + * @since 1.1 * @version 1.3.1 */ -add_action('mycred_load_hooks', 'mycred_load_events_manager_light_hook', 55); -function mycred_load_events_manager_light_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_Hook_Events_Manager') || ! function_exists('bp_em_init') ) { return; - } - - class myCRED_Hook_Events_Manager extends myCRED_Hook - { - - /** - * Construct - */ - function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'eventsmanager', - 'defaults' => array( - 'attend' => array( - 'creds' => 1, - 'log' => '%plural% for attending an event', - 'limit' => '0/x' - ), - 'cancel' => array( - 'creds' => 1, - 'log' => '%plural% for cancelled attendance an event' - ) - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.1 - * @version 1.2 - */ - public function run() - { - - if (get_option('dbem_multiple_bookings') ) { - add_action('em_bookings_added', array( $this, 'multiple_bookings' )); - - } else { - add_filter('em_bookings_add', array( $this, 'new_booking' ), 10, 2); - } - - add_filter('em_booking_set_status', array( $this, 'adjust_booking' ), 10, 2); - - } - - /** - * New Booking - * When users can make their own bookings. - * - * @since 1.1 - * @version 1.3 - */ - public function new_booking( $result, $booking ) - { - - // If bookings get automatically approved and booking was successfully added, add points - if (get_option('dbem_bookings_approval') == 0 && $result === true ) { - - // Check for exclusion - if ($this->core->exclude_user($booking->person_id) ) { return $result; - } - - // Limit - if (! $this->over_hook_limit('attend', 'event_booking', $booking->person_id) ) { - $this->core->add_creds( - 'event_booking', - $booking->person_id, - $this->prefs['attend']['creds'], - $this->prefs['attend']['log'], - $booking->event->post_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - } - - } - - return $result; - - } - - /** - * New Multiple Bookings - * - * @since 1.5.4 - * @version 1.1 - */ - public function multiple_bookings( $bookings ) - { - - foreach ( $bookings->get_bookings() as $EM_Booking ) { - - // Check for exclusion - if ($this->core->exclude_user($EM_Booking->person_id) ) { continue; - } - - // Limit - if (! $this->over_hook_limit('attend', 'event_booking', $EM_Booking->person_id) ) { - $this->core->add_creds( - 'event_booking', - $EM_Booking->person_id, - $this->prefs['attend']['creds'], - $this->prefs['attend']['log'], - $EM_Booking->event->post_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - } - - } - - } - - /** - * Adjust Booking - * Incase an administrator needs to approve bookings first or if booking gets - * cancelled. - * - * @since 1.1 - * @version 1.3 - */ - public function adjust_booking( $result, $booking ) - { - - // Check for exclusion - if ($this->core->exclude_user($booking->person_id) ) { return $result; - } - - // If the new status is 'approved', add points - if ($booking->booking_status == 1 && $booking->previous_status != 1 ) { - - // If we do not award points for attending an event bail now - if ($this->prefs['attend']['creds'] == 0 ) { return $result; - } - - // Limit - if (! $this->over_hook_limit('attend', 'event_attendance', $booking->person_id) ) { - $this->core->add_creds( - 'event_attendance', - $booking->person_id, - $this->prefs['attend']['creds'], - $this->prefs['attend']['log'], - $booking->event->post_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - } - } - - // Else if status got changed from previously 'approved', remove points given - elseif ($booking->booking_status != 1 && $booking->previous_status == 1 ) { - - // If we do not deduct points for cancellation bail now - if ($this->prefs['cancel']['creds'] == 0 ) { return $result; - } - - // Execute - $this->core->add_creds( - 'cancelled_event_attendance', - $booking->person_id, - $this->prefs['cancel']['creds'], - $this->prefs['cancel']['log'], - $booking->event->post_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - } - - return $result; - - } - - /** - * Preferences for Events Manager - * - * @since 1.1 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +add_action( 'mycred_load_hooks', 'mycred_load_events_manager_light_hook', 55 ); +function mycred_load_events_manager_light_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_Hook_Events_Manager' ) || ! function_exists( 'bp_em_init' ) ) return; + + class myCRED_Hook_Events_Manager extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'eventsmanager', + 'defaults' => array( + 'attend' => array( + 'creds' => 1, + 'log' => '%plural% for attending an event', + 'limit' => '0/x' + ), + 'cancel' => array( + 'creds' => 1, + 'log' => '%plural% for cancelled attendance an event' + ) + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.1 + * @version 1.2 + */ + public function run() { + + if ( get_option( 'dbem_multiple_bookings' ) ) + add_action( 'em_bookings_added', array( $this, 'multiple_bookings' ) ); + + else + add_filter( 'em_bookings_add', array( $this, 'new_booking' ), 10, 2 ); + + add_filter( 'em_booking_set_status', array( $this, 'adjust_booking' ), 10, 2 ); + + } + + /** + * New Booking + * When users can make their own bookings. + * @since 1.1 + * @version 1.3 + */ + public function new_booking( $result, $booking ) { + + // If bookings get automatically approved and booking was successfully added, add points + if ( get_option( 'dbem_bookings_approval' ) == 0 && $result === true ) { + + // Check for exclusion + if ( $this->core->exclude_user( $booking->person_id ) ) return $result; + + // Limit + if ( ! $this->over_hook_limit( 'attend', 'event_booking', $booking->person_id ) ) + $this->core->add_creds( + 'event_booking', + $booking->person_id, + $this->prefs['attend']['creds'], + $this->prefs['attend']['log'], + $booking->event->post_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + + } + + return $result; + + } + + /** + * New Multiple Bookings + * @since 1.5.4 + * @version 1.1 + */ + public function multiple_bookings( $bookings ) { + + foreach ( $bookings->get_bookings() as $EM_Booking ) { + + // Check for exclusion + if ( $this->core->exclude_user( $EM_Booking->person_id ) ) continue; + + // Limit + if ( ! $this->over_hook_limit( 'attend', 'event_booking', $EM_Booking->person_id ) ) + $this->core->add_creds( + 'event_booking', + $EM_Booking->person_id, + $this->prefs['attend']['creds'], + $this->prefs['attend']['log'], + $EM_Booking->event->post_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + + } + + } + + /** + * Adjust Booking + * Incase an administrator needs to approve bookings first or if booking gets + * cancelled. + * @since 1.1 + * @version 1.3 + */ + public function adjust_booking( $result, $booking ) { + + // Check for exclusion + if ( $this->core->exclude_user( $booking->person_id ) ) return $result; + + // If the new status is 'approved', add points + if ( $booking->booking_status == 1 && $booking->previous_status != 1 ) { + + // If we do not award points for attending an event bail now + if ( $this->prefs['attend']['creds'] == 0 ) return $result; + + // Limit + if ( ! $this->over_hook_limit( 'attend', 'event_attendance', $booking->person_id ) ) + $this->core->add_creds( + 'event_attendance', + $booking->person_id, + $this->prefs['attend']['creds'], + $this->prefs['attend']['log'], + $booking->event->post_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + } + + // Else if status got changed from previously 'approved', remove points given + elseif ( $booking->booking_status != 1 && $booking->previous_status == 1 ) { + + // If we do not deduct points for cancellation bail now + if ( $this->prefs['cancel']['creds'] == 0 ) return $result; + + // Execute + $this->core->add_creds( + 'cancelled_event_attendance', + $booking->person_id, + $this->prefs['cancel']['creds'], + $this->prefs['cancel']['log'], + $booking->event->post_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + } + + return $result; + + } + + /** + * Preferences for Events Manager + * @since 1.1 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'attend' => 'limit' )), $this->field_id(array( 'attend' => 'limit' )), $prefs['attend']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'attend' => 'limit' ) ), $this->field_id( array( 'attend' => 'limit' ) ), $prefs['attend']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - __('Gravityform Submissions', 'mycred'), - 'description' => __('Awards %_plural% for successful form submissions.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/submitting-gravity-forms/', - 'callback' => array( 'myCRED_Gravity_Forms' ) - ); + $installed['gravityform'] = array( + 'title' => __( 'Gravityform Submissions', 'mycred' ), + 'description' => __( 'Awards %_plural% for successful form submissions.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/submitting-gravity-forms/', + 'callback' => array( 'myCRED_Gravity_Forms' ) + ); - return $installed; + return $installed; } /** * Gravity Forms Hook - * - * @since 1.4 + * @since 1.4 * @version 1.1.1 */ -add_action('mycred_load_hooks', 'mycred_load_gravity_forms_hook', 65); -function mycred_load_gravity_forms_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_Gravity_Forms') || ! class_exists('GFForms') ) { return; - } - - class myCRED_Gravity_Forms extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'gravityform', - 'defaults' => array() - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.4 - * @version 1.0 - */ - public function run() - { - - add_action('gform_after_submission', array( $this, 'form_submission' ), 10, 2); - - } - - /** - * Successful Form Submission - * - * @since 1.4 - * @version 1.1 - */ - public function form_submission( $lead, $form ) - { - - // Login is required - if (! is_user_logged_in() || ! isset($lead['form_id']) ) { return; - } - - // Prep - $user_id = absint($lead['created_by']); - $form_id = absint($lead['form_id']); - - // Make sure form is setup and user is not excluded - if (! isset($this->prefs[ $form_id ]) || $this->core->exclude_user($user_id) ) { return; - } - - // Limit - if ($this->over_hook_limit($form_id, 'gravity_form_submission') ) { return; - } - - // Default values - $amount = $this->prefs[ $form_id ]['creds']; - $entry = $this->prefs[ $form_id ]['log']; - - // See if the form contains myCRED fields that override these defaults - if (isset($form['fields']) && ! empty($form['fields']) ) { - foreach ( $form['fields'] as $field ) { - - // Amount override - if ($field->label == 'mycred_amount' ) { - $amount = $this->core->number($field->defaultValue); - } - - // Entry override - if ($field->label == 'mycred_entry' ) { - $entry = sanitize_text_field($field->defaultValue); - } - - } - } - - // Amount can not be zero - if ($amount == 0 ) { return; - } - - // Execute - $this->core->add_creds( - 'gravity_form_submission', - $user_id, - $amount, - $entry, - $form_id, - '', - $this->mycred_type - ); - - } - - /** - * Preferences for Gravityforms Hook - * - * @since 1.4 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - $forms = RGFormsModel::get_forms(); - - // No forms found - if (empty($forms) ) { - echo '

    ' . __('No forms found.', 'mycred') . '

    '; - return; - } - - // Loop though prefs to make sure we always have a default setting - foreach ( $forms as $form ) { - if (! isset($prefs[ $form->id ]) ) { - $prefs[ $form->id ] = array( - 'creds' => 1, - 'log' => '', - 'limit' => '0/x' - ); - } - - if (! isset($prefs[ $form->id ]['limit']) ) { - $prefs[ $form->id ]['limit'] = '0/x'; - } - } - - // Set pref if empty - if (empty($prefs) ) { $this->prefs = $prefs; - } - - // Loop for settings - foreach ( $forms as $form ) { - - ?> +add_action( 'mycred_load_hooks', 'mycred_load_gravity_forms_hook', 65 ); +function mycred_load_gravity_forms_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_Gravity_Forms' ) || ! class_exists( 'GFForms' ) ) return; + + class myCRED_Gravity_Forms extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'gravityform', + 'defaults' => array() + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.4 + * @version 1.0 + */ + public function run() { + + add_action( 'gform_after_submission', array( $this, 'form_submission' ), 10, 2 ); + + } + + /** + * Successful Form Submission + * @since 1.4 + * @version 1.1 + */ + public function form_submission( $lead, $form ) { + + // Login is required + if ( ! is_user_logged_in() || ! isset( $lead['form_id'] ) ) return; + + // Prep + $user_id = absint( $lead['created_by'] ); + $form_id = absint( $lead['form_id'] ); + + // Make sure form is setup and user is not excluded + if ( ! isset( $this->prefs[ $form_id ] ) || $this->core->exclude_user( $user_id ) ) return; + + // Limit + if ( $this->over_hook_limit( $form_id, 'gravity_form_submission' ) ) return; + + // Default values + $amount = $this->prefs[ $form_id ]['creds']; + $entry = $this->prefs[ $form_id ]['log']; + + // See if the form contains myCRED fields that override these defaults + if ( isset( $form['fields'] ) && ! empty( $form['fields'] ) ) { + foreach ( $form['fields'] as $field ) { + + // Amount override + if ( $field->label == 'mycred_amount' ) { + $amount = $this->core->number( $field->defaultValue ); + } + + // Entry override + if ( $field->label == 'mycred_entry' ) { + $entry = sanitize_text_field( $field->defaultValue ); + } + + } + } + + // Amount can not be zero + if ( $amount == 0 ) return; + + // Execute + $this->core->add_creds( + 'gravity_form_submission', + $user_id, + $amount, + $entry, + $form_id, + '', + $this->mycred_type + ); + + } + + /** + * Preferences for Gravityforms Hook + * @since 1.4 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + $forms = RGFormsModel::get_forms(); + + // No forms found + if ( empty( $forms ) ) { + echo '

    ' . __( 'No forms found.', 'mycred' ) . '

    '; + return; + } + + // Loop though prefs to make sure we always have a default setting + foreach ( $forms as $form ) { + if ( ! isset( $prefs[ $form->id ] ) ) { + $prefs[ $form->id ] = array( + 'creds' => 1, + 'log' => '', + 'limit' => '0/x' + ); + } + + if ( ! isset( $prefs[ $form->id ]['limit'] ) ) + $prefs[ $form->id ]['limit'] = '0/x'; + } + + // Set pref if empty + if ( empty( $prefs ) ) $this->prefs = $prefs; + + // Loop for settings + foreach ( $forms as $form ) { + +?>
    -

    title); ?>

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( $form->id, 'limit' )), $this->field_id(array( $form->id, 'limit' )), $prefs[ $form->id ]['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    title ); ?>

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( $form->id, 'limit' ) ), $this->field_id( array( $form->id, 'limit' ) ), $prefs[ $form->id ]['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - id ]['limit']) && isset($data[ $form->id ]['limit_by']) ) { - $limit = sanitize_text_field($data[ $form->id ]['limit']); - if ($limit == '' ) { $limit = 0; - } - $data[ $form->id ]['limit'] = $limit . '/' . $data[ $form->id ]['limit_by']; - unset($data[ $form->id ]['limit_by']); - } + if ( isset( $data[ $form->id ]['limit'] ) && isset( $data[ $form->id ]['limit_by'] ) ) { + $limit = sanitize_text_field( $data[ $form->id ]['limit'] ); + if ( $limit == '' ) $limit = 0; + $data[ $form->id ]['limit'] = $limit . '/' . $data[ $form->id ]['limit_by']; + unset( $data[ $form->id ]['limit_by'] ); + } - } + } - return $data; + return $data; - } + } - } + } } diff --git a/includes/hooks/external/mycred-hook-invite-anyone.php b/includes/hooks/external/mycred-hook-invite-anyone.php index a036c1d..d0e639b 100644 --- a/includes/hooks/external/mycred-hook-invite-anyone.php +++ b/includes/hooks/external/mycred-hook-invite-anyone.php @@ -1,318 +1,283 @@ __('Invite Anyone Plugin', 'mycred'), - 'description' => __('Awards %_plural% for sending invitations and/or %_plural% if the invite is accepted.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/inviting-users/', - 'callback' => array( 'myCRED_Invite_Anyone' ) - ); + $installed['invite_anyone'] = array( + 'title' => __( 'Invite Anyone Plugin', 'mycred' ), + 'description' => __( 'Awards %_plural% for sending invitations and/or %_plural% if the invite is accepted.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/inviting-users/', + 'callback' => array( 'myCRED_Invite_Anyone' ) + ); - return $installed; + return $installed; } /** * Invite Anyone Hook - * - * @since 0.1 + * @since 0.1 * @version 1.4.1 */ -add_action('mycred_load_hooks', 'mycred_load_invite_anyone_hook', 70); -function mycred_load_invite_anyone_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_Invite_Anyone') || ! function_exists('invite_anyone_init') ) { return; - } - - class myCRED_Invite_Anyone extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'invite_anyone', - 'defaults' => array( - 'send_invite' => array( - 'creds' => 1, - 'log' => '%plural% for sending an invitation', - 'limit' => '0/x' - ), - 'accept_invite' => array( - 'creds' => 1, - 'log' => '%plural% for accepted invitation', - 'limit' => '0/x' - ) - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 0.1 - * @version 1.1 - */ - public function run() - { - - if ($this->prefs['send_invite']['creds'] != 0 ) { - add_action('sent_email_invite', array( $this, 'send_invite' ), 10, 3); - } - - if ($this->prefs['accept_invite']['creds'] != 0 ) { - - // Hook into user activation - if (function_exists('buddypress') ) { - add_action('bp_core_activated_user', array( $this, 'verified_signup' )); - } - - add_action('accepted_email_invite', array( $this, 'accept_invite' ), 10, 2); - - } - - } - - /** - * Sending Invites - * - * @since 0.1 - * @version 1.2 - */ - public function send_invite( $user_id, $email, $group ) - { - - // Check for exclusion - if ($this->core->exclude_user($user_id) ) { return; - } - - // Limit - if ($this->over_hook_limit('send_invite', 'sending_an_invite', $user_id) ) { return; - } - - // Award Points - $this->core->add_creds( - 'sending_an_invite', - $user_id, - $this->prefs['send_invite']['creds'], - $this->prefs['send_invite']['log'], - 0, - '', - $this->mycred_type - ); - - } - - /** - * Verified Signup - * If signups needs to be verified, award points first when they are. - * - * @since 1.4.6 - * @version 1.1 - */ - public function verified_signup( $user_id ) - { - - // Get Pending List - $pending = get_transient('mycred-pending-bp-signups'); - if ($pending === false || ! isset($pending[ $user_id ]) ) { return; - } - - // Check for exclusion - if (! $this->core->exclude_user($pending[ $user_id ]) && ! $this->over_hook_limit('accept_invite', 'accepting_an_invite', $pending[ $user_id ]) ) { - $this->core->add_creds( - 'accepting_an_invite', - $pending[ $user_id ], - $this->prefs['accept_invite']['creds'], - $this->prefs['accept_invite']['log'], - $user_id, - array( 'ref_type' => 'user' ), - $this->mycred_type - ); - } - - // Remove from list - unset($pending[ $user_id ]); - - // Update pending list - delete_transient('mycred-pending-bp-signups'); - set_transient('mycred-pending-bp-signups', $pending, 7 * DAY_IN_SECONDS); - - } - - /** - * Accepting Invites - * - * @since 0.1 - * @version 1.3.1 - */ - public function accept_invite( $invited_user_id, $inviters = array() ) - { - - if (empty($inviters) ) { return; - } - - // Invite Anyone will pass on an array of user IDs of those who have invited this user which we need to loop though - foreach ( (array) $inviters as $inviter_id ) { - - // Check for exclusion - if ($this->core->exclude_user($inviter_id) ) { continue; - } - - // Award Points - $run = true; - - if (function_exists('buddypress') ) { - - $run = false; - - // Get pending list - $pending = get_transient('mycred-pending-bp-signups'); - if ($pending === false ) { - $pending = array(); - } - - // Add to pending list if not there already - if (! isset($pending[ $invited_user_id ]) ) { - $pending[ $invited_user_id ] = $inviter_id; - - delete_transient('mycred-pending-bp-signups'); - set_transient('mycred-pending-bp-signups', $pending, 7 * DAY_IN_SECONDS); - } - - } - - if ($run && ! $this->over_hook_limit('accept_invite', 'accepting_an_invite', $inviter_id) ) { - $this->core->add_creds( - 'accepting_an_invite', - $inviter_id, - $this->prefs['accept_invite']['creds'], - $this->prefs['accept_invite']['log'], - $invited_user_id, - array( 'ref_type' => 'user' ), - $this->mycred_type - ); - } - - } - - } - - /** - * Preferences - * - * @since 0.1 - * @version 1.2 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +add_action( 'mycred_load_hooks', 'mycred_load_invite_anyone_hook', 70 ); +function mycred_load_invite_anyone_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_Invite_Anyone' ) || ! function_exists( 'invite_anyone_init' ) ) return; + + class myCRED_Invite_Anyone extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'invite_anyone', + 'defaults' => array( + 'send_invite' => array( + 'creds' => 1, + 'log' => '%plural% for sending an invitation', + 'limit' => '0/x' + ), + 'accept_invite' => array( + 'creds' => 1, + 'log' => '%plural% for accepted invitation', + 'limit' => '0/x' + ) + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 0.1 + * @version 1.1 + */ + public function run() { + + if ( $this->prefs['send_invite']['creds'] != 0 ) + add_action( 'sent_email_invite', array( $this, 'send_invite' ), 10, 3 ); + + if ( $this->prefs['accept_invite']['creds'] != 0 ) { + + // Hook into user activation + if ( function_exists( 'buddypress' ) ) + add_action( 'bp_core_activated_user', array( $this, 'verified_signup' ) ); + + add_action( 'accepted_email_invite', array( $this, 'accept_invite' ), 10, 2 ); + + } + + } + + /** + * Sending Invites + * @since 0.1 + * @version 1.2 + */ + public function send_invite( $user_id, $email, $group ) { + + // Check for exclusion + if ( $this->core->exclude_user( $user_id ) ) return; + + // Limit + if ( $this->over_hook_limit( 'send_invite', 'sending_an_invite', $user_id ) ) return; + + // Award Points + $this->core->add_creds( + 'sending_an_invite', + $user_id, + $this->prefs['send_invite']['creds'], + $this->prefs['send_invite']['log'], + 0, + '', + $this->mycred_type + ); + + } + + /** + * Verified Signup + * If signups needs to be verified, award points first when they are. + * @since 1.4.6 + * @version 1.1 + */ + public function verified_signup( $user_id ) { + + // Get Pending List + $pending = get_transient( 'mycred-pending-bp-signups' ); + if ( $pending === false || ! isset( $pending[ $user_id ] ) ) return; + + // Check for exclusion + if ( ! $this->core->exclude_user( $pending[ $user_id ] ) && ! $this->over_hook_limit( 'accept_invite', 'accepting_an_invite', $pending[ $user_id ] ) ) + $this->core->add_creds( + 'accepting_an_invite', + $pending[ $user_id ], + $this->prefs['accept_invite']['creds'], + $this->prefs['accept_invite']['log'], + $user_id, + array( 'ref_type' => 'user' ), + $this->mycred_type + ); + + // Remove from list + unset( $pending[ $user_id ] ); + + // Update pending list + delete_transient( 'mycred-pending-bp-signups' ); + set_transient( 'mycred-pending-bp-signups', $pending, 7 * DAY_IN_SECONDS ); + + } + + /** + * Accepting Invites + * @since 0.1 + * @version 1.3.1 + */ + public function accept_invite( $invited_user_id, $inviters = array() ) { + + if ( empty( $inviters ) ) return; + + // Invite Anyone will pass on an array of user IDs of those who have invited this user which we need to loop though + foreach ( (array) $inviters as $inviter_id ) { + + // Check for exclusion + if ( $this->core->exclude_user( $inviter_id ) ) continue; + + // Award Points + $run = true; + + if ( function_exists( 'buddypress' ) ) { + + $run = false; + + // Get pending list + $pending = get_transient( 'mycred-pending-bp-signups' ); + if ( $pending === false ) + $pending = array(); + + // Add to pending list if not there already + if ( ! isset( $pending[ $invited_user_id ] ) ) { + $pending[ $invited_user_id ] = $inviter_id; + + delete_transient( 'mycred-pending-bp-signups' ); + set_transient( 'mycred-pending-bp-signups', $pending, 7 * DAY_IN_SECONDS ); + } + + } + + if ( $run && ! $this->over_hook_limit( 'accept_invite', 'accepting_an_invite', $inviter_id ) ) + $this->core->add_creds( + 'accepting_an_invite', + $inviter_id, + $this->prefs['accept_invite']['creds'], + $this->prefs['accept_invite']['log'], + $invited_user_id, + array( 'ref_type' => 'user' ), + $this->mycred_type + ); + + } + + } + + /** + * Preferences + * @since 0.1 + * @version 1.2 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'send_invite' => 'limit' )), $this->field_id(array( 'send_invite' => 'limit' )), $prefs['send_invite']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'send_invite' => 'limit' ) ), $this->field_id( array( 'send_invite' => 'limit' ) ), $prefs['send_invite']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'accept_invite' => 'limit' )), $this->field_id(array( 'accept_invite' => 'limit' )), $prefs['accept_invite']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'accept_invite' => 'limit' ) ), $this->field_id( array( 'accept_invite' => 'limit' ) ), $prefs['accept_invite']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - __('Jetpack Subscriptions', 'mycred'), - 'description' => __('Awards %_plural% for users signing up for site or comment updates using Jetpack.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/jetpack-subscriptions/', - 'callback' => array( 'myCRED_Hook_Jetpack' ) - ); + $installed['jetpack'] = array( + 'title' => __( 'Jetpack Subscriptions', 'mycred' ), + 'description' => __( 'Awards %_plural% for users signing up for site or comment updates using Jetpack.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/jetpack-subscriptions/', + 'callback' => array( 'myCRED_Hook_Jetpack' ) + ); - return $installed; + return $installed; } /** * Jetpack Hook - * - * @since 1.0.5 + * @since 1.0.5 * @version 1.1.1 */ -add_action('mycred_load_hooks', 'mycred_load_jetpack_hook', 75); -function mycred_load_jetpack_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_Hook_Jetpack') || ! defined('JETPACK__PLUGIN_DIR') ) { return; - } - - class myCRED_Hook_Jetpack extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'jetpack', - 'defaults' => array( - 'subscribe_site' => array( - 'creds' => 1, - 'log' => '%plural% for site subscription' - ), - 'subscribe_comment' => array( - 'creds' => 1, - 'log' => '%plural% for comment subscription' - ) - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.0.5 - * @version 1.0 - */ - public function run() - { - - // Site Subscriptions - if ($this->prefs['subscribe_site']['creds'] != 0 ) { - add_filter('wp_redirect', array( $this, 'submit_redirect' ), 1); - } - - // Comment Subscriptions - if ($this->prefs['subscribe_comment']['creds'] != 0 ) { - add_action('comment_post', array( $this, 'comment_subscribe_submit' ), 99, 2); - } - - add_action('mycred_admin_init', array( $this, 'admin_init' )); - - } - - /** - * Admin Init - * Check pending emails if they have confirmed their subscription. If it's confirmed - * and no previous points have been awarded we do that here. Else if the email is marked - * as pending we save it for a later try. - * - * @since 1.0.5 - * @version 1.1.1 - */ - public function admin_init() - { - - $types = array(); - - if ($this->prefs['subscribe_site']['creds'] != 0 ) { - $types[] = 'site'; - } - - if ($this->prefs['subscribe_comment']['creds'] != 0 ) { - $types[] = 'comment'; - } - - // Not enabled, bail - if (empty($types) ) { return; - } - - foreach ( $types as $type ) { - - // Get list if it exist - if (false === ( $pending = get_option('mycred_jetpack_' . $type . '_pendings') ) ) { - continue; - } - - // Make sure list is not empty - if (empty($pending) ) { - // Clean up before exit - delete_option('mycred_jetpack_' . $type . '_pendings'); - continue; - } - - $new = array(); - foreach ( $pending as $id => $email ) { - - // Validate - if (trim($email) == '' || ! is_email($email) ) { continue; - } - - // Make sure user exist - $user = get_user_by('email', $email); - if ($user === false ) { continue; - } - - // Check for exclusion - if ($this->core->exclude_user($user->ID) === true ) { continue; - } - - // Make sure this is a unique event - if ($this->core->has_entry('site_subscription', 0, $user->ID) ) { continue; - } - - // Site Subscriptions - if ($type == 'site' ) { - - // Check subscription status - $subscription = $this->check_jetpack_subscription($email); - // Active status = award points if not already - if ($subscription == 'active' ) { - // Execute - $this->core->add_creds( - 'site_subscription', - $user->ID, - $this->prefs['subscribe_site']['creds'], - $this->prefs['subscribe_site']['log'], - 0, - '', - $this->mycred_type - ); - } - - // Pending status = save so we try again later - elseif ($subscription == 'pending' ) { - $new[] = $email; - continue; - } - - } - - // Comment Subscriptions - else { - - $comment = get_comment($id); - if (empty($comment) ) { continue; - } - - // If no user id exist, check and see if the authors email is used by someone - if ($comment->user_id == 0 ) { - $user = get_user_by('email', $email); - if ($user === false ) { continue; - } - } - - // Make sure the user still exist - else { - $user = get_user_by('id', $comment->user_id); - if ($user === false ) { continue; - } - } - - // Check for exclusion - if ($this->core->exclude_user($user->ID) === true ) { continue; - } - - // Start with making sure this is a unique event - if ($this->core->has_entry('comment_subscription', $id, $user->ID) ) { continue; - } - - $post_ids = array(); - - if (isset($_REQUEST['subscribe_comments']) ) { - $post_ids[] = $comment->comment_post_ID; - } - - // Attempt to subscribe again to get results - $subscription = $this->check_jetpack_subscription($email, array( $comment->comment_post_ID )); - - // Subscription is active - if ($subscription == 'active' ) { - // Execute - $this->core->add_creds( - 'comment_subscription', - $user->ID, - $this->prefs['subscribe_comment']['creds'], - $this->prefs['subscribe_comment']['log'], - $id, - array( 'ref_type' => 'comment' ), - $this->mycred_type - ); - } - // Subscription pending - elseif ($subscription == 'pending' ) { - $new[ $id ] = $email; - } - - } - - } - - // If we still have pending emails save for later - if (! empty($new) ) { - update_option('mycred_jetpack_' . $type . '_pendings', $new); - } - - // Else delete - else { - delete_option('mycred_jetpack_' . $type . '_pendings'); - } - - } - - } - - /** - * Submit Redirect - * Checks if Jetpack signup has been executed by parsing the redirect URL. - * - * @since 1.0.5 - * @version 1.0 - */ - public function submit_redirect( $location ) - { - - // Make sure we have what we need - if (! isset($_REQUEST['jetpack_subscriptions_widget']) || ! isset($_REQUEST['email']) || empty($_REQUEST['email']) ) { - return $location; - } - - // Make sure Jetpack has executed - if (! isset($_GET['subscribe']) || $_GET['subscribe'] != 'success' ) { - return $location; - } - - // Make sure user exist - $user = get_user_by('email', $_REQUEST['email']); - if ($user === false ) { - return $location; - } - - // Check for exclusion - if ($this->core->exclude_user($user->ID) === true ) { - return $location; - } - - // Check that this is a unique event - if ($this->core->has_entry('site_subscription', '', $user->ID) ) { - return $location; - } - - $this->site_subscribe($_REQUEST['email'], $user->ID); - - return $location; - - } - - /** - * Comment Subscribe Submit - * Manage the request to subscribe to comments and/or to the blog - * Based on Jetpack Subscriptions - * - * @see jetpack/modules/subscriptions.php - * @since 1.0.5 - * @version 1.0 - */ - public function comment_subscribe_submit( $comment_id, $approved ) - { - - if ('spam' === $approved ) { return; - } - - if (! isset($_REQUEST['subscribe_comments']) && ! isset($_REQUEST['subscribe_blog']) ) { - return; - } - - $comment = get_comment($comment_id); - - // If no user id exist, check and see if the authors email is used by someone - if ($comment->user_id == 0 ) { - $user = get_user_by('email', $comment->comment_author_email); - if ($user === false ) { return; - } - } - - // Make sure the user still exist - else { - $user = get_user_by('id', $comment->user_id); - if ($user === false ) { return; - } - } - - // Check for exclusion - if ($this->core->exclude_user($user->ID) === true ) { return; - } - - // Start with making sure this is a unique event - if ($this->core->has_entry('comment_subscription', $comment_id, $user->ID) ) { return; - } - - // Handle comment subscription - if (isset($_REQUEST['subscribe_comments']) ) { - $this->comment_subscribe($comment->comment_author_email, $comment->comment_post_ID, $user->ID, $comment_id); - } - - // Handle site subscription - if (isset($_REQUEST['subscribe_blog']) ) { - $this->site_subscribe($comment->comment_author_email, $user->ID); - } - - } - - /** - * Comment Subscribe - * Awards points for active subscriptions or adds email and comment id to the pending array. - * Note! This methods should only be called once the primary checks have been made, including making sure - * the user exist, is not excluded and that this is a unique event! - * - * @since 1.0.5 - * @version 1.1 - */ - protected function comment_subscribe( $email = '', $post_ids = '', $user_id = 0, $comment_id = 0 ) - { - - // Attempt to subscribe again to get results - $subscription = $this->check_jetpack_subscription($email, $post_ids); - - // Subscription is active - if ($subscription == 'active' ) { - - // Execute - $this->core->add_creds( - 'comment_subscription', - $user_id, - $this->prefs['subscribe_comment']['creds'], - $this->prefs['subscribe_comment']['log'], - $comment_id, - array( 'ref_type' => 'comment' ), - $this->mycred_type - ); - - // Let others share our success - do_action('mycred_jetpack_comment', $user_id, $comment_id); - - } - - // Subscription pending - elseif ($subscription == 'pending' ) { - // Add email to pending list if not in it already - if (! $this->is_pending($email, $comment_id) ) { - $this->add_to_pending($email, $comment_id); - } - } - - } - - /** - * Site Subscription - * Awards points for active site subscriptions or adds email to the pending array. - * Note! This methods should only be called once the primary checks have been made, including making sure - * the user exist, is not excluded and that this is a unique event! - * - * @since 1.0.5 - * @version 1.1 - */ - protected function site_subscribe( $email = '', $user_id = 0 ) - { - - // Attempt to add this email again to check it's status - $subscription = $this->check_jetpack_subscription($email); - - // Subscription is active - if ($subscription == 'active' ) { - - // Execute - $this->core->add_creds( - 'site_subscription', - $user_id, - $this->prefs['subscribe_site']['creds'], - $this->prefs['subscribe_site']['log'], - 0, - '', - $this->mycred_type - ); - - // Let others share our success - do_action('mycred_jetpack_site', $user_id, $GLOBALS['blog_id']); - - } - - // Subscription pending - elseif ($subscription == 'pending' ) { - // Add email to pending list if not in it already - if (! $this->is_pending($email) ) { - $this->add_to_pending($email); - } - } - - } - - /** - * Check Jetpack Subscription - * - * @since 1.0.5 - * @version 1.0 - */ - protected function check_jetpack_subscription( $email = null, $post_ids = null ) - { - - if ($email === null ) { return 'missing'; - } - - if (! class_exists('Jetpack') && defined('JETPACK__PLUGIN_DIR') ) { - include_once JETPACK__PLUGIN_DIR . 'jetpack.php'; - } - - if (! class_exists('Jetpack_Subscriptions') && defined('JETPACK__PLUGIN_DIR') ) { - include_once JETPACK__PLUGIN_DIR . 'modules/subscriptions.php'; - } - - if ($post_ids === null ) { - $subscribe = Jetpack_Subscriptions::subscribe($email, 0, false); - } else { - $subscribe = Jetpack_Subscriptions::subscribe($email, $post_ids, false); - } - - if (is_wp_error($subscribe) ) { - $error = $subscribe->get_error_code(); - } - else { - $error = false; - foreach ( $subscribe as $response ) { - if (is_wp_error($response) ) { - $error = $response->get_error_code(); - break; - } - } - } - - if ($error ) { - switch ( $error ) { - case 'invalid_email': - $return = 'invalid'; - break; - case 'active': - $return = 'active'; - break; - case 'pending': - $return = 'pending'; - break; - default: - $return = ''; - break; - } - } - - else { - if (is_array($subscribe) && $subscribe[0] === true ) { - $error = true; - } - $return = 'pending'; - } - - if ($error ) { - return $return; - } - - return 'new'; - - } - - /** - * Is Pending - * Checks the given email if it's in the pending array. - * - * @param $email (string) required email to check - * @param $section (string|int) either 'site' for site subscriptions or comment id, defaults to site - * @returns (bool) true or false - * @since 1.0.5 - * @version 1.0 - */ - protected function is_pending( $email = null, $section = 'site' ) - { - - if ($email === null || trim($email) === '' ) { return; - } - - if ($section == 'site' ) { - $name = $section; - } else { - $name = 'comment'; - } - - // If pending list does not exist, create it and add our email - if (false === ( $pending = get_option('mycred_jetpack_' . $name . '_pendings') ) ) { - if ($name == 'site' ) { - $pending = array( $email ); - } else { - $pending = array( $section => $email ); - } - - update_option('mycred_jetpack_' . $name . '_pendings', $pending); - } - - // Site check - if ($section == 'site' && in_array($email, $pending) ) { - return true; - } - - // Comment check - elseif (array_key_exists($section, $pending) && $pending[ $section ] == $email ) { - return true; - } - - return false; - - } - - /** - * Add to Pending - * Adds a given email to the pending array. - * - * @param $email (string) required email to check - * @param $section (string|int) either 'site' for site subscriptions or comment id, defaults to site - * @since 1.0.5 - * @version 1.0 - */ - protected function add_to_pending( $email = null, $section = 'site' ) - { - - if ($email === null || trim($email) === '' ) { return; - } - - if ($section == 'site' ) { - $name = $section; - } else { - $name = 'comment'; - } - - // If pending list does not exist, create it and add our email - if (false === ( $pending = get_option('mycred_jetpack_' . $name . '_pendings') ) ) { - if ($name == 'site' ) { - $pending = array( $email ); - } else { - $pending = array( $section => $email ); - } - - update_option('mycred_jetpack_' . $name . '_pendings', $pending); - } - - // Site pending list - if ($section == 'site' && ! in_array($email, $pending) ) { - $pending[] = $email; - update_option('mycred_jetpack_' . $name . '_pendings', $pending); - } - - // Comment pending list - elseif (! array_key_exists($section, $pending) ) { - $pending[ $section ] = $email; - update_option('mycred_jetpack_' . $name . '_pendings', $pending); - } - - } - - /** - * Preferences - * - * @since 1.0.5 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +add_action( 'mycred_load_hooks', 'mycred_load_jetpack_hook', 75 ); +function mycred_load_jetpack_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_Hook_Jetpack' ) || ! defined( 'JETPACK__PLUGIN_DIR' ) ) return; + + class myCRED_Hook_Jetpack extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'jetpack', + 'defaults' => array( + 'subscribe_site' => array( + 'creds' => 1, + 'log' => '%plural% for site subscription' + ), + 'subscribe_comment' => array( + 'creds' => 1, + 'log' => '%plural% for comment subscription' + ) + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.0.5 + * @version 1.0 + */ + public function run() { + + // Site Subscriptions + if ( $this->prefs['subscribe_site']['creds'] != 0 ) + add_filter( 'wp_redirect', array( $this, 'submit_redirect' ), 1 ); + + // Comment Subscriptions + if ( $this->prefs['subscribe_comment']['creds'] != 0 ) + add_action( 'comment_post', array( $this, 'comment_subscribe_submit' ), 99, 2 ); + + add_action( 'mycred_admin_init', array( $this, 'admin_init' ) ); + + } + + /** + * Admin Init + * Check pending emails if they have confirmed their subscription. If it's confirmed + * and no previous points have been awarded we do that here. Else if the email is marked + * as pending we save it for a later try. + * + * @since 1.0.5 + * @version 1.1.1 + */ + public function admin_init() { + + $types = array(); + + if ( $this->prefs['subscribe_site']['creds'] != 0 ) + $types[] = 'site'; + + if ( $this->prefs['subscribe_comment']['creds'] != 0 ) + $types[] = 'comment'; + + // Not enabled, bail + if ( empty( $types ) ) return; + + foreach ( $types as $type ) { + + // Get list if it exist + if ( false === ( $pending = get_option( 'mycred_jetpack_' . $type . '_pendings' ) ) ) + continue; + + // Make sure list is not empty + if ( empty( $pending ) ) { + // Clean up before exit + delete_option( 'mycred_jetpack_' . $type . '_pendings' ); + continue; + } + + $new = array(); + foreach ( $pending as $id => $email ) { + + // Validate + if ( trim( $email ) == '' || ! is_email( $email ) ) continue; + + // Make sure user exist + $user = get_user_by( 'email', $email ); + if ( $user === false ) continue; + + // Check for exclusion + if ( $this->core->exclude_user( $user->ID ) === true ) continue; + + // Make sure this is a unique event + if ( $this->core->has_entry( 'site_subscription', 0, $user->ID ) ) continue; + + // Site Subscriptions + if ( $type == 'site' ) { + + // Check subscription status + $subscription = $this->check_jetpack_subscription( $email ); + // Active status = award points if not already + if ( $subscription == 'active' ) { + // Execute + $this->core->add_creds( + 'site_subscription', + $user->ID, + $this->prefs['subscribe_site']['creds'], + $this->prefs['subscribe_site']['log'], + 0, + '', + $this->mycred_type + ); + } + + // Pending status = save so we try again later + elseif ( $subscription == 'pending' ) { + $new[] = $email; + continue; + } + + } + + // Comment Subscriptions + else { + + $comment = get_comment( $id ); + if ( empty( $comment ) ) continue; + + // If no user id exist, check and see if the authors email is used by someone + if ( $comment->user_id == 0 ) { + $user = get_user_by( 'email', $email ); + if ( $user === false ) continue; + } + + // Make sure the user still exist + else { + $user = get_user_by( 'id', $comment->user_id ); + if ( $user === false ) continue; + } + + // Check for exclusion + if ( $this->core->exclude_user( $user->ID ) === true ) continue; + + // Start with making sure this is a unique event + if ( $this->core->has_entry( 'comment_subscription', $id, $user->ID ) ) continue; + + $post_ids = array(); + + if ( isset( $_REQUEST['subscribe_comments'] ) ) + $post_ids[] = $comment->comment_post_ID; + + // Attempt to subscribe again to get results + $subscription = $this->check_jetpack_subscription( $email, array( $comment->comment_post_ID ) ); + + // Subscription is active + if ( $subscription == 'active' ) { + // Execute + $this->core->add_creds( + 'comment_subscription', + $user->ID, + $this->prefs['subscribe_comment']['creds'], + $this->prefs['subscribe_comment']['log'], + $id, + array( 'ref_type' => 'comment' ), + $this->mycred_type + ); + } + // Subscription pending + elseif ( $subscription == 'pending' ) { + $new[ $id ] = $email; + } + + } + + } + + // If we still have pending emails save for later + if ( ! empty( $new ) ) + update_option( 'mycred_jetpack_' . $type . '_pendings', $new ); + + // Else delete + else + delete_option( 'mycred_jetpack_' . $type . '_pendings' ); + + } + + } + + /** + * Submit Redirect + * Checks if Jetpack signup has been executed by parsing the redirect URL. + * @since 1.0.5 + * @version 1.0 + */ + public function submit_redirect( $location ) { + + // Make sure we have what we need + if ( ! isset( $_REQUEST['jetpack_subscriptions_widget'] ) || ! isset( $_REQUEST['email'] ) || empty( $_REQUEST['email'] ) ) + return $location; + + // Make sure Jetpack has executed + if ( ! isset( $_GET['subscribe'] ) || $_GET['subscribe'] != 'success' ) + return $location; + + // Make sure user exist + $user = get_user_by( 'email', $_REQUEST['email'] ); + if ( $user === false ) + return $location; + + // Check for exclusion + if ( $this->core->exclude_user( $user->ID ) === true ) + return $location; + + // Check that this is a unique event + if ( $this->core->has_entry( 'site_subscription', '', $user->ID ) ) + return $location; + + $this->site_subscribe( $_REQUEST['email'], $user->ID ); + + return $location; + + } + + /** + * Comment Subscribe Submit + * Manage the request to subscribe to comments and/or to the blog + * Based on Jetpack Subscriptions + * @see jetpack/modules/subscriptions.php + * @since 1.0.5 + * @version 1.0 + */ + public function comment_subscribe_submit( $comment_id, $approved ) { + + if ( 'spam' === $approved ) return; + + if ( ! isset( $_REQUEST['subscribe_comments'] ) && ! isset( $_REQUEST['subscribe_blog'] ) ) + return; + + $comment = get_comment( $comment_id ); + + // If no user id exist, check and see if the authors email is used by someone + if ( $comment->user_id == 0 ) { + $user = get_user_by( 'email', $comment->comment_author_email ); + if ( $user === false ) return; + } + + // Make sure the user still exist + else { + $user = get_user_by( 'id', $comment->user_id ); + if ( $user === false ) return; + } + + // Check for exclusion + if ( $this->core->exclude_user( $user->ID ) === true ) return; + + // Start with making sure this is a unique event + if ( $this->core->has_entry( 'comment_subscription', $comment_id, $user->ID ) ) return; + + // Handle comment subscription + if ( isset( $_REQUEST['subscribe_comments'] ) ) + $this->comment_subscribe( $comment->comment_author_email, $comment->comment_post_ID, $user->ID, $comment_id ); + + // Handle site subscription + if ( isset( $_REQUEST['subscribe_blog'] ) ) + $this->site_subscribe( $comment->comment_author_email, $user->ID ); + + } + + /** + * Comment Subscribe + * Awards points for active subscriptions or adds email and comment id to the pending array. + * Note! This methods should only be called once the primary checks have been made, including making sure + * the user exist, is not excluded and that this is a unique event! + * @since 1.0.5 + * @version 1.1 + */ + protected function comment_subscribe( $email = '', $post_ids = '', $user_id = 0, $comment_id = 0 ) { + + // Attempt to subscribe again to get results + $subscription = $this->check_jetpack_subscription( $email, $post_ids ); + + // Subscription is active + if ( $subscription == 'active' ) { + + // Execute + $this->core->add_creds( + 'comment_subscription', + $user_id, + $this->prefs['subscribe_comment']['creds'], + $this->prefs['subscribe_comment']['log'], + $comment_id, + array( 'ref_type' => 'comment' ), + $this->mycred_type + ); + + // Let others share our success + do_action( 'mycred_jetpack_comment', $user_id, $comment_id ); + + } + + // Subscription pending + elseif ( $subscription == 'pending' ) { + // Add email to pending list if not in it already + if ( ! $this->is_pending( $email, $comment_id ) ) + $this->add_to_pending( $email, $comment_id ); + } + + } + + /** + * Site Subscription + * Awards points for active site subscriptions or adds email to the pending array. + * Note! This methods should only be called once the primary checks have been made, including making sure + * the user exist, is not excluded and that this is a unique event! + * @since 1.0.5 + * @version 1.1 + */ + protected function site_subscribe( $email = '', $user_id = 0 ) { + + // Attempt to add this email again to check it's status + $subscription = $this->check_jetpack_subscription( $email ); + + // Subscription is active + if ( $subscription == 'active' ) { + + // Execute + $this->core->add_creds( + 'site_subscription', + $user_id, + $this->prefs['subscribe_site']['creds'], + $this->prefs['subscribe_site']['log'], + 0, + '', + $this->mycred_type + ); + + // Let others share our success + do_action( 'mycred_jetpack_site', $user_id, $GLOBALS['blog_id'] ); + + } + + // Subscription pending + elseif ( $subscription == 'pending' ) { + // Add email to pending list if not in it already + if ( ! $this->is_pending( $email ) ) + $this->add_to_pending( $email ); + } + + } + + /** + * Check Jetpack Subscription + * @since 1.0.5 + * @version 1.0 + */ + protected function check_jetpack_subscription( $email = NULL, $post_ids = NULL ) { + + if ( $email === NULL ) return 'missing'; + + if ( ! class_exists( 'Jetpack' ) && defined( 'JETPACK__PLUGIN_DIR' ) ) + require_once( JETPACK__PLUGIN_DIR . 'jetpack.php' ); + + if ( ! class_exists( 'Jetpack_Subscriptions' ) && defined( 'JETPACK__PLUGIN_DIR' ) ) + require_once( JETPACK__PLUGIN_DIR . 'modules/subscriptions.php' ); + + if ( $post_ids === NULL ) + $subscribe = Jetpack_Subscriptions::subscribe( $email, 0, false ); + else + $subscribe = Jetpack_Subscriptions::subscribe( $email, $post_ids, false ); + + if ( is_wp_error( $subscribe ) ) { + $error = $subscribe->get_error_code(); + } + else { + $error = false; + foreach ( $subscribe as $response ) { + if ( is_wp_error( $response ) ) { + $error = $response->get_error_code(); + break; + } + } + } + + if ( $error ) { + switch ( $error ) { + case 'invalid_email': + $return = 'invalid'; + break; + case 'active': + $return = 'active'; + break; + case 'pending': + $return = 'pending'; + break; + default: + $return = ''; + break; + } + } + + else { + if ( is_array( $subscribe ) && $subscribe[0] === true ) + $error = true; + $return = 'pending'; + } + + if ( $error ) + return $return; + + return 'new'; + + } + + /** + * Is Pending + * Checks the given email if it's in the pending array. + * @param $email (string) required email to check + * @param $section (string|int) either 'site' for site subscriptions or comment id, defaults to site + * @returns (bool) true or false + * @since 1.0.5 + * @version 1.0 + */ + protected function is_pending( $email = NULL, $section = 'site' ) { + + if ( $email === NULL || trim( $email ) === '' ) return; + + if ( $section == 'site' ) + $name = $section; + else + $name = 'comment'; + + // If pending list does not exist, create it and add our email + if ( false === ( $pending = get_option( 'mycred_jetpack_' . $name . '_pendings' ) ) ) { + if ( $name == 'site' ) + $pending = array( $email ); + else + $pending = array( $section => $email ); + + update_option( 'mycred_jetpack_' . $name . '_pendings', $pending ); + } + + // Site check + if ( $section == 'site' && in_array( $email, $pending ) ) + return true; + + // Comment check + elseif ( array_key_exists( $section, $pending ) && $pending[ $section ] == $email ) + return true; + + return false; + + } + + /** + * Add to Pending + * Adds a given email to the pending array. + * @param $email (string) required email to check + * @param $section (string|int) either 'site' for site subscriptions or comment id, defaults to site + * @since 1.0.5 + * @version 1.0 + */ + protected function add_to_pending( $email = NULL, $section = 'site' ) { + + if ( $email === NULL || trim( $email ) === '' ) return; + + if ( $section == 'site' ) + $name = $section; + else + $name = 'comment'; + + // If pending list does not exist, create it and add our email + if ( false === ( $pending = get_option( 'mycred_jetpack_' . $name . '_pendings' ) ) ) { + if ( $name == 'site' ) + $pending = array( $email ); + else + $pending = array( $section => $email ); + + update_option( 'mycred_jetpack_' . $name . '_pendings', $pending ); + } + + // Site pending list + if ( $section == 'site' && ! in_array( $email, $pending ) ) { + $pending[] = $email; + update_option( 'mycred_jetpack_' . $name . '_pendings', $pending ); + } + + // Comment pending list + elseif ( ! array_key_exists( $section, $pending ) ) { + $pending[ $section ] = $email; + update_option( 'mycred_jetpack_' . $name . '_pendings', $pending ); + } + + } + + /** + * Preferences + * @since 1.0.5 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - 'Simple:Press', - 'description' => __('Awards %_plural% for Simple:Press actions.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/simplepress-actions/', - 'callback' => array( 'myCRED_SimplePress' ) - ); + $installed['hook_simplepress'] = array( + 'title' => 'Simple:Press', + 'description' => __( 'Awards %_plural% for Simple:Press actions.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/simplepress-actions/', + 'callback' => array( 'myCRED_SimplePress' ) + ); - return $installed; + return $installed; } /** * Simple:Press Hook - * - * @since 1.3.3 + * @since 1.3.3 * @version 1.2.1 */ -add_action('mycred_load_hooks', 'mycred_load_simplepress_hook', 85); -function mycred_load_simplepress_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_SimplePress') || ! defined('SFTOPICS') ) { return; - } - - class myCRED_SimplePress extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'hook_simplepress', - 'defaults' => array( - 'new_topic' => array( - 'creds' => 1, - 'log' => '%plural% for new forum topic', - 'limit' => '0/x' - ), - 'delete_topic' => array( - 'creds' => 0-1, - 'log' => '%singular% deduction for deleted topic' - ), - 'new_post' => array( - 'creds' => 1, - 'log' => '%plural% for new topic post', - 'author' => 0, - 'limit' => '0/x' - ), - 'delete_post' => array( - 'creds' => 0-1, - 'log' => '%singular% deduction for deleted topic reply' - ) - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.3.3 - * @version 1.0 - */ - public function run() - { - - // New Topic - if ($this->prefs['new_topic']['creds'] != 0 ) { - add_action('sph_post_create', array( $this, 'new_topic' )); - } - - // Delete Topic - if ($this->prefs['delete_topic']['creds'] != 0 ) { - add_action('sph_topic_delete', array( $this, 'delete_topic' )); - } - - // New Reply - if ($this->prefs['new_post']['creds'] != 0 ) { - add_action('sph_post_create', array( $this, 'new_post' )); - } - - // Delete Reply - if ($this->prefs['delete_post']['creds'] != 0 ) { - add_action('sph_post_delete', array( $this, 'delete_post' )); - } - - add_filter('mycred_parse_log_entry', array( $this, 'adjust_log_templates' ), 10, 2); - - } - - /** - * Custom Template Tags - * - * @since 1.3.3 - * @version 1.1 - */ - public function adjust_log_templates( $content, $log_entry ) - { - - if (! isset($log_entry->ref) || $log_entry->data != 'simplepress' ) { return $content; - } - - switch ( $log_entry->ref ) { - case 'new_forum_topic' : - - global $wpdb; - - $db = SFTOPICS; - $topic = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$db} WHERE user_id = %d AND topic_id = %d;", $log_entry->user_id, $log_entry->ref_id)); - $topic_name = ''; - - if (isset($topic->topic_name) ) { - $topic_name = $topic->topic_name; - } - - $content = str_replace('%topic_name%', $topic_name, $content); - - break; - } - - return $content; - - } - - /** - * New Topic - * - * @since 1.3.3 - * @version 1.2 - */ - public function new_topic( $post ) - { - - if ($post['action'] != 'topic' ) { return; - } - - // Topic details - $topic_author = $post['userid']; - - $forum_id = $post['forumid']; - $topic_id = $post['topicid']; - - // Check if user is excluded - if ($this->core->exclude_user($topic_author) ) { return; - } - - // Limit - if ($this->over_hook_limit('new_topic', 'new_forum_topic', $topic_author) ) { return; - } - - // Make sure this is unique event - if ($this->has_entry('new_forum_topic', $topic_id, $topic_author) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_forum_topic', - $topic_author, - $this->prefs['new_topic']['creds'], - $this->prefs['new_topic']['log'], - $topic_id, - 'simplepress', - $this->mycred_type - ); - - } - - /** - * Delete Topic - * - * @since 1.3.3 - * @version 1.1 - */ - public function delete_topic( $topic ) - { - - if ($topic->user_id == 0 ) { return; - } - - // Topic details - $topic_author = $topic->user_id; - $topic_id = $topic->topic_id; - - // If gained, points, deduct - if ($this->has_entry('new_forum_topic', $topic_id, $topic_author) ) { - - // Execute - $this->core->add_creds( - 'deleted_topic', - $topic_author, - $this->prefs['delete_topic']['creds'], - $this->prefs['delete_topic']['log'], - $topic_id, - 'simplepress', - $this->mycred_type - ); - - } - - } - - /** - * New Post - * - * @since 1.3.3 - * @version 1.2 - */ - public function new_post( $post ) - { - - if ($post['action'] != 'post' ) { return; - } - - // Post details - $post_author = $post['userid']; - $post_id = $post['postid']; - $topic_id = $post['topicid']; - - // Check if user is excluded - if ($this->core->exclude_user($post_author) ) { return; - } - - // Check if topic author gets points for their own replies - if ((bool) $this->prefs['new_post']['author'] === false && $this->get_topic_author($topic_id) == $post_author ) { return; - } - - // Limit - if ($this->over_hook_limit('new_post', 'new_topic_post', $post_author) ) { return; - } - - // Make sure this is unique event - if ($this->has_entry('new_topic_post', $post_id, $post_author) ) { return; - } - - // Execute - $this->core->add_creds( - 'new_topic_post', - $post_author, - $this->prefs['new_post']['creds'], - $this->prefs['new_post']['log'], - $post_id, - 'simplepress', - $this->mycred_type - ); - - } - - /** - * Delete Post - * - * @since 1.3.3 - * @version 1.0 - */ - public function delete_post( $target ) - { - - if ($target->user_id == 0 ) { return; - } - - // Post details - $post_author = $target->user_id; - $post_id = $target->post_id; - - // If gained, points, deduct - if ($this->has_entry('new_topic_post', $post_id, $post_author) ) { - - // Execute - $this->core->add_creds( - 'deleted_topic_post', - $post_author, - $this->prefs['delete_post']['creds'], - $this->prefs['delete_post']['log'], - $post_id, - 'simplepress', - $this->mycred_type - ); - - } - - } - - /** - * Get SimplePress Topic Author ID - * - * @since 1.3.3 - * @version 1.0 - */ - public function get_topic_author( $topic_id = '' ) - { - - global $wpdb; - - $db = SFTOPICS; - - return $wpdb->get_var($wpdb->prepare("SELECT user_id FROM {$db} WHERE topic_id = %d;", $topic_id)); - - } - - /** - * Preferences - * - * @since 1.3.3 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +add_action( 'mycred_load_hooks', 'mycred_load_simplepress_hook', 85 ); +function mycred_load_simplepress_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_SimplePress' ) || ! defined( 'SFTOPICS' ) ) return; + + class myCRED_SimplePress extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'hook_simplepress', + 'defaults' => array( + 'new_topic' => array( + 'creds' => 1, + 'log' => '%plural% for new forum topic', + 'limit' => '0/x' + ), + 'delete_topic' => array( + 'creds' => 0-1, + 'log' => '%singular% deduction for deleted topic' + ), + 'new_post' => array( + 'creds' => 1, + 'log' => '%plural% for new topic post', + 'author' => 0, + 'limit' => '0/x' + ), + 'delete_post' => array( + 'creds' => 0-1, + 'log' => '%singular% deduction for deleted topic reply' + ) + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.3.3 + * @version 1.0 + */ + public function run() { + + // New Topic + if ( $this->prefs['new_topic']['creds'] != 0 ) + add_action( 'sph_post_create', array( $this, 'new_topic' ) ); + + // Delete Topic + if ( $this->prefs['delete_topic']['creds'] != 0 ) + add_action( 'sph_topic_delete', array( $this, 'delete_topic' ) ); + + // New Reply + if ( $this->prefs['new_post']['creds'] != 0 ) + add_action( 'sph_post_create', array( $this, 'new_post' ) ); + + // Delete Reply + if ( $this->prefs['delete_post']['creds'] != 0 ) + add_action( 'sph_post_delete', array( $this, 'delete_post' ) ); + + add_filter( 'mycred_parse_log_entry', array( $this, 'adjust_log_templates' ), 10, 2 ); + + } + + /** + * Custom Template Tags + * @since 1.3.3 + * @version 1.1 + */ + public function adjust_log_templates( $content, $log_entry ) { + + if ( ! isset( $log_entry->ref ) || $log_entry->data != 'simplepress' ) return $content; + + switch ( $log_entry->ref ) { + case 'new_forum_topic' : + + global $wpdb; + + $db = SFTOPICS; + $topic = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$db} WHERE user_id = %d AND topic_id = %d;", $log_entry->user_id, $log_entry->ref_id ) ); + $topic_name = ''; + + if ( isset( $topic->topic_name ) ) + $topic_name = $topic->topic_name; + + $content = str_replace( '%topic_name%', $topic_name, $content ); + + break; + } + + return $content; + + } + + /** + * New Topic + * @since 1.3.3 + * @version 1.2 + */ + public function new_topic( $post ) { + + if ( $post['action'] != 'topic' ) return; + + // Topic details + $topic_author = $post['userid']; + + $forum_id = $post['forumid']; + $topic_id = $post['topicid']; + + // Check if user is excluded + if ( $this->core->exclude_user( $topic_author ) ) return; + + // Limit + if ( $this->over_hook_limit( 'new_topic', 'new_forum_topic', $topic_author ) ) return; + + // Make sure this is unique event + if ( $this->has_entry( 'new_forum_topic', $topic_id, $topic_author ) ) return; + + // Execute + $this->core->add_creds( + 'new_forum_topic', + $topic_author, + $this->prefs['new_topic']['creds'], + $this->prefs['new_topic']['log'], + $topic_id, + 'simplepress', + $this->mycred_type + ); + + } + + /** + * Delete Topic + * @since 1.3.3 + * @version 1.1 + */ + public function delete_topic( $topic ) { + + if ( $topic->user_id == 0 ) return; + + // Topic details + $topic_author = $topic->user_id; + $topic_id = $topic->topic_id; + + // If gained, points, deduct + if ( $this->has_entry( 'new_forum_topic', $topic_id, $topic_author ) ) { + + // Execute + $this->core->add_creds( + 'deleted_topic', + $topic_author, + $this->prefs['delete_topic']['creds'], + $this->prefs['delete_topic']['log'], + $topic_id, + 'simplepress', + $this->mycred_type + ); + + } + + } + + /** + * New Post + * @since 1.3.3 + * @version 1.2 + */ + public function new_post( $post ) { + + if ( $post['action'] != 'post' ) return; + + // Post details + $post_author = $post['userid']; + $post_id = $post['postid']; + $topic_id = $post['topicid']; + + // Check if user is excluded + if ( $this->core->exclude_user( $post_author ) ) return; + + // Check if topic author gets points for their own replies + if ( (bool) $this->prefs['new_post']['author'] === false && $this->get_topic_author( $topic_id ) == $post_author ) return; + + // Limit + if ( $this->over_hook_limit( 'new_post', 'new_topic_post', $post_author ) ) return; + + // Make sure this is unique event + if ( $this->has_entry( 'new_topic_post', $post_id, $post_author ) ) return; + + // Execute + $this->core->add_creds( + 'new_topic_post', + $post_author, + $this->prefs['new_post']['creds'], + $this->prefs['new_post']['log'], + $post_id, + 'simplepress', + $this->mycred_type + ); + + } + + /** + * Delete Post + * @since 1.3.3 + * @version 1.0 + */ + public function delete_post( $target ) { + + if ( $target->user_id == 0 ) return; + + // Post details + $post_author = $target->user_id; + $post_id = $target->post_id; + + // If gained, points, deduct + if ( $this->has_entry( 'new_topic_post', $post_id, $post_author ) ) { + + // Execute + $this->core->add_creds( + 'deleted_topic_post', + $post_author, + $this->prefs['delete_post']['creds'], + $this->prefs['delete_post']['log'], + $post_id, + 'simplepress', + $this->mycred_type + ); + + } + + } + + /** + * Get SimplePress Topic Author ID + * @since 1.3.3 + * @version 1.0 + */ + public function get_topic_author( $topic_id = '' ) { + + global $wpdb; + + $db = SFTOPICS; + + return $wpdb->get_var( $wpdb->prepare( "SELECT user_id FROM {$db} WHERE topic_id = %d;", $topic_id ) ); + + } + + /** + * Preferences + * @since 1.3.3 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_topic', 'limit' )), $this->field_id(array( 'new_topic', 'limit' )), $prefs['new_topic']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' ), '%topic_name%'); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_topic', 'limit' ) ), $this->field_id( array( 'new_topic', 'limit' ) ), $prefs['new_topic']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ), '%topic_name%' ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'new_post', 'limit' )), $this->field_id(array( 'new_post', 'limit' )), $prefs['new_post']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'new_post', 'limit' ) ), $this->field_id( array( 'new_post', 'limit' ) ), $prefs['new_post']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - __('WP Favorite Posts', 'mycred'), - 'description' => __('Awards %_plural% for users adding posts to their favorites.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/wp-favorite-posts-actions/', - 'callback' => array( 'myCRED_Hook_WPFavorite' ) - ); + $installed['wpfavorite'] = array( + 'title' => __( 'WP Favorite Posts', 'mycred' ), + 'description' => __( 'Awards %_plural% for users adding posts to their favorites.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/wp-favorite-posts-actions/', + 'callback' => array( 'myCRED_Hook_WPFavorite' ) + ); - return $installed; + return $installed; } /** * WP Favorite Hook - * - * @since 1.1 + * @since 1.1 * @version 1.1 */ -add_action('mycred_load_hooks', 'mycred_load_wp_favorite_posts_hook', 100); -function mycred_load_wp_favorite_posts_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_Hook_WPFavorite') || ! function_exists('wp_favorite_posts') ) { return; - } - - class myCRED_Hook_WPFavorite extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'wpfavorite', - 'defaults' => array( - 'add' => array( - 'creds' => 1, - 'log' => '%plural% for adding a post as favorite', - 'limit' => '0/x' - ), - 'added' => array( - 'creds' => 1, - 'log' => '%plural% for your post being added to favorite', - 'limit' => '0/x' - ), - 'remove' => array( - 'creds' => 1, - 'log' => '%plural% deduction for removing a post from favorites' - ), - 'removed' => array( - 'creds' => 1, - 'log' => '%plural% deduction for post removed from favorites' - ) - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.1 - * @version 1.0.1 - */ - public function run() - { - - add_action('wpfp_after_add', array( $this, 'add_favorite' )); - add_action('wpfp_after_remove', array( $this, 'remove_favorite' )); - - } - - /** - * Add Favorite - * - * @since 1.1 - * @version 1.2 - */ - public function add_favorite( $post_id ) - { - - // Must be logged in - if (! is_user_logged_in() ) { return; - } - - $post = mycred_get_post($post_id); - $user_id = get_current_user_id(); - - if ($user_id != $post->post_author ) { - - // Award the user adding to favorite - if ($this->prefs['add']['creds'] != 0 && ! $this->core->exclude_user($user_id) ) { - - // Limit - if (! $this->over_hook_limit('add', 'add_favorite_post', $user_id) ) { - - // Make sure this is unique event - if (! $this->core->has_entry('add_favorite_post', $post_id, $user_id) ) { - - // Execute - $this->core->add_creds( - 'add_favorite_post', - $user_id, - $this->prefs['add']['creds'], - $this->prefs['add']['log'], - $post_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); - - } - - } - - } - - // Award post author for being added to favorite - if ($this->prefs['added']['creds'] != 0 && ! $this->core->exclude_user($post->post_author) ) { - - // Limit - if (! $this->over_hook_limit('added', 'add_favorite_post', $post->post_author) ) { - - // Make sure this is unique event - if (! $this->core->has_entry('favorited_post', $post_id, $post->post_author) ) { - - // Execute - $this->core->add_creds( - 'favorited_post', - $post->post_author, - $this->prefs['added']['creds'], - $this->prefs['added']['log'], - $post_id, - array( 'ref_type' => 'post', 'by' => $user_id ), - $this->mycred_type - ); - - } - - } - - } +add_action( 'mycred_load_hooks', 'mycred_load_wp_favorite_posts_hook', 100 ); +function mycred_load_wp_favorite_posts_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_Hook_WPFavorite' ) || ! function_exists( 'wp_favorite_posts' ) ) return; + + class myCRED_Hook_WPFavorite extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'wpfavorite', + 'defaults' => array( + 'add' => array( + 'creds' => 1, + 'log' => '%plural% for adding a post as favorite', + 'limit' => '0/x' + ), + 'added' => array( + 'creds' => 1, + 'log' => '%plural% for your post being added to favorite', + 'limit' => '0/x' + ), + 'remove' => array( + 'creds' => 1, + 'log' => '%plural% deduction for removing a post from favorites' + ), + 'removed' => array( + 'creds' => 1, + 'log' => '%plural% deduction for post removed from favorites' + ) + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.1 + * @version 1.0.1 + */ + public function run() { + + add_action( 'wpfp_after_add', array( $this, 'add_favorite' ) ); + add_action( 'wpfp_after_remove', array( $this, 'remove_favorite' ) ); + + } + + /** + * Add Favorite + * @since 1.1 + * @version 1.2 + */ + public function add_favorite( $post_id ) { + + // Must be logged in + if ( ! is_user_logged_in() ) return; + + $post = mycred_get_post( $post_id ); + $user_id = get_current_user_id(); + + if ( $user_id != $post->post_author ) { + + // Award the user adding to favorite + if ( $this->prefs['add']['creds'] != 0 && ! $this->core->exclude_user( $user_id ) ) { + + // Limit + if ( ! $this->over_hook_limit( 'add', 'add_favorite_post', $user_id ) ) { + + // Make sure this is unique event + if ( ! $this->core->has_entry( 'add_favorite_post', $post_id, $user_id ) ) { + + // Execute + $this->core->add_creds( + 'add_favorite_post', + $user_id, + $this->prefs['add']['creds'], + $this->prefs['add']['log'], + $post_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); + + } + + } + + } + + // Award post author for being added to favorite + if ( $this->prefs['added']['creds'] != 0 && ! $this->core->exclude_user( $post->post_author ) ) { - } + // Limit + if ( ! $this->over_hook_limit( 'added', 'add_favorite_post', $post->post_author ) ) { - } + // Make sure this is unique event + if ( ! $this->core->has_entry( 'favorited_post', $post_id, $post->post_author ) ) { - /** - * Remove Favorite - * - * @since 1.1 - * @version 1.2 - */ - public function remove_favorite( $post_id ) - { + // Execute + $this->core->add_creds( + 'favorited_post', + $post->post_author, + $this->prefs['added']['creds'], + $this->prefs['added']['log'], + $post_id, + array( 'ref_type' => 'post', 'by' => $user_id ), + $this->mycred_type + ); - // Must be logged in - if (! is_user_logged_in() ) { return; - } + } - $post = mycred_get_post($post_id); - $user_id = get_current_user_id(); + } - if ($user_id != $post->post_author ) { + } - if ($this->prefs['remove']['creds'] != 0 && ! $this->core->exclude_user($user_id) ) { + } - if (! $this->core->has_entry('favorite_post_removed', $post_id, $user_id) ) { + } - $this->core->add_creds( - 'favorite_post_removed', - $user_id, - $this->prefs['remove']['creds'], - $this->prefs['remove']['log'], - $post_id, - array( 'ref_type' => 'post' ), - $this->mycred_type - ); + /** + * Remove Favorite + * @since 1.1 + * @version 1.2 + */ + public function remove_favorite( $post_id ) { - } + // Must be logged in + if ( ! is_user_logged_in() ) return; - } + $post = mycred_get_post( $post_id ); + $user_id = get_current_user_id(); - if ($this->prefs['removed']['creds'] != 0 && ! $this->core->exclude_user($post->post_author) ) { + if ( $user_id != $post->post_author ) { - if (! $this->core->has_entry('favorite_post_removal', $post_id, $post->post_author) ) { + if ( $this->prefs['remove']['creds'] != 0 && ! $this->core->exclude_user( $user_id ) ) { - $this->core->add_creds( - 'favorite_post_removal', - $post->post_author, - $this->prefs['removed']['creds'], - $this->prefs['removed']['log'], - $post_id, - array( 'ref_type' => 'post', 'by' => $user_id ), - $this->mycred_type - ); + if ( ! $this->core->has_entry( 'favorite_post_removed', $post_id, $user_id ) ) { - } + $this->core->add_creds( + 'favorite_post_removed', + $user_id, + $this->prefs['remove']['creds'], + $this->prefs['remove']['log'], + $post_id, + array( 'ref_type' => 'post' ), + $this->mycred_type + ); - } + } - } + } - } + if ( $this->prefs['removed']['creds'] != 0 && ! $this->core->exclude_user( $post->post_author ) ) { - /** - * Preferences for WP-Polls - * - * @since 1.1 - * @version 1.1 - */ - public function preferences() - { + if ( ! $this->core->has_entry( 'favorite_post_removal', $post_id, $post->post_author ) ) { - $prefs = $this->prefs; + $this->core->add_creds( + 'favorite_post_removal', + $post->post_author, + $this->prefs['removed']['creds'], + $this->prefs['removed']['log'], + $post_id, + array( 'ref_type' => 'post', 'by' => $user_id ), + $this->mycred_type + ); - ?> + } + + } + + } + + } + + /** + * Preferences for WP-Polls + * @since 1.1 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'add', 'limit' )), $this->field_id(array( 'add', 'limit' )), $prefs['add']['limit']); ?> -
    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'added', 'limit' )), $this->field_id(array( 'added', 'limit' )), $prefs['added']['limit']); ?> -
    -
    -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'add', 'limit' ) ), $this->field_id( array( 'add', 'limit' ) ), $prefs['add']['limit'] ); ?> +
    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'added', 'limit' ) ), $this->field_id( array( 'added', 'limit' ) ), $prefs['added']['limit'] ); ?> +
    +
    +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - __('WP-Polls', 'mycred'), - 'description' => __('Awards %_plural% for users voting in polls.', 'mycred'), - 'documentation' => '', - 'callback' => array( 'myCRED_Hook_WPPolls' ) - ); + $installed['wppolls'] = array( + 'title' => __( 'WP-Polls', 'mycred' ), + 'description' => __( 'Awards %_plural% for users voting in polls.', 'mycred' ), + 'documentation' => '', + 'callback' => array( 'myCRED_Hook_WPPolls' ) + ); - return $installed; + return $installed; } /** * WP-Polls Hook - * - * @since 1.1 + * @since 1.1 * @version 1.1 */ -add_action('mycred_load_hooks', 'mycred_load_wp_polls_hook', 105); -function mycred_load_wp_polls_hook() -{ +add_action( 'mycred_load_hooks', 'mycred_load_wp_polls_hook', 105 ); +function mycred_load_wp_polls_hook() { - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_Hook_WPPolls') || ! function_exists('vote_poll') ) { return; - } + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_Hook_WPPolls' ) || ! function_exists( 'vote_poll' ) ) return; - class myCRED_Hook_WPPolls extends myCRED_Hook - { + class myCRED_Hook_WPPolls extends myCRED_Hook { - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { - parent::__construct( - array( - 'id' => 'wppolls', - 'defaults' => array( - 'creds' => 1, - 'log' => '%plural% for voting' - ) - ), $hook_prefs, $type - ); + parent::__construct( array( + 'id' => 'wppolls', + 'defaults' => array( + 'creds' => 1, + 'log' => '%plural% for voting' + ) + ), $hook_prefs, $type ); - } + } - /** - * Run - * - * @since 1.1 - * @version 1.0 - */ - public function run() - { + /** + * Run + * @since 1.1 + * @version 1.0 + */ + public function run() { - add_action('wp_ajax_polls', array( $this, 'vote_poll' ), 1); - add_filter('mycred_parse_tags_poll', array( $this, 'parse_custom_tags' ), 10, 2); + add_action( 'wp_ajax_polls', array( $this, 'vote_poll' ), 1 ); + add_filter( 'mycred_parse_tags_poll', array( $this, 'parse_custom_tags' ), 10, 2 ); - } + } - /** - * Poll Voting - * - * @since 1.1 - * @version 1.1 - */ - public function vote_poll() - { + /** + * Poll Voting + * @since 1.1 + * @version 1.1 + */ + public function vote_poll() { - if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'polls' && is_user_logged_in() ) { + if ( isset( $_REQUEST['action'] ) && $_REQUEST['action'] == 'polls' && is_user_logged_in() ) { - // Get Poll ID - $poll_id = ( isset($_REQUEST['poll_id']) ? intval($_REQUEST['poll_id']) : 0 ); + // Get Poll ID + $poll_id = ( isset( $_REQUEST['poll_id'] ) ? intval( $_REQUEST['poll_id'] ) : 0 ); - // Ensure Poll ID Is Valid - if ($poll_id != 0 ) { + // Ensure Poll ID Is Valid + if ( $poll_id != 0 ) { - // Verify Referer - if (check_ajax_referer('poll_' . $poll_id . '-nonce', 'poll_' . $poll_id . '_nonce', false) ) { + // Verify Referer + if ( check_ajax_referer( 'poll_' . $poll_id . '-nonce', 'poll_' . $poll_id . '_nonce', false ) ) { - // Which View - switch ( $_REQUEST['view'] ) { + // Which View + switch ( $_REQUEST['view'] ) { - case 'process': + case 'process': - $poll_aid = $_POST["poll_$poll_id"]; - $poll_aid_array = array_unique(array_map('intval', explode(',', $poll_aid))); + $poll_aid = $_POST["poll_$poll_id"]; + $poll_aid_array = array_unique( array_map( 'intval', explode( ',', $poll_aid ) ) ); - if ($poll_id > 0 && ! empty($poll_aid_array) && check_allowtovote() ) { + if ( $poll_id > 0 && ! empty( $poll_aid_array ) && check_allowtovote() ) { - $check_voted = check_voted($poll_id); + $check_voted = check_voted( $poll_id ); - if ($check_voted == 0 ) { + if ( $check_voted == 0 ) { - $user_id = get_current_user_id(); + $user_id = get_current_user_id(); - // Make sure we are not excluded - if (! $this->core->exclude_user($user_id) ) { - $this->core->add_creds( - 'poll_voting', - $user_id, - $this->prefs['creds'], - $this->prefs['log'], - $poll_id, - array( 'ref_type' => 'poll' ), - $this->mycred_type - ); - } + // Make sure we are not excluded + if ( ! $this->core->exclude_user( $user_id ) ) { + $this->core->add_creds( + 'poll_voting', + $user_id, + $this->prefs['creds'], + $this->prefs['log'], + $poll_id, + array( 'ref_type' => 'poll' ), + $this->mycred_type + ); + } - } + } - } + } - break; + break; - } + } - } + } - } + } - } + } - } + } - /** - * Parse Custom Tags in Log - * - * @since 1.1 - * @version 1.0 - */ - public function parse_custom_tags( $content, $log_entry ) - { + /** + * Parse Custom Tags in Log + * @since 1.1 + * @version 1.0 + */ + public function parse_custom_tags( $content, $log_entry ) { - $poll_id = $log_entry->ref_id; - $content = str_replace('%poll_id%', $poll_id, $content); - $content = str_replace('%poll_question%', $this->get_poll_name($poll_id), $content); + $poll_id = $log_entry->ref_id; + $content = str_replace( '%poll_id%', $poll_id, $content ); + $content = str_replace( '%poll_question%', $this->get_poll_name( $poll_id ), $content ); - return $content; + return $content; - } + } - /** - * Get Poll Name (Question) - * - * @since 1.1 - * @version 1.0 - */ - protected function get_poll_name( $poll_id ) - { + /** + * Get Poll Name (Question) + * @since 1.1 + * @version 1.0 + */ + protected function get_poll_name( $poll_id ) { - global $wpdb; - $sql = "SELECT pollq_question FROM {$wpdb->pollsq} WHERE pollq_id = %d "; + global $wpdb; + $sql = "SELECT pollq_question FROM {$wpdb->pollsq} WHERE pollq_id = %d "; - return $wpdb->get_var($wpdb->prepare($sql, $poll_id)); + return $wpdb->get_var( $wpdb->prepare( $sql, $poll_id ) ); - } + } - /** - * Preferences for WP-Polls - * - * @since 1.1 - * @version 1.0 - */ - public function preferences() - { + /** + * Preferences for WP-Polls + * @since 1.1 + * @version 1.0 + */ + public function preferences() { - $prefs = $this->prefs; + $prefs = $this->prefs; - ?> +?>
    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - __('Post Ratings', 'mycred'), - 'description' => __('Awards %_plural% for post ratings. Supports awarding %_plural% both to post author and the user rating.', 'mycred'), - 'documentation' => 'http://codex.mycred.me/hooks/wp-postratings-actions/', - 'callback' => array( 'myCRED_WP_Postratings' ) - ); + $installed['wp_postratings'] = array( + 'title' => __( 'Post Ratings', 'mycred' ), + 'description' => __( 'Awards %_plural% for post ratings. Supports awarding %_plural% both to post author and the user rating.', 'mycred' ), + 'documentation' => 'http://codex.mycred.me/hooks/wp-postratings-actions/', + 'callback' => array( 'myCRED_WP_Postratings' ) + ); - return $installed; + return $installed; } /** * WP Postratings Hook - * - * @since 1.6 + * @since 1.6 * @version 1.0 */ -add_action('mycred_load_hooks', 'mycred_load_wp_postratings_hook', 110); -function mycred_load_wp_postratings_hook() -{ - - // If the hook has been replaced or if plugin is not installed, exit now - if (class_exists('myCRED_WP_Postratings') || ! defined('WP_POSTRATINGS_VERSION') ) { return; - } - - class myCRED_WP_Postratings extends myCRED_Hook - { - - /** - * Construct - */ - public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) - { - - parent::__construct( - array( - 'id' => 'wp_postratings', - 'defaults' => array( - 'rating' => array( - 'creds' => 0, - 'log' => '%plural% for rating', - 'limit' => '0/x', - 'value' => 0 - ), - 'rated' => array( - 'creds' => 0, - 'log' => '%plural% for getting a rating', - 'limit' => '0/x', - 'value' => 0 - ) - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.6 - * @version 1.0 - */ - public function run() - { - - add_action('rate_post', array( $this, 'new_rating' ), 10, 3); - add_filter('mycred_hook_table_creds', array( $this, 'table_amount' ), 10, 3); - - } - - /** - * Table Amount - * - * @since 1.6 - * @version 1.0 - */ - public function table_amount( $amount, $id, $prefs ) - { - - if (! in_array($id, array( 'rating', 'rated' )) || ! isset($prefs['value']) ) { return $amount; - } - - if ($prefs['value'] == 1 ) { - return __('Based on rating', 'mycred'); - } - - return $amount; - - } - - /** - * Successful Form Submission - * - * @since 1.6 - * @version 1.0 - */ - public function new_rating( $user_id, $post_id, $rating_value ) - { - - // Get post - $post = mycred_get_post($post_id); - - // Authors can not get points for rating their own stuff - if (! isset($post->post_author) && $post->post_author == $user_id ) { return; - } - - // Determen the amount to award - $amount = $this->prefs['rating']['creds']; - if ($this->prefs['rating']['value'] == 1 ) { - $amount = $rating_value; - } - - // If enabled - award the rater - if ($amount != 0 ) { - - // Only award if the user is not excluded and not over their limit - if (! $this->core->exclude_user($user_id) && ! $this->over_hook_limit('rating', 'post_rating', $user_id) ) { - $this->core->add_creds( - 'post_rating', - $user_id, - $amount, - $this->prefs['rating']['log'], - $post_id, - array( 'ref_type' => 'post', 'value' => $rating_value ), - $this->mycred_type - ); - } - - } - - // Determen the amount to award for author - $amount = $this->prefs['rated']['creds']; - if ($this->prefs['rated']['value'] == 1 ) { - $amount = $rating_value; - } - - // If enabled - award the rater - if ($amount != 0 ) { - - // Only award if the author is not excluded and not over their limit - if (! $this->core->exclude_user($post->post_author) && ! $this->over_hook_limit('rated', 'post_rating_author', $post->post_author) ) { - $this->core->add_creds( - 'post_rating_author', - $post->post_author, - $amount, - $this->prefs['rated']['log'], - $post_id, - array( 'ref_type' => 'post', 'value' => $rating_value ), - $this->mycred_type - ); - } - - } - - } - - /** - * Preferences for WP Postratings Hook - * - * @since 1.6 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +add_action( 'mycred_load_hooks', 'mycred_load_wp_postratings_hook', 110 ); +function mycred_load_wp_postratings_hook() { + + // If the hook has been replaced or if plugin is not installed, exit now + if ( class_exists( 'myCRED_WP_Postratings' ) || ! defined( 'WP_POSTRATINGS_VERSION' ) ) return; + + class myCRED_WP_Postratings extends myCRED_Hook { + + /** + * Construct + */ + public function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'wp_postratings', + 'defaults' => array( + 'rating' => array( + 'creds' => 0, + 'log' => '%plural% for rating', + 'limit' => '0/x', + 'value' => 0 + ), + 'rated' => array( + 'creds' => 0, + 'log' => '%plural% for getting a rating', + 'limit' => '0/x', + 'value' => 0 + ) + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.6 + * @version 1.0 + */ + public function run() { + + add_action( 'rate_post', array( $this, 'new_rating' ), 10, 3 ); + add_filter( 'mycred_hook_table_creds', array( $this, 'table_amount' ), 10, 3 ); + + } + + /** + * Table Amount + * @since 1.6 + * @version 1.0 + */ + public function table_amount( $amount, $id, $prefs ) { + + if ( ! in_array( $id, array( 'rating', 'rated' ) ) || ! isset( $prefs['value'] ) ) return $amount; + + if ( $prefs['value'] == 1 ) + return __( 'Based on rating', 'mycred' ); + + return $amount; + + } + + /** + * Successful Form Submission + * @since 1.6 + * @version 1.0 + */ + public function new_rating( $user_id, $post_id, $rating_value ) { + + // Get post + $post = mycred_get_post( $post_id ); + + // Authors can not get points for rating their own stuff + if ( ! isset( $post->post_author ) && $post->post_author == $user_id ) return; + + // Determen the amount to award + $amount = $this->prefs['rating']['creds']; + if ( $this->prefs['rating']['value'] == 1 ) + $amount = $rating_value; + + // If enabled - award the rater + if ( $amount != 0 ) { + + // Only award if the user is not excluded and not over their limit + if ( ! $this->core->exclude_user( $user_id ) && ! $this->over_hook_limit( 'rating', 'post_rating', $user_id ) ) + $this->core->add_creds( + 'post_rating', + $user_id, + $amount, + $this->prefs['rating']['log'], + $post_id, + array( 'ref_type' => 'post', 'value' => $rating_value ), + $this->mycred_type + ); + + } + + // Determen the amount to award for author + $amount = $this->prefs['rated']['creds']; + if ( $this->prefs['rated']['value'] == 1 ) + $amount = $rating_value; + + // If enabled - award the rater + if ( $amount != 0 ) { + + // Only award if the author is not excluded and not over their limit + if ( ! $this->core->exclude_user( $post->post_author ) && ! $this->over_hook_limit( 'rated', 'post_rating_author', $post->post_author ) ) + $this->core->add_creds( + 'post_rating_author', + $post->post_author, + $amount, + $this->prefs['rated']['log'], + $post_id, + array( 'ref_type' => 'post', 'value' => $rating_value ), + $this->mycred_type + ); + + } + + } + + /** + * Preferences for WP Postratings Hook + * @since 1.6 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'rating', 'limit' )), $this->field_id(array( 'rating', 'limit' )), $prefs['rating']['limit']); ?> -
    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'rated', 'limit' )), $this->field_id(array( 'rated', 'limit' )), $prefs['rated']['limit']); ?> -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'rating', 'limit' ) ), $this->field_id( array( 'rating', 'limit' ) ), $prefs['rating']['limit'] ); ?> +
    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'rated', 'limit' ) ), $this->field_id( array( 'rated', 'limit' ) ), $prefs['rated']['limit'] ); ?> +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - +?> \ No newline at end of file diff --git a/includes/hooks/mycred-hook-anniversary.php b/includes/hooks/mycred-hook-anniversary.php index 2be117a..eb2ab1d 100644 --- a/includes/hooks/mycred-hook-anniversary.php +++ b/includes/hooks/mycred-hook-anniversary.php @@ -1,141 +1,125 @@ 'anniversary', - 'defaults' => array( - 'creds' => 10, - 'log' => '%plural% for being a member for a year' - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.8 - * @version 1.0 - */ - public function run() - { - - add_action('template_redirect', array( $this, 'page_load' )); - - } - - /** - * Page Load - * - * @since 1.8 - * @version 1.0 - */ - public function page_load() - { - - if (! is_user_logged_in() ) { return; - } - - $user_id = get_current_user_id(); - - // Make sure user is not excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Make sure this only runs once a day - $last_run = mycred_get_user_meta($user_id, 'anniversary-' . $this->mycred_type, '', true); - $today = date('Y-m-d', current_time('timestamp')); - if ($last_run == $today ) { return; - } - - global $wpdb; - - $result = $wpdb->get_row($wpdb->prepare("SELECT user_registered, TIMESTAMPDIFF( YEAR, user_registered, CURDATE()) AS difference FROM {$wpdb->users} WHERE ID = %d;", $user_id)); - - // If we have been a member for more then one year - if (isset($result->user_registered) && $result->difference >= 1 ) { - - $year_joined = substr($result->user_registered, 0, 4); - $date_joined = strtotime($result->user_registered); - - // First time we give points we might need to give for more then one year - // so we give points for each year. - for ( $i = 0; $i < $result->difference; $i++ ) { - - $year_joined++; - if ($this->core->has_entry('anniversary', $year_joined, $user_id, $date_joined, $this->mycred_type) ) { continue; - } - - // Execute - $this->core->add_creds( - 'anniversary', - $user_id, - $this->prefs['creds'], - $this->prefs['log'], - $year_joined, - $date_joined, - $this->mycred_type - ); - - } - - } - - mycred_update_user_meta($user_id, 'anniversary-' . $this->mycred_type, '', $today); - - } - - /** - * Preference for Anniversary Hook - * - * @since 1.8 - * @version 1.0 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +if ( ! class_exists( 'myCRED_Hook_Anniversary' ) ) : + class myCRED_Hook_Anniversary extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'anniversary', + 'defaults' => array( + 'creds' => 10, + 'log' => '%plural% for being a member for a year' + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.8 + * @version 1.0 + */ + public function run() { + + add_action( 'template_redirect', array( $this, 'page_load' ) ); + + } + + /** + * Page Load + * @since 1.8 + * @version 1.0 + */ + public function page_load() { + + if ( ! is_user_logged_in() ) return; + + $user_id = get_current_user_id(); + + // Make sure user is not excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Make sure this only runs once a day + $last_run = mycred_get_user_meta( $user_id, 'anniversary-' . $this->mycred_type, '', true ); + $today = date( 'Y-m-d', current_time( 'timestamp' ) ); + if ( $last_run == $today ) return; + + global $wpdb; + + $result = $wpdb->get_row( $wpdb->prepare( "SELECT user_registered, TIMESTAMPDIFF( YEAR, user_registered, CURDATE()) AS difference FROM {$wpdb->users} WHERE ID = %d;", $user_id ) ); + + // If we have been a member for more then one year + if ( isset( $result->user_registered ) && $result->difference >= 1 ) { + + $year_joined = substr( $result->user_registered, 0, 4 ); + $date_joined = strtotime( $result->user_registered ); + + // First time we give points we might need to give for more then one year + // so we give points for each year. + for ( $i = 0; $i < $result->difference; $i++ ) { + + $year_joined++; + if ( $this->core->has_entry( 'anniversary', $year_joined, $user_id, $date_joined, $this->mycred_type ) ) continue; + + // Execute + $this->core->add_creds( + 'anniversary', + $user_id, + $this->prefs['creds'], + $this->prefs['log'], + $year_joined, + $date_joined, + $this->mycred_type + ); + + } + + } + + mycred_update_user_meta( $user_id, 'anniversary-' . $this->mycred_type, '', $today ); + + } + + /** + * Preference for Anniversary Hook + * @since 1.8 + * @version 1.0 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - 'comments', - 'defaults' => array( - 'limits' => array( - 'self_reply' => 0, - 'per_post' => 10, - 'per_day' => 0 - ), - 'approved' => array( - 'creds' => 1, - 'log' => '%plural% for Approved Comment', - 'author' => 0 - ), - 'spam' => array( - 'creds' => '-5', - 'log' => '%plural% deduction for Comment marked as SPAM', - 'author' => 0 - ), - 'trash' => array( - 'creds' => '-1', - 'log' => '%plural% deduction for deleted / unapproved Comment', - 'author' => 0 - ) - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 0.1 - * @version 1.2 - */ - public function run() - { - - if (! function_exists('dsq_is_installed') ) { - add_action('comment_post', array( $this, 'new_comment' ), 99, 2); - add_action('transition_comment_status', array( $this, 'comment_transitions' ), 99, 3); - } - else { - add_action('wp_insert_comment', array( $this, 'disqus' ), 99, 2); - } - - } - - /** - * New Comment - * If comments are approved without moderation, we apply the corresponding method - * or else we will wait till the appropriate instance. - * - * @since 0.1 - * @version 1.2.2 - */ - public function new_comment( $comment_id, $comment_status ) - { - - // Marked SPAM - if ($comment_status === 'spam' ) { - $this->comment_transitions('spam', 'unapproved', $comment_id); - } - - // Approved comment - elseif ($comment_status == 1 ) { - $this->comment_transitions('approved', 'unapproved', $comment_id); - } - - } - - /** - * Discuss Support - * - * @since 1.4 - * @version 1.0 - */ - function disqus( $id, $comment ) - { - - // Attempt to get a comment authors ID - if ($comment->user_id == 0 ) { - - $email = get_user_by('email', $comment->comment_author_email); - // Failed to find author, can not award points - if ($email === false ) { return; - } - $comment->user_id = $email->ID; - - } - - $new_status = 'spam'; - if ($comment->comment_approved == 1 ) { - $new_status = 'approved'; - - } elseif ($comment->comment_approved == 0 ) { - $new_status = 'unapproved'; - } - - $this->comment_transitions($new_status, 'unapproved', $comment); - - } - - /** - * Comment Transitions - * - * @since 1.1.2 - * @version 1.5 - */ - public function comment_transitions( $new_status, $old_status, $comment ) - { - - // Passing an integer instead of an object means we need to grab the comment object ourselves - if (! is_object($comment) ) { - $comment = get_comment($comment); - } - - // No comment object so lets bail - if ($comment === null ) { return; - } - - // Ignore Pingbacks or Trackbacks - if (! in_array($comment->comment_type, array( '', 'comment' )) ) { return; - } - - // Logged out users miss out - if ($comment->user_id == 0 ) { return; - } - - if (apply_filters('mycred_comment_gets_cred', true, $comment, $new_status, $old_status) === false ) { return; - } - - // Get comment author - $comment_author = $comment->user_id; - - // Get content author - $content_author = null; - if (isset($comment->comment_post_ID) || $comment->comment_post_ID != '' ) { - $post = mycred_get_post((int) $comment->comment_post_ID); - $content_author = $post->post_author; - } - - $comment_author_points = $this->core->zero(); - $content_author_points = $this->core->zero(); - - $reference = ''; - $log = ''; - - // Approved Comments - if ($new_status == 'approved' ) { - $reference = 'approved_comment'; - $log = $this->prefs['approved']['log']; - - // From unapproved / hold - if (in_array($old_status, array( 'unapproved', 'hold' )) ) { - // Comment author - if (! $this->user_exceeds_limit($comment_author, $comment->comment_post_ID) ) { - $comment_author_points = $this->prefs['approved']['creds']; - } - - // Content author - $content_author_points = $this->prefs['approved']['author']; - } - - // From being marked as spam - elseif ($old_status == 'spam' ) { - $comment_author_points = abs($this->prefs['spam']['creds']); - $content_author_points = abs($this->prefs['spam']['author']); - } - - // From being in trash - elseif ($old_status == 'trash' ) { - $comment_author_points = abs($this->prefs['trash']['creds']); - $content_author_points = abs($this->prefs['trash']['author']); - } - } - - // Unapproved Comments - elseif ($new_status == 'unapproved' && $old_status == 'approved' ) { - $reference = 'unapproved_comment'; - $log = $this->prefs['trash']['log']; - - // If we deducted points for approved comments we want to add them back - if ($this->prefs['approved']['creds'] < $this->core->zero() ) { - $comment_author_points = abs($this->prefs['approved']['creds']); - $content_author_points = abs($this->prefs['approved']['author']); - } - - // Else use what we have set - else { - $comment_author_points = $this->prefs['trash']['creds']; - $content_author_points = $this->prefs['trash']['author']; - } - } - - // Marked as SPAM - elseif ($new_status == 'spam' ) { - $reference = 'spam_comment'; - $log = $this->prefs['spam']['log']; - - $comment_author_points = $this->prefs['spam']['creds']; - $content_author_points = $this->prefs['spam']['author']; - } - - // Trashed Comments - elseif ($new_status == 'trash' ) { - $reference = 'deleted_comment'; - $log = $this->prefs['trash']['log']; - - $comment_author_points = $this->prefs['trash']['creds']; - $content_author_points = $this->prefs['trash']['author']; - } - - // Comment Author - if (! $this->core->exclude_user($comment_author) && $comment_author_points != $this->core->zero() ) { - - // Check if we are allowed to comment our own comment and are doing it - if ($this->prefs['limits']['self_reply'] != 0 && $comment->comment_parent != 0 ) { - $parent = get_comment($comment->comment_parent); - // Comment author is not replying to their own comments - if ($parent->user_id != $comment_author ) { - $this->core->add_creds( - $reference, - $comment_author, - $comment_author_points, - $log, - $comment->comment_ID, - array( 'ref_type' => 'comment' ), - $this->mycred_type - ); - } - } - // Else - else { - $this->core->add_creds( - $reference, - $comment_author, - $comment_author_points, - $log, - $comment->comment_ID, - array( 'ref_type' => 'comment' ), - $this->mycred_type - ); - } - - } - - if ($content_author === null ) { return; - } - - // Content Author - if (! $this->core->exclude_user($content_author) && $content_author_points != $this->core->zero() ) { - $this->core->add_creds( - $reference, - $content_author, - $content_author_points, - $log, - $comment->comment_ID, - array( 'ref_type' => 'comment' ), - $this->mycred_type - ); - } - - } - - /** - * Check if user exceeds limit - * - * @since 1.1.1 - * @version 1.1 - */ - public function user_exceeds_limit( $user_id = null, $post_id = null ) - { - - if (! isset($this->prefs['limits']) ) { return false; - } - - // Prep - $today = date('Y-m-d', current_time('timestamp')); - - // First we check post limit - if ($this->prefs['limits']['per_post'] > 0 ) { - $post_limit = 0; - - // Grab limit - if (! $this->is_main_type ) { - $limit = mycred_get_user_meta($user_id, 'mycred_comment_limit_post_' . $this->mycred_type, '', true); - } else { - $limit = mycred_get_user_meta($user_id, 'mycred_comment_limit_post', '', true); - } - - // Apply default if none exist - if (empty($limit) ) { $limit = array( $post_id => $post_limit ); - } - - // Check if post_id is in limit array - if (array_key_exists($post_id, $limit) ) { - $post_limit = $limit[ $post_id ]; - - // Limit is reached - if ($post_limit >= $this->prefs['limits']['per_post'] ) { return true; - } - } - - // Add / Replace post_id counter with an incremented value - $limit[ $post_id ] = $post_limit+1; - - // Save - if (! $this->is_main_type ) { - mycred_update_user_meta($user_id, 'mycred_comment_limit_post_' . $this->mycred_type, '', $limit); - } else { - mycred_update_user_meta($user_id, 'mycred_comment_limit_post', '', $limit); - } - - } - - // Second we check daily limit - if ($this->prefs['limits']['per_day'] > 0 ) { - $daily_limit = 0; - - // Grab limit - if (! $this->is_main_type ) { - $limit = mycred_get_user_meta($user_id, 'mycred_comment_limit_day_' . $this->mycred_type, '', true); - } else { - $limit = mycred_get_user_meta($user_id, 'mycred_comment_limit_day', '', true); - } - - // Apply default if none exist - if (empty($limit) ) { $limit = array(); - } - - // Check if todays date is in limit - if (array_key_exists($today, $limit) ) { - $daily_limit = $limit[ $today ]; - - // Limit is reached - if ($daily_limit >= $this->prefs['limits']['per_day'] ) { return true; - } - } - // Today is not in limit array so we reset to remove other dates - else { - $limit = array(); - } - - // Add / Replace todays counter with an imcremented value - $limit[ $today ] = $daily_limit+1; - - // Save - if (! $this->is_main_type ) { - mycred_update_user_meta($user_id, 'mycred_comment_limit_day_' . $this->mycred_type, '', $limit); - } else { - mycred_update_user_meta($user_id, 'mycred_comment_limit_day', '', $limit); - } - - } - - return false; - - } - - /** - * Preferences for Commenting Hook - * - * @since 0.1 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - if (! isset($prefs['limits']) ) { - $prefs['limits'] = array( - 'self_reply' => 0, - 'per_post' => 10, - 'per_day' => 0 - ); - } - - if (function_exists('dsq_is_installed') ) { - echo '

    ' . $this->core->template_tags_general(__('%plural% are only awarded when your website has been synced with the Disqus server!', 'mycred')) . '

    '; - } - - ?> +if ( ! class_exists( 'myCRED_Hook_Comments' ) ) : + class myCRED_Hook_Comments extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'comments', + 'defaults' => array( + 'limits' => array( + 'self_reply' => 0, + 'per_post' => 10, + 'per_day' => 0 + ), + 'approved' => array( + 'creds' => 1, + 'log' => '%plural% for Approved Comment', + 'author' => 0 + ), + 'spam' => array( + 'creds' => '-5', + 'log' => '%plural% deduction for Comment marked as SPAM', + 'author' => 0 + ), + 'trash' => array( + 'creds' => '-1', + 'log' => '%plural% deduction for deleted / unapproved Comment', + 'author' => 0 + ) + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 0.1 + * @version 1.2 + */ + public function run() { + + if ( ! function_exists( 'dsq_is_installed' ) ) { + add_action( 'comment_post', array( $this, 'new_comment' ), 99, 2 ); + add_action( 'transition_comment_status', array( $this, 'comment_transitions' ), 99, 3 ); + } + else { + add_action( 'wp_insert_comment', array( $this, 'disqus' ), 99, 2 ); + } + + } + + /** + * New Comment + * If comments are approved without moderation, we apply the corresponding method + * or else we will wait till the appropriate instance. + * @since 0.1 + * @version 1.2.2 + */ + public function new_comment( $comment_id, $comment_status ) { + + // Marked SPAM + if ( $comment_status === 'spam' ) + $this->comment_transitions( 'spam', 'unapproved', $comment_id ); + + // Approved comment + elseif ( $comment_status == 1 ) + $this->comment_transitions( 'approved', 'unapproved', $comment_id ); + + } + + /** + * Discuss Support + * @since 1.4 + * @version 1.0 + */ + function disqus( $id, $comment ) { + + // Attempt to get a comment authors ID + if ( $comment->user_id == 0 ) { + + $email = get_user_by( 'email', $comment->comment_author_email ); + // Failed to find author, can not award points + if ( $email === false ) return; + $comment->user_id = $email->ID; + + } + + $new_status = 'spam'; + if ( $comment->comment_approved == 1 ) + $new_status = 'approved'; + + elseif ( $comment->comment_approved == 0 ) + $new_status = 'unapproved'; + + $this->comment_transitions( $new_status, 'unapproved', $comment ); + + } + + /** + * Comment Transitions + * @since 1.1.2 + * @version 1.5 + */ + public function comment_transitions( $new_status, $old_status, $comment ) { + + // Passing an integer instead of an object means we need to grab the comment object ourselves + if ( ! is_object( $comment ) ) + $comment = get_comment( $comment ); + + // No comment object so lets bail + if ( $comment === NULL ) return; + + // Ignore Pingbacks or Trackbacks + if ( ! in_array( $comment->comment_type, array( '', 'comment' ) ) ) return; + + // Logged out users miss out + if ( $comment->user_id == 0 ) return; + + if ( apply_filters( 'mycred_comment_gets_cred', true, $comment, $new_status, $old_status ) === false ) return; + + // Get comment author + $comment_author = $comment->user_id; + + // Get content author + $content_author = NULL; + if ( isset( $comment->comment_post_ID ) || $comment->comment_post_ID != '' ) { + $post = mycred_get_post( (int) $comment->comment_post_ID ); + $content_author = $post->post_author; + } + + $comment_author_points = $this->core->zero(); + $content_author_points = $this->core->zero(); + + $reference = ''; + $log = ''; + + // Approved Comments + if ( $new_status == 'approved' ) { + $reference = 'approved_comment'; + $log = $this->prefs['approved']['log']; + + // From unapproved / hold + if ( in_array( $old_status, array( 'unapproved', 'hold' ) ) ) { + // Comment author + if ( ! $this->user_exceeds_limit( $comment_author, $comment->comment_post_ID ) ) + $comment_author_points = $this->prefs['approved']['creds']; + + // Content author + $content_author_points = $this->prefs['approved']['author']; + } + + // From being marked as spam + elseif ( $old_status == 'spam' ) { + $comment_author_points = abs( $this->prefs['spam']['creds'] ); + $content_author_points = abs( $this->prefs['spam']['author'] ); + } + + // From being in trash + elseif ( $old_status == 'trash' ) { + $comment_author_points = abs( $this->prefs['trash']['creds'] ); + $content_author_points = abs( $this->prefs['trash']['author'] ); + } + } + + // Unapproved Comments + elseif ( $new_status == 'unapproved' && $old_status == 'approved' ) { + $reference = 'unapproved_comment'; + $log = $this->prefs['trash']['log']; + + // If we deducted points for approved comments we want to add them back + if ( $this->prefs['approved']['creds'] < $this->core->zero() ) { + $comment_author_points = abs( $this->prefs['approved']['creds'] ); + $content_author_points = abs( $this->prefs['approved']['author'] ); + } + + // Else use what we have set + else { + $comment_author_points = $this->prefs['trash']['creds']; + $content_author_points = $this->prefs['trash']['author']; + } + } + + // Marked as SPAM + elseif ( $new_status == 'spam' ) { + $reference = 'spam_comment'; + $log = $this->prefs['spam']['log']; + + $comment_author_points = $this->prefs['spam']['creds']; + $content_author_points = $this->prefs['spam']['author']; + } + + // Trashed Comments + elseif ( $new_status == 'trash' ) { + $reference = 'deleted_comment'; + $log = $this->prefs['trash']['log']; + + $comment_author_points = $this->prefs['trash']['creds']; + $content_author_points = $this->prefs['trash']['author']; + } + + // Comment Author + if ( ! $this->core->exclude_user( $comment_author ) && $comment_author_points != $this->core->zero() ) { + + // Check if we are allowed to comment our own comment and are doing it + if ( $this->prefs['limits']['self_reply'] != 0 && $comment->comment_parent != 0 ) { + $parent = get_comment( $comment->comment_parent ); + // Comment author is not replying to their own comments + if ( $parent->user_id != $comment_author ) { + $this->core->add_creds( + $reference, + $comment_author, + $comment_author_points, + $log, + $comment->comment_ID, + array( 'ref_type' => 'comment' ), + $this->mycred_type + ); + } + } + // Else + else { + $this->core->add_creds( + $reference, + $comment_author, + $comment_author_points, + $log, + $comment->comment_ID, + array( 'ref_type' => 'comment' ), + $this->mycred_type + ); + } + + } + + if ( $content_author === NULL ) return; + + // Content Author + if ( ! $this->core->exclude_user( $content_author ) && $content_author_points != $this->core->zero() ) { + $this->core->add_creds( + $reference, + $content_author, + $content_author_points, + $log, + $comment->comment_ID, + array( 'ref_type' => 'comment' ), + $this->mycred_type + ); + } + + } + + /** + * Check if user exceeds limit + * @since 1.1.1 + * @version 1.1 + */ + public function user_exceeds_limit( $user_id = NULL, $post_id = NULL ) { + + if ( ! isset( $this->prefs['limits'] ) ) return false; + + // Prep + $today = date( 'Y-m-d', current_time( 'timestamp' ) ); + + // First we check post limit + if ( $this->prefs['limits']['per_post'] > 0 ) { + $post_limit = 0; + + // Grab limit + if ( ! $this->is_main_type ) + $limit = mycred_get_user_meta( $user_id, 'mycred_comment_limit_post_' . $this->mycred_type, '', true ); + else + $limit = mycred_get_user_meta( $user_id, 'mycred_comment_limit_post', '', true ); + + // Apply default if none exist + if ( empty( $limit ) ) $limit = array( $post_id => $post_limit ); + + // Check if post_id is in limit array + if ( array_key_exists( $post_id, $limit ) ) { + $post_limit = $limit[ $post_id ]; + + // Limit is reached + if ( $post_limit >= $this->prefs['limits']['per_post'] ) return true; + } + + // Add / Replace post_id counter with an incremented value + $limit[ $post_id ] = $post_limit+1; + + // Save + if ( ! $this->is_main_type ) + mycred_update_user_meta( $user_id, 'mycred_comment_limit_post_' . $this->mycred_type, '', $limit ); + else + mycred_update_user_meta( $user_id, 'mycred_comment_limit_post', '', $limit ); + + } + + // Second we check daily limit + if ( $this->prefs['limits']['per_day'] > 0 ) { + $daily_limit = 0; + + // Grab limit + if ( ! $this->is_main_type ) + $limit = mycred_get_user_meta( $user_id, 'mycred_comment_limit_day_' . $this->mycred_type, '', true ); + else + $limit = mycred_get_user_meta( $user_id, 'mycred_comment_limit_day', '', true ); + + // Apply default if none exist + if ( empty( $limit ) ) $limit = array(); + + // Check if todays date is in limit + if ( array_key_exists( $today, $limit ) ) { + $daily_limit = $limit[ $today ]; + + // Limit is reached + if ( $daily_limit >= $this->prefs['limits']['per_day'] ) return true; + } + // Today is not in limit array so we reset to remove other dates + else { + $limit = array(); + } + + // Add / Replace todays counter with an imcremented value + $limit[ $today ] = $daily_limit+1; + + // Save + if ( ! $this->is_main_type ) + mycred_update_user_meta( $user_id, 'mycred_comment_limit_day_' . $this->mycred_type, '', $limit ); + else + mycred_update_user_meta( $user_id, 'mycred_comment_limit_day', '', $limit ); + + } + + return false; + + } + + /** + * Preferences for Commenting Hook + * @since 0.1 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + + if ( ! isset( $prefs['limits'] ) ) + $prefs['limits'] = array( + 'self_reply' => 0, + 'per_post' => 10, + 'per_day' => 0 + ); + + if ( function_exists( 'dsq_is_installed' ) ) + echo '

    ' . $this->core->template_tags_general( __( '%plural% are only awarded when your website has been synced with the Disqus server!', 'mycred' ) ) . '

    '; + +?>
    -

    -
    -
    -
    - - - -
    -
    -
    -
    - - - -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'comment' )); ?> -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    -
    - - - core->template_tags_general(__('The number of comments per post that grants %_plural% to the comment author. Use zero for unlimited.', 'mycred')); ?> -
    -
    -
    -
    - - - core->template_tags_general(__('Number of comments per day that grants %_plural%. Use zero for unlimited.', 'mycred')); ?> -
    -
    -
    +

    +
    +
    +
    + + + +
    +
    +
    +
    + + + +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'comment' ) ); ?> +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    + + + core->template_tags_general( __( 'The number of comments per post that grants %_plural% to the comment author. Use zero for unlimited.', 'mycred' ) ); ?> +
    +
    +
    +
    + + + core->template_tags_general( __( 'Number of comments per day that grants %_plural%. Use zero for unlimited.', 'mycred' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - - -
    -
    -
    -
    - - - -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'comment' )); ?> -
    -
    -
    +

    +
    +
    +
    + + + +
    +
    +
    +
    + + + +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'comment' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - - -
    -
    -
    -
    - - - -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'comment' )); ?> -
    -
    -
    +

    +
    +
    +
    + + + +
    +
    +
    +
    + + + +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'comment' ) ); ?> +
    +
    +
    - array( - 'creds' => 1, - 'log' => '%plural% for deleted Post', - 'limit' => '0/x' - ), - 'page' => array( - 'creds' => 1, - 'log' => '%plural% for deleted Page', - 'limit' => '0/x' - ) - ); - - if (isset($hook_prefs['deleted_content']) ) { - $defaults = $hook_prefs['deleted_content']; - } - - parent::__construct( - array( - 'id' => 'deleted_content', - 'defaults' => $defaults - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.7 - * @version 1.0 - */ - public function run() - { - - if (EMPTY_TRASH_DAYS > 0 ) { - add_action('trashed_post', array( $this, 'delete_content' )); - } else { - add_action('before_delete_post', array( $this, 'delete_content' )); - } - - } - - /** - * Delete Content Hook - * - * @since 1.7 - * @version 1.1 - */ - public function delete_content( $post_id ) - { - - global $post_type; - - $post = mycred_get_post($post_id); - - $user_id = $post->post_author; - $post_type = $post->post_type; - - // Check for exclusions - if ($this->core->exclude_user($user_id) === true ) { return; - } - - // Make sure we award points other then zero - if (! isset($this->prefs[ $post_type ]['creds']) || empty($this->prefs[ $post_type ]['creds']) || $this->prefs[ $post_type ]['creds'] == 0 ) { return; - } - - // Prep - $entry = $this->prefs[ $post_type ]['log']; - $data = array( 'ref_type' => 'post' ); - $references = apply_filters('mycred_delete_hook_ref', 'deleted_content', $post, $this); - - // Make sure this is unique - if ($this->core->has_entry($references, $post_id, $user_id, $data, $this->mycred_type) ) { return; - } - - // Check limit - if (! $this->over_hook_limit($post_type, $references, $user_id) ) { - $this->core->add_creds( - $references, - $user_id, - $this->prefs[ $post_type ]['creds'], - $entry, - $post_id, - $data, - $this->mycred_type - ); - } - - } - - /** - * Preference for Delete Content Hook - * - * @since 1.7 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +if ( ! class_exists( 'myCRED_Hook_Delete_Content' ) ) : + class myCRED_Hook_Delete_Content extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + $defaults = array( + 'post' => array( + 'creds' => 1, + 'log' => '%plural% for deleted Post', + 'limit' => '0/x' + ), + 'page' => array( + 'creds' => 1, + 'log' => '%plural% for deleted Page', + 'limit' => '0/x' + ) + ); + + if ( isset( $hook_prefs['deleted_content'] ) ) + $defaults = $hook_prefs['deleted_content']; + + parent::__construct( array( + 'id' => 'deleted_content', + 'defaults' => $defaults + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.7 + * @version 1.0 + */ + public function run() { + + if ( EMPTY_TRASH_DAYS > 0 ) + add_action( 'trashed_post', array( $this, 'delete_content' ) ); + else + add_action( 'before_delete_post', array( $this, 'delete_content' ) ); + + } + + /** + * Delete Content Hook + * @since 1.7 + * @version 1.1 + */ + public function delete_content( $post_id ) { + + global $post_type; + + $post = mycred_get_post( $post_id ); + + $user_id = $post->post_author; + $post_type = $post->post_type; + + // Check for exclusions + if ( $this->core->exclude_user( $user_id ) === true ) return; + + // Make sure we award points other then zero + if ( ! isset( $this->prefs[ $post_type ]['creds'] ) || empty( $this->prefs[ $post_type ]['creds'] ) || $this->prefs[ $post_type ]['creds'] == 0 ) return; + + // Prep + $entry = $this->prefs[ $post_type ]['log']; + $data = array( 'ref_type' => 'post' ); + $references = apply_filters( 'mycred_delete_hook_ref', 'deleted_content', $post, $this ); + + // Make sure this is unique + if ( $this->core->has_entry( $references, $post_id, $user_id, $data, $this->mycred_type ) ) return; + + // Check limit + if ( ! $this->over_hook_limit( $post_type, $references, $user_id ) ) + $this->core->add_creds( + $references, + $user_id, + $this->prefs[ $post_type ]['creds'], + $entry, + $post_id, + $data, + $this->mycred_type + ); + + } + + /** + * Preference for Delete Content Hook + * @since 1.7 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'post' => 'limit' )), $this->field_id(array( 'post' => 'limit' )), $prefs['post']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'post' => 'limit' ) ), $this->field_id( array( 'post' => 'limit' ) ), $prefs['post']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'page' => 'limit' )), $this->field_id(array( 'page' => 'limit' )), $prefs['page']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'page' => 'limit' ) ), $this->field_id( array( 'page' => 'limit' ) ), $prefs['page']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - true, - '_builtin' => false - ); - $post_types = get_post_types($post_type_args, 'objects', 'and'); - - foreach ( $post_types as $post_type ) { - - // Start by checking if this post type should be excluded - if (! $this->include_post_type($post_type->name) ) { continue; - } - - // Points to award/deduct - if (isset($prefs[ $post_type->name ]['creds']) ) { - $_creds = $prefs[ $post_type->name ]['creds']; - } else { - $_creds = 0; - } - - // Log template - if (isset($prefs[ $post_type->name ]['log']) ) { - $_log = $prefs[ $post_type->name ]['log']; - } else { - $_log = '%plural% for deleted content'; - } - - if (isset($prefs[ $post_type->name ]['limit']) ) { - $_limit = $prefs[ $post_type->name ]['limit']; - } else { - $_limit = '0/x'; - } - - ?> + true, + '_builtin' => false + ); + $post_types = get_post_types( $post_type_args, 'objects', 'and' ); + + foreach ( $post_types as $post_type ) { + + // Start by checking if this post type should be excluded + if ( ! $this->include_post_type( $post_type->name ) ) continue; + + // Points to award/deduct + if ( isset( $prefs[ $post_type->name ]['creds'] ) ) + $_creds = $prefs[ $post_type->name ]['creds']; + else + $_creds = 0; + + // Log template + if ( isset( $prefs[ $post_type->name ]['log'] ) ) + $_log = $prefs[ $post_type->name ]['log']; + else + $_log = '%plural% for deleted content'; + + if ( isset( $prefs[ $post_type->name ]['limit'] ) ) + $_limit = $prefs[ $post_type->name ]['limit']; + else + $_limit = '0/x'; + +?>
    -

    labels->name); ?>

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( $post_type->name => 'limit' )), $this->field_id(array( $post_type->name => 'limit' )), $_limit); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    labels->name ); ?>

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( $post_type->name => 'limit' ) ), $this->field_id( array( $post_type->name => 'limit' ) ), $_limit ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - true, - '_builtin' => false - ); - $post_types = get_post_types($post_type_args, 'objects', 'and'); - - foreach ( $post_types as $post_type ) { - - // Start by checking if this post type should be excluded - if (! $this->include_post_type($post_type->name) ) { continue; - } - - if (isset($data[ $post_type->name ]['limit']) && isset($data[ $post_type->name ]['limit_by']) ) { - $limit = sanitize_text_field($data[ $post_type->name ]['limit']); - if ($limit == '' ) { $limit = 0; - } - $data[ $post_type->name ]['limit'] = $limit . '/' . $data[ $post_type->name ]['limit_by']; - unset($data[ $post_type->name ]['limit_by']); - } - - } - - return $data; - - } - - } + true, + '_builtin' => false + ); + $post_types = get_post_types( $post_type_args, 'objects', 'and' ); + + foreach ( $post_types as $post_type ) { + + // Start by checking if this post type should be excluded + if ( ! $this->include_post_type( $post_type->name ) ) continue; + + if ( isset( $data[ $post_type->name ]['limit'] ) && isset( $data[ $post_type->name ]['limit_by'] ) ) { + $limit = sanitize_text_field( $data[ $post_type->name ]['limit'] ); + if ( $limit == '' ) $limit = 0; + $data[ $post_type->name ]['limit'] = $limit . '/' . $data[ $post_type->name ]['limit_by']; + unset( $data[ $post_type->name ]['limit_by'] ); + } + + } + + return $data; + + } + + } endif; diff --git a/includes/hooks/mycred-hook-link-clicks.php b/includes/hooks/mycred-hook-link-clicks.php index e3c9176..c80360d 100644 --- a/includes/hooks/mycred-hook-link-clicks.php +++ b/includes/hooks/mycred-hook-link-clicks.php @@ -1,359 +1,315 @@ 'link_click', - 'defaults' => array( - 'limit_by' => 'none', - 'creds' => 1, - 'log' => '%plural% for clicking on link to: %url%' - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.1 - * @version 1.0 - */ - public function run() - { - - if (! is_user_logged_in() ) { return; - } - - add_action('mycred_register_assets', array( $this, 'register_script' )); - add_action('mycred_front_enqueue_footer', array( $this, 'enqueue_footer' )); - add_filter('mycred_parse_tags_link', array( $this, 'parse_custom_tags' ), 10, 2); - - if (isset($_POST['action']) && $_POST['action'] == 'mycred-click-points' && isset($_POST['token']) && wp_verify_nonce($_POST['token'], 'mycred-link-points') ) { - $this->ajax_call_link_points(); - } - - } - - /** - * Customize Limit Options - * - * @since 1.1 - * @version 1.0 - */ - public function custom_limit() - { - - return array( - 'none' => __('No limit', 'mycred'), - 'url' => __('Once for each unique URL', 'mycred'), - 'id' => __('Once for each unique link id', 'mycred') - ); - - } - - /** - * Parse Custom Tags in Log - * - * @since 1.1 - * @version 1.1.1 - */ - public function parse_custom_tags( $content, $log_entry ) - { - - $data = maybe_unserialize($log_entry->data); - $content = str_replace('%url%', $data['link_url'], $content); - $content = str_replace('%id%', $data['link_id'], $content); - - if (isset($data['link_title']) ) { - $content = str_replace('%title%', $data['link_title'], $content); - } - - return $content; - - } - - /** - * Register Script - * - * @since 1.1 - * @version 1.0 - */ - public function register_script() - { - - global $mycred_link_points; - - $mycred_link_points = false; - - wp_register_script( - 'mycred-link-points', - plugins_url('assets/js/links.js', myCRED_THIS), - array( 'jquery' ), - myCRED_VERSION . '.1', - true - ); - - } - - /** - * WP Fotter - * - * @since 1.1 - * @version 1.1 - */ - public function enqueue_footer() - { - - global $mycred_link_points; - - if ($mycred_link_points === true ) { - - global $post; - - wp_localize_script( - 'mycred-link-points', - 'myCREDlink', - array( - 'ajaxurl' => esc_url(isset($post->ID) ? mycred_get_permalink($post->ID) : home_url('/')), - 'token' => wp_create_nonce('mycred-link-points') - ) - ); - wp_enqueue_script('mycred-link-points'); - - } - - } - - /** - * Custom Has Entry Check - * - * @since 1.1 - * @version 1.1.2 - */ - public function has_entry( $action = '', $reference = '', $user_id = '', $data = '', $type = '' ) - { - - global $wpdb, $mycred_log_table; - - if ($this->prefs['limit_by'] == 'url' ) { - $reference = urldecode($reference); - $string = '%s:8:"link_url";s:' . strlen($reference) . ':"' . $reference . '";%'; - } - elseif ($this->prefs['limit_by'] == 'id' ) { - $string = '%s:7:"link_id";s:' . strlen($reference) . ':"' . $reference . '";%'; - } - else { return false; - } - - $sql = "SELECT id FROM {$mycred_log_table} WHERE ref = %s AND user_id = %d AND data LIKE %s AND ctype = %s;"; - $wpdb->get_results($wpdb->prepare($sql, $action, $user_id, $string, $this->mycred_type)); - if ($wpdb->num_rows > 0 ) { return true; - } - - return false; - - } - - /** - * AJAX Call Handler - * - * @since 1.1 - * @version 1.5 - */ - public function ajax_call_link_points() - { - - // We must be logged in - if (! is_user_logged_in() ) { return; - } - - // Make sure we only handle our own point type - if (! isset($_POST['ctype']) || $_POST['ctype'] != $this->mycred_type || ! isset($_POST['url']) ) { return; - } - - // Security - check_ajax_referer('mycred-link-points', 'token'); - - // Current User - $user_id = get_current_user_id(); - - if (mycred_force_singular_session($user_id, 'mycred-last-linkclick') ) { - wp_send_json(101); - } - - // Check if user should be excluded - if ($this->core->exclude_user($user_id) ) { wp_send_json(200); - } - - // Token - if (! isset($_POST['key']) ) { wp_send_json(300); - } - $token = mycred_verify_token($_POST['key'], 4); - if ($token === false ) { wp_send_json(305); - } - - list ( $amount, $point_type, $id, $url ) = $token; - if ($amount == '' || $point_type == '' || $id == '' || $url == '' ) { wp_send_json(310); - } - - // Make sure the token is not abused - if ($url != urlencode($_POST['url']) ) { wp_send_json(315); - } - - // Bail now if this was not intenteded for this type - if ($point_type != $this->mycred_type ) { return; - } - - // Amount - if ($amount == 0 ) { - $amount = $this->prefs['creds']; - } else { - $amount = $this->core->number($amount); - } - - if ($amount == 0 || $amount == $this->core->zero() ) { wp_send_json(400); - } - - $data = array( - 'ref_type' => 'link', - 'link_url' => esc_url_raw($_POST['url']), - 'link_id' => $id, - 'link_title' => ( isset($_POST['etitle']) ) ? sanitize_text_field($_POST['etitle']) : '' - ); - - // Limits - if ($this->prefs['limit_by'] == 'url' ) { - if ($this->has_clicked($user_id, 'link_url', $data['link_url']) ) { wp_send_json(600); - } - } - elseif ($this->prefs['limit_by'] == 'id' ) { - if ($this->has_clicked($user_id, 'link_id', $data['link_id']) ) { wp_send_json(700); - } - } - - $amount = apply_filters('mycred_link_click_amount', $amount, $user_id, $point_type, $data, $this->prefs['log']); - - // Execute - $this->core->add_creds( - 'link_click', - $user_id, - $amount, - $this->prefs['log'], - '', - $data, - $point_type - ); - - // Report the good news - wp_send_json('done'); - - } - - /** - * Has Clicked - * Checks if a user has received points for a link based on either - * an ID or URL. - * - * @since 1.3.3.1 - * @version 1.0.1 - */ - public function has_clicked( $user_id = null, $by = '', $check = '' ) - { - - global $wpdb, $mycred_log_table; - - $rows = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$mycred_log_table} WHERE ref = %s AND user_id = %d AND ctype = %s", 'link_click', $user_id, $this->mycred_type)); - if (count($rows) == 0 ) { return false; - } - - $reply = false; - foreach ( $rows as $row ) { - - $data = maybe_unserialize($row->data); - if (! is_array($data) || ! isset($data[ $by ]) ) { continue; - } - - if ($data[ $by ] == $check ) { - $reply = true; - break; - } - - } - - return $reply; - - } - - /** - * Preference for Link Click Hook - * - * @since 1.1 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +if ( ! class_exists( 'myCRED_Hook_Click_Links' ) ) : + class myCRED_Hook_Click_Links extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'link_click', + 'defaults' => array( + 'limit_by' => 'none', + 'creds' => 1, + 'log' => '%plural% for clicking on link to: %url%' + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.1 + * @version 1.0 + */ + public function run() { + + if ( ! is_user_logged_in() ) return; + + add_action( 'mycred_register_assets', array( $this, 'register_script' ) ); + add_action( 'mycred_front_enqueue_footer', array( $this, 'enqueue_footer' ) ); + add_filter( 'mycred_parse_tags_link', array( $this, 'parse_custom_tags' ), 10, 2 ); + + if ( isset( $_POST['action'] ) && $_POST['action'] == 'mycred-click-points' && isset( $_POST['token'] ) && wp_verify_nonce( $_POST['token'], 'mycred-link-points' ) ) + $this->ajax_call_link_points(); + + } + + /** + * Customize Limit Options + * @since 1.1 + * @version 1.0 + */ + public function custom_limit() { + + return array( + 'none' => __( 'No limit', 'mycred' ), + 'url' => __( 'Once for each unique URL', 'mycred' ), + 'id' => __( 'Once for each unique link id', 'mycred' ) + ); + + } + + /** + * Parse Custom Tags in Log + * @since 1.1 + * @version 1.1.1 + */ + public function parse_custom_tags( $content, $log_entry ) { + + $data = maybe_unserialize( $log_entry->data ); + $content = str_replace( '%url%', $data['link_url'], $content ); + $content = str_replace( '%id%', $data['link_id'], $content ); + + if ( isset( $data['link_title'] ) ) + $content = str_replace( '%title%', $data['link_title'], $content ); + + return $content; + + } + + /** + * Register Script + * @since 1.1 + * @version 1.0 + */ + public function register_script() { + + global $mycred_link_points; + + $mycred_link_points = false; + + wp_register_script( + 'mycred-link-points', + plugins_url( 'assets/js/links.js', myCRED_THIS ), + array( 'jquery' ), + myCRED_VERSION . '.1', + true + ); + + } + + /** + * WP Fotter + * @since 1.1 + * @version 1.1 + */ + public function enqueue_footer() { + + global $mycred_link_points; + + if ( $mycred_link_points === true ) { + + global $post; + + wp_localize_script( + 'mycred-link-points', + 'myCREDlink', + array( + 'ajaxurl' => esc_url( isset( $post->ID ) ? mycred_get_permalink( $post->ID ) : home_url( '/' ) ), + 'token' => wp_create_nonce( 'mycred-link-points' ) + ) + ); + wp_enqueue_script( 'mycred-link-points' ); + + } + + } + + /** + * Custom Has Entry Check + * @since 1.1 + * @version 1.1.2 + */ + public function has_entry( $action = '', $reference = '', $user_id = '', $data = '', $type = '' ) { + + global $wpdb, $mycred_log_table; + + if ( $this->prefs['limit_by'] == 'url' ) { + $reference = urldecode( $reference ); + $string = '%s:8:"link_url";s:' . strlen( $reference ) . ':"' . $reference . '";%'; + } + elseif ( $this->prefs['limit_by'] == 'id' ) { + $string = '%s:7:"link_id";s:' . strlen( $reference ) . ':"' . $reference . '";%'; + } + else return false; + + $sql = "SELECT id FROM {$mycred_log_table} WHERE ref = %s AND user_id = %d AND data LIKE %s AND ctype = %s;"; + $wpdb->get_results( $wpdb->prepare( $sql, $action, $user_id, $string, $this->mycred_type ) ); + if ( $wpdb->num_rows > 0 ) return true; + + return false; + + } + + /** + * AJAX Call Handler + * @since 1.1 + * @version 1.5 + */ + public function ajax_call_link_points() { + + // We must be logged in + if ( ! is_user_logged_in() ) return; + + // Make sure we only handle our own point type + if ( ! isset( $_POST['ctype'] ) || $_POST['ctype'] != $this->mycred_type || ! isset( $_POST['url'] ) ) return; + + // Security + check_ajax_referer( 'mycred-link-points', 'token' ); + + // Current User + $user_id = get_current_user_id(); + + if ( mycred_force_singular_session( $user_id, 'mycred-last-linkclick' ) ) + wp_send_json( 101 ); + + // Check if user should be excluded + if ( $this->core->exclude_user( $user_id ) ) wp_send_json( 200 ); + + // Token + if ( ! isset( $_POST['key'] ) ) wp_send_json( 300 ); + $token = mycred_verify_token( $_POST['key'], 4 ); + if ( $token === false ) wp_send_json( 305 ); + + list ( $amount, $point_type, $id, $url ) = $token; + if ( $amount == '' || $point_type == '' || $id == '' || $url == '' ) wp_send_json( 310 ); + + // Make sure the token is not abused + if ( $url != urlencode( $_POST['url'] ) ) wp_send_json( 315 ); + + // Bail now if this was not intenteded for this type + if ( $point_type != $this->mycred_type ) return; + + // Amount + if ( $amount == 0 ) + $amount = $this->prefs['creds']; + else + $amount = $this->core->number( $amount ); + + if ( $amount == 0 || $amount == $this->core->zero() ) wp_send_json( 400 ); + + $data = array( + 'ref_type' => 'link', + 'link_url' => esc_url_raw( $_POST['url'] ), + 'link_id' => $id, + 'link_title' => ( isset( $_POST['etitle'] ) ) ? sanitize_text_field( $_POST['etitle'] ) : '' + ); + + // Limits + if ( $this->prefs['limit_by'] == 'url' ) { + if ( $this->has_clicked( $user_id, 'link_url', $data['link_url'] ) ) wp_send_json( 600 ); + } + elseif ( $this->prefs['limit_by'] == 'id' ) { + if ( $this->has_clicked( $user_id, 'link_id', $data['link_id'] ) ) wp_send_json( 700 ); + } + + $amount = apply_filters( 'mycred_link_click_amount', $amount, $user_id, $point_type, $data, $this->prefs['log'] ); + + // Execute + $this->core->add_creds( + 'link_click', + $user_id, + $amount, + $this->prefs['log'], + '', + $data, + $point_type + ); + + // Report the good news + wp_send_json( 'done' ); + + } + + /** + * Has Clicked + * Checks if a user has received points for a link based on either + * an ID or URL. + * @since 1.3.3.1 + * @version 1.0.1 + */ + public function has_clicked( $user_id = NULL, $by = '', $check = '' ) { + + global $wpdb, $mycred_log_table; + + $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$mycred_log_table} WHERE ref = %s AND user_id = %d AND ctype = %s", 'link_click', $user_id, $this->mycred_type ) ); + if ( count( $rows ) == 0 ) return false; + + $reply = false; + foreach ( $rows as $row ) { + + $data = maybe_unserialize( $row->data ); + if ( ! is_array( $data ) || ! isset( $data[ $by ] ) ) continue; + + if ( $data[ $by ] == $check ) { + $reply = true; + break; + } + + } + + return $reply; + + } + + /** + * Preference for Link Click Hook + * @since 1.1 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'user' ), '%url%, %title% or %id%'); ?> -
    -
    -
    -
    -
    -
    - - impose_limits_dropdown('limit_by', false); - - ?> -
    -
    -
    - -
    -
    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'user' ), '%url%, %title% or %id%' ); ?> +
    +
    +
    +
    +
    +
    + +impose_limits_dropdown( 'limit_by', false ); + +?> +
    +
    +
    + +
    +
    - 'logging_in', - 'defaults' => array( - 'creds' => 1, - 'log' => '%plural% for logging in', - 'limit' => '1/d' - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 0.1 - * @version 1.1 - */ - public function run() - { - - // Social Connect - if (function_exists('sc_social_connect_process_login') ) { - add_action('social_connect_login', array( $this, 'social_login' )); - } - - // WordPress - add_action('wp_login', array( $this, 'logging_in' ), 10, 2); - - } - - /** - * Social Login - * Adds support for Social Connect plugin - * - * @since 1.4 - * @version 1.1 - */ - public function social_login( $user_login = 0 ) - { - - // Get user - $user = get_user_by('login', $user_login); - if (! isset($user->ID) ) { - // In case we use emails for login instead of username - $user = get_user_by('email', $user_login); - if (! is_object($user) ) { return; - } - } - - // Check for exclusion - if ($this->core->exclude_user($user->ID) ) { return; - } - - // Limit - if (! $this->over_hook_limit('', 'logging_in', $user->ID) ) { - $this->core->add_creds( - 'logging_in', - $user->ID, - $this->prefs['creds'], - $this->prefs['log'], - 0, - '', - $this->mycred_type - ); - } - - } - - /** - * Login Hook - * - * @since 0.1 - * @version 1.3 - */ - public function logging_in( $user_login, $user = '' ) - { - - // In case the user object is not past along - if (! is_object($user) ) { - - $user = get_user_by('login', $user_login); - if (! is_object($user) ) { - - // In case we use emails for login instead of username - $user = get_user_by('email', $user_login); - if (! is_object($user) ) { return; - } - - } - - } - - // Check for exclusion - if ($this->core->exclude_user($user->ID) ) { return; - } - - // Limit - if (! $this->over_hook_limit('', 'logging_in', $user->ID) ) { - $this->core->add_creds( - 'logging_in', - $user->ID, - $this->prefs['creds'], - $this->prefs['log'], - 0, - '', - $this->mycred_type - ); - } - - } - - /** - * Preference for Login Hook - * - * @since 0.1 - * @version 1.2 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +if ( ! class_exists( 'myCRED_Hook_Logging_In' ) ) : + class myCRED_Hook_Logging_In extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'logging_in', + 'defaults' => array( + 'creds' => 1, + 'log' => '%plural% for logging in', + 'limit' => '1/d' + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 0.1 + * @version 1.1 + */ + public function run() { + + // Social Connect + if ( function_exists( 'sc_social_connect_process_login' ) ) + add_action( 'social_connect_login', array( $this, 'social_login' ) ); + + // WordPress + add_action( 'wp_login', array( $this, 'logging_in' ), 10, 2 ); + + } + + /** + * Social Login + * Adds support for Social Connect plugin + * @since 1.4 + * @version 1.1 + */ + public function social_login( $user_login = 0 ) { + + // Get user + $user = get_user_by( 'login', $user_login ); + if ( ! isset( $user->ID ) ) { + // In case we use emails for login instead of username + $user = get_user_by( 'email', $user_login ); + if ( ! is_object( $user ) ) return; + } + + // Check for exclusion + if ( $this->core->exclude_user( $user->ID ) ) return; + + // Limit + if ( ! $this->over_hook_limit( '', 'logging_in', $user->ID ) ) + $this->core->add_creds( + 'logging_in', + $user->ID, + $this->prefs['creds'], + $this->prefs['log'], + 0, + '', + $this->mycred_type + ); + + } + + /** + * Login Hook + * @since 0.1 + * @version 1.3 + */ + public function logging_in( $user_login, $user = '' ) { + + // In case the user object is not past along + if ( ! is_object( $user ) ) { + + $user = get_user_by( 'login', $user_login ); + if ( ! is_object( $user ) ) { + + // In case we use emails for login instead of username + $user = get_user_by( 'email', $user_login ); + if ( ! is_object( $user ) ) return; + + } + + } + + // Check for exclusion + if ( $this->core->exclude_user( $user->ID ) ) return; + + // Limit + if ( ! $this->over_hook_limit( '', 'logging_in', $user->ID ) ) + $this->core->add_creds( + 'logging_in', + $user->ID, + $this->prefs['creds'], + $this->prefs['log'], + 0, + '', + $this->mycred_type + ); + + } + + /** + * Preference for Login Hook + * @since 0.1 + * @version 1.2 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name('limit'), $this->field_id('limit'), $prefs['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( 'limit' ), $this->field_id( 'limit' ), $prefs['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - array( - 'creds' => 1, - 'log' => '%plural% for new Post', - 'limit' => '0/x' - ), - 'page' => array( - 'creds' => 1, - 'log' => '%plural% for new Page', - 'limit' => '0/x' - ) - ); - - if (isset($hook_prefs['publishing_content']) ) { - $defaults = $hook_prefs['publishing_content']; - } - - parent::__construct( - array( - 'id' => 'publishing_content', - 'defaults' => $defaults - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 0.1 - * @version 1.0 - */ - public function run() - { - - add_action('transition_post_status', array( $this, 'publishing_content' ), 10, 3); - - } - - /** - * Publish Content Hook - * - * @since 0.1 - * @version 1.2 - */ - public function publishing_content( $new_status, $old_status, $post ) - { - - $user_id = $post->post_author; - $post_id = $post->ID; - $post_type = $post->post_type; - - // Check for exclusions - if ($this->core->exclude_user($user_id) === true ) { return; - } - - // Make sure we award points other then zero - if (! isset($this->prefs[ $post_type ]['creds']) || empty($this->prefs[ $post_type ]['creds']) || $this->prefs[ $post_type ]['creds'] == 0 ) { return; - } - - // We want to fire when content get published or when it gets privatly published - $status = apply_filters('mycred_publish_hook_old', array( 'new', 'auto-draft', 'draft', 'private', 'pending', 'future' ), $post_id, $this->mycred_type); - $publish_status = apply_filters('mycred_publish_hook_new', array( 'publish', 'private' ), $post_id, $this->mycred_type); - $references = apply_filters('mycred_publish_hook_ref', 'publishing_content', $post, $new_status, $old_status, $this); - - if (in_array($old_status, $status) && in_array($new_status, $publish_status) && array_key_exists($post_type, $this->prefs) ) { - - // Prep - $entry = $this->prefs[ $post_type ]['log']; - $data = array( 'ref_type' => 'post' ); - - // Make sure this is unique - if ($this->core->has_entry($references, $post_id, $user_id, $data, $this->mycred_type) ) { return; - } - - // Check limit - if (! $this->over_hook_limit($post_type, $references, $user_id) ) { - $this->core->add_creds( - $references, - $user_id, - $this->prefs[ $post_type ]['creds'], - $entry, - $post_id, - $data, - $this->mycred_type - ); - } - - } - - } - - /** - * Preference for Publish Content Hook - * - * @since 0.1 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +if ( ! class_exists( 'myCRED_Hook_Publishing_Content' ) ) : + class myCRED_Hook_Publishing_Content extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + $defaults = array( + 'post' => array( + 'creds' => 1, + 'log' => '%plural% for new Post', + 'limit' => '0/x' + ), + 'page' => array( + 'creds' => 1, + 'log' => '%plural% for new Page', + 'limit' => '0/x' + ) + ); + + if ( isset( $hook_prefs['publishing_content'] ) ) + $defaults = $hook_prefs['publishing_content']; + + parent::__construct( array( + 'id' => 'publishing_content', + 'defaults' => $defaults + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 0.1 + * @version 1.0 + */ + public function run() { + + add_action( 'transition_post_status', array( $this, 'publishing_content' ), 10, 3 ); + + } + + /** + * Publish Content Hook + * @since 0.1 + * @version 1.2 + */ + public function publishing_content( $new_status, $old_status, $post ) { + + $user_id = $post->post_author; + $post_id = $post->ID; + $post_type = $post->post_type; + + // Check for exclusions + if ( $this->core->exclude_user( $user_id ) === true ) return; + + // Make sure we award points other then zero + if ( ! isset( $this->prefs[ $post_type ]['creds'] ) || empty( $this->prefs[ $post_type ]['creds'] ) || $this->prefs[ $post_type ]['creds'] == 0 ) return; + + // We want to fire when content get published or when it gets privatly published + $status = apply_filters( 'mycred_publish_hook_old', array( 'new', 'auto-draft', 'draft', 'private', 'pending', 'future' ), $post_id, $this->mycred_type ); + $publish_status = apply_filters( 'mycred_publish_hook_new', array( 'publish', 'private' ), $post_id, $this->mycred_type ); + $references = apply_filters( 'mycred_publish_hook_ref', 'publishing_content', $post, $new_status, $old_status, $this ); + + if ( in_array( $old_status, $status ) && in_array( $new_status, $publish_status ) && array_key_exists( $post_type, $this->prefs ) ) { + + // Prep + $entry = $this->prefs[ $post_type ]['log']; + $data = array( 'ref_type' => 'post' ); + + // Make sure this is unique + if ( $this->core->has_entry( $references, $post_id, $user_id, $data, $this->mycred_type ) ) return; + + // Check limit + if ( ! $this->over_hook_limit( $post_type, $references, $user_id ) ) + $this->core->add_creds( + $references, + $user_id, + $this->prefs[ $post_type ]['creds'], + $entry, + $post_id, + $data, + $this->mycred_type + ); + + } + + } + + /** + * Preference for Publish Content Hook + * @since 0.1 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'post' => 'limit' )), $this->field_id(array( 'post' => 'limit' )), $prefs['post']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'post' => 'limit' ) ), $this->field_id( array( 'post' => 'limit' ) ), $prefs['post']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'page' => 'limit' )), $this->field_id(array( 'page' => 'limit' )), $prefs['page']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'page' => 'limit' ) ), $this->field_id( array( 'page' => 'limit' ) ), $prefs['page']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - true, - '_builtin' => false - ); - $post_types = get_post_types($post_type_args, 'objects', 'and'); - - foreach ( $post_types as $post_type ) { - - // Start by checking if this post type should be excluded - if (! $this->include_post_type($post_type->name) ) { continue; - } - - // Points to award/deduct - if (isset($prefs[ $post_type->name ]['creds']) ) { - $_creds = $prefs[ $post_type->name ]['creds']; - } else { - $_creds = 0; - } - - // Log template - if (isset($prefs[ $post_type->name ]['log']) ) { - $_log = $prefs[ $post_type->name ]['log']; - } else { - $_log = '%plural% for published content'; - } - - if (isset($prefs[ $post_type->name ]['limit']) ) { - $_limit = $prefs[ $post_type->name ]['limit']; - } else { - $_limit = '0/x'; - } - - ?> + true, + '_builtin' => false + ); + $post_types = get_post_types( $post_type_args, 'objects', 'and' ); + + foreach ( $post_types as $post_type ) { + + // Start by checking if this post type should be excluded + if ( ! $this->include_post_type( $post_type->name ) ) continue; + + // Points to award/deduct + if ( isset( $prefs[ $post_type->name ]['creds'] ) ) + $_creds = $prefs[ $post_type->name ]['creds']; + else + $_creds = 0; + + // Log template + if ( isset( $prefs[ $post_type->name ]['log'] ) ) + $_log = $prefs[ $post_type->name ]['log']; + else + $_log = '%plural% for published content'; + + if ( isset( $prefs[ $post_type->name ]['limit'] ) ) + $_limit = $prefs[ $post_type->name ]['limit']; + else + $_limit = '0/x'; + +?>
    -

    labels->name); ?>

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( $post_type->name => 'limit' )), $this->field_id(array( $post_type->name => 'limit' )), $_limit); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    labels->name ); ?>

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( $post_type->name => 'limit' ) ), $this->field_id( array( $post_type->name => 'limit' ) ), $_limit ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - true, - '_builtin' => false - ); - $post_types = get_post_types($post_type_args, 'objects', 'and'); - - foreach ( $post_types as $post_type ) { - - // Start by checking if this post type should be excluded - if (! $this->include_post_type($post_type->name) ) { continue; - } - - if (isset($data[ $post_type->name ]['limit']) && isset($data[ $post_type->name ]['limit_by']) ) { - $limit = sanitize_text_field($data[ $post_type->name ]['limit']); - if ($limit == '' ) { $limit = 0; - } - $data[ $post_type->name ]['limit'] = $limit . '/' . $data[ $post_type->name ]['limit_by']; - unset($data[ $post_type->name ]['limit_by']); - } - - } - - return $data; - - } - - } + true, + '_builtin' => false + ); + $post_types = get_post_types( $post_type_args, 'objects', 'and' ); + + foreach ( $post_types as $post_type ) { + + // Start by checking if this post type should be excluded + if ( ! $this->include_post_type( $post_type->name ) ) continue; + + if ( isset( $data[ $post_type->name ]['limit'] ) && isset( $data[ $post_type->name ]['limit_by'] ) ) { + $limit = sanitize_text_field( $data[ $post_type->name ]['limit'] ); + if ( $limit == '' ) $limit = 0; + $data[ $post_type->name ]['limit'] = $limit . '/' . $data[ $post_type->name ]['limit_by']; + unset( $data[ $post_type->name ]['limit_by'] ); + } + + } + + return $data; + + } + + } endif; diff --git a/includes/hooks/mycred-hook-referrals.php b/includes/hooks/mycred-hook-referrals.php index ae23ce6..b0a4fd6 100644 --- a/includes/hooks/mycred-hook-referrals.php +++ b/includes/hooks/mycred-hook-referrals.php @@ -1,25 +1,21 @@ 'affiliate', @@ -43,912 +39,820 @@ function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) 'buddypress' => array( 'profile' => 0, 'priority' => 10, - 'title' => __('Affiliate Program', 'mycred'), + 'title' => __( 'Affiliate Program', 'mycred' ), 'desc' => '' ) ) ); - $hook_defaults = apply_filters('mycred_hook_referrals', $hook_defaults); + $hook_defaults = apply_filters( 'mycred_hook_referrals', $hook_defaults ); - parent::__construct($hook_defaults, $hook_prefs, $type); + parent::__construct( $hook_defaults , $hook_prefs, $type ); - // Let others play with the limit by - $this->limit_by = apply_filters( - 'mycred_affiliate_limit_by', array( - 'total' => __('Total', 'mycred'), - 'daily' => __('Per Day', 'mycred') - ), $this - ); + // Let others play with the limit by + $this->limit_by = apply_filters( 'mycred_affiliate_limit_by', array( + 'total' => __( 'Total', 'mycred' ), + 'daily' => __( 'Per Day', 'mycred' ) + ), $this ); - // Let others play with the ref key - $this->ref_key = apply_filters('mycred_affiliate_key', 'mref', $this); - - add_filter('mycred_parse_log_entry_signup_referral', array( $this, 'parse_log_entry' ), 10, 2); - add_action('wp_footer', 'copy_ref_link'); - - } - - /** - * Run - * - * @since 1.4 - * @version 1.2.1 - */ - public function run() - { - - // Insert into BuddyPress profile - if (function_exists('bp_is_active') && bp_is_active('xprofile') && $this->prefs['buddypress']['profile'] ) { - add_action('bp_after_profile_loop_content', array( $this, 'buddypress_profile' ), $this->prefs['buddypress']['priority']); - } - - - // Hook into user activation - if (function_exists('buddypress') ) { - add_action('mycred_bp_user_activated', array( $this, 'verified_signup' )); - } - - // Register Shortcodes - add_filter('mycred_affiliate_link_' . $this->mycred_type, array( $this, 'shortcode_affiliate_link' ), 10, 2); - add_filter('mycred_affiliate_id_' . $this->mycred_type, array( $this, 'shortcode_affiliate_id' ), 10, 2); - - add_filter('mycred_referral_keys', array( $this, 'add_key' )); - - // Logged in users do not get points - if (is_user_logged_in() && apply_filters('mycred_affiliate_allow_members', false) === false ) { return; - } - - // Points for visits - if ($this->prefs['visit']['creds'] != 0 || $this->prefs['signup']['creds'] != 0 ) { - add_action('mycred_referred_visit', array( $this, 'site_visits' )); - } - - // Points for signups - if ($this->prefs['signup']['creds'] != 0 ) { - add_action('mycred_referred_signup', array( $this, 'site_signup' )); - } - - } - - /** - * Parse Log Entry - * Add support for user related template tags in signup referrals. - * - * @since 1.4 - * @version 1.0 - */ - public function parse_log_entry( $content, $entry ) - { - - $user_id = absint($entry->ref_id); - return $this->core->template_tags_user($content, $user_id); - - } - - /** - * Add Referral Key - * - * @since 1.5.3 - * @version 1.0 - */ - public function add_key( $keys ) - { - - if (! isset($_GET[ $this->ref_key ]) || isset($_COOKIE[ 'mycred_ref' . $this->mycred_type ]) ) { return $keys; - } - - if (! in_array($this->ref_key, $keys) ) { - $keys[] = $this->ref_key; - } - - return $keys; - - } - - /** - * Shortcode: Affiliate Link - * Appends the current users affiliate link to either a given - * URL or if not set, the current URL. If user is not logged in, - * the set URL is returned. If this is not set, the shortcode - * will return an empty string. - * - * @since 1.4 - * @version 1.1 - */ - public function shortcode_affiliate_link( $content, $atts ) - { - - extract( - shortcode_atts( - array( - 'url' => 0, - 'user_id' => '', - 'post_id' => '' - ), $atts - ) - ); + // Let others play with the ref key + $this->ref_key = apply_filters( 'mycred_affiliate_key', 'mref', $this ); - if (! is_user_logged_in() && $user_id == '' ) { - return $url; - } - - if ($user_id == '' ) { - $user_id = get_current_user_id(); - } - - if ($post_id != '' ) { - $url = mycred_get_permalink($post_id); - } - - return $this->get_ref_link($user_id, $url); - - } - - /** - * Shortcode: Affiliate ID - * Returns the current users affiliate ID. Returns an empty - * string if the user is not logged in. - * - * @since 1.4 - * @version 1.1 - */ - public function shortcode_affiliate_id( $content, $atts ) - { - - extract( - shortcode_atts( - array( - 'user_id' => '' - ), $atts - ) - ); + add_filter( 'mycred_parse_log_entry_signup_referral', array( $this, 'parse_log_entry' ), 10, 2 ); + add_action( 'wp_footer', 'copy_ref_link' ); - if (! is_user_logged_in() && $user_id == '' ) { - $ref_id = ''; + } - } else { + /** + * Run + * @since 1.4 + * @version 1.2.1 + */ + public function run() { - if ($user_id == '' ) { - $user_id = get_current_user_id(); - } + // Insert into BuddyPress profile + if ( function_exists( 'bp_is_active' ) && bp_is_active( 'xprofile' ) && $this->prefs['buddypress']['profile'] ) + add_action( 'bp_after_profile_loop_content', array( $this, 'buddypress_profile' ), $this->prefs['buddypress']['priority'] ); - $ref_id = $this->get_ref_id($user_id); - } + // Hook into user activation + if ( function_exists( 'buddypress' ) ) + add_action( 'mycred_bp_user_activated', array( $this, 'verified_signup' ) ); - return apply_filters('mycred_affiliate_id', $ref_id, $atts, $this); + // Register Shortcodes + add_filter( 'mycred_affiliate_link_' . $this->mycred_type, array( $this, 'shortcode_affiliate_link' ), 10, 2 ); + add_filter( 'mycred_affiliate_id_' . $this->mycred_type, array( $this, 'shortcode_affiliate_id' ), 10, 2 ); - } + add_filter( 'mycred_referral_keys', array( $this, 'add_key' ) ); - /** - * BuddyPress Profile - * - * @since 1.4 - * @version 1.1 - */ - public function buddypress_profile() - { + // Logged in users do not get points + if ( is_user_logged_in() && apply_filters( 'mycred_affiliate_allow_members', false ) === false ) return; - // Prep - $output = ''; - $user_id = bp_displayed_user_id(); + // Points for visits + if ( $this->prefs['visit']['creds'] != 0 || $this->prefs['signup']['creds'] != 0 ) + add_action( 'mycred_referred_visit', array( $this, 'site_visits' ) ); - // Check for exclusion - if ($this->core->exclude_user($user_id) ) { return; - } - - $users_ref_link = ''; + // Points for signups + if ( $this->prefs['signup']['creds'] != 0 ) + add_action( 'mycred_referred_signup', array( $this, 'site_signup' ) ); - // If it is my profile or other members allowed to view eachothers profiles or if we are admins - if (bp_is_my_profile() || mycred_is_admin() ) { + } - $users_ref_link = $this->get_ref_link($user_id, home_url('/')); + /** + * Parse Log Entry + * Add support for user related template tags in signup referrals. + * @since 1.4 + * @version 1.0 + */ + public function parse_log_entry( $content, $entry ) { - $output .= '
    '; + $user_id = absint( $entry->ref_id ); + return $this->core->template_tags_user( $content, $user_id ); - // Title if set - if ($this->prefs['buddypress']['title'] != '' ) { - $output .= '

    ' . $this->prefs['buddypress']['title'] . '

    '; - } + } - // Table - $output .= ''; - $output .= sprintf('', __('Link', 'mycred'), $users_ref_link); + /** + * Add Referral Key + * @since 1.5.3 + * @version 1.0 + */ + public function add_key( $keys ) { - // Show Visitor referral count - if ($this->prefs['visit']['creds'] != 0 ) { - $output .= sprintf('', __('Visitors Referred', 'mycred'), mycred_count_ref_instances('visitor_referral', $user_id, $this->mycred_type)); - } + if ( ! isset( $_GET[ $this->ref_key ] ) || isset( $_COOKIE[ 'mycred_ref' . $this->mycred_type ] ) ) return $keys; - // Show Signup referral count - if ($this->prefs['signup']['creds'] != 0 ) { - $output .= sprintf('', __('Signups Referred', 'mycred'), mycred_count_ref_instances('signup_referral', $user_id, $this->mycred_type)); - } + if ( ! in_array( $this->ref_key, $keys ) ) + $keys[] = $this->ref_key; - $output .= '
    %s%s
    '; + return $keys; - // Description if set - if (! empty($this->prefs['buddypress']['desc']) ) { - $output .= wpautop(wptexturize($this->prefs['buddypress']['desc'])); - } + } - $output .= '
    '; - } + /** + * Shortcode: Affiliate Link + * Appends the current users affiliate link to either a given + * URL or if not set, the current URL. If user is not logged in, + * the set URL is returned. If this is not set, the shortcode + * will return an empty string. + * @since 1.4 + * @version 1.1 + */ + public function shortcode_affiliate_link( $content, $atts ) { - $output = do_shortcode($output); - echo apply_filters('mycred_affiliate_bp_profile', $output, $user_id, $users_ref_link, $this); + extract( shortcode_atts( array( + 'url' => 0, + 'user_id' => '', + 'post_id' => '' + ), $atts ) ); - } + if ( ! is_user_logged_in() && $user_id == '' ) + return $url; - /** - * Visits - * - * @since 1.4 - * @version 1.3.1 - */ - public function site_visits() - { + if ( $user_id == '' ) + $user_id = get_current_user_id(); - // Required - if (! isset($_GET[ $this->ref_key ]) || empty($_GET[ $this->ref_key ]) || isset($_COOKIE[ 'mycred_ref' . $this->mycred_type ]) ) { return; - } + if ( $post_id != '' ) + $url = mycred_get_permalink( $post_id ); - // Attempt to get the user id based on the referral id - $user_id = $this->get_user_id_from_ref_id($_GET[ $this->ref_key ]); - if ($user_id !== null && ! is_user_logged_in() ) { + return $this->get_ref_link( $user_id, $url ); - // Attempt to get the users IP - $IP = apply_filters('mycred_affiliate_IP', sanitize_text_field($_SERVER['REMOTE_ADDR']), 'visit', $this); - if ($IP != '' && $IP != '0.0.0.0' ) { + } - // If referral counts - if ($this->ref_counts($user_id, $IP) ) { + /** + * Shortcode: Affiliate ID + * Returns the current users affiliate ID. Returns an empty + * string if the user is not logged in. + * @since 1.4 + * @version 1.1 + */ + public function shortcode_affiliate_id( $content, $atts ) { - if ($this->core->has_entry('visitor_referral', time(), $user_id, $IP, $this->mycred_type) ) { return; - } + extract( shortcode_atts( array( + 'user_id' => '' + ), $atts ) ); - // Award - $this->core->add_creds( - 'visitor_referral', - $user_id, - $this->prefs['visit']['creds'], - $this->prefs['visit']['log'], - time(), - $IP, - $this->mycred_type - ); + if ( ! is_user_logged_in() && $user_id == '' ) + $ref_id = ''; - + else { - do_action('mycred_visitor_referral', $user_id, $IP, $this); + if ( $user_id == '' ) + $user_id = get_current_user_id(); - } + $ref_id = $this->get_ref_id( $user_id ); - // Set cookies - if (! headers_sent() ) { + } - setcookie('mycred_ref' . $this->mycred_type, $_GET[ $this->ref_key ], apply_filters('mycred_affiliate_cookie', ( time()+3600*24 ), false, $this), COOKIEPATH, COOKIE_DOMAIN); + return apply_filters( 'mycred_affiliate_id', $ref_id, $atts, $this ); - if (get_option('users_can_register') && $this->prefs['signup']['creds'] > 0 ) { - setcookie('signup_ref' . $this->mycred_type, $_GET[ $this->ref_key ], apply_filters('mycred_affiliate_cookie', ( time()+3600*24 ), true, $this), COOKIEPATH, COOKIE_DOMAIN); - } + } - } + /** + * BuddyPress Profile + * @since 1.4 + * @version 1.1 + */ + public function buddypress_profile() { - } + // Prep + $output = ''; + $user_id = bp_displayed_user_id(); - } + // Check for exclusion + if ( $this->core->exclude_user( $user_id ) ) return; + + $users_ref_link = ''; - } + // If it is my profile or other members allowed to view eachothers profiles or if we are admins + if ( bp_is_my_profile() || mycred_is_admin() ) { - /** - * Signups - * - * @since 1.4 - * @version 1.2.1 - */ - public function site_signup( $new_user_id ) - { + $users_ref_link = $this->get_ref_link( $user_id, home_url( '/' ) ); - // Requirement - $ref = false; - $key = ''; - if (isset($_COOKIE[ 'signup_ref' . $this->mycred_type ]) ) { - $ref = $_COOKIE[ 'signup_ref' . $this->mycred_type ]; - $key = 'signup_ref' . $this->mycred_type; - } - elseif (isset($_COOKIE[ 'mycred_ref' . $this->mycred_type ]) ) { - $ref = $_COOKIE[ 'mycred_ref' . $this->mycred_type ]; - $key = 'mycred_ref' . $this->mycred_type; - } + $output .= '
    '; - if ($ref === false ) { return; - } + // Title if set + if ( $this->prefs['buddypress']['title'] != '' ) + $output .= '

    ' . $this->prefs['buddypress']['title'] . '

    '; - // Attempt to get the user id based on the referrer - $user_id = $this->get_user_id_from_ref_id($ref); - if ($user_id === null ) { + // Table + $output .= ''; + $output .= sprintf( '', __( 'Link', 'mycred' ), $users_ref_link ); - if (! headers_sent() ) { - setcookie($key, $ref, time()-3600, COOKIEPATH, COOKIE_DOMAIN); - } + // Show Visitor referral count + if ( $this->prefs['visit']['creds'] != 0 ) + $output .= sprintf( '', __( 'Visitors Referred', 'mycred' ), mycred_count_ref_instances( 'visitor_referral', $user_id, $this->mycred_type ) ); - return; + // Show Signup referral count + if ( $this->prefs['signup']['creds'] != 0 ) + $output .= sprintf( '', __( 'Signups Referred', 'mycred' ), mycred_count_ref_instances( 'signup_referral', $user_id, $this->mycred_type ) ); - } + $output .= '
    %s%s
    '; - // Delete Cookie - if (! headers_sent() ) { - setcookie($key, $ref, time()-3600, COOKIEPATH, COOKIE_DOMAIN); - } + // Description if set + if ( ! empty( $this->prefs['buddypress']['desc'] ) ) + $output .= wpautop( wptexturize( $this->prefs['buddypress']['desc'] ) ); - + $output .= '
    '; + } - // Attempt to get the users IP - $IP = apply_filters('mycred_affiliate_IP', sanitize_text_field($_SERVER['REMOTE_ADDR']), 'signup', $this); + $output = do_shortcode( $output ); + echo apply_filters( 'mycred_affiliate_bp_profile', $output, $user_id, $users_ref_link, $this ); - if ($this->core->has_entry('signup_referral', $new_user_id, $user_id, $IP, $this->mycred_type) ) { return; - } + } + /** + * Visits + * @since 1.4 + * @version 1.3.1 + */ + public function site_visits() { - if ($IP != '' && $IP != '0.0.0.0' ) { + // Required + if ( ! isset( $_GET[ $this->ref_key ] ) || empty( $_GET[ $this->ref_key ] ) || isset( $_COOKIE[ 'mycred_ref' . $this->mycred_type ] ) ) return; - if ($this->core->has_entry('signup_referral', $new_user_id, $user_id, $IP, $this->mycred_type) ) { return; - } + // Attempt to get the user id based on the referral id + $user_id = $this->get_user_id_from_ref_id( $_GET[ $this->ref_key ] ); + if ( $user_id !== NULL && ! is_user_logged_in() ) { - if ($this->ref_counts($user_id, $IP, 'signup') ) { + // Attempt to get the users IP + $IP = apply_filters( 'mycred_affiliate_IP', $_SERVER['REMOTE_ADDR'], 'visit', $this ); + if ( $IP != '' && $IP != '0.0.0.0' ) { - // Award when users account gets activated - if (function_exists('buddypress') ) { + // If referral counts + if ( $this->ref_counts( $user_id, $IP ) ) { - mycred_add_user_meta($new_user_id, 'referred_by_', $this->mycred_type, $user_id, true); - mycred_add_user_meta($new_user_id, 'referred_by_IP_', $this->mycred_type, $IP, true); - mycred_add_user_meta($new_user_id, 'referred_by_type_', $this->mycred_type, $this->mycred_type, true); + if ( $this->core->has_entry( 'visitor_referral', time(), $user_id, $IP, $this->mycred_type ) ) return; - } - // Award now - else { + // Award + $this->core->add_creds( + 'visitor_referral', + $user_id, + $this->prefs['visit']['creds'], + $this->prefs['visit']['log'], + time(), + $IP, + $this->mycred_type + ); - $execute = apply_filters('mycred_signup_referral_execute_woo', true, $user_id, $IP, $new_user_id, $this); + - if ($this->core->has_entry('signup_referral', $new_user_id, $user_id, $IP, $this->mycred_type) ) { return; - } + do_action( 'mycred_visitor_referral', $user_id, $IP, $this ); - if ($execute === true ) { - $this->core->add_creds( - 'signup_referral', - $user_id, - $this->prefs['signup']['creds'], - $this->prefs['signup']['log'], - $new_user_id, - $IP, - $this->mycred_type - ); + } - } + // Set cookies + if ( ! headers_sent() ) { - do_action('mycred_signup_referral', $user_id, $IP, $new_user_id, $this); + setcookie( 'mycred_ref' . $this->mycred_type, $_GET[ $this->ref_key ], apply_filters( 'mycred_affiliate_cookie', ( time()+3600*24 ), false, $this ), COOKIEPATH, COOKIE_DOMAIN ); - } + if ( get_option( 'users_can_register' ) && $this->prefs['signup']['creds'] > 0 ) + setcookie( 'signup_ref' . $this->mycred_type, $_GET[ $this->ref_key ], apply_filters( 'mycred_affiliate_cookie', ( time()+3600*24 ), true, $this ), COOKIEPATH, COOKIE_DOMAIN ); - } + } - } + } - } + } - /** - * Verified Signup - * If signups need to be verified, award points now. - * - * @since 1.5 - * @version 1.0 - */ - public function verified_signup( $user_id ) - { + } - // Check if there is a referral - $referred_by = mycred_get_user_meta($user_id, 'referred_by_', $this->mycred_type, true); - $referred_by_IP = mycred_get_user_meta($user_id, 'referred_by_IP_', $this->mycred_type, true); - $referred_type = mycred_get_user_meta($user_id, 'referred_by_type_', $this->mycred_type, true); + /** + * Signups + * @since 1.4 + * @version 1.2.1 + */ + public function site_signup( $new_user_id ) { - if ($referred_by == '' || $referred_by_IP == '' || $this->mycred_type != $referred_type ) { return; - } + // Requirement + $ref = false; + $key = ''; + if ( isset( $_COOKIE[ 'signup_ref' . $this->mycred_type ] ) ) { + $ref = $_COOKIE[ 'signup_ref' . $this->mycred_type ]; + $key = 'signup_ref' . $this->mycred_type; + } + elseif ( isset( $_COOKIE[ 'mycred_ref' . $this->mycred_type ] ) ) { + $ref = $_COOKIE[ 'mycred_ref' . $this->mycred_type ]; + $key = 'mycred_ref' . $this->mycred_type; + } - if ($this->core->has_entry('signup_referral', $user_id, $referred_by, $referred_by_IP, $this->mycred_type) ) { return; - } + if ( $ref === false ) return; - // Award - $this->core->add_creds( - 'signup_referral', - $referred_by, - $this->prefs['signup']['creds'], - $this->prefs['signup']['log'], - $user_id, - $referred_by_IP, - $this->mycred_type - ); + // Attempt to get the user id based on the referrer + $user_id = $this->get_user_id_from_ref_id( $ref ); + if ( $user_id === NULL ) { + + if ( ! headers_sent() ) + setcookie( $key, $ref, time()-3600, COOKIEPATH, COOKIE_DOMAIN ); + + return; + + } + + // Delete Cookie + if ( ! headers_sent() ) + setcookie( $key, $ref, time()-3600, COOKIEPATH, COOKIE_DOMAIN ); + + + + // Attempt to get the users IP + $IP = apply_filters( 'mycred_affiliate_IP', $_SERVER['REMOTE_ADDR'], 'signup', $this ); + + if ( $this->core->has_entry( 'signup_referral', $new_user_id, $user_id, $IP, $this->mycred_type ) ) return; + + + if ( $IP != '' && $IP != '0.0.0.0' ) { + + if ( $this->core->has_entry( 'signup_referral', $new_user_id, $user_id, $IP, $this->mycred_type ) ) return; + + if ( $this->ref_counts( $user_id, $IP, 'signup' ) ) { + + // Award when users account gets activated + if ( function_exists( 'buddypress' ) ) { + + mycred_add_user_meta( $new_user_id, 'referred_by_', $this->mycred_type, $user_id, true ); + mycred_add_user_meta( $new_user_id, 'referred_by_IP_', $this->mycred_type, $IP, true ); + mycred_add_user_meta( $new_user_id, 'referred_by_type_', $this->mycred_type, $this->mycred_type, true ); + + } + // Award now + else { + + $execute = apply_filters( 'mycred_signup_referral_execute_woo', true, $user_id, $IP, $new_user_id , $this ); + + if ( $this->core->has_entry( 'signup_referral', $new_user_id, $user_id, $IP, $this->mycred_type ) ) return; + + if ( $execute === true ) { + $this->core->add_creds( + 'signup_referral', + $user_id, + $this->prefs['signup']['creds'], + $this->prefs['signup']['log'], + $new_user_id, + $IP, + $this->mycred_type + ); + + } - do_action('mycred_signup_referral', $referred_by, $referred_by_IP, $user_id, $this); + do_action( 'mycred_signup_referral', $user_id, $IP, $new_user_id, $this ); - // Clean up - mycred_delete_user_meta($user_id, 'referred_by_', $this->mycred_type); - mycred_delete_user_meta($user_id, 'referred_by_IP_', $this->mycred_type); - mycred_delete_user_meta($user_id, 'referred_by_type_', $this->mycred_type); + } - } + } - /** - * Get Ref Link - * Returns a given users referral id with optional url appended. - * - * @since 1.4 - * @version 1.0.1 - */ - public function get_ref_link( $user_id = '', $url = '' ) - { + } - // User ID is required - if (empty($user_id) || $user_id === 0 ) { return ''; - } + } - // Get Ref ID - $ref_id = $this->get_ref_id($user_id); - if ($ref_id === null ) { return ''; - } + /** + * Verified Signup + * If signups need to be verified, award points now. + * @since 1.5 + * @version 1.0 + */ + public function verified_signup( $user_id ) { - // Appent to specific URL - if (! empty($url) ) { - $link = add_query_arg(array( $this->ref_key => $ref_id ), $url); - } + // Check if there is a referral + $referred_by = mycred_get_user_meta( $user_id, 'referred_by_', $this->mycred_type, true ); + $referred_by_IP = mycred_get_user_meta( $user_id, 'referred_by_IP_', $this->mycred_type, true ); + $referred_type = mycred_get_user_meta( $user_id, 'referred_by_type_', $this->mycred_type, true ); - // Append to current URL - else { - $link = add_query_arg(array( $this->ref_key => $ref_id )); - } + if ( $referred_by == '' || $referred_by_IP == '' || $this->mycred_type != $referred_type ) return; - return apply_filters('mycred_affiliate_get_ref_link', esc_url($link), $user_id, $url, $this); + if ( $this->core->has_entry( 'signup_referral', $user_id, $referred_by, $referred_by_IP, $this->mycred_type ) ) return; - } + // Award + $this->core->add_creds( + 'signup_referral', + $referred_by, + $this->prefs['signup']['creds'], + $this->prefs['signup']['log'], + $user_id, + $referred_by_IP, + $this->mycred_type + ); - /** - * Get Ref ID - * Returns a given users referral ID. - * - * @since 1.4 - * @since 2.3 Filter `mycred_affiliate_user_id` added - * @version 1.1 - */ - public function get_ref_id( $user_id ) - { + do_action( 'mycred_signup_referral', $referred_by, $referred_by_IP, $user_id, $this ); - $ref_id = null; + // Clean up + mycred_delete_user_meta( $user_id, 'referred_by_', $this->mycred_type ); + mycred_delete_user_meta( $user_id, 'referred_by_IP_', $this->mycred_type ); + mycred_delete_user_meta( $user_id, 'referred_by_type_', $this->mycred_type ); - // Link format - switch ( $this->prefs['setup']['links'] ) { + } - case 'username' : + /** + * Get Ref Link + * Returns a given users referral id with optional url appended. + * @since 1.4 + * @version 1.0.1 + */ + public function get_ref_link( $user_id = '', $url = '' ) { - $user = get_userdata($user_id); - if (isset($user->user_login) ) { $ref_id = urlencode($user->user_login); - } + // User ID is required + if ( empty( $user_id ) || $user_id === 0 ) return ''; - break; + // Get Ref ID + $ref_id = $this->get_ref_id( $user_id ); + if ( $ref_id === NULL ) return ''; - case 'numeric' : + // Appent to specific URL + if ( ! empty( $url ) ) + $link = add_query_arg( array( $this->ref_key => $ref_id ), $url ); - $id = mycred_get_user_meta($user_id, 'mycred_affiliate_link', '', true); - if (! is_numeric($id) ) { + // Append to current URL + else + $link = add_query_arg( array( $this->ref_key => $ref_id ) ); - $counter = absint(get_option('mycred_affiliate_counter', 0)); - $number = $counter+1; + return apply_filters( 'mycred_affiliate_get_ref_link', esc_url( $link ), $user_id, $url, $this ); - mycred_update_option('mycred_affiliate_counter', $number); + } - $number = apply_filters('mycred_affiliate_user_id', $number); + /** + * Get Ref ID + * Returns a given users referral ID. + * @since 1.4 + * @since 2.3 Filter `mycred_affiliate_user_id` added + * @version 1.1 + */ + public function get_ref_id( $user_id ) { - mycred_update_user_meta($user_id, 'mycred_affiliate_link', '', $number); + $ref_id = NULL; - $ref_id = $number; + // Link format + switch ( $this->prefs['setup']['links'] ) { - } - else { + case 'username' : - $id = apply_filters('mycred_affiliate_user_id', $id); + $user = get_userdata( $user_id ); + if ( isset( $user->user_login ) ) $ref_id = urlencode( $user->user_login ); - $ref_id = $id; - - } + break; - break; + case 'numeric' : - } + $id = mycred_get_user_meta( $user_id, 'mycred_affiliate_link', '', true ); + if ( ! is_numeric( $id ) ) { - return apply_filters('mycred_affiliate_get_ref_id', $ref_id, $user_id, $this); + $counter = absint( get_option( 'mycred_affiliate_counter', 0 ) ); + $number = $counter+1; - } + mycred_update_option( 'mycred_affiliate_counter', $number ); - /** - * Get User ID from Ref ID - * - * @since 1.4 - * @since 2.3 @filter added `mycred_affiliate_by_user_id` - * @version 1.0.1 - */ - public function get_user_id_from_ref_id( $string = '' ) - { + $number = apply_filters( 'mycred_affiliate_user_id', $number ); - if(apply_filters('mycred_affiliate_by_user_id', false) ) { - return $string; - } + mycred_update_user_meta( $user_id, 'mycred_affiliate_link', '', $number ); - global $wpdb; + $ref_id = $number; - $user_id = null; + } + else { - switch ( $this->prefs['setup']['links'] ) { + $id = apply_filters( 'mycred_affiliate_user_id', $id ); - case 'username' : + $ref_id = $id; + + } - $ref_id = sanitize_text_field(urldecode($string)); - $user = get_user_by('login', $ref_id); - if (isset($user->ID) ) { - $user_id = $user->ID; - } + break; - break; + } - case 'numeric' : + return apply_filters( 'mycred_affiliate_get_ref_id', $ref_id, $user_id, $this ); - $referral_id_key = mycred_get_meta_key('mycred_affiliate_link'); - $ref_id = absint($string); - $user_id = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value = %d;", $referral_id_key, $ref_id)); + } - break; + /** + * Get User ID from Ref ID + * @since 1.4 + * @since 2.3 @filter added `mycred_affiliate_by_user_id` + * @version 1.0.1 + */ + public function get_user_id_from_ref_id( $string = '' ) { - } + if( apply_filters( 'mycred_affiliate_by_user_id', false ) ) + return $string; - // Make sure if the referring user is excluded we do not do anything - if ($user_id !== null && $this->core->exclude_user($user_id) ) { - $user_id = null; - } + global $wpdb; - - return apply_filters('mycred_affiliate_get_user_id', $user_id, $string, $this); + $user_id = NULL; - } + switch ( $this->prefs['setup']['links'] ) { - /** - * Ref Counts - * Checks to see if this referral counts. - * - * @since 1.4 - * @version 1.2.1 - */ - public function ref_counts( $user_id, $IP = '', $instance = 'visit' ) - { + case 'username' : - global $wpdb, $mycred_log_table; + $ref_id = sanitize_text_field( urldecode( $string ) ); + $user = get_user_by( 'login', $ref_id ); + if ( isset( $user->ID ) ) + $user_id = $user->ID; - // Prep - $reply = true; + break; - if ($instance == 'signup' ) { - $ref = 'signup_referral'; - } else { - $ref = 'visitor_referral'; - } + case 'numeric' : - // We start by enforcing the global IP rule - if ($this->prefs['setup']['IP'] > 0 ) { + $referral_id_key = mycred_get_meta_key( 'mycred_affiliate_link' ); + $ref_id = absint( $string ); + $user_id = $wpdb->get_var( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value = %d;", $referral_id_key, $ref_id ) ); - // Count the occurence of this IP - $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$mycred_log_table} WHERE ref = %s AND data = %s AND ctype = %s;", $ref, $IP, $this->mycred_type)); + break; - if ($count !== null && $count >= $this->prefs['setup']['IP'] ) { - $reply = false; - } + } - } + // Make sure if the referring user is excluded we do not do anything + if ( $user_id !== NULL && $this->core->exclude_user( $user_id ) ) + $user_id = NULL; - // If reply is still true we check limit - if ($reply !== false && $this->over_hook_limit($instance, $ref, $user_id) ) { - $reply = false; - } + + return apply_filters( 'mycred_affiliate_get_user_id', $user_id, $string, $this ); - return apply_filters('mycred_affiliate_ref_counts', $reply, $this); + } - } + /** + * Ref Counts + * Checks to see if this referral counts. + * @since 1.4 + * @version 1.2.1 + */ + public function ref_counts( $user_id, $IP = '', $instance = 'visit' ) { - /** - * Preference for Affiliate Hook - * - * @since 1.4 - * @version 1.1 - */ - public function preferences() - { + global $wpdb, $mycred_log_table; - $prefs = $this->prefs; + // Prep + $reply = true; - ?> + if ( $instance == 'signup' ) + $ref = 'signup_referral'; + else + $ref = 'visitor_referral'; + + // We start by enforcing the global IP rule + if ( $this->prefs['setup']['IP'] > 0 ) { + + // Count the occurence of this IP + $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$mycred_log_table} WHERE ref = %s AND data = %s AND ctype = %s;", $ref, $IP, $this->mycred_type ) ); + + if ( $count !== NULL && $count >= $this->prefs['setup']['IP'] ) + $reply = false; + + } + + // If reply is still true we check limit + if ( $reply !== false && $this->over_hook_limit( $instance, $ref, $user_id ) ) + $reply = false; + + return apply_filters( 'mycred_affiliate_ref_counts', $reply, $this ); + + } + + /** + * Preference for Affiliate Hook + * @since 1.4 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'visit', 'limit' )), $this->field_id(array( 'visit', 'limit' )), $prefs['visit']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'visit', 'limit' ) ), $this->field_id( array( 'visit', 'limit' ) ), $prefs['visit']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    -

    - - - -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'signup', 'limit' )), $this->field_id(array( 'signup', 'limit' )), $prefs['signup']['limit']); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general' ), '%user_name%'); ?> -
    -
    -
    - - - - - -
    -
    -

    Registrations are disabled.

    - - - -
    +

    + + + +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'signup', 'limit' ) ), $this->field_id( array( 'signup', 'limit' ) ), $prefs['signup']['limit'] ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general' ), '%user_name%' ); ?> +
    +
    + + + + + +
    +
    +

    Registrations are disabled.

    + + + +
    +
    - +
    -

    -
    -
    -
    - - ref_key => 1 ), home_url('/')))); ?> -
    -
    -
    -
    - - ref_key => 'john+doe' ), home_url('/')))); ?> -
    -
    -
    -
    -
    -
    - - - core->template_tags_general(__('The number of times each IP address grants %_plural%. Use zero for unlimited.', 'mycred')); ?> -
    -
    - -
    +

    +
    +
    +
    + + ref_key => 1 ), home_url( '/' ) ) ) ); ?> +
    +
    +
    +
    + + ref_key => 'john+doe' ), home_url( '/' ) ) ) ); ?> +
    +
    +
    +
    +
    +
    + + + core->template_tags_general( __( 'The number of times each IP address grants %_plural%. Use zero for unlimited.', 'mycred' ) ); ?> +
    +
    + +
    - +
    -

    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    -
    -
    - - -
    -
    -
    -
    -
    - - -
    -
    -
    -
    -
    -
    - - - -
    -
    -
    +

    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + + +
    +
    +
    +
    +
    +
    + + + +
    +
    +
    - - - - + + + + - - - + + 'registration', - 'defaults' => array( - 'creds' => 10, - 'log' => '%plural% for becoming a member' - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 0.1 - * @version 1.2.1 - */ - public function run() - { - - add_action('user_register', array( $this, 'registration' )); - - } - - /** - * Registration Hook - * - * @since 0.1 - * @version 1.1 - */ - public function registration( $user_id ) - { - - // Make sure user is not excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - $data = array( 'ref_type' => 'user' ); - - // Make sure this is unique - if ($this->core->has_entry('registration', $user_id, $user_id, $data, $this->mycred_type) ) { return; - } - - // Execute - $this->core->add_creds( - 'registration', - $user_id, - $this->prefs['creds'], - $this->prefs['log'], - $user_id, - $data, - $this->mycred_type - ); - - } - - /** - * Preference for Registration Hook - * - * @since 0.1 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +if ( ! class_exists( 'myCRED_Hook_Registration' ) ) : + class myCRED_Hook_Registration extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'registration', + 'defaults' => array( + 'creds' => 10, + 'log' => '%plural% for becoming a member' + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 0.1 + * @version 1.2.1 + */ + public function run() { + + add_action( 'user_register', array( $this, 'registration' ) ); + + } + + /** + * Registration Hook + * @since 0.1 + * @version 1.1 + */ + public function registration( $user_id ) { + + // Make sure user is not excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + $data = array( 'ref_type' => 'user' ); + + // Make sure this is unique + if ( $this->core->has_entry( 'registration', $user_id, $user_id, $data, $this->mycred_type ) ) return; + + // Execute + $this->core->add_creds( + 'registration', + $user_id, + $this->prefs['creds'], + $this->prefs['log'], + $user_id, + $data, + $this->mycred_type + ); + + } + + /** + * Preference for Registration Hook + * @since 0.1 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'user' )); ?> -
    -
    -
    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'user' ) ); ?> +
    +
    +
    - 'site_visit', - 'defaults' => array( - 'creds' => 1, - 'log' => '%plural% for site visit' - ) - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.5 - * @version 1.0.2 - */ - public function run() - { - - // Make sure user is logged in. Also to prevent unneccery db queries we - // check to make sure the user does not have the cookie. - if (is_user_logged_in() && ! isset($_COOKIE['mycred_site_visit']) ) { - add_action('init', array( $this, 'site_visit' )); - } - - } - - /** - * Visit Hook - * - * @since 1.5 - * @version 1.1.3 - */ - public function site_visit() - { - - if (defined('DOING_AJAX') && DOING_AJAX ) { return; - } - - // Current User ID - $user_id = get_current_user_id(); - $now = current_time('timestamp'); - - // Set cookie to prevent db queries again today. - $lifespan = (int) ( 24*3600 ) - ( date('H', $now) * 3600 + date('i', $now) * 60 + date('s', $now) ); - if (! headers_sent() ) { setcookie('mycred_site_visit', 1, time() +$lifespan, COOKIEPATH, COOKIE_DOMAIN, true); - } - - // Make sure user is not excluded - if ($this->core->exclude_user($user_id) ) { return; - } - - // Store todays date as an integer - $today = (int) apply_filters('mycred_site_visit_id', date('Ymd', $now)); - $data = ''; - - // Make sure this is unique - if ($this->core->has_entry('site_visit', $today, $user_id, $data, $this->mycred_type) ) { return; - } - - // Execute - $this->core->add_creds( - 'site_visit', - $user_id, - $this->prefs['creds'], - $this->prefs['log'], - $today, - $data, - $this->mycred_type - ); - - } - - /** - * Preference for Site Visit Hook - * - * @since 1.5 - * @version 1.1 - */ - public function preferences() - { - - $prefs = $this->prefs; - - ?> +if ( ! class_exists( 'myCRED_Hook_Site_Visits' ) ) : + class myCRED_Hook_Site_Visits extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + parent::__construct( array( + 'id' => 'site_visit', + 'defaults' => array( + 'creds' => 1, + 'log' => '%plural% for site visit' + ) + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.5 + * @version 1.0.2 + */ + public function run() { + + // Make sure user is logged in. Also to prevent unneccery db queries we + // check to make sure the user does not have the cookie. + if ( is_user_logged_in() && ! isset( $_COOKIE['mycred_site_visit'] ) ) + add_action( 'init', array( $this, 'site_visit' ) ); + + } + + /** + * Visit Hook + * @since 1.5 + * @version 1.1.3 + */ + public function site_visit() { + + if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) return; + + // Current User ID + $user_id = get_current_user_id(); + $now = current_time( 'timestamp' ); + + // Set cookie to prevent db queries again today. + $lifespan = (int) ( 24*3600 ) - ( date( 'H', $now ) * 3600 + date( 'i', $now ) * 60 + date( 's', $now ) ); + if ( ! headers_sent() ) setcookie( 'mycred_site_visit', 1, time() +$lifespan, COOKIEPATH, COOKIE_DOMAIN, true ); + + // Make sure user is not excluded + if ( $this->core->exclude_user( $user_id ) ) return; + + // Store todays date as an integer + $today = (int) apply_filters( 'mycred_site_visit_id', date( 'Ymd', $now ) ); + $data = ''; + + // Make sure this is unique + if ( $this->core->has_entry( 'site_visit', $today, $user_id, $data, $this->mycred_type ) ) return; + + // Execute + $this->core->add_creds( + 'site_visit', + $user_id, + $this->prefs['creds'], + $this->prefs['log'], + $today, + $data, + $this->mycred_type + ); + + } + + /** + * Preference for Site Visit Hook + * @since 1.5 + * @version 1.1 + */ + public function preferences() { + + $prefs = $this->prefs; + +?>
    -
    -
    -
    - - -
    -
    -
    -
    - - - available_template_tags(array( 'general' )); ?> -
    -
    -
    +
    +
    +
    + + +
    +
    +
    +
    + + + available_template_tags( array( 'general' ) ); ?> +
    +
    +
    - array( - 'creds' => 1, - 'log' => '%plural% for viewing a post', - 'acreds' => 1, - 'limit' => '0/x', - 'alog' => '%plural% for view of your post', - 'visitor' => 0, - 'alimit' => '0/x' - ), - 'page' => array( - 'creds' => 1, - 'log' => '%plural% for viewing a page', - 'acreds' => 1, - 'limit' => '0/x', - 'alog' => '%plural% for view of your page', - 'visitor' => 0, - 'alimit' => '0/x' - ) - ); - - if (isset($hook_prefs['view_contents']) ) { - $defaults = $hook_prefs['view_contents']; - } - - parent::__construct( - array( - 'id' => 'view_contents', - 'defaults' => $defaults - ), $hook_prefs, $type - ); - - } - - /** - * Run - * - * @since 1.5.1 - * @version 1.0.1 - */ - public function run() - { - - // First instance where we can safely use conditional template tags - add_action('template_redirect', array( $this, 'content_loading' ), 999); - - add_filter('mycred_hook_limit_query', array( $this, 'view_content_query' ), 10, 7); - - } - - /** - * Content Loaded - * - * @since 1.5.1 - * @version 1.2 - */ - public function content_loading() - { - - // Only applicable on single post type view by logged in users - if (! is_singular() || ! is_user_logged_in() ) { return; - } - - global $post; - - $user_id = get_current_user_id(); - $pay_author = true; - $data = array( 'ref_type' => 'post' ); - - // Post author can not generate points for themselves - if ($post->post_author == $user_id ) { return; - } - - // Make sure this post type award points. Any amount but zero. - if (isset($this->prefs[ $post->post_type ]['creds']) && $this->prefs[ $post->post_type ]['creds'] != 0 && apply_filters('mycred_view_content', true, $this) === true ) { - - // Make sure we are not excluded - if (! $this->core->exclude_user($user_id) ) { - - // Enforce limit and make sure users only get points once per unique post - if (! $this->over_hook_limit($post->post_type, 'view_content', $user_id) && ! $this->core->has_entry('view_content', $post->ID, $user_id, $data, $this->mycred_type) ) { - - $this->core->add_creds( - 'view_content', - $user_id, - $this->prefs[ $post->post_type ]['creds'], - $this->prefs[ $post->post_type ]['log'], - $post->ID, - $data, - $this->mycred_type - ); - - } - - // If the visitor does not get points, neither does the author - else { $pay_author = false; - } - - } - - } - - // Make sure this post type award points to the author. Any amount but zero. - if (isset($this->prefs[ $post->post_type ]['acreds']) && $this->prefs[ $post->post_type ]['acreds'] != 0 && apply_filters('mycred_view_content_author', $pay_author, $this) === true ) { - - // No payout for viewing our own content - if (! $this->core->exclude_user($post->post_author) ) { - - $data['cui'] = $user_id; - - // Limit - if (! $this->over_hook_limit($post->post_type, 'view_content_author', $post->post_author) ) { - $this->core->add_creds( - 'view_content_author', - $post->post_author, - $this->prefs[ $post->post_type ]['acreds'], - $this->prefs[ $post->post_type ]['alog'], - $post->ID, - $data, - $this->mycred_type - ); - } +if ( ! class_exists( 'myCRED_Hook_View_Contents' ) ) : + class myCRED_Hook_View_Contents extends myCRED_Hook { + + /** + * Construct + */ + function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) { + + $defaults = array( + 'post' => array( + 'creds' => 1, + 'log' => '%plural% for viewing a post', + 'acreds' => 1, + 'limit' => '0/x', + 'alog' => '%plural% for view of your post', + 'visitor' => 0, + 'alimit' => '0/x' + ), + 'page' => array( + 'creds' => 1, + 'log' => '%plural% for viewing a page', + 'acreds' => 1, + 'limit' => '0/x', + 'alog' => '%plural% for view of your page', + 'visitor' => 0, + 'alimit' => '0/x' + ) + ); + + if ( isset( $hook_prefs['view_contents'] ) ) + $defaults = $hook_prefs['view_contents']; + + parent::__construct( array( + 'id' => 'view_contents', + 'defaults' => $defaults + ), $hook_prefs, $type ); + + } + + /** + * Run + * @since 1.5.1 + * @version 1.0.1 + */ + public function run() { + + // First instance where we can safely use conditional template tags + add_action( 'template_redirect', array( $this, 'content_loading' ), 999 ); + + add_filter( 'mycred_hook_limit_query', array( $this, 'view_content_query' ), 10, 7 ); + + } + + /** + * Content Loaded + * @since 1.5.1 + * @version 1.2 + */ + public function content_loading() { + + // Only applicable on single post type view by logged in users + if ( ! is_singular() || ! is_user_logged_in() ) return; + + global $post; + + $user_id = get_current_user_id(); + $pay_author = true; + $data = array( 'ref_type' => 'post' ); + + // Post author can not generate points for themselves + if ( $post->post_author == $user_id ) return; + + // Make sure this post type award points. Any amount but zero. + if ( isset( $this->prefs[ $post->post_type ]['creds'] ) && $this->prefs[ $post->post_type ]['creds'] != 0 && apply_filters( 'mycred_view_content', true, $this ) === true ) { + + // Make sure we are not excluded + if ( ! $this->core->exclude_user( $user_id ) ) { + + // Enforce limit and make sure users only get points once per unique post + if ( ! $this->over_hook_limit( $post->post_type, 'view_content', $user_id ) && ! $this->core->has_entry( 'view_content', $post->ID, $user_id, $data, $this->mycred_type ) ) { + + $this->core->add_creds( + 'view_content', + $user_id, + $this->prefs[ $post->post_type ]['creds'], + $this->prefs[ $post->post_type ]['log'], + $post->ID, + $data, + $this->mycred_type + ); + + } + + // If the visitor does not get points, neither does the author + else $pay_author = false; + + } + + } + + // Make sure this post type award points to the author. Any amount but zero. + if ( isset( $this->prefs[ $post->post_type ]['acreds'] ) && $this->prefs[ $post->post_type ]['acreds'] != 0 && apply_filters( 'mycred_view_content_author', $pay_author, $this ) === true ) { + + // No payout for viewing our own content + if ( ! $this->core->exclude_user( $post->post_author ) ) { + + $data['cui'] = $user_id; + + // Limit + if ( ! $this->over_hook_limit( $post->post_type, 'view_content_author', $post->post_author ) ) + $this->core->add_creds( + 'view_content_author', + $post->post_author, + $this->prefs[ $post->post_type ]['acreds'], + $this->prefs[ $post->post_type ]['alog'], + $post->ID, + $data, + $this->mycred_type + ); - } + } - } + } - } + } - /** - * Preference for read content hook - * - * @since 1.5.1 - * @version 1.1 - */ - public function preferences() - { + /** + * Preference for read content hook + * @since 1.5.1 + * @version 1.1 + */ + public function preferences() { - $prefs = $this->prefs; + $prefs = $this->prefs; - ?> +?>
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'post', 'limit' )), $this->field_id(array( 'post', 'limit' )), $prefs['post']['limit']); ?> -
    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'post', 'alimit' )), $this->field_id(array( 'post', 'alimit' )), $prefs['post']['alimit']); ?> -
    -
    -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'post', 'limit' ) ), $this->field_id( array( 'post', 'limit' ) ), $prefs['post']['limit'] ); ?> +
    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'post', 'alimit' ) ), $this->field_id( array( 'post', 'alimit' ) ), $prefs['post']['alimit'] ); ?> +
    +
    +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    -

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'page', 'limit' )), $this->field_id(array( 'page', 'limit' )), $prefs['page']['limit']); ?> -
    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( 'page', 'alimit' )), $this->field_id(array( 'page', 'alimit' )), $prefs['page']['alimit']); ?> -
    -
    -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'page', 'limit' ) ), $this->field_id( array( 'page', 'limit' ) ), $prefs['page']['limit'] ); ?> +
    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( 'page', 'alimit' ) ), $this->field_id( array( 'page', 'alimit' ) ), $prefs['page']['alimit'] ); ?> +
    +
    +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - true, - '_builtin' => false - ); - $post_types = get_post_types($post_type_args, 'objects', 'and'); - - foreach ( $post_types as $post_type ) { - - // Points to award/deduct - if (isset($prefs[ $post_type->name ]['creds']) ) { - $_creds = $prefs[ $post_type->name ]['creds']; - } else { - $_creds = 0; - } - - if (isset($prefs[ $post_type->name ]['limit']) ) { - $limit = $prefs[ $post_type->name ]['limit']; - } else { - $limit = '0/x'; - } - - // Log template - if (isset($prefs[ $post_type->name ]['log']) ) { - $_log = $prefs[ $post_type->name ]['log']; - } else { - $_log = '%plural% for viewing ' . $post_type->labels->name; - } - - // Points to award/deduct - if (isset($prefs[ $post_type->name ]['acreds']) ) { - $_acreds = $prefs[ $post_type->name ]['acreds']; - } else { - $_acreds = 0; - } - - if (isset($prefs[ $post_type->name ]['alimit']) ) { - $alimit = $prefs[ $post_type->name ]['alimit']; - } else { - $alimit = '0/x'; - } - - // Log template - if (isset($prefs[ $post_type->name ]['alog']) ) { - $_alog = $prefs[ $post_type->name ]['alog']; - } else { - $_alog = '%plural% for view of your ' . $post_type->labels->name; - } - - ?> + true, + '_builtin' => false + ); + $post_types = get_post_types( $post_type_args, 'objects', 'and' ); + + foreach ( $post_types as $post_type ) { + + // Points to award/deduct + if ( isset( $prefs[ $post_type->name ]['creds'] ) ) + $_creds = $prefs[ $post_type->name ]['creds']; + else + $_creds = 0; + + if ( isset( $prefs[ $post_type->name ]['limit'] ) ) + $limit = $prefs[ $post_type->name ]['limit']; + else + $limit = '0/x'; + + // Log template + if ( isset( $prefs[ $post_type->name ]['log'] ) ) + $_log = $prefs[ $post_type->name ]['log']; + else + $_log = '%plural% for viewing ' . $post_type->labels->name; + + // Points to award/deduct + if ( isset( $prefs[ $post_type->name ]['acreds'] ) ) + $_acreds = $prefs[ $post_type->name ]['acreds']; + else + $_acreds = 0; + + if ( isset( $prefs[ $post_type->name ]['alimit'] ) ) + $alimit = $prefs[ $post_type->name ]['alimit']; + else + $alimit = '0/x'; + + // Log template + if ( isset( $prefs[ $post_type->name ]['alog'] ) ) + $_alog = $prefs[ $post_type->name ]['alog']; + else + $_alog = '%plural% for view of your ' . $post_type->labels->name; + +?>
    -

    labels->name); ?>

    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( $post_type->name, 'limit' )), $this->field_id(array( $post_type->name, 'limit' )), $limit); ?> -
    -
    -
    -
    - - -
    -
    -
    -
    - - hook_limit_setting($this->field_name(array( $post_type->name, 'alimit' )), $this->field_id(array( $post_type->name, 'alimit' )), $alimit); ?> -
    -
    -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    -
    - - - available_template_tags(array( 'general', 'post' )); ?> -
    -
    -
    +

    labels->name ); ?>

    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( $post_type->name, 'limit' ) ), $this->field_id( array( $post_type->name, 'limit' ) ), $limit ); ?> +
    +
    +
    +
    + + +
    +
    +
    +
    + + hook_limit_setting( $this->field_name( array( $post_type->name, 'alimit' ) ), $this->field_id( array( $post_type->name, 'alimit' ) ), $alimit ); ?> +
    +
    +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    +
    + + + available_template_tags( array( 'general', 'post' ) ); ?> +
    +
    +
    - true, - '_builtin' => false - ); - $post_types = get_post_types($post_type_args, 'objects', 'and'); - - foreach ( $post_types as $post_type ) { - - if (isset($data[ $post_type->name ]['limit']) && isset($data[ $post_type->name ]['limit_by']) ) { - $limit = sanitize_text_field($data[ $post_type->name ]['limit']); - if ($limit == '' ) { $limit = 0; - } - $data[ $post_type->name ]['limit'] = $limit . '/' . $data[ $post_type->name ]['limit_by']; - unset($data[ $post_type->name ]['limit_by']); - } - - if (isset($data[ $post_type->name ]['alimit']) && isset($data[ $post_type->name ]['alimit_by']) ) { - $limit = sanitize_text_field($data[ $post_type->name ]['alimit']); - if ($limit == '' ) { $limit = 0; - } - $data[ $post_type->name ]['alimit'] = $limit . '/' . $data[ $post_type->name ]['alimit_by']; - unset($data[ $post_type->name ]['alimit_by']); - } - - } - - return $data; - - } - - public function view_content_query( $query, $instance, $reference, $user_id, $ref_id, $wheres ) - { - - global $wpdb, $mycred_log_table; - - if ('view_content' == $reference || 'view_content_author' == $reference ) { - $query = "SELECT COUNT(l.id) FROM {$mycred_log_table} as l JOIN {$wpdb->prefix}posts as p on l.ref_id = p.ID WHERE p.post_type = '{$instance}' AND {$wheres}"; - } - - return $query; - } - - } + true, + '_builtin' => false + ); + $post_types = get_post_types( $post_type_args, 'objects', 'and' ); + + foreach ( $post_types as $post_type ) { + + if ( isset( $data[ $post_type->name ]['limit'] ) && isset( $data[ $post_type->name ]['limit_by'] ) ) { + $limit = sanitize_text_field( $data[ $post_type->name ]['limit'] ); + if ( $limit == '' ) $limit = 0; + $data[ $post_type->name ]['limit'] = $limit . '/' . $data[ $post_type->name ]['limit_by']; + unset( $data[ $post_type->name ]['limit_by'] ); + } + + if ( isset( $data[ $post_type->name ]['alimit'] ) && isset( $data[ $post_type->name ]['alimit_by'] ) ) { + $limit = sanitize_text_field( $data[ $post_type->name ]['alimit'] ); + if ( $limit == '' ) $limit = 0; + $data[ $post_type->name ]['alimit'] = $limit . '/' . $data[ $post_type->name ]['alimit_by']; + unset( $data[ $post_type->name ]['alimit_by'] ); + } + + } + + return $data; + + } + + public function view_content_query( $query, $instance, $reference, $user_id, $ref_id, $wheres ) { + + global $wpdb, $mycred_log_table; + + if ( 'view_content' == $reference || 'view_content_author' == $reference ) { + $query = "SELECT COUNT(l.id) FROM {$mycred_log_table} as l JOIN {$wpdb->prefix}posts as p on l.ref_id = p.ID WHERE p.post_type = '{$instance}' AND {$wheres}"; + } + + return $query; + } + + } endif; diff --git a/includes/importers/index.php b/includes/importers/index.php index 1580272..4e6c07c 100644 --- a/includes/importers/index.php +++ b/includes/importers/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/includes/importers/mycred-balances.php b/includes/importers/mycred-balances.php index d765c2f..a190706 100644 --- a/includes/importers/mycred-balances.php +++ b/includes/importers/mycred-balances.php @@ -1,378 +1,347 @@ import_page = MYCRED_SLUG . '-import-balance'; - $this->delimiter = empty($_POST['delimiter']) ? ',' : (string) strip_tags(trim($_POST['delimiter'])); - $this->documentation = 'http://codex.mycred.me/chapter-ii/import-data/importing-balances/'; + $this->import_page = MYCRED_SLUG . '-import-balance'; + $this->delimiter = empty( $_POST['delimiter'] ) ? ',' : (string) strip_tags( trim( $_POST['delimiter'] ) ); + $this->documentation = 'http://codex.mycred.me/chapter-ii/import-data/importing-balances/'; - } + } - /** - * Registered callback function for the WordPress Importer - * Manages the three separate stages of the CSV import process - * - * @version 1.0 - */ - public function load() - { + /** + * Registered callback function for the WordPress Importer + * Manages the three separate stages of the CSV import process + * @version 1.0 + */ + public function load() { - $this->header(); + $this->header(); - $load = true; - $step = ( ! isset($_GET['step']) ) ? 0 : absint($_GET['step']); - if ($step > 1 ) { $step = 0; - } + $load = true; + $step = ( ! isset( $_GET['step'] ) ) ? 0 : absint( $_GET['step'] ); + if ( $step > 1 ) $step = 0; - switch ( $step ) { + switch ( $step ) { - case 1 : + case 1 : - check_admin_referer('import-upload'); + check_admin_referer( 'import-upload' ); - if ($this->handle_upload() ) { + if ( $this->handle_upload() ) { - if ($this->id ) { - $file = get_attached_file($this->id); - } else { - $file = ABSPATH . $this->file_url; - } + if ( $this->id ) + $file = get_attached_file( $this->id ); + else + $file = ABSPATH . $this->file_url; - if ($file !== false ) { + if ( $file !== false ) { - add_filter('http_request_timeout', array( $this, 'bump_request_timeout' )); + add_filter( 'http_request_timeout', array( $this, 'bump_request_timeout' ) ); - $load = $this->import($file); + $load = $this->import( $file ); - } + } - } + } - break; + break; - } + } - if ($load ) { - $this->greet(); - } + if ( $load ) + $this->greet(); - $this->footer(); + $this->footer(); - } + } - /** - * UTF-8 encode the data if `$enc` value isn't UTF-8. - * - * @version 1.0 - */ - public function format_data_from_csv( $data, $enc ) - { - return ( $enc == 'UTF-8' ) ? $data : utf8_encode($data); - } + /** + * UTF-8 encode the data if `$enc` value isn't UTF-8. + * @version 1.0 + */ + public function format_data_from_csv( $data, $enc ) { + return ( $enc == 'UTF-8' ) ? $data : utf8_encode( $data ); + } - /** - * Handles the CSV upload and initial parsing of the file to prepare for - * displaying author import options - * - * @return bool False if error uploading or invalid file, true otherwise - * @version 1.1 - */ - public function handle_upload() - { + /** + * Handles the CSV upload and initial parsing of the file to prepare for + * displaying author import options + * @return bool False if error uploading or invalid file, true otherwise + * @version 1.1 + */ + public function handle_upload() { - if (empty($_POST['file_url']) ) { + if ( empty( $_POST['file_url'] ) ) { - $file = wp_import_handle_upload(); + $file = wp_import_handle_upload(); - if (isset($file['error']) ) { + if ( isset( $file['error'] ) ) { - echo '

    ' . esc_html($file['error']) . '

    '; - return false; + echo '

    ' . esc_html( $file['error'] ) . '

    '; + return false; - } + } - $this->id = (int) $file['id']; + $this->id = (int) $file['id']; - } else { + } else { - if (file_exists(ABSPATH . $_POST['file_url']) ) { + if ( file_exists( ABSPATH . $_POST['file_url'] ) ) { - $this->file_url = esc_attr($_POST['file_url']); + $this->file_url = esc_attr( $_POST['file_url'] ); - } else { + } else { - echo '

    ' . __('The file does not exist or could not be read.', 'mycred') . '

    '; - return false; + echo '

    ' . __( 'The file does not exist or could not be read.', 'mycred' ) . '

    '; + return false; - } + } - } + } - return true; + return true; - } + } - /** - * Import Function - * Handles the actual import based on a given file. - * - * @version 1.0 - */ - public function import( $file ) - { + /** + * Import Function + * Handles the actual import based on a given file. + * @version 1.0 + */ + public function import( $file ) { - global $wpdb; + global $wpdb; - $ran = false; - $show_greet = true; - $loop = 0; + $ran = false; + $show_greet = true; + $loop = 0; - // Make sure the file exists - if (! is_file($file) ) { + // Make sure the file exists + if ( ! is_file( $file ) ) { - echo '

    ' . __('The file does not exist or could not be read.', 'mycred') . '

    '; - return true; + echo '

    ' . __( 'The file does not exist or could not be read.', 'mycred' ) . '

    '; + return true; - } + } - if (function_exists('gc_enable') ) { - gc_enable(); - } + if ( function_exists( 'gc_enable' ) ) + gc_enable(); - @set_time_limit(0); - @ob_flush(); - @flush(); + @set_time_limit(0); + @ob_flush(); + @flush(); - // Begin by opening the file - if (( $handle = fopen($file, "r") ) !== false ) { + // Begin by opening the file + if ( ( $handle = fopen( $file, "r" ) ) !== false ) { - // Need to get the header of the CSV file so we know how many columns we are using - $header = fgetcsv($handle, 0, $this->delimiter); - $no_of_columns = sizeof($header); + // Need to get the header of the CSV file so we know how many columns we are using + $header = fgetcsv( $handle, 0, $this->delimiter ); + $no_of_columns = sizeof( $header ); - // Make sure we have the correct number of columns - if ($no_of_columns == 3 || $no_of_columns == 4 ) { + // Make sure we have the correct number of columns + if ( $no_of_columns == 3 || $no_of_columns == 4 ) { - // Begin import loop - while ( ( $row = fgetcsv($handle, 0, $this->delimiter) ) !== false ) { + // Begin import loop + while ( ( $row = fgetcsv( $handle, 0, $this->delimiter ) ) !== false ) { - $log_entry = ''; - if ($no_of_columns == 3 ) { - list ( $identification, $balance, $point_type ) = $row; - } else { - list ( $identification, $balance, $point_type, $log_entry ) = $row; - } + $log_entry = ''; + if ( $no_of_columns == 3 ) + list ( $identification, $balance, $point_type ) = $row; + else + list ( $identification, $balance, $point_type, $log_entry ) = $row; - // Attempt to identify the user - $user_id = mycred_get_user_id($identification); + // Attempt to identify the user + $user_id = mycred_get_user_id( $identification ); - // Failed to find the user - Next! - if ($user_id === false ) { - $this->skipped ++; - continue; - } + // Failed to find the user - Next! + if ( $user_id === false ) { + $this->skipped ++; + continue; + } - // Make sure the point type exists - if (! mycred_point_type_exists($point_type) ) { + // Make sure the point type exists + if ( ! mycred_point_type_exists( $point_type ) ) { - // The point type column actually holds the log entry - if ($point_type != '' ) { - $log_entry = $point_type; - } + // The point type column actually holds the log entry + if ( $point_type != '' ) + $log_entry = $point_type; - $point_type = MYCRED_DEFAULT_TYPE_KEY; + $point_type = MYCRED_DEFAULT_TYPE_KEY; - } + } - $mycred = mycred($point_type); - $method = trim($_POST['method']); + $mycred = mycred( $point_type ); + $method = trim( $_POST['method'] ); - // If a log entry should be added with the import - if (! empty($log_entry) ) { - $mycred->add_to_log('import', $user_id, $balance, $log_entry); - } + // If a log entry should be added with the import + if ( ! empty( $log_entry ) ) + $mycred->add_to_log( 'import', $user_id, $balance, $log_entry ); - // Add to the balance - if ($method == 'add' ) { - $mycred->update_users_balance($user_id, $balance); - } + // Add to the balance + if ( $method == 'add' ) + $mycred->update_users_balance( $user_id, $balance ); - // Change the balance - else { - $mycred->set_users_balance($user_id, $balance); - } + // Change the balance + else + $mycred->set_users_balance( $user_id, $balance ); - $loop ++; - $this->imported++; + $loop ++; + $this->imported++; - } + } - $show_greet = false; - $ran = true; + $show_greet = false; + $ran = true; - } else { + } else { - echo '

    ' . __('Invalid CSV file. Please consult the documentation for further assistance.', 'mycred') . '

    '; + echo '

    ' . __( 'Invalid CSV file. Please consult the documentation for further assistance.', 'mycred' ) . '

    '; - } + } - fclose($handle); + fclose( $handle ); - } + } - if ($ran ) { - echo '

    ' . sprintf(__('Import complete - A total of %d balances were successfully imported. %d was skipped.', 'mycred'), $this->imported, $this->skipped) . '

    '; - echo '

    ' . __('View Users', 'mycred') . '

    '; - } + if ( $ran ) { + echo '

    ' . sprintf( __( 'Import complete - A total of %d balances were successfully imported. %d was skipped.', 'mycred' ), $this->imported, $this->skipped ) . '

    '; + echo '

    ' . __( 'View Users', 'mycred' ) . '

    '; + } - do_action('import_end'); + do_action( 'import_end' ); - return $show_greet; + return $show_greet; - } + } - /** - * Render Screen Header - * - * @version 1.0 - */ - public function header() - { + /** + * Render Screen Header + * @version 1.0 + */ + public function header() { - $label = __('Import Balances', 'mycred'); - if (MYCRED_DEFAULT_LABEL === 'myCRED' ) { - $label .= ' ' . __('Documentation', 'mycred') . ''; - } + $label = __( 'Import Balances', 'mycred' ); + if ( MYCRED_DEFAULT_LABEL === 'myCRED' ) + $label .= ' ' . __( 'Documentation', 'mycred' ) . ''; - echo '

    ' . $label . '

    '; + echo '

    ' . $label . '

    '; - } + } - /** - * Render Screem Fppter - * - * @version 1.0 - */ - public function footer() - { + /** + * Render Screem Fppter + * @version 1.0 + */ + public function footer() { - echo '
    '; + echo '
    '; - } + } - /** - * Greet Screen - * - * @version 1.0 - */ - public function greet() - { + /** + * Greet Screen + * @version 1.0 + */ + public function greet() { - $bytes = apply_filters('import_upload_size_limit', wp_max_upload_size()); - $size = size_format($bytes); - $upload_dir = wp_upload_dir(); - $action_url = add_query_arg(array( 'import' => $this->import_page, 'step' => 1 ), admin_url('admin.php')); + $bytes = apply_filters( 'import_upload_size_limit', wp_max_upload_size() ); + $size = size_format( $bytes ); + $upload_dir = wp_upload_dir(); + $action_url = add_query_arg( array( 'import' => $this->import_page, 'step' => 1 ), admin_url( 'admin.php' ) ); - if (! empty($upload_dir['error']) ) : + if ( ! empty( $upload_dir['error'] ) ) : - ?> +?>

    - -
    - - - - - - - - - - - - - - - - - - - -
    - - - - - - -
    - - - -
    - - - -
    - - - -
    -

    - -

    + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + +
    + + + +
    + + + +
    + + + +
    +

    + +

    - import_page = MYCRED_SLUG . '-import-cp'; - $this->delimiter = empty($_POST['delimiter']) ? ',' : (string) strip_tags(trim($_POST['delimiter'])); - $this->documentation = 'http://codex.mycred.me/chapter-ii/import-data/import-cubepoints/'; - - } + /** + * Construct + * @version 1.0 + */ + public function __construct() { - /** - * Registered callback function for the WordPress Importer - * Manages the three separate stages of the CSV import process - * - * @version 1.0 - */ - public function load() - { - - $this->header(); - - $load = true; - $step = ( ! isset($_GET['step']) ) ? 0 : absint($_GET['step']); - if ($step > 1 ) { $step = 0; - } - - switch ( $step ) { - - case 1 : - - if ($this->check_cubepoints() ) { - - $load = $this->import(); - - } - - break; + $this->import_page = MYCRED_SLUG . '-import-cp'; + $this->delimiter = empty( $_POST['delimiter'] ) ? ',' : (string) strip_tags( trim( $_POST['delimiter'] ) ); + $this->documentation = 'http://codex.mycred.me/chapter-ii/import-data/import-cubepoints/'; + + } - } + /** + * Registered callback function for the WordPress Importer + * Manages the three separate stages of the CSV import process + * @version 1.0 + */ + public function load() { - if ($load ) { - $this->greet(); - } + $this->header(); - $this->footer(); + $load = true; + $step = ( ! isset( $_GET['step'] ) ) ? 0 : absint( $_GET['step'] ); + if ( $step > 1 ) $step = 0; - } + switch ( $step ) { - /** - * UTF-8 encode the data if `$enc` value isn't UTF-8. - * - * @version 1.0 - */ - public function format_data_from_csv( $data, $enc ) - { - return ( $enc == 'UTF-8' ) ? $data : utf8_encode($data); - } + case 1 : - + if ( $this->check_cubepoints() ) { - /** - * Checks CubePoints Installation - * - * @version 1.1 - */ - public function check_cubepoints() - { + $load = $this->import(); - global $wpdb; + } - $cubepoints = $wpdb->prefix . 'cp'; - if ($wpdb->get_var("SHOW TABLES LIKE '{$cubepoints}';") != $cubepoints ) { - echo '

    ' . __('Could not find a CubePoints installation.', 'mycred') . '

    '; - return false; - } + break; - return true; + } - } + if ( $load ) + $this->greet(); - public function add_to_log( $ref = '', $user_id = '', $amount = '', $entry = '', $ref_id = '', $data = '', $type = null, $entrytime ) - { + $this->footer(); - // Minimum Requirements: Reference not empty, User ID not empty and Amount is not empty - if (empty($ref) || empty($user_id) || empty($amount) || empty($entry) ) { return false; - } + } - $myCred = mycred($type); + /** + * UTF-8 encode the data if `$enc` value isn't UTF-8. + * @version 1.0 + */ + public function format_data_from_csv( $data, $enc ) { + return ( $enc == 'UTF-8' ) ? $data : utf8_encode( $data ); + } - // Prep amount - $amount = $myCred->number($amount); - $amount = $myCred->enforce_max($user_id, $amount); - if ($amount === $myCred->zero() || $amount == 0 ) { return false; - } - - $insert_id = 0; + - mycred_update_users_history($user_id, $type, $ref, $ref_id, $amount); + /** + * Checks CubePoints Installation + * @version 1.1 + */ + public function check_cubepoints() { - // Option to disable logging - if (MYCRED_ENABLE_LOGGING ) { + global $wpdb; - global $wpdb, $mycred_types; + $cubepoints = $wpdb->prefix . 'cp'; + if ( $wpdb->get_var( "SHOW TABLES LIKE '{$cubepoints}';" ) != $cubepoints ) { + echo '

    ' . __( 'Could not find a CubePoints installation.', 'mycred' ) . '

    '; + return false; + } - // Strip HTML from log entry - $entry = $myCred->allowed_tags($entry); + return true; - // Point type - if ($type === null || ! array_key_exists($type, $mycred_types) ) { - $type = $myCred->get_point_type_key(); - } + } - - $insert = array( - 'ref' => $ref, - 'ref_id' => $ref_id, - 'user_id' => (int) $user_id, - 'creds' => $amount, - 'ctype' => $type, - 'time' => $entrytime, - 'entry' => $entry, - 'data' => ( is_array($data) || is_object($data) ) ? serialize($data) : $data - ); + public function add_to_log( $ref = '', $user_id = '', $amount = '', $entry = '', $ref_id = '', $data = '', $type = NULL, $entrytime ) { - // Insert into DB - $wpdb->insert( - $myCred->log_table, - $insert, - array( '%s', '%d', '%d', '%s', '%s', '%d', '%s', ( is_numeric($data) ) ? '%d' : '%s' ) - ); + // Minimum Requirements: Reference not empty, User ID not empty and Amount is not empty + if ( empty( $ref ) || empty( $user_id ) || empty( $amount ) || empty( $entry ) ) return false; - $insert_id = $wpdb->insert_id; + $myCred = mycred($type); - wp_cache_delete('mycred_references' . $type, MYCRED_SLUG); + // Prep amount + $amount = $myCred->number( $amount ); + $amount = $myCred->enforce_max( $user_id, $amount ); + if ( $amount === $myCred->zero() || $amount == 0 ) return false; + + $insert_id = 0; - delete_transient('mycred_log_entries'); + mycred_update_users_history( $user_id, $type, $ref, $ref_id, $amount ); - } + // Option to disable logging + if ( MYCRED_ENABLE_LOGGING ) { - return $insert; + global $wpdb, $mycred_types; - } + // Strip HTML from log entry + $entry = $myCred->allowed_tags( $entry ); + // Point type + if ( $type === NULL || ! array_key_exists( $type, $mycred_types ) ) + $type = $myCred->get_point_type_key(); - /** - * Import Function - * Handles the actual import based on a given file. - * - * @version 1.0 - */ - public function import() - { + + $insert = array( + 'ref' => $ref, + 'ref_id' => $ref_id, + 'user_id' => (int) $user_id, + 'creds' => $amount, + 'ctype' => $type, + 'time' => $entrytime, + 'entry' => $entry, + 'data' => ( is_array( $data ) || is_object( $data ) ) ? serialize( $data ) : $data + ); - global $wpdb; + // Insert into DB + $wpdb->insert( + $myCred->log_table, + $insert, + array( '%s', '%d', '%d', '%s', '%s', '%d', '%s', ( is_numeric( $data ) ) ? '%d' : '%s' ) + ); - $action = $_POST['action']; - $point_type = $_POST['type']; - $cubepoints = $wpdb->prefix . 'cp'; + $insert_id = $wpdb->insert_id; - $show_greet = true; - $loop = 0; + wp_cache_delete( 'mycred_references' . $type, MYCRED_SLUG ); - if (! mycred_point_type_exists($point_type) ) { $point_type = MYCRED_DEFAULT_TYPE_KEY; - } - $mycred = mycred($type); + delete_transient( 'mycred_log_entries' ); - + } - // Import Log - if ($action == 'log' || $action == 'both' ) { + return $insert; - $entries = $wpdb->get_results("SELECT * FROM {$cubepoints};"); - if (! empty($entries) ) { - foreach ( $entries as $entry ) { + } - $reference = false; - $log_entry = false; - $ref_id = false; - $data = ''; - if ($entry->type == 'comment' ) { + /** + * Import Function + * Handles the actual import based on a given file. + * @version 1.0 + */ + public function import() { - $reference = 'approved_comment'; - $log_entry = '%plural% for approved comment'; + global $wpdb; - } + $action = $_POST['action']; + $point_type = $_POST['type']; + $cubepoints = $wpdb->prefix . 'cp'; - elseif ($entry->type == 'comment_remove' ) { + $show_greet = true; + $loop = 0; - $reference = 'unapproved_comment'; - $log_entry = '%plural% for deleted comment'; + if ( ! mycred_point_type_exists( $point_type ) ) $point_type = MYCRED_DEFAULT_TYPE_KEY; + $mycred = mycred( $type ); - } + - elseif ($entry->type == 'post' ) { + // Import Log + if ( $action == 'log' || $action == 'both' ) { - $reference = 'publishing_content'; - $log_entry = '%plural% for publishing content'; + $entries = $wpdb->get_results( "SELECT * FROM {$cubepoints};" ); + if ( ! empty( $entries ) ) { + foreach ( $entries as $entry ) { - } + $reference = false; + $log_entry = false; + $ref_id = false; + $data = ''; - elseif ($entry->type == 'register' ) { + if ( $entry->type == 'comment' ) { - $reference = 'registration'; - $log_entry = '%plural% for registration'; + $reference = 'approved_comment'; + $log_entry = '%plural% for approved comment'; - } + } - elseif ($entry->type == 'addpoints' ) { + elseif ( $entry->type == 'comment_remove' ) { - $reference = 'manual'; - $log_entry = '%plural% via manual adjustment'; + $reference = 'unapproved_comment'; + $log_entry = '%plural% for deleted comment'; - } + } - elseif ($entry->type == 'dailypoints' ) { + elseif ( $entry->type == 'post' ) { - $reference = 'payout'; - $log_entry = 'Daily %plural%'; + $reference = 'publishing_content'; + $log_entry = '%plural% for publishing content'; - } + } - elseif ($entry->type == 'donate_from' ) { + elseif ( $entry->type == 'register' ) { - $reference = 'transfer'; - $data = maybe_unserialize($entry->data); + $reference = 'registration'; + $log_entry = '%plural% for registration'; - if (isset($data['to']) ) { $ref_id = absint($data['to']); - } + } - $log_entry = 'Transfer from %display_name%'; - $data = array( 'ref_type' => 'user', 'tid' => 'TXID' . $entry->timestamp . $entry->uid ); + elseif ( $entry->type == 'addpoints' ) { - } + $reference = 'manual'; + $log_entry = '%plural% via manual adjustment'; - elseif ($entry->type == 'donate_to' ) { + } - $reference = 'transfer'; - $data = maybe_unserialize($entry->data); + elseif ( $entry->type == 'dailypoints' ) { - if (isset($data['to']) ) { $ref_id = absint($data['to']); - } + $reference = 'payout'; + $log_entry = 'Daily %plural%'; - $log_entry = 'Transfer to %display_name%'; - $data = array( 'ref_type' => 'user', 'tid' => 'TXID' . $entry->timestamp . $entry->uid ); + } - } + elseif ( $entry->type == 'donate_from' ) { - elseif ($entry->type == 'pcontent' ) { + $reference = 'transfer'; + $data = maybe_unserialize( $entry->data ); - $reference = 'buy_content'; - $log_entry = 'Purchase of %link_with_title%'; - $ref_id = absint($entry->data); - $data = array( 'ref_type' => 'post', 'purchase_id' => 'TXID' . $entry->timestamp ); + if ( isset( $data['to'] ) ) $ref_id = absint( $data['to'] ); - } + $log_entry = 'Transfer from %display_name%'; + $data = array( 'ref_type' => 'user', 'tid' => 'TXID' . $entry->timestamp . $entry->uid ); - elseif ($entry->type == 'pcontent_author' ) { + } - $reference = 'buy_content'; - $log_entry = 'Sale of %link_with_title%'; + elseif ( $entry->type == 'donate_to' ) { - $data = maybe_unserialize($entry->data); - $ref_id = absint($data[0]); + $reference = 'transfer'; + $data = maybe_unserialize( $entry->data ); - $data = array( 'ref_type' => 'post', 'purchase_id' => 'TXID' . $entry->timestamp, 'buyer' => $data[1] ); + if ( isset( $data['to'] ) ) $ref_id = absint( $data['to'] ); - } + $log_entry = 'Transfer to %display_name%'; + $data = array( 'ref_type' => 'user', 'tid' => 'TXID' . $entry->timestamp . $entry->uid ); - elseif ($entry->type == 'paypal' ) { + } - $reference = 'buy_creds_with_paypal_standard'; - $log_entry = '%plural% purchase'; + elseif ( $entry->type == 'pcontent' ) { - $data = maybe_unserialize($entry->data); - $data = array( 'txn_id' => $data['txn_id'], 'payer_id' => $data['payer_email'] ); + $reference = 'buy_content'; + $log_entry = 'Purchase of %link_with_title%'; + $ref_id = absint( $entry->data ); + $data = array( 'ref_type' => 'post', 'purchase_id' => 'TXID' . $entry->timestamp ); - } + } - elseif ($entry->type == 'post_comment' ) { + elseif ( $entry->type == 'pcontent_author' ) { - $reference = 'approved_comment'; - $log_entry = '%plural% for approved comment'; - $data = array( 'ref_type' => 'comment' ); + $reference = 'buy_content'; + $log_entry = 'Sale of %link_with_title%'; - } + $data = maybe_unserialize( $entry->data ); + $ref_id = absint( $data[0] ); - elseif ($entry->type == 'post_comment_remove' ) { + $data = array( 'ref_type' => 'post', 'purchase_id' => 'TXID' . $entry->timestamp, 'buyer' => $data[1] ); - $reference = 'unapproved_comment'; - $log_entry = '%plural% for deleted comment'; - $data = array( 'ref_type' => 'comment' ); + } - } + elseif ( $entry->type == 'paypal' ) { - elseif ($entry->type == 'youtube' ) { + $reference = 'buy_creds_with_paypal_standard'; + $log_entry = '%plural% purchase'; - $reference = 'watching_video'; - $log_entry = '%plural% for viewing video'; - $data = absint($entry->data); + $data = maybe_unserialize( $entry->data ); + $data = array( 'txn_id' => $data['txn_id'], 'payer_id' => $data['payer_email'] ); - } + } - if ($reference === false ) { - $this->skipped ++; - continue; - } + elseif ( $entry->type == 'post_comment' ) { - $entry_data = maybe_unserialize($entry->data); - if ($ref_id === false && ! empty($entry_data) && ! is_array($entry_data) ) { $ref_id = absint($entry->data); - } - if ($ref_id === false ) { $ref_id = 0; - } + $reference = 'approved_comment'; + $log_entry = '%plural% for approved comment'; + $data = array( 'ref_type' => 'comment' ); - $this->add_to_log($reference, $entry->uid, $entry->points, $log_entry, $ref_id, $data, $point_type, $entry->timestamp); + } - + elseif ( $entry->type == 'post_comment_remove' ) { - $loop ++; - $this->imported++; + $reference = 'unapproved_comment'; + $log_entry = '%plural% for deleted comment'; + $data = array( 'ref_type' => 'comment' ); - } + } - } + elseif ( $entry->type == 'youtube' ) { - } + $reference = 'watching_video'; + $log_entry = '%plural% for viewing video'; + $data = absint( $entry->data ); - if ($action == 'balance' || $action == 'both' ) { + } - $rows = $wpdb->update( - $wpdb->usermeta, - array( 'meta_key' => mycred_get_meta_key($point_type) ), - array( 'meta_key' => 'cpoints' ), - array( '%s' ), - array( '%s' ) - ); + if ( $reference === false ) { + $this->skipped ++; + continue; + } - $this->imported = $rows; + $entry_data = maybe_unserialize( $entry->data ); + if ( $ref_id === false && ! empty( $entry_data ) && ! is_array( $entry_data ) ) $ref_id = absint( $entry->data ); + if ( $ref_id === false ) $ref_id = 0; - } + $this->add_to_log( $reference, $entry->uid, $entry->points, $log_entry, $ref_id, $data, $point_type, $entry->timestamp ); - // Show Result - if ($this->imported == 0 ) { + - echo '

    ' . ( ( $action == 'balance' ) ? __('No balances were imported.', 'mycred') : __('No log entries were imported!', 'mycred') ) . '

    '; + $loop ++; + $this->imported++; - } - else { + } - $show_greet = false; - echo '

    ' . sprintf(__('Import complete - A total of %d balances were successfully imported. %d was skipped.', 'mycred'), $this->imported, $this->skipped) . '

    '; - echo '

    ' . __('View Users', 'mycred') . '

    '; + } - } + } - do_action('import_end'); + if ( $action == 'balance' || $action == 'both' ) { - return $show_greet; + $rows = $wpdb->update( + $wpdb->usermeta, + array( 'meta_key' => mycred_get_meta_key( $point_type ) ), + array( 'meta_key' => 'cpoints' ), + array( '%s' ), + array( '%s' ) + ); - } + $this->imported = $rows; - /** - * Render Screen Header - * - * @version 1.0 - */ - public function header() - { + } - $label = __('Import CubePoints', 'mycred'); - if (MYCRED_DEFAULT_LABEL === 'myCRED' ) { - $label .= ' ' . __('Documentation', 'mycred') . ''; - } + // Show Result + if ( $this->imported == 0 ) { - echo '

    ' . $label . '

    '; + echo '

    ' . ( ( $action == 'balance' ) ? __( 'No balances were imported.', 'mycred' ) : __( 'No log entries were imported!', 'mycred' ) ) . '

    '; - } + } + else { - /** - * Render Screen Footer - * - * @version 1.0 - */ - public function footer() - { + $show_greet = false; + echo '

    ' . sprintf( __( 'Import complete - A total of %d balances were successfully imported. %d was skipped.', 'mycred' ), $this->imported, $this->skipped ) . '

    '; + echo '

    ' . __( 'View Users', 'mycred' ) . '

    '; - echo '
    '; + } - } + do_action( 'import_end' ); - /** - * Greet Screen - * - * @version 1.1 - */ - public function greet() - { + return $show_greet; - $action_url = add_query_arg(array( 'import' => $this->import_page, 'step' => 1 ), admin_url('admin.php')); + } - // Make sure we have something to import - if (! $this->check_cubepoints() ) : + /** + * Render Screen Header + * @version 1.0 + */ + public function header() { - // $this->check_cubepoints() will render our error message + $label = __( 'Import CubePoints', 'mycred' ); + if ( MYCRED_DEFAULT_LABEL === 'myCRED' ) + $label .= ' ' . __( 'Documentation', 'mycred' ) . ''; - else : + echo '

    ' . $label . '

    '; - ?> -
    - - - - - - - - - - - -
    - - - -
    - - - - - -
    -

    - -

    + } + + /** + * Render Screen Footer + * @version 1.0 + */ + public function footer() { + + echo '
    '; + + } + + /** + * Greet Screen + * @version 1.1 + */ + public function greet() { + + $action_url = add_query_arg( array( 'import' => $this->import_page, 'step' => 1 ), admin_url( 'admin.php' ) ); + + // Make sure we have something to import + if ( ! $this->check_cubepoints() ) : + + // $this->check_cubepoints() will render our error message + + else : + +?> + + + + + + + + + + + + +
    + + + +
    + + + + + +
    +

    + +

    - import_page = MYCRED_SLUG . '-import-log'; - $this->delimiter = empty($_POST['delimiter']) ? ',' : (string) strip_tags(trim($_POST['delimiter'])); - $this->documentation = 'http://codex.mycred.me/chapter-ii/import-data/importing-log-entries/'; + $this->import_page = MYCRED_SLUG . '-import-log'; + $this->delimiter = empty( $_POST['delimiter'] ) ? ',' : (string) strip_tags( trim( $_POST['delimiter'] ) ); + $this->documentation = 'http://codex.mycred.me/chapter-ii/import-data/importing-log-entries/'; - } + } - /** - * Registered callback function for the WordPress Importer - * Manages the three separate stages of the CSV import process - * - * @version 1.0 - */ - public function load() - { + /** + * Registered callback function for the WordPress Importer + * Manages the three separate stages of the CSV import process + * @version 1.0 + */ + public function load() { - $this->header(); + $this->header(); - $load = true; - $step = ( ! isset($_GET['step']) ) ? 0 : absint($_GET['step']); - if ($step > 1 ) { $step = 0; - } + $load = true; + $step = ( ! isset( $_GET['step'] ) ) ? 0 : absint( $_GET['step'] ); + if ( $step > 1 ) $step = 0; - switch ( $step ) { + switch ( $step ) { - case 1 : + case 1 : - check_admin_referer('import-upload'); + check_admin_referer( 'import-upload' ); - if ($this->handle_upload() ) { + if ( $this->handle_upload() ) { - if ($this->id ) { - $file = get_attached_file($this->id); - } else { - $file = ABSPATH . $this->file_url; - } + if ( $this->id ) + $file = get_attached_file( $this->id ); + else + $file = ABSPATH . $this->file_url; - if ($file !== false ) { + if ( $file !== false ) { - add_filter('http_request_timeout', array( $this, 'bump_request_timeout' )); + add_filter( 'http_request_timeout', array( $this, 'bump_request_timeout' ) ); - $load = $this->import($file); + $load = $this->import( $file ); - } + } - } + } - break; + break; - } + } - if ($load ) { - $this->greet(); - } + if ( $load ) + $this->greet(); - $this->footer(); + $this->footer(); - } + } - /** - * UTF-8 encode the data if `$enc` value isn't UTF-8. - * - * @version 1.0 - */ - public function format_data_from_csv( $data, $enc ) - { - return ( $enc == 'UTF-8' ) ? $data : utf8_encode($data); - } + /** + * UTF-8 encode the data if `$enc` value isn't UTF-8. + * @version 1.0 + */ + public function format_data_from_csv( $data, $enc ) { + return ( $enc == 'UTF-8' ) ? $data : utf8_encode( $data ); + } - /** - * Handles the CSV upload and initial parsing of the file to prepare for - * displaying author import options - * - * @return bool False if error uploading or invalid file, true otherwise - * @version 1.1 - */ - public function handle_upload() - { + /** + * Handles the CSV upload and initial parsing of the file to prepare for + * displaying author import options + * @return bool False if error uploading or invalid file, true otherwise + * @version 1.1 + */ + public function handle_upload() { - if (empty($_POST['file_url']) ) { + if ( empty( $_POST['file_url'] ) ) { - $file = wp_import_handle_upload(); + $file = wp_import_handle_upload(); - if (isset($file['error']) ) { + if ( isset( $file['error'] ) ) { - echo '

    ' . esc_html($file['error']) . '

    '; - return false; + echo '

    ' . esc_html( $file['error'] ) . '

    '; + return false; - } + } - $this->id = (int) $file['id']; + $this->id = (int) $file['id']; - } else { + } else { - if (file_exists(ABSPATH . $_POST['file_url']) ) { + if ( file_exists( ABSPATH . $_POST['file_url'] ) ) { - $this->file_url = esc_attr($_POST['file_url']); + $this->file_url = esc_attr( $_POST['file_url'] ); - } else { + } else { - echo '

    ' . __('The file does not exist or could not be read.', 'mycred') . '

    '; - return false; + echo '

    ' . __( 'The file does not exist or could not be read.', 'mycred' ) . '

    '; + return false; - } + } - } + } - return true; + return true; - } + } - /** - * import function. - */ - function import( $file ) - { + /** + * import function. + */ + function import( $file ) { - global $wpdb; + global $wpdb; - $ran = false; - $show_greet = true; - $loop = 0; + $ran = false; + $show_greet = true; + $loop = 0; - // Make sure the file exists - if (! is_file($file) ) { + // Make sure the file exists + if ( ! is_file( $file ) ) { - echo '

    ' . __('The file does not exist or could not be read.', 'mycred') . '

    '; - return true; + echo '

    ' . __( 'The file does not exist or could not be read.', 'mycred' ) . '

    '; + return true; - } + } - if (function_exists('gc_enable') ) { - gc_enable(); - } + if ( function_exists( 'gc_enable' ) ) + gc_enable(); - @set_time_limit(0); - @ob_flush(); - @flush(); + @set_time_limit(0); + @ob_flush(); + @flush(); - // Begin by opening the file - if (( $handle = fopen($file, "r") ) !== false ) { + // Begin by opening the file + if ( ( $handle = fopen( $file, "r" ) ) !== FALSE ) { - // Need to get the header of the CSV file so we know how many columns we are using - $header = fgetcsv($handle, 0, $this->delimiter); + // Need to get the header of the CSV file so we know how many columns we are using + $header = fgetcsv( $handle, 0, $this->delimiter ); - // Make sure we have the correct number of columns - if (sizeof($header) == 8 ) { + // Make sure we have the correct number of columns + if ( sizeof( $header ) == 8 ) { - // Begin import loop - while ( ( $row = fgetcsv($handle, 0, $this->delimiter) ) !== false ) { + // Begin import loop + while ( ( $row = fgetcsv( $handle, 0, $this->delimiter ) ) !== false ) { - list ( $reference, $ref_id, $identification, $amount, $point_type, $time, $entry, $data ) = $row; + list ( $reference, $ref_id, $identification, $amount, $point_type, $time, $entry, $data ) = $row; - // Minimum requirements for this to work - if (empty($reference) || empty($identification) || empty($amount) || empty($time) ) { - $this->skipped ++; - continue; - } + // Minimum requirements for this to work + if ( empty( $reference ) || empty( $identification ) || empty( $amount ) || empty( $time ) ) { + $this->skipped ++; + continue; + } - // Attempt to identify the user - $user_id = mycred_get_user_id($identification); + // Attempt to identify the user + $user_id = mycred_get_user_id( $identification ); - // Failed to find the user - Next! - if ($user_id === false ) { - $this->skipped ++; - continue; - } + // Failed to find the user - Next! + if ( $user_id === false ) { + $this->skipped ++; + continue; + } - if (! mycred_point_type_exists($point_type) ) { $point_type = MYCRED_DEFAULT_TYPE_KEY; - } + if ( ! mycred_point_type_exists( $point_type ) ) $point_type = MYCRED_DEFAULT_TYPE_KEY; - $mycred = mycred($point_type); - $this->time = $time; + $mycred = mycred( $point_type ); + $this->time = $time; - add_filter('mycred_log_time', array( $this, 'log_time' )); + add_filter( 'mycred_log_time', array( $this, 'log_time' ) ); - $mycred->add_to_log($reference, $user_id, $amount, $entry, $ref_id, $data, $point_type); + $mycred->add_to_log( $reference, $user_id, $amount, $entry, $ref_id, $data, $point_type ); - remove_filter('mycred_log_time', array( $this, 'log_time' )); + remove_filter( 'mycred_log_time', array( $this, 'log_time' ) ); - $loop ++; - $this->imported++; + $loop ++; + $this->imported++; - } + } - $show_greet = false; - $ran = true; + $show_greet = false; + $ran = true; - } else { + } else { - echo '

    ' . __('Invalid CSV file. Please consult the documentation for further assistance.', 'mycred') . '

    '; + echo '

    ' . __( 'Invalid CSV file. Please consult the documentation for further assistance.', 'mycred' ) . '

    '; - } + } - fclose($handle); + fclose( $handle ); - } + } - if ($ran ) { - echo '

    ' . sprintf(__('Import complete - A total of %d log entries were successfully imported. %d was skipped.', 'mycred'), $this->imported, $this->skipped) . '

    '; - echo '

    ' . __('View Log', 'mycred') . '

    '; - } + if ( $ran ) { + echo '

    ' . sprintf( __( 'Import complete - A total of %d log entries were successfully imported. %d was skipped.', 'mycred' ), $this->imported, $this->skipped ) . '

    '; + echo '

    ' . __( 'View Log', 'mycred' ) . '

    '; + } - do_action('import_end'); + do_action( 'import_end' ); - return $show_greet; + return $show_greet; - } + } - /** - * Log Time - * - * @version 1.0 - */ - public function log_time( $time ) - { + /** + * Log Time + * @version 1.0 + */ + public function log_time( $time ) { - return $this->time; + return $this->time; - } + } - /** - * Render Screen Header - * - * @version 1.0 - */ - public function header() - { + /** + * Render Screen Header + * @version 1.0 + */ + public function header() { - $label = __('Import Log Entries', 'mycred'); - if (MYCRED_DEFAULT_LABEL === 'myCRED' ) { - $label .= ' ' . __('Documentation', 'mycred') . ''; - } + $label = __( 'Import Log Entries', 'mycred' ); + if ( MYCRED_DEFAULT_LABEL === 'myCRED' ) + $label .= ' ' . __( 'Documentation', 'mycred' ) . ''; - echo '

    ' . $label . '

    '; + echo '

    ' . $label . '

    '; - } + } - /** - * Render Screem Fppter - * - * @version 1.0 - */ - public function footer() - { + /** + * Render Screem Fppter + * @version 1.0 + */ + public function footer() { - echo '
    '; + echo '
    '; - } + } - /** - * Greet Screen - * - * @version 1.0 - */ - public function greet() - { + /** + * Greet Screen + * @version 1.0 + */ + public function greet() { - global $mycred; + global $mycred; - $bytes = apply_filters('import_upload_size_limit', wp_max_upload_size()); - $size = size_format($bytes); - $upload_dir = wp_upload_dir(); - $action_url = add_query_arg(array( 'import' => $this->import_page, 'step' => 1 ), admin_url('admin.php')); + $bytes = apply_filters( 'import_upload_size_limit', wp_max_upload_size() ); + $size = size_format( $bytes ); + $upload_dir = wp_upload_dir(); + $action_url = add_query_arg( array( 'import' => $this->import_page, 'step' => 1 ), admin_url( 'admin.php' ) ); - if (! empty($upload_dir['error']) ) : + if ( ! empty( $upload_dir['error'] ) ) : - ?> +?>

    - -
    - - - - - - - - - - - - - - - -
    - - - - - - -
    - - - -
    - - - -
    -

    - -

    + + + + + + + + + + + + + + + + + +
    + + + + + + +
    + + + +
    + + + +
    +

    + +

    - +?> \ No newline at end of file diff --git a/includes/mycred-about.php b/includes/mycred-about.php index ac29bf7..efd2aec 100644 --- a/includes/mycred-about.php +++ b/includes/mycred-about.php @@ -1,19 +1,16 @@ +?> '; - } - - do_action('mycred_front_history', $user_id); - - ?> +if ( ! function_exists( 'mycred_render_shortcode_history' ) ) : + function mycred_render_shortcode_history( $atts, $content = '' ) { + + extract( shortcode_atts( array( + 'user_id' => '', + 'number' => 10, + 'time' => '', + 'ref' => '', + 'order' => '', + 'show_user' => 0, + 'show_nav' => 1, + 'login' => '', + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'pagination' => 10, + 'inlinenav' => 0 + ), $atts, MYCRED_SLUG . '_history' ) ); + + // If we are not logged in + if ( ! is_user_logged_in() && $login != '' ) + return $login . $content; + + if ( ! MYCRED_ENABLE_LOGGING ) return ''; + + $user_id = mycred_get_user_id( $user_id ); + + if ( ! mycred_point_type_exists( $type ) ) + $type = MYCRED_DEFAULT_TYPE_KEY; + + $args = array( 'ctype' => $type ); + + if ( $user_id != 0 && $user_id != '' ) + $args['user_id'] = absint( $user_id ); + + if ( absint( $number ) > 0 ) + $args['number'] = absint( $number ); + + if ( $time != '' ) + $args['time'] = $time; + + if ( $ref != '' ) + $args['ref'] = $ref; + + if ( $order != '' ) + $args['order'] = $order; + + $log = new myCRED_Query_Log( apply_filters( 'mycred_front_history_args', $args, $atts ) ); + + ob_start(); + + if ( $inlinenav ) echo ''; + + do_action( 'mycred_front_history', $user_id ); + +?>
    - front_navigation('top', $pagination); - } ?> + front_navigation( 'top', $pagination ); ?> - display(); ?> + display(); ?> - front_navigation('bottom', $pagination); - } ?> + front_navigation( 'bottom', $pagination ); ?>
    - reset_query(); + $log->reset_query(); - return $content; + return $content; - } + } endif; -add_shortcode(MYCRED_SLUG . '_history', 'mycred_render_shortcode_history'); +add_shortcode( MYCRED_SLUG . '_history', 'mycred_render_shortcode_history' ); diff --git a/includes/shortcodes/mycred_hook_table.php b/includes/shortcodes/mycred_hook_table.php index 4823e15..49cc963 100644 --- a/includes/shortcodes/mycred_hook_table.php +++ b/includes/shortcodes/mycred_hook_table.php @@ -1,172 +1,160 @@ MYCRED_DEFAULT_TYPE_KEY, - 'gains' => 1, - 'user' => '-user-', - 'post' => '-post-', - 'comment' => '-comment-', - 'amount' => '', - 'nothing' => __('No instances found for this point type', 'mycred') - ), $atts, MYCRED_SLUG . '_hook_table' - ) - ); + extract( shortcode_atts( array( + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'gains' => 1, + 'user' => '-user-', + 'post' => '-post-', + 'comment' => '-comment-', + 'amount' => '', + 'nothing' => __( 'No instances found for this point type', 'mycred' ) + ), $atts, MYCRED_SLUG . '_hook_table' ) ); - if (! mycred_point_type_exists($type) ) { return __('Point type not found.', 'mycred'); - } + if ( ! mycred_point_type_exists( $type ) ) return __( 'Point type not found.', 'mycred' ); - $mycred = mycred($type); - $id = str_replace('_', '-', $type); - $prefs_key = apply_filters('mycred_option_id', 'mycred_pref_hooks'); + $mycred = mycred( $type ); + $id = str_replace( '_', '-', $type ); + $prefs_key = apply_filters( 'mycred_option_id', 'mycred_pref_hooks' ); - if ($type != MYCRED_DEFAULT_TYPE_KEY ) { - $prefs_key .= '_' . $type; - } + if ( $type != MYCRED_DEFAULT_TYPE_KEY ) + $prefs_key .= '_' . $type; - $applicable = array(); + $applicable = array(); - $hooks = get_option($prefs_key, false); - if (isset($hooks['active']) && ! empty($hooks['active']) ) { + $hooks = get_option( $prefs_key, false ); + if ( isset( $hooks['active'] ) && ! empty( $hooks['active'] ) ) { - foreach ( $hooks['active'] as $active_hook_id ) { + foreach ( $hooks['active'] as $active_hook_id ) { - $hook_prefs = $hooks['hook_prefs'][ $active_hook_id ]; + $hook_prefs = $hooks['hook_prefs'][ $active_hook_id ]; - // Single Instance - if (isset($hook_prefs['creds']) ) { + // Single Instance + if ( isset( $hook_prefs['creds'] ) ) { - if (( $gains == 1 && $hook_prefs['creds'] > 0 ) || ( $gains == 0 && $hook_prefs['creds'] < 0 ) ) { - $applicable[ $active_hook_id ] = $hook_prefs; - } + if ( ( $gains == 1 && $hook_prefs['creds'] > 0 ) || ( $gains == 0 && $hook_prefs['creds'] < 0 ) ) + $applicable[ $active_hook_id ] = $hook_prefs; - } + } - // Multiple Instances - else { + // Multiple Instances + else { - foreach ( $hook_prefs as $instance_id => $instance_prefs ) { + foreach ( $hook_prefs as $instance_id => $instance_prefs ) { - if (! isset($instance_prefs['creds']) ) { continue; - } + if ( ! isset( $instance_prefs['creds'] ) ) continue; - if (( $gains == 1 && $instance_prefs['creds'] > 0 ) || ( $gains == 0 && $instance_prefs['creds'] < 0 ) ) { - if($active_hook_id==='deleted_content' || $active_hook_id==='publishing_content' || $active_hook_id==='view_contents' ) { - $applicable[ $active_hook_id."_".$instance_id ] = $instance_prefs; - } - else{ - $applicable[ $instance_id ] = $instance_prefs; - } - } + if ( ( $gains == 1 && $instance_prefs['creds'] > 0 ) || ( $gains == 0 && $instance_prefs['creds'] < 0 ) ){ + if($active_hook_id==='deleted_content' || $active_hook_id==='publishing_content' || $active_hook_id==='view_contents' ){ + $applicable[ $active_hook_id."_".$instance_id ] = $instance_prefs; + } + else{ + $applicable[ $instance_id ] = $instance_prefs; + } + } - } + } - } + } - } + } - } + } - ob_start(); + ob_start(); - if (! empty($applicable) ) { + if ( ! empty( $applicable ) ) { - ?> +?>
    - - - - - - - - - - $prefs ) { - - $log = $mycred->template_tags_general($prefs['log']); - - $log = strip_tags($log); - $log = str_replace(array( '%user_id%', '%user_name%', '%user_name_en%', '%display_name%', '%user_profile_url%', '%user_profile_link%', '%user_nicename%', '%user_email%', '%user_url%', '%balance%', '%balance_f%' ), $user, $log); - $log = str_replace(array( '%post_title%', '%post_url%', '%link_with_title%', '%post_type%' ), $post, $log); - $log = str_replace(array( 'comment_id', 'c_post_id', 'c_post_title', 'c_post_url', 'c_link_with_title' ), $comment, $log); - $log = str_replace(array( '%cred%', '%cred_f%' ), $amount, $log); - $log = apply_filters('mycred_hook_table_log', $log, $id, $prefs, $atts); - - $limit = ''; - if (isset($prefs['limit']) ) { - $limit = $prefs['limit']; - } - - if($id == "approved" ) { - if (isset($hooks["hook_prefs"]["comments"]["limits"]) ) { - $approved_limits = $hooks["hook_prefs"]["comments"]["limits"]; - if((int) $approved_limits["per_post"] > 0 && (int) $approved_limits["per_day"] > 0 ) { - - $limit = sprintf(__('Maximum %s times per post and Maximum %s times per day', 'mycred'), $approved_limits["per_post"], $approved_limits["per_day"]); - } - elseif((int) $approved_limits["per_post"] > 0 && (int) $approved_limits["per_day"] < 1 ) { - - $limit = sprintf(__('Maximum %s times per post', 'mycred'), $approved_limits["per_post"]); - } - elseif((int) $approved_limits["per_post"] < 1 && (int) $approved_limits["per_day"] > 0 ) { - - $limit = sprintf(__('Maximum %s times per day', 'mycred'), $approved_limits["per_day"]); - } - else { - $limit = __('No limit', 'mycred'); - } - } - } - else { - $limit = mycred_translate_limit_code($limit, $id, $mycred); - } - - $creds = apply_filters('mycred_hook_table_creds', $mycred->format_creds($prefs['creds']), $id, $prefs, $atts); - - ?> - - - - - - - -
    + + + + + + + + + + $prefs ) { + + $log = $mycred->template_tags_general( $prefs['log'] ); + + $log = strip_tags( $log ); + $log = str_replace( array( '%user_id%', '%user_name%', '%user_name_en%', '%display_name%', '%user_profile_url%', '%user_profile_link%', '%user_nicename%', '%user_email%', '%user_url%', '%balance%', '%balance_f%' ), $user, $log ); + $log = str_replace( array( '%post_title%', '%post_url%', '%link_with_title%', '%post_type%' ), $post, $log ); + $log = str_replace( array( 'comment_id', 'c_post_id', 'c_post_title', 'c_post_url', 'c_link_with_title' ), $comment, $log ); + $log = str_replace( array( '%cred%', '%cred_f%' ), $amount, $log ); + $log = apply_filters( 'mycred_hook_table_log', $log, $id, $prefs, $atts ); + + $limit = ''; + if ( isset( $prefs['limit'] ) ) + $limit = $prefs['limit']; + + if( $id == "approved" ) { + if ( isset( $hooks["hook_prefs"]["comments"]["limits"] ) ) { + $approved_limits = $hooks["hook_prefs"]["comments"]["limits"]; + if( (int) $approved_limits["per_post"] > 0 && (int) $approved_limits["per_day"] > 0 ) { + + $limit = sprintf( __( 'Maximum %s times per post and Maximum %s times per day', 'mycred' ), $approved_limits["per_post"], $approved_limits["per_day"] ); + } + elseif( (int) $approved_limits["per_post"] > 0 && (int) $approved_limits["per_day"] < 1 ) { + + $limit = sprintf( __( 'Maximum %s times per post', 'mycred' ), $approved_limits["per_post"] ); + } + elseif( (int) $approved_limits["per_post"] < 1 && (int) $approved_limits["per_day"] > 0 ) { + + $limit = sprintf( __( 'Maximum %s times per day', 'mycred' ), $approved_limits["per_day"] ); + } + else { + $limit = __('No limit', 'mycred'); + } + } + } + else { + $limit = mycred_translate_limit_code( $limit, $id, $mycred ); + } + + $creds = apply_filters( 'mycred_hook_table_creds', $mycred->format_creds( $prefs['creds'] ), $id, $prefs, $atts ); + +?> + + + + + + + +
    - ' . $nothing . '

    '; - } + } + else { + echo '

    ' . $nothing . '

    '; + } - $content = ob_get_contents(); - ob_end_clean(); + $content = ob_get_contents(); + ob_end_clean(); - return apply_filters('mycred_render_hook_table', $content, $atts); + return apply_filters( 'mycred_render_hook_table', $content, $atts ); - } + } endif; -add_shortcode(MYCRED_SLUG . '_hook_table', 'mycred_render_shortcode_hook_table'); +add_shortcode( MYCRED_SLUG . '_hook_table', 'mycred_render_shortcode_hook_table' ); diff --git a/includes/shortcodes/mycred_leaderboard.php b/includes/shortcodes/mycred_leaderboard.php index 49c37c7..bba3596 100644 --- a/includes/shortcodes/mycred_leaderboard.php +++ b/includes/shortcodes/mycred_leaderboard.php @@ -1,48 +1,43 @@ 25, - 'order' => 'DESC', - 'offset' => 0, - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'based_on' => 'balance', - 'total' => 0, - 'wrap' => 'li', - 'template' => '#%position% %user_profile_link% %image% %cred_f%', - 'nothing' => 'Leaderboard is empty', - 'current' => 0, - 'exclude_zero' => 1, - 'timeframe' => '', - 'to' => '', - 'exclude' => '', - 'image' => 0 - ), $atts, MYCRED_SLUG . '_leaderboard' - ); + $args = shortcode_atts( array( + 'number' => 25, + 'order' => 'DESC', + 'offset' => 0, + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'based_on' => 'balance', + 'total' => 0, + 'wrap' => 'li', + 'template' => '#%position% %user_profile_link% %image% %cred_f%', + 'nothing' => 'Leaderboard is empty', + 'current' => 0, + 'exclude_zero' => 1, + 'timeframe' => '', + 'to' => '', + 'exclude' => '', + 'image' => 0 + ), $atts, MYCRED_SLUG . '_leaderboard' ); - // Construct the leaderboard class - $leaderboard = mycred_get_leaderboard($args); + // Construct the leaderboard class + $leaderboard = mycred_get_leaderboard( $args ); - // Just constructing the class will not yeld any results - // We need to run the query to populate the leaderboard - $leaderboard->get_leaderboard_results((bool) $args['current']); + // Just constructing the class will not yeld any results + // We need to run the query to populate the leaderboard + $leaderboard->get_leaderboard_results( (bool) $args['current'] ); - // Render and return - return do_shortcode($leaderboard->render($args, $content)); + // Render and return + return do_shortcode( $leaderboard->render( $args, $content ) ); - } + } endif; -add_shortcode(MYCRED_SLUG . '_leaderboard', 'mycred_render_shortcode_leaderboard'); +add_shortcode( MYCRED_SLUG . '_leaderboard', 'mycred_render_shortcode_leaderboard' ); diff --git a/includes/shortcodes/mycred_leaderboard_position.php b/includes/shortcodes/mycred_leaderboard_position.php index 74973c1..62e9ec9 100644 --- a/includes/shortcodes/mycred_leaderboard_position.php +++ b/includes/shortcodes/mycred_leaderboard_position.php @@ -1,52 +1,45 @@ 'current', - 'ctype' => MYCRED_DEFAULT_TYPE_KEY, - 'type' => '', - 'based_on' => 'balance', - 'total' => 0, - 'missing' => '-', - 'suffix' => 0, - 'timeframe' => '' - ), $atts, MYCRED_SLUG . '_leaderboard_position' - ); - - // Get the user ID we need a position for - $user_id = mycred_get_user_id($args['user_id']); - - // Backwards comp. - if ($args['type'] == '' ) { - $args['type'] = $args['ctype']; - } - - // Construct the leaderboard class - $leaderboard = mycred_get_leaderboard($args); - - // Query the users position - $position = $leaderboard->get_users_current_position($user_id, $args['missing']); - - if ($position != $args['missing'] && $args['suffix'] == 1 ) { - $position = mycred_ordinal_suffix($position, true); - } - - return $position; - - } +if ( ! function_exists( 'mycred_render_shortcode_leaderbaord_position' ) ) : + function mycred_render_shortcode_leaderbaord_position( $atts, $content = '' ) { + + $args = shortcode_atts( array( + 'user_id' => 'current', + 'ctype' => MYCRED_DEFAULT_TYPE_KEY, + 'type' => '', + 'based_on' => 'balance', + 'total' => 0, + 'missing' => '-', + 'suffix' => 0, + 'timeframe' => '' + ), $atts, MYCRED_SLUG . '_leaderboard_position' ); + + // Get the user ID we need a position for + $user_id = mycred_get_user_id( $args['user_id'] ); + + // Backwards comp. + if ( $args['type'] == '' ) + $args['type'] = $args['ctype']; + + // Construct the leaderboard class + $leaderboard = mycred_get_leaderboard( $args ); + + // Query the users position + $position = $leaderboard->get_users_current_position( $user_id, $args['missing'] ); + + if ( $position != $args['missing'] && $args['suffix'] == 1 ) + $position = mycred_ordinal_suffix( $position, true ); + + return $position; + + } endif; -add_shortcode(MYCRED_SLUG . '_leaderboard_position', 'mycred_render_shortcode_leaderbaord_position'); +add_shortcode( MYCRED_SLUG . '_leaderboard_position', 'mycred_render_shortcode_leaderbaord_position' ); diff --git a/includes/shortcodes/mycred_link.php b/includes/shortcodes/mycred_link.php index e39e0b3..cd53ceb 100644 --- a/includes/shortcodes/mycred_link.php +++ b/includes/shortcodes/mycred_link.php @@ -1,6 +1,5 @@ '', - 'rel' => '', - 'class' => '', - 'href' => '', - 'title' => '', - 'target' => '', - 'style' => '', - 'amount' => 0, - 'ctype' => MYCRED_DEFAULT_TYPE_KEY, - 'hreflang' => '', - 'media' => '', - 'type' => '', - 'onclick' => '' - ), $atts, MYCRED_SLUG . '_link' - ); - - // Make sure point type exists - if (! mycred_point_type_exists($atts['ctype']) ) { - $atts['ctype'] = MYCRED_DEFAULT_TYPE_KEY; - } - - // HREF is required - if (empty($atts['href']) ) { - $atts['href'] = '#'; - } - - // All links must contain the 'mycred-points-link' class - if (empty($atts['class']) ) { - $atts['class'] = 'mycred-points-link'; - } else { - $atts['class'] = 'mycred-points-link ' . $atts['class']; - } - - // If no id exists, make one - if (empty($atts['id']) ) { - $id = str_replace(array( 'http://', 'https://', 'http%3A%2F%2F', 'https%3A%2F%2F' ), 'hs', $atts['href']); - $id = str_replace(array( '/', '-', '_', ':', '.', '?', '=', '+', '\\', '%2F' ), '', $id); - $atts['id'] = $id; - } - - // Construct anchor attributes - $attr = array(); - foreach ( $atts as $attribute => $value ) { - if (! empty($value) && ! in_array($attribute, array( 'amount', 'ctype' )) ) { - $attr[] = $attribute . '="' . $value . '"'; - } - } - - // Add point type as a data attribute - $attr[] = 'data-type="' . esc_attr($atts['ctype']) . '"'; - - // Only usable for members - if (is_user_logged_in() ) { - - // If amount is zero, use the amount we set in the hooks settings - if ($atts['amount'] == 0 ) { - - // Get hook settings - $prf_hook = apply_filters('mycred_option_id', 'mycred_pref_hooks'); - $hooks = mycred_get_option($prf_hook, false); - if ($atts['ctype'] != MYCRED_DEFAULT_TYPE_KEY ) { - $hooks = mycred_get_option('mycred_pref_hooks_' . sanitize_key($atts['ctype']), false); - } - - // Apply points value - if ($hooks !== false && is_array($hooks) && array_key_exists('link_click', $hooks['hook_prefs']) ) { - $atts['amount'] = $hooks['hook_prefs']['link_click']['creds']; - } - - } - - // Add key - $token = mycred_create_token(array( $atts['amount'], $atts['ctype'], $atts['id'], urlencode($atts['href']) )); - $attr[] = 'data-token="' . $token . '"'; - - // Make sure jQuery script is called - $mycred_link_points = true; - - } - - // Return result - return apply_filters('mycred_link', '' . do_shortcode($link_title) . '', $atts, $link_title); - - } +if ( ! function_exists( 'mycred_render_shortcode_link' ) ) : + function mycred_render_shortcode_link( $atts, $link_title = '' ) { + + global $mycred_link_points; + + $atts = shortcode_atts( array( + 'id' => '', + 'rel' => '', + 'class' => '', + 'href' => '', + 'title' => '', + 'target' => '', + 'style' => '', + 'amount' => 0, + 'ctype' => MYCRED_DEFAULT_TYPE_KEY, + 'hreflang' => '', + 'media' => '', + 'type' => '', + 'onclick' => '' + ), $atts, MYCRED_SLUG . '_link' ); + + // Make sure point type exists + if ( ! mycred_point_type_exists( $atts['ctype'] ) ) + $atts['ctype'] = MYCRED_DEFAULT_TYPE_KEY; + + // HREF is required + if ( empty( $atts['href'] ) ) + $atts['href'] = '#'; + + // All links must contain the 'mycred-points-link' class + if ( empty( $atts['class'] ) ) + $atts['class'] = 'mycred-points-link'; + else + $atts['class'] = 'mycred-points-link ' . $atts['class']; + + // If no id exists, make one + if ( empty( $atts['id'] ) ) { + $id = str_replace( array( 'http://', 'https://', 'http%3A%2F%2F', 'https%3A%2F%2F' ), 'hs', $atts['href'] ); + $id = str_replace( array( '/', '-', '_', ':', '.', '?', '=', '+', '\\', '%2F' ), '', $id ); + $atts['id'] = $id; + } + + // Construct anchor attributes + $attr = array(); + foreach ( $atts as $attribute => $value ) { + if ( ! empty( $value ) && ! in_array( $attribute, array( 'amount', 'ctype' ) ) ) { + $attr[] = $attribute . '="' . $value . '"'; + } + } + + // Add point type as a data attribute + $attr[] = 'data-type="' . esc_attr( $atts['ctype'] ) . '"'; + + // Only usable for members + if ( is_user_logged_in() ) { + + // If amount is zero, use the amount we set in the hooks settings + if ( $atts['amount'] == 0 ) { + + // Get hook settings + $prf_hook = apply_filters( 'mycred_option_id', 'mycred_pref_hooks' ); + $hooks = mycred_get_option( $prf_hook, false ); + if ( $atts['ctype'] != MYCRED_DEFAULT_TYPE_KEY ) + $hooks = mycred_get_option( 'mycred_pref_hooks_' . sanitize_key( $atts['ctype'] ), false ); + + // Apply points value + if ( $hooks !== false && is_array( $hooks ) && array_key_exists( 'link_click', $hooks['hook_prefs'] ) ) { + $atts['amount'] = $hooks['hook_prefs']['link_click']['creds']; + } + + } + + // Add key + $token = mycred_create_token( array( $atts['amount'], $atts['ctype'], $atts['id'], urlencode( $atts['href'] ) ) ); + $attr[] = 'data-token="' . $token . '"'; + + // Make sure jQuery script is called + $mycred_link_points = true; + + } + + // Return result + return apply_filters( 'mycred_link', '' . do_shortcode( $link_title ) . '', $atts, $link_title ); + + } endif; -add_shortcode(MYCRED_SLUG . '_link', 'mycred_render_shortcode_link'); +add_shortcode( MYCRED_SLUG . '_link', 'mycred_render_shortcode_link' ); diff --git a/includes/shortcodes/mycred_my_balance.php b/includes/shortcodes/mycred_my_balance.php index 46455c4..943522b 100644 --- a/includes/shortcodes/mycred_my_balance.php +++ b/includes/shortcodes/mycred_my_balance.php @@ -1,105 +1,86 @@ 'current', - 'title' => '', - 'title_el' => 'h1', - 'balance_el' => 'div', - 'wrapper' => 1, - 'formatted' => 1, - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'image' => 0 - ), $atts, MYCRED_SLUG . '_my_balance' - ) - ); - - $mycred = mycred($type); - - $output = ''; - - // Not logged in - if (! is_user_logged_in() && $user_id == 'current' ) { - return $content; - } - - // Get user ID - $user_id = mycred_get_user_id($user_id); - - // Make sure we have a valid point type - if (! mycred_point_type_exists($type) ) { - $type = MYCRED_DEFAULT_TYPE_KEY; - } - - // Get the users myCRED account object - $account = mycred_get_account($user_id); - if ($account === false ) { return; - } - - // Check for exclusion - if (empty($account->balance) || ! array_key_exists($type, $account->balance) || $account->balance[ $type ] === false ) { return; - } - - $balance = $account->balance[ $type ]; - - if ($wrapper ) { - $output .= '
    '; - } - - // Title - if (! empty($title) ) { - if (! empty($title_el) ) { - $output .= '<' . $title_el . '>'; - } - - $output .= $title; - - if (! empty($title_el) ) { - $output .= ''; - } - } - - // Balance - if (! empty($balance_el) ) { - $output .= '<' . $balance_el . '>'; - } - - //Image - if($image && $mycred->image_url) { - $output .= ""; - } - - if ($formatted ) { - $output .= $balance->point_type->format($balance->current); - } else { - $output .= $balance->point_type->number($balance->current); - } - - if (! empty($balance_el) ) { - $output .= ''; - } - - if ($wrapper ) { - $output .= '
    '; - } - - return $output; - - } +if ( ! function_exists( 'mycred_render_shortcode_my_balance' ) ) : + function mycred_render_shortcode_my_balance( $atts, $content = '' ) { + + extract( shortcode_atts( array( + 'user_id' => 'current', + 'title' => '', + 'title_el' => 'h1', + 'balance_el' => 'div', + 'wrapper' => 1, + 'formatted' => 1, + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'image' => 0 + ), $atts, MYCRED_SLUG . '_my_balance' ) ); + + $mycred = mycred( $type ); + + $output = ''; + + // Not logged in + if ( ! is_user_logged_in() && $user_id == 'current' ) + return $content; + + // Get user ID + $user_id = mycred_get_user_id( $user_id ); + + // Make sure we have a valid point type + if ( ! mycred_point_type_exists( $type ) ) + $type = MYCRED_DEFAULT_TYPE_KEY; + + // Get the users myCRED account object + $account = mycred_get_account( $user_id ); + if ( $account === false ) return; + + // Check for exclusion + if ( empty( $account->balance ) || ! array_key_exists( $type, $account->balance ) || $account->balance[ $type ] === false ) return; + + $balance = $account->balance[ $type ]; + + if ( $wrapper ) + $output .= '
    '; + + // Title + if ( ! empty( $title ) ) { + if ( ! empty( $title_el ) ) + $output .= '<' . $title_el . '>'; + + $output .= $title; + + if ( ! empty( $title_el ) ) + $output .= ''; + } + + // Balance + if ( ! empty( $balance_el ) ) + $output .= '<' . $balance_el . '>'; + + //Image + if( $image && $mycred->image_url) + $output .= ""; + + if ( $formatted ) + $output .= $balance->point_type->format( $balance->current ); + else + $output .= $balance->point_type->number( $balance->current ); + + if ( ! empty( $balance_el ) ) + $output .= ''; + + if ( $wrapper ) + $output .= '
    '; + + return $output; + + } endif; -add_shortcode(MYCRED_SLUG . '_my_balance', 'mycred_render_shortcode_my_balance'); +add_shortcode( MYCRED_SLUG . '_my_balance', 'mycred_render_shortcode_my_balance' ); diff --git a/includes/shortcodes/mycred_my_balance_converted.php b/includes/shortcodes/mycred_my_balance_converted.php index 45ed6d2..6930b3f 100644 --- a/includes/shortcodes/mycred_my_balance_converted.php +++ b/includes/shortcodes/mycred_my_balance_converted.php @@ -1,154 +1,144 @@ MYCRED_DEFAULT_TYPE_KEY, - 'rate' => 1, - 'prefix' => '', - 'suffix' => '', - 'decimal' => 1, - 'timeframe' => '' - ), $atts, MYCRED_SLUG . '_my_balance_converted' - ) - ); + extract( shortcode_atts( array( + 'ctype' => MYCRED_DEFAULT_TYPE_KEY, + 'rate' => 1, + 'prefix' => '', + 'suffix' => '', + 'decimal' => 1, + 'timeframe' => '' + ), $atts, MYCRED_SLUG . '_my_balance_converted' ) ); - $output = ''; + $output = ''; - $timeframe_balance = ''; + $timeframe_balance = ''; - // Not logged in - if (! is_user_logged_in() ) { - return $content; - } + // Not logged in + if ( ! is_user_logged_in() ) + return $content; - // Get user ID - $user_id = mycred_get_user_id(get_current_user_id()); + // Get user ID + $user_id = mycred_get_user_id( get_current_user_id() ); - // Make sure we have a valid point type - if (! mycred_point_type_exists($ctype) ) { - $ctype = MYCRED_DEFAULT_TYPE_KEY; - } + // Make sure we have a valid point type + if ( ! mycred_point_type_exists( $ctype ) ) + $ctype = MYCRED_DEFAULT_TYPE_KEY; - // Get the users myCRED account object - $account = mycred_get_account($user_id); - if ($account === false ) { return; - } + // Get the users myCRED account object + $account = mycred_get_account( $user_id ); + if ( $account === false ) return; - // Check for exclusion - if (empty($account->balance) || ! array_key_exists($ctype, $account->balance) || $account->balance[ $ctype ] === false ) { return; - } + // Check for exclusion + if ( empty( $account->balance ) || ! array_key_exists( $ctype, $account->balance ) || $account->balance[ $ctype ] === false ) return; - if(empty($timeframe) ) { - $balance = $account->balance[ $ctype ]; - } else { - $timeframe_balance = mycred_my_bc_get_balance($user_id, $timeframe, $ctype); - } + if( empty( $timeframe ) ) + $balance = $account->balance[ $ctype ]; + else + $timeframe_balance = mycred_my_bc_get_balance( $user_id, $timeframe, $ctype ); - $output = '
    '; + $output = '
    '; - if (! empty($prefix) ) { - $output .= ''.esc_attr($prefix).''; - } + if ( ! empty( $prefix ) ) + $output .= ''.esc_attr( $prefix ).''; - if(floatval($rate) == 0 ) { $rate = 1; - } + if( floatval( $rate ) == 0 ) $rate = 1; - $converted_balance = floatval(empty($timeframe) ? $balance->current : $timeframe_balance) * floatval($rate); + $converted_balance = floatval( empty( $timeframe ) ? $balance->current : $timeframe_balance ) * floatval( $rate ); - $output .= number_format($converted_balance, intval($decimal), '.', ''); + $output .= number_format( $converted_balance, intval( $decimal ), '.', '' ); - if (! empty($suffix) ) { - $output .= ''.esc_attr($suffix).''; - } + if ( ! empty( $suffix ) ) + $output .= ''.esc_attr( $suffix ).''; - $output .= '
    '; + $output .= '
    '; - return $output; + return $output; - } + } endif; -add_shortcode(MYCRED_SLUG . '_my_balance_converted', 'mycred_render_shortcode_my_balance_converted'); - -if(!function_exists('mycred_my_bc_get_balance') ) : - function mycred_my_bc_get_balance( $user_id, $timeframe, $ctype ) - { - global $wpdb, $mycred_log_table; - - //Current Timestamp - $timestamp = time(); - - //Current day end time - $end_day = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 23:59:59'))->getTimestamp(); - - $day_start = ''; - $day_end = ''; - - - if($timeframe == 'today' ) { - $day_start = DateTime::createFromFormat('Y-m-d H:i:s', ( new DateTime() )->setTimestamp($timestamp)->format('Y-m-d 00:00:00'))->getTimestamp(); - } - - if($timeframe == 'yesterday' ) { - $timestamp = strtotime('-1 day', $timestamp); - - $day_start = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 00:00:00'))->getTimestamp(); - - $end_day = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 23:59:59'))->getTimestamp(); - } - - if($timeframe == 'this-week' ) { - $week_day = apply_filters('mycred_my_bc_last_week_day', 'sunday'); - - $day_start = strtotime("{$week_day} last week", $timestamp); - } - - if($timeframe == 'this-month' ) { - $day_start = strtotime("first day of this month", $timestamp); - - $day_start = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($day_start)->format('Y-m-d 00:00:00'))->getTimestamp(); - } - - if($timeframe == 'last-month' ) { - $day_start = strtotime("first day of -1 month", $timestamp); - - $end_day = strtotime("last day of -1 month", $timestamp); - - $day_start = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($day_start)->format('Y-m-d 00:00:00'))->getTimestamp(); - - $end_day = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($end_day)->format('Y-m-d 23:59:59'))->getTimestamp(); - } - - - - $balance = $wpdb->get_var( - $wpdb->prepare( - "SELECT SUM(creds) +add_shortcode( MYCRED_SLUG . '_my_balance_converted', 'mycred_render_shortcode_my_balance_converted' ); + +if( !function_exists( 'mycred_my_bc_get_balance' ) ): +function mycred_my_bc_get_balance( $user_id, $timeframe, $ctype ) +{ + global $wpdb, $mycred_log_table; + + //Current Timestamp + $timestamp = time(); + + //Current day end time + $end_day = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 23:59:59'))->getTimestamp(); + + $day_start = ''; + $day_end = ''; + + + if( $timeframe == 'today' ) + { + $day_start = DateTime::createFromFormat( 'Y-m-d H:i:s', ( new DateTime() )->setTimestamp( $timestamp )->format( 'Y-m-d 00:00:00' ) )->getTimestamp(); + } + + if( $timeframe == 'yesterday' ) + { + $timestamp = strtotime( '-1 day', $timestamp ); + + $day_start = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 00:00:00'))->getTimestamp(); + + $end_day = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 23:59:59'))->getTimestamp(); + } + + if( $timeframe == 'this-week' ) + { + $week_day = apply_filters( 'mycred_my_bc_last_week_day', 'sunday' ); + + $day_start = strtotime( "{$week_day} last week", $timestamp ); + } + + if( $timeframe == 'this-month' ) + { + $day_start = strtotime( "first day of this month", $timestamp ); + + $day_start = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($day_start)->format('Y-m-d 00:00:00'))->getTimestamp(); + } + + if( $timeframe == 'last-month' ) + { + $day_start = strtotime( "first day of -1 month", $timestamp ); + + $end_day = strtotime( "last day of -1 month", $timestamp ); + + $day_start = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($day_start)->format('Y-m-d 00:00:00'))->getTimestamp(); + + $end_day = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($end_day)->format('Y-m-d 23:59:59'))->getTimestamp(); + } + + + + $balance = $wpdb->get_var( + $wpdb->prepare( + "SELECT SUM(creds) FROM {$mycred_log_table} WHERE `user_id` = %d AND `ctype` = %s AND `time` BETWEEN %d AND %d", - $user_id, - $ctype, - $day_start, - $end_day - ) - ); - - return $balance; - } -endif; + $user_id, + $ctype, + $day_start, + $end_day + ) + ); + + return $balance; +} +endif; \ No newline at end of file diff --git a/includes/shortcodes/mycred_referral_stats.php b/includes/shortcodes/mycred_referral_stats.php index ad5b296..5e43053 100644 --- a/includes/shortcodes/mycred_referral_stats.php +++ b/includes/shortcodes/mycred_referral_stats.php @@ -1,61 +1,51 @@ MYCRED_DEFAULT_TYPE_KEY - - ), $atts, MYCRED_SLUG . '_referral' - ) - ); - - $hooks = mycred_get_option('mycred_pref_hooks', false); - - if ($ctype != MYCRED_DEFAULT_TYPE_KEY ) { - $hooks = mycred_get_option('mycred_pref_hooks_' . sanitize_key($ctype), false); - } - $active = $hooks['active']; - if(is_array($active) && in_array('affiliate', $active)) { - - $visit = $hooks['hook_prefs']['affiliate']['visit']; - $signup = $hooks['hook_prefs']['affiliate']['signup']; - - $output = ''; - - $user_id = get_current_user_id(); - - $output .= ''; - - // Show Visitor referral count - if ($visit['creds'] != 0 ) { - $output .= sprintf('', __('Visitors Referred', 'mycred'), mycred_count_ref_instances('visitor_referral', $user_id, $ctype)); - } - - // Show Signup referral count - if ($signup['creds'] != 0 ) { - $output .= sprintf('', __('Signups Referred', 'mycred'), mycred_count_ref_instances('signup_referral', $user_id, $ctype)); - } - - $output .= '
    %s%s
    '; - return $output; - } - } +if ( ! function_exists( 'mycred_referral_front' ) ) : + function mycred_referral_front( $atts ){ + + extract( shortcode_atts( array( + + 'ctype' => MYCRED_DEFAULT_TYPE_KEY + + ), $atts, MYCRED_SLUG . '_referral' ) ); + + $hooks = mycred_get_option( 'mycred_pref_hooks', false ); + + if ( $ctype != MYCRED_DEFAULT_TYPE_KEY ) + $hooks = mycred_get_option( 'mycred_pref_hooks_' . sanitize_key( $ctype ), false ); + $active = $hooks['active']; + if( is_array( $active) && in_array( 'affiliate' , $active )){ + + $visit = $hooks['hook_prefs']['affiliate']['visit']; + $signup = $hooks['hook_prefs']['affiliate']['signup']; + + $output = ''; + + $user_id = get_current_user_id(); + + $output .= ''; + + // Show Visitor referral count + if ( $visit['creds'] != 0 ) + $output .= sprintf( '', __( 'Visitors Referred', 'mycred' ), mycred_count_ref_instances( 'visitor_referral', $user_id, $ctype ) ); + + // Show Signup referral count + if ( $signup['creds'] != 0 ) + $output .= sprintf( '', __( 'Signups Referred', 'mycred' ), mycred_count_ref_instances( 'signup_referral', $user_id, $ctype ) ); + + $output .= '
    %s%s
    '; + return $output; + } + } endif; -add_shortcode(MYCRED_SLUG . '_referral_stats', 'mycred_referral_front'); +add_shortcode( MYCRED_SLUG . '_referral_stats' , 'mycred_referral_front' ); \ No newline at end of file diff --git a/includes/shortcodes/mycred_send.php b/includes/shortcodes/mycred_send.php index c24b215..ae7b6c3 100644 --- a/includes/shortcodes/mycred_send.php +++ b/includes/shortcodes/mycred_send.php @@ -1,188 +1,164 @@ 0, - 'to' => '', - 'log' => '', - 'ref' => 'gift', - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'class' => 'button button-primary btn btn-primary', - 'reload' => 0 - ), $atts, MYCRED_SLUG . '_send' - ) - ); + extract( shortcode_atts( array( + 'amount' => 0, + 'to' => '', + 'log' => '', + 'ref' => 'gift', + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'class' => 'button button-primary btn btn-primary', + 'reload' => 0 + ), $atts, MYCRED_SLUG . '_send' ) ); - if (! mycred_point_type_exists($type) ) { return 'Point type not found.'; - } + if ( ! mycred_point_type_exists( $type ) ) return 'Point type not found.'; - global $post; + global $post; - // Send points to the post author (assuming this shortcode is used inside the loop) - $to = mycred_get_user_id($to); + // Send points to the post author (assuming this shortcode is used inside the loop) + $to = mycred_get_user_id( $to ); - // We will not render for ourselves. - $user_id = get_current_user_id(); - $recipient = absint($to); - if ($recipient === $user_id || $recipient === 0 ) { return; - } + // We will not render for ourselves. + $user_id = get_current_user_id(); + $recipient = absint( $to ); + if ( $recipient === $user_id || $recipient === 0 ) return; - global $mycred_sending_points; + global $mycred_sending_points; - $mycred_sending_points = false; + $mycred_sending_points = false; - $mycred = mycred($type); + $mycred = mycred( $type ); - // Make sure current user or recipient is not excluded! - if ($mycred->exclude_user($recipient) || $mycred->exclude_user($user_id) ) { return; - } + // Make sure current user or recipient is not excluded! + if ( $mycred->exclude_user( $recipient ) || $mycred->exclude_user( $user_id ) ) return; - $account_limit = $mycred->number(apply_filters('mycred_transfer_acc_limit', 0)); - $balance = $mycred->get_users_balance($user_id, $type); - $amount = $mycred->number($amount); + $account_limit = $mycred->number( apply_filters( 'mycred_transfer_acc_limit', 0 ) ); + $balance = $mycred->get_users_balance( $user_id, $type ); + $amount = $mycred->number( $amount ); - // Insufficient Funds - if ($balance-$amount < $account_limit ) { return; - } + // Insufficient Funds + if ( $balance-$amount < $account_limit ) return; - // We are ready! - $mycred_sending_points = true; + // We are ready! + $mycred_sending_points = true; - if ($class != '' ) { - $class = ' ' . sanitize_text_field($class); - } + if ( $class != '' ) + $class = ' ' . sanitize_text_field( $class ); - $reload = absint($reload); + $reload = absint( $reload ); - $render = ''; + $render = ''; - return apply_filters('mycred_send', $render, $atts, $content); + return apply_filters( 'mycred_send', $render, $atts, $content ); - } + } endif; -add_shortcode(MYCRED_SLUG . '_send', 'mycred_render_shortcode_send'); +add_shortcode( MYCRED_SLUG . '_send', 'mycred_render_shortcode_send' ); /** * myCRED Send Points Ajax - * - * @since 0.1 + * @since 0.1 * @version 1.4.1 */ -if (! function_exists('mycred_shortcode_send_points_ajax') ) : - function mycred_shortcode_send_points_ajax() - { - - // Security - check_ajax_referer('mycred-send-points', 'token'); - - $user_id = get_current_user_id(); - - if (mycred_force_singular_session($user_id, 'mycred-last-send') ) { - wp_send_json('error'); - } - - $point_type = MYCRED_DEFAULT_TYPE_KEY; - if (isset($_POST['type']) ) { - $point_type = sanitize_text_field($_POST['type']); - } - - // Make sure the type exists - if (! mycred_point_type_exists($point_type) ) { die(); - } - - // Prep - $recipient = (int) sanitize_text_field($_POST['recipient']); - $reference = sanitize_text_field($_POST['reference']); - $log_entry = strip_tags(trim($_POST['log']), ''); - - // No sending to ourselves - if ($user_id == $recipient ) { - wp_send_json('error'); - } - - $mycred = mycred($point_type); - - // Prep amount - $amount = sanitize_text_field($_POST['amount']); - $amount = $mycred->number(abs($amount)); - - // Check solvency - $account_limit = $mycred->number(apply_filters('mycred_transfer_acc_limit', $mycred->zero())); - $balance = $mycred->get_users_balance($user_id, $point_type); - $new_balance = $balance-$amount; - - $data = array( 'ref_type' => 'user' ); - - // Insufficient Funds - if ($new_balance < $account_limit ) { - die(); - } - - // After this transfer our account will reach zero - elseif ($new_balance == $account_limit ) { - $reply = 'zero'; - } - - // Check if this is the last time we can do these kinds of amounts - elseif ($new_balance - $amount < $account_limit ) { - $reply = 'minus'; - } - - // Else everything is fine - else { - $reply = 'done'; - } - - // First deduct points - if ($mycred->add_creds( - $reference, - $user_id, - 0 - $amount, - $log_entry, - $recipient, - $data, - $point_type - ) - ) { - - // Then add to recipient - $mycred->add_creds( - $reference, - $recipient, - $amount, - $log_entry, - $user_id, - $data, - $point_type - ); - - } - else { - $reply = 'error'; - } - - // Share the good news - wp_send_json($reply); - - } +if ( ! function_exists( 'mycred_shortcode_send_points_ajax' ) ) : + function mycred_shortcode_send_points_ajax() { + + // Security + check_ajax_referer( 'mycred-send-points', 'token' ); + + $user_id = get_current_user_id(); + + if ( mycred_force_singular_session( $user_id, 'mycred-last-send' ) ) + wp_send_json( 'error' ); + + $point_type = MYCRED_DEFAULT_TYPE_KEY; + if ( isset( $_POST['type'] ) ) + $point_type = sanitize_text_field( $_POST['type'] ); + + // Make sure the type exists + if ( ! mycred_point_type_exists( $point_type ) ) die(); + + // Prep + $recipient = (int) sanitize_text_field( $_POST['recipient'] ); + $reference = sanitize_text_field( $_POST['reference'] ); + $log_entry = strip_tags( trim( $_POST['log'] ), '' ); + + // No sending to ourselves + if ( $user_id == $recipient ) + wp_send_json( 'error' ); + + $mycred = mycred( $point_type ); + + // Prep amount + $amount = sanitize_text_field( $_POST['amount'] ); + $amount = $mycred->number( abs( $amount ) ); + + // Check solvency + $account_limit = $mycred->number( apply_filters( 'mycred_transfer_acc_limit', $mycred->zero() ) ); + $balance = $mycred->get_users_balance( $user_id, $point_type ); + $new_balance = $balance-$amount; + + $data = array( 'ref_type' => 'user' ); + + // Insufficient Funds + if ( $new_balance < $account_limit ) + die(); + + // After this transfer our account will reach zero + elseif ( $new_balance == $account_limit ) + $reply = 'zero'; + + // Check if this is the last time we can do these kinds of amounts + elseif ( $new_balance - $amount < $account_limit ) + $reply = 'minus'; + + // Else everything is fine + else + $reply = 'done'; + + // First deduct points + if ( $mycred->add_creds( + $reference, + $user_id, + 0 - $amount, + $log_entry, + $recipient, + $data, + $point_type + ) ) { + + // Then add to recipient + $mycred->add_creds( + $reference, + $recipient, + $amount, + $log_entry, + $user_id, + $data, + $point_type + ); + + } + else { + $reply = 'error'; + } + + // Share the good news + wp_send_json( $reply ); + + } endif; -add_action('wp_ajax_mycred-send-points', 'mycred_shortcode_send_points_ajax'); +add_action( 'wp_ajax_mycred-send-points', 'mycred_shortcode_send_points_ajax' ); diff --git a/includes/shortcodes/mycred_show_if.php b/includes/shortcodes/mycred_show_if.php index bfc1185..98dca58 100644 --- a/includes/shortcodes/mycred_show_if.php +++ b/includes/shortcodes/mycred_show_if.php @@ -1,141 +1,122 @@ -1, - 'rank' => -1, - 'ref' => '', - 'count' => -1, - 'ctype' => MYCRED_DEFAULT_TYPE_KEY, - 'visitors' => '', - 'comp' => 'AND', - 'user_id' => 'current' - ), $atts, MYCRED_SLUG . '_show_if' - ) - ); + extract( shortcode_atts( array( + 'balance' => -1, + 'rank' => -1, + 'ref' => '', + 'count' => -1, + 'ctype' => MYCRED_DEFAULT_TYPE_KEY, + 'visitors' => '', + 'comp' => 'AND', + 'user_id' => 'current' + ), $atts, MYCRED_SLUG . '_show_if' ) ); - // Visitors - if (! is_user_logged_in() ) { + // Visitors + if ( ! is_user_logged_in() ) { - if ($visitors != '' ) { return $visitors; - } + if ( $visitors != '' ) return $visitors; - return; + return; - } + } - // Get the user ID - $user_id = mycred_get_user_id($user_id); + // Get the user ID + $user_id = mycred_get_user_id( $user_id ); - // You can only use AND or OR for comparisons - if (! in_array($comp, array( 'AND', 'OR' )) ) { - $comp = 'AND'; - } + // You can only use AND or OR for comparisons + if ( ! in_array( $comp, array( 'AND', 'OR' ) ) ) + $comp = 'AND'; - // Make sure the point type we nominated exists - if (! mycred_point_type_exists($ctype) ) { return 'invalid point type'; - } + // Make sure the point type we nominated exists + if ( ! mycred_point_type_exists( $ctype ) ) return 'invalid point type'; - // Load myCRED with the requested point type - $mycred = mycred($ctype); + // Load myCRED with the requested point type + $mycred = mycred( $ctype ); - // Make sure user is not excluded - if ($mycred->exclude_user($user_id) ) { return; - } + // Make sure user is not excluded + if ( $mycred->exclude_user( $user_id ) ) return; - // Lets start determening if the user can see the content - $should_show = false; + // Lets start determening if the user can see the content + $should_show = false; - // Balance related requirement - if ($balance >= 0 ) { + // Balance related requirement + if ( $balance >= 0 ) { - $users_balance = $mycred->get_users_balance($user_id, $ctype); - $balance = $mycred->number($balance); + $users_balance = $mycred->get_users_balance( $user_id, $ctype ); + $balance = $mycred->number( $balance ); - // Zero balance requirement - if ($balance == $mycred->zero() && $users_balance == $mycred->zero() ) { - $should_show = true; - } + // Zero balance requirement + if ( $balance == $mycred->zero() && $users_balance == $mycred->zero() ) + $should_show = true; - // Balance must be higher or equal to the amount set - elseif ($users_balance >= $balance ) { - $should_show = true; - } + // Balance must be higher or equal to the amount set + elseif ( $users_balance >= $balance ) + $should_show = true; - } + } - // Reference related requirement - if (MYCRED_ENABLE_LOGGING && strlen($ref) > 0 ) { + // Reference related requirement + if ( MYCRED_ENABLE_LOGGING && strlen( $ref ) > 0 ) { - $ref_count = mycred_count_ref_instances($ref, $user_id, $ctype); + $ref_count = mycred_count_ref_instances( $ref, $user_id, $ctype ); - // Combined with a balance requirement we must have references - if ($balance >= 0 && $ref_count == 0 && $comp === 'AND' ) { - $should_show = false; - } + // Combined with a balance requirement we must have references + if ( $balance >= 0 && $ref_count == 0 && $comp === 'AND' ) + $should_show = false; - // Ref count must be higher or equal to the count set - elseif ($ref_count >= $count ) { - $should_show = true; - } + // Ref count must be higher or equal to the count set + elseif ( $ref_count >= $count ) + $should_show = true; - } + } - // Rank related requirement - if ($rank !== -1 && function_exists('mycred_get_users_rank') ) { + // Rank related requirement + if ( $rank !== -1 && function_exists( 'mycred_get_users_rank' ) ) { - $rank_id = mycred_get_rank_object_id($rank); + $rank_id = mycred_get_rank_object_id( $rank ); - // Rank ID provided - if (is_numeric($rank) ) { - $users_rank = mycred_get_users_rank($user_id, $ctype); - } + // Rank ID provided + if ( is_numeric( $rank ) ) + $users_rank = mycred_get_users_rank( $user_id, $ctype ); - // Rank title provided - else { - $users_rank = mycred_get_users_rank($user_id, $ctype); - } + // Rank title provided + else + $users_rank = mycred_get_users_rank( $user_id, $ctype ); - if (isset($users_rank->post_id) && $rank_id !== false ) { + if ( isset( $users_rank->post_id ) && $rank_id !== false ) { - if ($users_rank->post_id != $rank_id && $comp === 'AND' ) { - $should_show = false; + if ( $users_rank->post_id != $rank_id && $comp === 'AND' ) + $should_show = false; - } elseif ($users_rank->post_id == $rank_id ) { - $should_show = true; - } + elseif ( $users_rank->post_id == $rank_id ) + $should_show = true; - } + } - } + } - // Allow others to play - $should_show = apply_filters('mycred_show_if', $should_show, $user_id, $atts, $content); + // Allow others to play + $should_show = apply_filters( 'mycred_show_if', $should_show, $user_id, $atts, $content ); - // Sorry, no show - if ($should_show !== true ) { return; - } + // Sorry, no show + if ( $should_show !== true ) return; - $content = '
    ' . $content . '
    '; + $content = '
    ' . $content . '
    '; - // Return content - return do_shortcode(apply_filters('mycred_show_if_render', $content, $user_id, $atts, $content)); + // Return content + return do_shortcode( apply_filters( 'mycred_show_if_render', $content, $user_id, $atts, $content ) ); - } + } endif; -add_shortcode(MYCRED_SLUG . '_show_if', 'mycred_render_shortcode_show_if'); +add_shortcode( MYCRED_SLUG . '_show_if', 'mycred_render_shortcode_show_if' ); diff --git a/includes/shortcodes/mycred_total_balance.php b/includes/shortcodes/mycred_total_balance.php index 5763145..a8b9de1 100644 --- a/includes/shortcodes/mycred_total_balance.php +++ b/includes/shortcodes/mycred_total_balance.php @@ -1,102 +1,87 @@ 'current', - 'types' => MYCRED_DEFAULT_TYPE_KEY, - 'raw' => 0, - 'total' => 0 - ), $atts, MYCRED_SLUG . '_total_balance' - ) - ); + extract( shortcode_atts( array( + 'user_id' => 'current', + 'types' => MYCRED_DEFAULT_TYPE_KEY, + 'raw' => 0, + 'total' => 0 + ), $atts, MYCRED_SLUG . '_total_balance' ) ); - // If user ID is not set, get the current users ID - if (! is_user_logged_in() && $user_id == 'current' ) { - return $content; - } + // If user ID is not set, get the current users ID + if ( ! is_user_logged_in() && $user_id == 'current' ) + return $content; - $user_id = mycred_get_user_id($user_id); + $user_id = mycred_get_user_id( $user_id ); - // Get the users myCRED account object - $account = mycred_get_account($user_id); - if ($account === false ) { return; - } + // Get the users myCRED account object + $account = mycred_get_account( $user_id ); + if ( $account === false ) return; - // Check for exclusion - if (empty($account->balance) ) { return; - } + // Check for exclusion + if ( empty( $account->balance ) ) return; - // Assume we want all balances added up - $point_types = $account->point_types; + // Assume we want all balances added up + $point_types = $account->point_types; - // If we set types="" to either one or a comma separared list of type keys - if (! empty($types) && $types != 'all' ) { + // If we set types="" to either one or a comma separared list of type keys + if ( ! empty( $types ) && $types != 'all' ) { - $types_to_addup = array(); - foreach ( explode(',', $types) as $type_key ) { + $types_to_addup = array(); + foreach ( explode( ',', $types ) as $type_key ) { - $type_key = sanitize_text_field($type_key); - if (! array_key_exists($type_key, $account->balance) ) { continue; - } + $type_key = sanitize_text_field( $type_key ); + if ( ! array_key_exists( $type_key, $account->balance ) ) continue; - if (! in_array($type_key, $types_to_addup) ) { - $types_to_addup[] = $type_key; - } + if ( ! in_array( $type_key, $types_to_addup ) ) + $types_to_addup[] = $type_key; - } - $point_types = $types_to_addup; + } + $point_types = $types_to_addup; - } + } - // Lets add up - $balance_sum = 0; - if (! empty($point_types) ) { - foreach ( $point_types as $type_key ) { + // Lets add up + $balance_sum = 0; + if ( ! empty( $point_types ) ) { + foreach ( $point_types as $type_key ) { - $balance = $account->balance[ $type_key ]; - if ($balance === false ) { continue; - } + $balance = $account->balance[ $type_key ]; + if ( $balance === false ) continue; - if ($total == 1 ) { - $balance_sum += $balance->accumulated; - } else { - $balance_sum += $balance->current; - } + if ( $total == 1 ) + $balance_sum += $balance->accumulated; + else + $balance_sum += $balance->current; - } - } + } + } - // If we only added up one, we can format (if set) - if (count($point_types) == 1 ) { + // If we only added up one, we can format (if set) + if ( count( $point_types ) == 1 ) { - $point_type = $account->balance[ $types_to_addup[0] ]->point_type; + $point_type = $account->balance[ $types_to_addup[0] ]->point_type; - // Format requested - if (! $raw && ! empty($point_type) ) { - $balance_sum = $point_type->format($balance_sum); - } + // Format requested + if ( ! $raw && ! empty( $point_type ) ) + $balance_sum = $point_type->format( $balance_sum ); - } + } - return apply_filters('mycred_total_balances_output', $balance_sum, $atts); + return apply_filters( 'mycred_total_balances_output', $balance_sum, $atts ); - } + } endif; -add_shortcode(MYCRED_SLUG . '_total_balance', 'mycred_render_shortcode_total'); +add_shortcode( MYCRED_SLUG . '_total_balance', 'mycred_render_shortcode_total' ); diff --git a/includes/shortcodes/mycred_total_points.php b/includes/shortcodes/mycred_total_points.php index a46af3f..3b46f00 100644 --- a/includes/shortcodes/mycred_total_points.php +++ b/includes/shortcodes/mycred_total_points.php @@ -1,106 +1,91 @@ MYCRED_DEFAULT_TYPE_KEY, - 'ref' => '', - 'ref_id' => '', - 'user_id' => 'current', - 'formatted' => 1 - ), $atts, MYCRED_SLUG . '_total_points' - ) - ); + extract( shortcode_atts( array( + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'ref' => '', + 'ref_id' => '', + 'user_id' => 'current', + 'formatted' => 1 + ), $atts, MYCRED_SLUG . '_total_points' ) ); - if (! mycred_point_type_exists($type) ) { - $type = MYCRED_DEFAULT_TYPE_KEY; - } + if ( ! mycred_point_type_exists( $type ) ) + $type = MYCRED_DEFAULT_TYPE_KEY; - $user_id = mycred_get_user_id($user_id); - $mycred = mycred($type); + $user_id = mycred_get_user_id( $user_id ); + $mycred = mycred( $type ); - global $wpdb, $mycred_log_table; + global $wpdb, $mycred_log_table; - // Simple - if ($ref == '' && $ref_id == '' && $user_id == '' ) { + // Simple + if ( $ref == '' && $ref_id == '' && $user_id == '' ) { - // Add up all balances - $total = $wpdb->get_var($wpdb->prepare("SELECT SUM( meta_value ) FROM {$wpdb->usermeta} WHERE meta_key = %s", mycred_get_meta_key($type))); + // Add up all balances + $total = $wpdb->get_var( $wpdb->prepare( "SELECT SUM( meta_value ) FROM {$wpdb->usermeta} WHERE meta_key = %s", mycred_get_meta_key( $type ) ) ); - } + } - // Complex - else { + // Complex + else { - $wheres = array(); - $wheres[] = $wpdb->prepare("ctype = %s", mycred_get_meta_key($type)); + $wheres = array(); + $wheres[] = $wpdb->prepare( "ctype = %s", mycred_get_meta_key( $type ) ); - if (strlen($ref) > 0 ) { + if ( strlen( $ref ) > 0 ) { - // Either we have just one reference - $multiple = explode(',', $ref); - if (count($multiple) == 1 ) { - $wheres[] = $wpdb->prepare("ref = %s", $ref); - } + // Either we have just one reference + $multiple = explode( ',', $ref ); + if ( count( $multiple ) == 1 ) + $wheres[] = $wpdb->prepare( "ref = %s", $ref ); - // Or a comma seperated list of references - else { + // Or a comma seperated list of references + else { - $_clean = array(); - foreach ( $multiple as $ref ) { - $ref = sanitize_key($ref); - if (strlen($ref) > 0 ) { - $_clean[] = $ref; - } - } + $_clean = array(); + foreach ( $multiple as $ref ) { + $ref = sanitize_key( $ref ); + if ( strlen( $ref ) > 0 ) + $_clean[] = $ref; + } - if (! empty($_clean) ) { - $wheres[] = "ref IN ( '" . implode("', '", $_clean) . "' )"; - } + if ( ! empty( $_clean ) ) + $wheres[] = "ref IN ( '" . implode( "', '", $_clean ) . "' )"; - } + } - } + } - $ref_id = absint($ref_id); - if ($ref_id > 0 ) { - $wheres[] = $wpdb->prepare("ref_id = %d", $ref_id); - } + $ref_id = absint( $ref_id ); + if ( $ref_id > 0 ) + $wheres[] = $wpdb->prepare( "ref_id = %d", $ref_id ); - $user_id = absint($user_id); - if ($user_id != '' && $user_id != 0 ) { - $wheres[] = $wpdb->prepare("user_id = %d", $user_id); - } + $user_id = absint( $user_id ); + if ( $user_id != '' && $user_id != 0 ) + $wheres[] = $wpdb->prepare( "user_id = %d", $user_id ); - $wheres = implode(" AND ", $wheres); - $total = $wpdb->get_var("SELECT SUM( creds ) FROM {$mycred_log_table} WHERE {$wheres};"); + $wheres = implode( " AND ", $wheres ); + $total = $wpdb->get_var( "SELECT SUM( creds ) FROM {$mycred_log_table} WHERE {$wheres};" ); - } + } - if ($total === null ) { - $total = 0; - } + if ( $total === NULL ) + $total = 0; - if ($formatted == 1 ) { - return $mycred->format_creds($total); - } + if ( $formatted == 1 ) + return $mycred->format_creds( $total ); - return $total; + return $total; - } + } endif; -add_shortcode(MYCRED_SLUG . '_total_points', 'mycred_render_shortcode_total_points'); +add_shortcode( MYCRED_SLUG . '_total_points', 'mycred_render_shortcode_total_points' ); diff --git a/includes/shortcodes/mycred_total_since.php b/includes/shortcodes/mycred_total_since.php index a5f9645..78749a1 100644 --- a/includes/shortcodes/mycred_total_since.php +++ b/includes/shortcodes/mycred_total_since.php @@ -1,48 +1,38 @@ 'today', - 'until' => 'now', - 'type' => MYCRED_DEFAULT_TYPE_KEY, - 'ref' => '', - 'user_id' => 'current', - 'formatted' => 1 - ), $atts, MYCRED_SLUG . '_total_since' - ) - ); - - if (! mycred_point_type_exists($type) ) { - $type = MYCRED_DEFAULT_TYPE_KEY; - } - - if ($ref == '' ) { $ref = null; - } - - $user_id = mycred_get_user_id($user_id); - $mycred = mycred($type); - $total = mycred_get_total_by_time($from, $until, $ref, $user_id, $type); - - if (substr($total, 0, 7) != 'Invalid' && $formatted == 1 ) { - $total = $mycred->format_creds($total); - } - - return $total; - - } +if ( ! function_exists( 'mycred_render_shortcode_total_since' ) ) : + function mycred_render_shortcode_total_since( $atts, $content = '' ) { + + extract( shortcode_atts( array( + 'from' => 'today', + 'until' => 'now', + 'type' => MYCRED_DEFAULT_TYPE_KEY, + 'ref' => '', + 'user_id' => 'current', + 'formatted' => 1 + ), $atts, MYCRED_SLUG . '_total_since' ) ); + + if ( ! mycred_point_type_exists( $type ) ) + $type = MYCRED_DEFAULT_TYPE_KEY; + + if ( $ref == '' ) $ref = NULL; + + $user_id = mycred_get_user_id( $user_id ); + $mycred = mycred( $type ); + $total = mycred_get_total_by_time( $from, $until, $ref, $user_id, $type ); + + if ( substr( $total, 0, 7 ) != 'Invalid' && $formatted == 1 ) + $total = $mycred->format_creds( $total ); + + return $total; + + } endif; -add_shortcode(MYCRED_SLUG . '_total_since', 'mycred_render_shortcode_total_since'); +add_shortcode( MYCRED_SLUG . '_total_since', 'mycred_render_shortcode_total_since' ); diff --git a/includes/shortcodes/mycred_video.php b/includes/shortcodes/mycred_video.php index d532994..23b1a0e 100644 --- a/includes/shortcodes/mycred_video.php +++ b/includes/shortcodes/mycred_video.php @@ -1,138 +1,119 @@ null, - 'width' => 560, - 'height' => 315, - 'amount' => '', - 'logic' => '', - 'interval' => '', - 'streaming' => '', - 'duration' => '', - 'ctype' => MYCRED_DEFAULT_TYPE_KEY - ), $atts, MYCRED_SLUG . '_video' - ) - ); - - $prf_hook = apply_filters('mycred_option_id', 'mycred_pref_hooks'); - $hooks = mycred_get_option($prf_hook, false); - if ($ctype != MYCRED_DEFAULT_TYPE_KEY ) { - $hooks = mycred_get_option('mycred_pref_hooks_' . sanitize_key($ctype), false); - } +if ( ! function_exists( 'mycred_render_shortcode_video' ) ) : + function mycred_render_shortcode_video( $atts ) { - if ($hooks === false || ! is_array($hooks) || ! array_key_exists('video_view', $hooks['hook_prefs']) ) { return; - } - $prefs = $hooks['hook_prefs']['video_view']; + global $mycred_video_points; - if ($amount == '' ) { - $amount = $prefs['creds']; - } + extract( shortcode_atts( array( + 'id' => NULL, + 'width' => 560, + 'height' => 315, + 'amount' => '', + 'logic' => '', + 'interval' => '', + 'streaming' => '', + 'duration' => '', + 'ctype' => MYCRED_DEFAULT_TYPE_KEY + ), $atts, MYCRED_SLUG . '_video' ) ); - if ($logic == '' ) { - $logic = $prefs['logic']; - } + $prf_hook = apply_filters( 'mycred_option_id', 'mycred_pref_hooks' ); + $hooks = mycred_get_option( $prf_hook, false ); + if ( $ctype != MYCRED_DEFAULT_TYPE_KEY ) + $hooks = mycred_get_option( 'mycred_pref_hooks_' . sanitize_key( $ctype ), false ); - if ($interval == '' ) { - $interval = $prefs['interval']; - } + if ( $hooks === false || ! is_array( $hooks ) || ! array_key_exists( 'video_view', $hooks['hook_prefs'] ) ) return; + $prefs = $hooks['hook_prefs']['video_view']; - if ($streaming == '' ) { - $streaming = 'off'; - } + if ( $amount == '' ) + $amount = $prefs['creds']; - if ($duration == '' ) { - $duration = 300; - } + if ( $logic == '' ) + $logic = $prefs['logic']; - // ID is required - if ($id === null || empty($id) ) { return __('A video ID is required for this shortcode', 'mycred'); - } + if ( $interval == '' ) + $interval = $prefs['interval']; - // Interval - if ($interval ) { - $interval = (float) $interval; - $interval = abs($interval * 1000); - } + if ( $streaming == '' ) + $streaming = 'off'; - // Video ID - $video_id = str_replace('-', '__', $id); + if ( $duration == '' ) + $duration = 300; - // Create key - $key = mycred_create_token(array( 'youtube', $video_id, $amount, $logic, $interval, $ctype )); + // ID is required + if ( $id === NULL || empty( $id ) ) return __( 'A video ID is required for this shortcode', 'mycred' ); - if (! isset($mycred_video_points) || ! is_array($mycred_video_points) ) { - $mycred_video_points = array(); + // Interval + if ( $interval ) { + $interval = (float) $interval; + $interval = abs( $interval * 1000 ); } - // Construct YouTube Query - $query = apply_filters( - 'mycred_video_query_youtube', array( - 'enablejsapi' => 1, - 'version' => 3, - 'playerapiid' => 'mycred_vvideo_v' . $video_id, - 'rel' => 0, - 'controls' => 1, - 'showinfo' => 0 - ), $atts, $video_id - ); - - if (! is_user_logged_in() ) { - unset($query['playerapiid']); - } + // Video ID + $video_id = str_replace( '-', '__', $id ); + + // Create key + $key = mycred_create_token( array( 'youtube', $video_id, $amount, $logic, $interval, $ctype ) ); + + if ( ! isset( $mycred_video_points ) || ! is_array( $mycred_video_points ) ) + $mycred_video_points = array(); - // Construct Youtube Query Address - $url = 'https://www.youtube.com/embed/' . $id; - $url = add_query_arg($query, $url); + // Construct YouTube Query + $query = apply_filters( 'mycred_video_query_youtube', array( + 'enablejsapi' => 1, + 'version' => 3, + 'playerapiid' => 'mycred_vvideo_v' . $video_id, + 'rel' => 0, + 'controls' => 1, + 'showinfo' => 0 + ), $atts, $video_id ); - $mycred_video_points[] = 'youtube'; + if ( ! is_user_logged_in() ) + unset( $query['playerapiid'] ); - // Make sure video source ids are unique - $mycred_video_points = array_unique($mycred_video_points); + // Construct Youtube Query Address + $url = 'https://www.youtube.com/embed/' . $id; + $url = add_query_arg( $query, $url ); - ob_start(); + $mycred_video_points[] = 'youtube'; - ?> + // Make sure video source ids are unique + $mycred_video_points = array_unique( $mycred_video_points ); + + ob_start(); + +?>
    -
    - -
    +
    + +
    - +?> - +?> \ No newline at end of file diff --git a/index.php b/index.php index 1580272..4e6c07c 100644 --- a/index.php +++ b/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/lang/index.php b/lang/index.php index 1580272..4e6c07c 100644 --- a/lang/index.php +++ b/lang/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/membership/index.php b/membership/index.php index 1580272..4e6c07c 100644 --- a/membership/index.php +++ b/membership/index.php @@ -1,3 +1,3 @@ +?> \ No newline at end of file diff --git a/membership/mycred-connect-membership.php b/membership/mycred-connect-membership.php index d0d6da9..69dc8ee 100644 --- a/membership/mycred-connect-membership.php +++ b/membership/mycred-connect-membership.php @@ -2,69 +2,64 @@ /** * Class to connect mycred with membership * - * @since 1.0 + * @since 1.0 * @version 1.0 */ // If this file is called directly, abort. -if (! defined('ABSPATH') ) { +if ( ! defined( 'ABSPATH' ) ) { exit; } -if (! class_exists('myCRED_Connect_Membership') ) : - Class myCRED_Connect_Membership - { +if ( ! class_exists( 'myCRED_Connect_Membership' ) ) : + Class myCRED_Connect_Membership { /** * Construct */ - public function __construct() - { - - add_action('admin_menu', array( $this, 'mycred_membership_menu' )); - add_action('admin_menu', array( $this, 'mycred_treasures' )); - add_action('admin_menu', array( $this, 'mycred_support' )); - add_action('admin_init', array( $this, 'add_styles' )); - add_filter('admin_footer_text', array( $this, 'mycred_admin_footer_text')); + public function __construct() { + + add_action( 'admin_menu', array( $this, 'mycred_membership_menu' ) ); + add_action( 'admin_menu', array( $this, 'mycred_treasures' ) ); + add_action( 'admin_menu', array( $this, 'mycred_support' ) ); + add_action( 'admin_init', array( $this, 'add_styles' ) ); + add_filter( 'admin_footer_text', array( $this, 'mycred_admin_footer_text') ); } - public function add_styles() - { + public function add_styles() { - wp_register_style('admin-subscription-css', plugins_url('assets/css/admin-subscription.css', myCRED_THIS), array(), '1.2', 'all'); + wp_register_style('admin-subscription-css', plugins_url( 'assets/css/admin-subscription.css', myCRED_THIS ), array(), '1.2', 'all'); - if(isset($_GET['page']) && $_GET['page'] == 'mycred-membership' ) { - wp_enqueue_style('mycred-bootstrap-grid'); + if( isset($_GET['page']) && $_GET['page'] == 'mycred-membership' ) { + wp_enqueue_style( 'mycred-bootstrap-grid' ); } - elseif(isset($_GET['page']) && $_GET['page'] == 'mycred-treasures' ) { - wp_enqueue_style('mycred-bootstrap-grid'); + elseif( isset($_GET['page']) && $_GET['page'] == 'mycred-treasures' ) { + wp_enqueue_style( 'mycred-bootstrap-grid' ); } - elseif(isset($_GET['page']) && $_GET['page'] == 'mycred-support' ) { - wp_enqueue_style('mycred-bootstrap-grid'); + elseif( isset($_GET['page']) && $_GET['page'] == 'mycred-support' ) { + wp_enqueue_style( 'mycred-bootstrap-grid' ); } wp_enqueue_style('admin-subscription-css'); } - public function mycred_admin_footer_text( $footer_text ) - { + public function mycred_admin_footer_text( $footer_text ) { global $typenow; - if(isset($_GET['page']) && $_GET['page'] == 'mycred-support' ) { + if( isset($_GET['page']) && $_GET['page'] == 'mycred-support' ) { - $mycred_footer_text = sprintf( - __('Thank you for being a
    myCred user! Please give your %3$s rating on WordPress.org', 'mycred'), + $mycred_footer_text = sprintf( __( 'Thank you for being a myCred user! Please give your %3$s rating on WordPress.org', 'mycred' ), 'https://mycred.me', 'https://wordpress.org/support/plugin/mycred/reviews/?rate=5#new-post', '★★★★★' ); - return str_replace('', '', $footer_text) . ' | ' . $mycred_footer_text . ''; + return str_replace( '', '', $footer_text ) . ' | ' . $mycred_footer_text . ''; } else { @@ -78,8 +73,7 @@ public function mycred_admin_footer_text( $footer_text ) /** * Register membership menu */ - public function mycred_membership_menu() - { + public function mycred_membership_menu() { mycred_add_main_submenu( 'License', 'License', @@ -90,10 +84,9 @@ public function mycred_membership_menu() } /** - * Register membership menu - */ - public function mycred_treasures() - { + * Register membership menu + */ + public function mycred_treasures() { mycred_add_main_submenu( 'Treasures', 'Treasures', @@ -106,8 +99,7 @@ public function mycred_treasures() /** * Register Help / Support menu */ - public function mycred_support() - { + public function mycred_support() { mycred_add_main_submenu( 'Support', 'Support', @@ -117,8 +109,7 @@ public function mycred_support() ); } - public function mycred_support_callback() - { + public function mycred_support_callback() { $references = mycred_get_all_references(); @@ -158,11 +149,15 @@ public function mycred_support_callback()

    If you need to build a custom feature, simply submit a request on our myCred website.


    +

    myCred Add-ons Update:

    +

    For our users' convenience and their site optimization, we made a unified license system for individual and membership users. Click here to update your add-ons

    +
    +

    myCred Log References:

    - $entry ):?> + $entry ):?>
    -
    - +
    @@ -170,15 +165,13 @@ public function mycred_support_callback() - + public function mycred_treasures_callback() {?>
    @@ -190,7 +183,7 @@ public function mycred_treasures_callback()
    - Treasure Badges + Treasure Badges

    Badges

    40 unique and beautifully designed Badge designs available in Gold, Silver and Bronze.

    @@ -203,7 +196,7 @@ public function mycred_treasures_callback()
    - Treasure Ranks + Treasure Ranks

    Ranks

    40 unique and beautifully designed virtual Ranks are available in Red, Silver and Gold.

    @@ -216,7 +209,7 @@ public function mycred_treasures_callback()
    - Treasure Currencies + Treasure Currencies

    Currency

    17 unique and beautifully designed Currency designs available in Gold, Silver & Bronze.

    @@ -229,7 +222,7 @@ public function mycred_treasures_callback()
    - Treasure Learning + Treasure Learning

    Learning

    30 unique and beautifully designed Learning icons are available in four different shapes.

    @@ -242,7 +235,7 @@ public function mycred_treasures_callback()
    - Treasure Fitness + Treasure Fitness

    Fitness

    30 unique and beautifully designed Fitness icons are available in three different shapes.

    @@ -255,7 +248,7 @@ public function mycred_treasures_callback()
    - Treasure Gems + Treasure Gems

    Gems

    500 unique and beautifully designed gem icons are available in four different shapes.

    @@ -269,41 +262,39 @@ public function mycred_treasures_callback()
    - mycred_save_license(); - $membership_key = get_option('mycred_membership_key'); - if(!isset($membership_key) && !empty($membership_key) ) { + $membership_key = get_option( 'mycred_membership_key' ); + if( !isset( $membership_key ) && !empty( $membership_key ) ) $membership_key = ''; - } ?>
    -
    +
    '; - } - else { - // if membership is not active in current site and the membership key is entered - echo ''; - } + if(mycred_is_valid_license_key( $membership_key )) { + echo ''; + } + else { + // if membership is not active in current site and the membership key is entered + echo ''; + } ?> - + -