Пример #1
0
 /**
  * @return boolean
  */
 public static function isCurrentAccountActive()
 {
     $user = wp_get_current_user();
     $user->membership_level = pmpro_getMembershipLevelsForUser($user->ID);
     $today = new \DateTime();
     if ($today->getTimestamp() < (int) $user->membership_level[0]->enddate) {
         return true;
     } else {
         return false;
     }
 }
Пример #2
0
function pmpro_manage_users_custom_column($column_data, $column_name, $user_id)
{
    if ($column_name == 'pmpro_membership_level') {
        $levels = pmpro_getMembershipLevelsForUser($user_id);
        $level_names = array();
        if (!empty($levels)) {
            foreach ($levels as $key => $level) {
                $level_names[] = $level->name;
            }
            $column_data = implode(',', $level_names);
        } else {
            $column_data = __('None', 'pmpro');
        }
    }
    return $column_data;
}
Пример #3
0
function pmpro_changeMembershipLevel($level, $user_id = NULL, $old_level_status = 'inactive')
{
    global $wpdb;
    global $current_user, $pmpro_error;
    if (empty($user_id)) {
        $user_id = $current_user->ID;
    }
    if (empty($user_id)) {
        $pmpro_error = __("User ID not found.", "pmpro");
        return false;
    }
    //make sure user id is int for security
    $user_id = intval($user_id);
    if (empty($level)) {
        $level = 0;
    } else {
        if (is_array($level)) {
            //custom level
        } else {
            $level_obj = pmpro_getLevel($level);
            if (empty($level_obj)) {
                $pmpro_error = __("Invalid level.", "pmpro");
                return false;
            }
            $level = $level_obj->id;
        }
    }
    //if it's a custom level, they're changing
    if (!is_array($level)) {
        //are they even changing?
        if (pmpro_hasMembershipLevel($level, $user_id)) {
            $pmpro_error = __("not changing?", "pmpro");
            return false;
            //not changing
        }
    }
    //get all active membershipships for this user
    $old_levels = pmpro_getMembershipLevelsForUser($user_id);
    //deactivate old memberships based on the old_level_status passed in (updates pmpro_memberships_users table)
    if ($old_levels) {
        foreach ($old_levels as $old_level) {
            $sql = "UPDATE {$wpdb->pmpro_memberships_users} SET `status`='{$old_level_status}', `enddate`='" . current_time('mysql') . "' WHERE `id`=" . $old_level->subscription_id;
            if (!$wpdb->query($sql)) {
                $pmpro_error = __("Error interacting with database", "pmpro") . ": " . (mysql_errno() ? mysql_error() : 'unavailable');
                return false;
            }
        }
    }
    //should we cancel their gateway subscriptions?
    $pmpro_cancel_previous_subscriptions = true;
    if (isset($_REQUEST['cancel_membership']) && $_REQUEST['cancel_membership'] == false) {
        $pmpro_cancel_previous_subscriptions = false;
    }
    $pmpro_cancel_previous_subscriptions = apply_filters("pmpro_cancel_previous_subscriptions", $pmpro_cancel_previous_subscriptions);
    //cancel any other subscriptions they have (updates pmpro_membership_orders table)
    if ($pmpro_cancel_previous_subscriptions) {
        $other_order_ids = $wpdb->get_col("SELECT id FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '" . $user_id . "' AND status = 'success' ORDER BY id DESC");
        foreach ($other_order_ids as $order_id) {
            $c_order = new MemberOrder($order_id);
            $c_order->cancel();
            if (!empty($c_order->error)) {
                $pmpro_error = $c_order->error;
            }
        }
    }
    //insert current membership
    if (!empty($level)) {
        if (is_array($level)) {
            //make sure the dates are in good formats
            if ($level['startdate'] != current_time('mysql') && $level['startdate'] != "NULL" && substr($level['startdate'], 0, 1) != "'") {
                $level['startdate'] = "'" . $level['startdate'] . "'";
            }
            if ($level['enddate'] != current_time('mysql') && $level['enddate'] != "NULL" && substr($level['enddate'], 0, 1) != "'") {
                $level['enddate'] = "'" . $level['enddate'] . "'";
            }
            //Better support mySQL Strict Mode by passing  a proper enum value for cycle_period
            if ($level['cycle_period'] == '') {
                $level['cycle_period'] = 0;
            }
            $sql = "INSERT INTO {$wpdb->pmpro_memberships_users} (user_id, membership_id, code_id, initial_payment, billing_amount, cycle_number, cycle_period, billing_limit, trial_amount, trial_limit, startdate, enddate)\n\t\t\t\t\tVALUES('" . $level['user_id'] . "',\n\t\t\t\t\t'" . $level['membership_id'] . "',\n\t\t\t\t\t'" . intval($level['code_id']) . "',\n\t\t\t\t\t'" . $level['initial_payment'] . "',\n\t\t\t\t\t'" . $level['billing_amount'] . "',\n\t\t\t\t\t'" . $level['cycle_number'] . "',\n\t\t\t\t\t'" . $level['cycle_period'] . "',\n\t\t\t\t\t'" . $level['billing_limit'] . "',\n\t\t\t\t\t'" . $level['trial_amount'] . "',\n\t\t\t\t\t'" . $level['trial_limit'] . "',\n\t\t\t\t\t" . $level['startdate'] . ",\n\t\t\t\t\t" . $level['enddate'] . ")";
            if (!$wpdb->query($sql)) {
                $pmpro_error = __("Error interacting with database", "pmpro") . ": " . (mysql_errno() ? mysql_error() : 'unavailable');
                return false;
            }
        } else {
            $sql = "INSERT INTO {$wpdb->pmpro_memberships_users} (user_id, membership_id, code_id, initial_payment, billing_amount, cycle_number, cycle_period, billing_limit, trial_amount, trial_limit, startdate, enddate)\n\t\t\t    VALUES (\n\t\t\t    '" . $user_id . "',\n\t\t\t    '" . $level . "',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '" . current_time('mysql') . "',\n                \t    '0000-00-00 00:00:00'\n                \t    )";
            if (!$wpdb->query($sql)) {
                $pmpro_error = __("Error interacting with database", "pmpro") . ": " . (mysql_errno() ? mysql_error() : 'unavailable');
                return false;
            }
        }
    }
    //get level id
    if (is_array($level)) {
        $level_id = $level['membership_id'];
    } else {
        $level_id = $level;
    }
    //just id
    //remove cached level
    global $all_membership_levels;
    unset($all_membership_levels[$user_id]);
    //update user data and call action
    pmpro_set_current_user();
    do_action("pmpro_after_change_membership_level", $level_id, $user_id);
    //$level is the $level_id here
    return true;
}
Пример #4
0
 /**
  * 
  * @param \WP_User $user
  */
 public function updateZohoContact($user)
 {
     $userId = $user->ID;
     $user->membership_level = pmpro_getMembershipLevelsForUser($userId);
     $endDate = gmdate("m/d/Y", $user->membership_level[0]->enddate);
     $address1 = get_user_meta($userId, "address1", true);
     $address2 = get_user_meta($userId, "address2", true);
     if ($address2 !== null) {
         $address = $address1 . " " . $address2;
     } else {
         $address = $address1;
     }
     $contactId = get_user_meta($userId, "contact_id", true);
     $params = "authtoken=" . self::ZOHO_TOKEN . "&scope=" . self::ZOHO_CRM . "&newFormat=1&wfTrigger=true";
     $params .= "&id=" . $contactId . "&xmlData=";
     $params .= "<Contacts><row no='1'>";
     $params .= '<FL val="First Name">' . $user->first_name . '</FL>';
     $params .= '<FL val="Last Name">' . $user->last_name . '</FL>';
     $params .= '<FL val="Email">' . $user->user_email . '</FL>';
     $params .= '<FL val="Phone">' . get_user_meta($userId, "telephone", true) . '</FL>';
     $params .= '<FL val="Membership Expiration Date">' . $endDate . '</FL>';
     $params .= '<FL val="Mailing Street">' . $address . '</FL>';
     $params .= '<FL val="Mailing City">' . get_user_meta($userId, "city", true) . '</FL>';
     $params .= '<FL val="Mailing State">' . get_user_meta($userId, "state", true) . '</FL>';
     $params .= '<FL val="Mailing Zip">' . get_user_meta($userId, "zip", true) . '</FL>';
     $params .= '<FL val="Billing Street">' . $address . '</FL>';
     $params .= '<FL val="Billing City">' . get_user_meta($userId, "city", true) . '</FL>';
     $params .= '<FL val="Billing State">' . get_user_meta($userId, "state", true) . '</FL>';
     $params .= '<FL val="Billing Code">' . get_user_meta($userId, "zip", true) . '</FL>';
     $params .= '</row></Contacts>';
     //header("Content-type: application/xml");
     $url = self::ZOHO_URL . "Contacts/updateRecords?";
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_TIMEOUT, 30);
     curl_setopt($ch, CURLOPT_VERBOSE, 1);
     //standard i/o streams
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     //Set to return data to string ($response)
     curl_setopt($ch, CURLOPT_POST, 1);
     //Regular post
     curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
     $result = curl_exec($ch);
     curl_close($ch);
 }
Пример #5
0
function pmpro_search_filter($query)
{
    global $current_user, $wpdb, $pmpro_pages;
    //hide pmpro pages from search results
    if (!$query->is_admin && $query->is_search && empty($query->query['post_parent'])) {
        if (empty($query->query_vars['post_parent'])) {
            //avoiding post_parent queries for now
            $query->set('post__not_in', $pmpro_pages);
        }
        $query->set('post__not_in', $pmpro_pages);
        // id of page or post
    }
    //hide member pages from non-members (make sure they aren't hidden from members)
    if (!$query->is_admin && !$query->is_singular && empty($query->query['post_parent']) && (empty($query->query_vars['post_type']) || in_array($query->query_vars['post_type'], apply_filters('pmpro_search_filter_post_types', array("page", "post"))))) {
        //get page ids that are in my levels
        $levels = pmpro_getMembershipLevelsForUser($current_user->ID);
        $my_pages = array();
        if ($levels) {
            foreach ($levels as $key => $level) {
                //get restricted posts for level
                $sql = "SELECT page_id FROM {$wpdb->pmpro_memberships_pages} WHERE membership_id=" . $current_user->membership_level->ID;
                $member_pages = $wpdb->get_col($sql);
                $my_pages = array_unique(array_merge($my_pages, $member_pages));
            }
        }
        //get hidden page ids
        if (!empty($my_pages)) {
            $sql = "SELECT page_id FROM {$wpdb->pmpro_memberships_pages} WHERE page_id NOT IN(" . implode(',', $my_pages) . ")";
        } else {
            $sql = "SELECT page_id FROM {$wpdb->pmpro_memberships_pages}";
        }
        $hidden_page_ids = array_values(array_unique($wpdb->get_col($sql)));
        if ($hidden_page_ids) {
            if (empty($query->query_vars['post_parent'])) {
                //avoiding post_parent queries for now
                $query->set('post__not_in', $hidden_page_ids);
            }
        }
        //get categories that are filtered by level, but not my level
        global $pmpro_my_cats;
        $pmpro_my_cats = array();
        if ($levels) {
            foreach ($levels as $key => $level) {
                $member_cats = pmpro_getMembershipCategories($level->id);
                $pmpro_my_cats = array_unique(array_merge($pmpro_my_cats, $member_cats));
            }
        }
        //get hidden cats
        if (!empty($pmpro_my_cats)) {
            $sql = "SELECT category_id FROM {$wpdb->pmpro_memberships_categories} WHERE category_id NOT IN(" . implode(',', $pmpro_my_cats) . ")";
        } else {
            $sql = "SELECT category_id FROM {$wpdb->pmpro_memberships_categories}";
        }
        $hidden_cat_ids = array_values(array_unique($wpdb->get_col($sql)));
        //make this work
        if ($hidden_cat_ids) {
            $query->set('category__not_in', $hidden_cat_ids);
            //filter so posts in this member's categories are allowed
            add_action('posts_where', 'pmpro_posts_where_unhide_cats');
        }
    }
    return $query;
}
Пример #6
0
						<thead>
							<tr>
								<th><?php 
            _e("Level", "pmpro");
            ?>
</th>
								<th><?php 
            _e("Expiration", "pmpro");
            ?>
</th>
								<th></th>
							</tr>
						</thead>
						<tbody>
							<?php 
            $current_user->membership_levels = pmpro_getMembershipLevelsForUser($current_user->ID);
            foreach ($current_user->membership_levels as $level) {
                ?>
								<tr>
									<td class="pmpro_cancel-membership-levelname">
										<?php 
                echo $level->name;
                ?>
									</td>
									<td class="pmpro_cancel-membership-expiration">
									<?php 
                if ($level->enddate) {
                    echo date_i18n(get_option('date_format'), $level->enddate);
                } else {
                    echo "---";
                }
Пример #7
0
function pmpro_set_current_user()
{
    //this code runs at the beginning of the plugin
    global $current_user, $wpdb;
    get_currentuserinfo();
    $id = intval($current_user->ID);
    if ($id) {
        $current_user->membership_level = pmpro_getMembershipLevelForUser($current_user->ID);
        if (!empty($current_user->membership_level)) {
            $current_user->membership_level->categories = pmpro_getMembershipCategories($current_user->membership_level->ID);
        }
        $current_user->membership_levels = pmpro_getMembershipLevelsForUser($current_user->ID);
    }
    //hiding ads?
    $hideads = pmpro_getOption("hideads");
    $hideadslevels = pmpro_getOption("hideadslevels");
    if (!is_array($hideadslevels)) {
        $hideadslevels = explode(",", $hideadslevels);
    }
    if ($hideads == 1 && pmpro_hasMembershipLevel() || $hideads == 2 && pmpro_hasMembershipLevel($hideadslevels)) {
        //disable ads in ezAdsense
        if (class_exists("ezAdSense")) {
            global $ezCount, $urCount;
            $ezCount = 100;
            $urCount = 100;
        }
        //disable ads in Easy Adsense (newer versions)
        if (class_exists("EzAdSense")) {
            global $ezAdSense;
            $ezAdSense->ezCount = 100;
            $ezAdSense->urCount = 100;
        }
        //set a global variable to hide ads
        global $pmpro_display_ads;
        $pmpro_display_ads = false;
    } else {
        global $pmpro_display_ads;
        $pmpro_display_ads = true;
    }
    do_action("pmpro_after_set_current_user");
}
Пример #8
0
/**
 * Create, add, remove or updates the membership level of the given user to the given level.
 *
 * $level may either be the ID or name of the desired membership_level.
 * If $user_id is omitted, the value will be retrieved from $current_user.
 *
 * @param int $level ID of level to set as new level, use 0 to cancel membership
 * @param int $user_id ID of the user to change levels for
 * @param string $old_level_status The status to set for the row in the memberships users table. (e.g. inactive, cancelled, admin_cancelled, expired) Defaults to 'inactive'.
 * $param int $cancel_level If set cancel just this one level instead of all active levels (to support Multiple Memberships per User)
 *
 * Return values:
 *		Success returns boolean true.
 *		Failure returns boolean false.
 */
function pmpro_changeMembershipLevel($level, $user_id = NULL, $old_level_status = 'inactive', $cancel_level = NULL)
{
    global $wpdb;
    global $current_user, $pmpro_error;
    if (empty($user_id)) {
        $user_id = $current_user->ID;
    }
    if (empty($user_id)) {
        $pmpro_error = __("User ID not found.", "pmpro");
        return false;
    }
    //make sure user id is int for security
    $user_id = intval($user_id);
    if (empty($level)) {
        $level = 0;
    } else {
        if (is_array($level)) {
            //custom level
        } else {
            $level_obj = pmpro_getLevel($level);
            if (empty($level_obj)) {
                $pmpro_error = __("Invalid level.", "pmpro");
                return false;
            }
            $level = $level_obj->id;
        }
    }
    //if it's a custom level, they're changing
    if (!is_array($level)) {
        //are they even changing?
        if (pmpro_hasMembershipLevel($level, $user_id)) {
            $pmpro_error = __("not changing?", "pmpro");
            return false;
            //not changing
        }
    }
    //get all active membershipships for this user
    $old_levels = pmpro_getMembershipLevelsForUser($user_id);
    //get level id
    if (is_array($level)) {
        $level_id = $level['membership_id'];
    } else {
        $level_id = $level;
    }
    //just id
    /**
     * Action to run before the membership level changes.
     *
     * @param int $level_id ID of the level changed to.
     * @param int $user_id ID of the user changed.
     * @param array $old_levels array of prior levels the user belonged to.
     * $param int $cancel_level ID of the level being cancelled if specified
     */
    do_action("pmpro_before_change_membership_level", $level_id, $user_id, $old_levels, $cancel_level);
    //deactivate old memberships based on the old_level_status passed in (updates pmpro_memberships_users table)
    $pmpro_deactivate_old_levels = true;
    /**
     * Filter whether old levels should be deactivated or not. This supports the MMPU addon.
     * Typically you'll want to hook into pmpro_before_change_membership_level 
     * or pmpro_after_change_membership_level later to run your own deactivation logic.
     * 
     * @since  1.8.11
     * @var $pmpro_deactivate_old_levels bool True or false if levels should be deactivated. Defaults to true.
     */
    $pmpro_deactivate_old_levels = apply_filters("pmpro_deactivate_old_levels", $pmpro_deactivate_old_levels);
    //make sure we deactivate the specified level if it's passed in
    if (!empty($cancel_level)) {
        $pmpro_deactivate_old_levels = true;
        $new_old_levels = array();
        foreach ($old_levels as $key => $old_level) {
            if ($old_level->id == $cancel_level) {
                $new_old_levels[] = $old_levels[$key];
                break;
            }
        }
        $old_levels = $new_old_levels;
    }
    if ($old_levels && $pmpro_deactivate_old_levels) {
        foreach ($old_levels as $old_level) {
            $sql = "UPDATE {$wpdb->pmpro_memberships_users} SET `status`='{$old_level_status}', `enddate`='" . current_time('mysql') . "' WHERE `id`=" . $old_level->subscription_id;
            if (!$wpdb->query($sql)) {
                $pmpro_error = __("Error interacting with database", "pmpro") . ": " . ($wpdb->last_error ? $wpdb->last_error : 'unavailable');
                return false;
            }
        }
    }
    //should we cancel their gateway subscriptions?
    if (!empty($cancel_level)) {
        $pmpro_cancel_previous_subscriptions = true;
        //don't filter cause we're doing just the one
        $other_order_ids = $wpdb->get_col("SELECT id FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '" . $user_id . "' AND status = 'success' AND membership_id = '" . esc_sql($cancel_level) . "' ORDER BY id DESC");
    } else {
        $pmpro_cancel_previous_subscriptions = true;
        if (isset($_REQUEST['cancel_membership']) && $_REQUEST['cancel_membership'] == false) {
            $pmpro_cancel_previous_subscriptions = false;
        }
        $pmpro_cancel_previous_subscriptions = apply_filters("pmpro_cancel_previous_subscriptions", $pmpro_cancel_previous_subscriptions);
        $other_order_ids = $wpdb->get_col("SELECT id FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '" . $user_id . "' AND status = 'success' ORDER BY id DESC");
    }
    //cancel any other subscriptions they have (updates pmpro_membership_orders table)
    if ($pmpro_cancel_previous_subscriptions && !empty($other_order_ids)) {
        foreach ($other_order_ids as $order_id) {
            $c_order = new MemberOrder($order_id);
            $c_order->cancel();
            if (!empty($c_order->error)) {
                $pmpro_error = $c_order->error;
            }
        }
    }
    //insert current membership
    if (!empty($level)) {
        //make sure the dates are in good formats
        if (is_array($level)) {
            //Better support mySQL Strict Mode by passing  a proper enum value for cycle_period
            if ($level['cycle_period'] == '') {
                $level['cycle_period'] = 0;
            }
            // clean up date formatting (string/not string)
            $level['startdate'] = preg_replace('/\'/', '', $level['startdate']);
            $level['enddate'] = preg_replace('/\'/', '', $level['enddate']);
            $sql = $wpdb->prepare("\r\n\t\t\t\t\tINSERT INTO {$wpdb->pmpro_memberships_users}\r\n\t\t\t\t\t(`user_id`, `membership_id`, `code_id`, `initial_payment`, `billing_amount`, `cycle_number`, `cycle_period`, `billing_limit`, `trial_amount`, `trial_limit`, `startdate`, `enddate`)\r\n\t\t\t\t\tVALUES\r\n\t\t\t\t\t( %d, %d, %d, %s, %s, %d, %s, %d, %s, %d, %s, %s )", $level['user_id'], $level['membership_id'], $level['code_id'], $level['initial_payment'], $level['billing_amount'], $level['cycle_number'], $level['cycle_period'], $level['billing_limit'], $level['trial_amount'], $level['trial_limit'], $level['startdate'], $level['enddate']);
        } else {
            $sql = $wpdb->prepare("\r\n\t\t\t\tINSERT INTO {$wpdb->pmpro_memberships_users}\r\n\t\t\t\t( `user_id`, `membership_id`, `code_id`, `initial_payment`, `billing_amount`, `cycle_number`, `cycle_period`, `billing_limit`, `trial_amount`, `trial_limit`, `startdate`, `enddate`)\r\n\t\t\t\t\tVALUES \r\n\t\t\t\t\t( %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %s, %s )", $user_id, $level_id, '0', '0', '0', '0', '0', '0', '0', '0', current_time('mysql'), '0000-00-00 00:00:00');
        }
        if (false === $wpdb->query($sql)) {
            $pmpro_error = sprintf(__("Error interacting with database: %s", "pmpro"), !empty($wpdb->last_error) ? $wpdb->last_error : 'unavailable');
            return false;
        }
    }
    //remove cached level
    global $all_membership_levels;
    unset($all_membership_levels[$user_id]);
    //update user data and call action
    pmpro_set_current_user();
    /**
     * Action to run after the membership level changes.
     *
     * @param int $level_id ID of the level changed to.
     * @param int $user_id ID of the user changed.
     * $param int $cancel_level ID of the level being cancelled if specified.
     */
    do_action("pmpro_after_change_membership_level", $level_id, $user_id, $cancel_level);
    return true;
}
Пример #9
0
	function pmpro_changeMembershipLevel($level, $user_id = NULL)
	{
		global $wpdb;
		global $current_user, $pmpro_error;

		if(empty($user_id))
		{
			$user_id = $current_user->ID;
		}

		if(empty($user_id))
		{
			$pmpro_error = "User ID not found.";
			return false;
		}

		if(empty($level)) //cancelling membership
		{
			$level = 0;
		}
		else if(is_array($level))
		{
			//custom level
		}
		else
		{
			$level_obj = pmpro_getLevel($level);
			if(empty($level_obj))
			{
				$pmpro_error = "Invalid level.";
				return false;
			}
			$level = $level_obj->id;
		}
		

		//if it's a custom level, they're changing
		if(!is_array($level))
		{
			//are they even changing?
			if(pmpro_hasMembershipLevel($level, $user_id)) {
				$pmpro_error = "not is changing?";
				return false; //not changing
			}
		}

		$old_levels = pmpro_getMembershipLevelsForUser($user_id);
					
		$pmpro_cancel_previous_subscriptions = apply_filters("pmpro_cancel_previous_subscriptions", true);
		if($pmpro_cancel_previous_subscriptions)
		{
			//deactivate old memberships (updates pmpro_memberships_users table)
			if(!empty($old_levels))
			{
				foreach($old_levels as $old_level) {
					$sql = "UPDATE $wpdb->pmpro_memberships_users SET `status`='inactive', `enddate`=NOW() WHERE `id`=".$old_level->subscription_id;				
					if(!$wpdb->query($sql))
					{
						$pmpro_error = "Error interacting with database: ".(mysql_errno()?mysql_error():'unavailable');
						return false;
					}										
				}
			}

			//cancel any other subscriptions they have (updates pmpro_membership_orders table)
			$other_order_ids = $wpdb->get_col("SELECT id FROM $wpdb->pmpro_membership_orders WHERE user_id = '" . $user_id . "' AND status = 'success' ORDER BY id DESC");
			foreach($other_order_ids as $order_id)
			{
				$c_order = new MemberOrder($order_id);
				$c_order->cancel();
			}
		}

		//insert current membership
		if(!empty($level)) //are we getting a new one or just cancelling the old ones
		{
			if(is_array($level))
			{
				//make sure the dates are in good formats				
				if($level['startdate'] != "NOW()" && $level['startdate'] != "NULL" && substr($level['startdate'], 0, 1) != "'")
					$level['startdate'] = "'" . $level['startdate'] . "'";
								
				if($level['enddate'] != "NOW()" && $level['enddate'] != "NULL" && substr($level['enddate'], 0, 1) != "'")
					$level['enddate'] = "'" . $level['enddate'] . "'";
											
				$sql = "INSERT INTO $wpdb->pmpro_memberships_users (user_id, membership_id, code_id, initial_payment, billing_amount, cycle_number, cycle_period, billing_limit, trial_amount, trial_limit, startdate, enddate)
						VALUES('" . $level['user_id'] . "',
						'" . $level['membership_id'] . "',
						'" . intval($level['code_id']) . "',
						'" . $level['initial_payment'] . "',
						'" . $level['billing_amount'] . "',
						'" . $level['cycle_number'] . "',
						'" . $level['cycle_period'] . "',
						'" . $level['billing_limit'] . "',
						'" . $level['trial_amount'] . "',
						'" . $level['trial_limit'] . "',
						" . $level['startdate'] . ",
						" . $level['enddate'] . ")";
								
				if(!$wpdb->query($sql))
				{
					$pmpro_error = "Error interacting with database: ".(mysql_errno()?mysql_error():'unavailable');
					return false;
				}
			}
			else
			{
				$sql = "INSERT INTO $wpdb->pmpro_memberships_users (`membership_id`,`user_id`) VALUES ('" . $level . "','" . $user_id . "')";
				if(!$wpdb->query($sql))
				{
					$pmpro_error = "Error interacting with database: ".(mysql_errno()?mysql_error():'unavailable');
					return false;
				}
			}
		}

		//get level id
		if(is_array($level))
			$level_id = $level['membership_id'];	//custom level
		else
			$level_id = $level;	//just id
		
		//update user data and call action
		pmpro_set_current_user();
		do_action("pmpro_after_change_membership_level", $level_id, $user_id);	//$level is the $level_id here
		return true;
	}
function pmpro_shortcode_account($atts, $content = null, $code = "")
{
    global $wpdb, $pmpro_msg, $pmpro_msgt, $pmpro_levels, $current_user, $levels;
    // $atts    ::= array of attributes
    // $content ::= text within enclosing form of shortcode element
    // $code    ::= the shortcode found, when == callback name
    // examples: [pmpro_account] [pmpro_account sections="membership,profile"/]
    extract(shortcode_atts(array('section' => '', 'sections' => 'membership,profile,invoices,links'), $atts));
    //did they use 'section' instead of 'sections'?
    if (!empty($section)) {
        $sections = $section;
    }
    //Extract the user-defined sections for the shortcode
    $sections = array_map('trim', explode(",", $sections));
    ob_start();
    //if a member is logged in, show them some info here (1. past invoices. 2. billing information with button to update.)
    if (pmpro_hasMembershipLevel()) {
        $ssorder = new MemberOrder();
        $ssorder->getLastMemberOrder();
        $mylevels = pmpro_getMembershipLevelsForUser();
        $pmpro_levels = pmpro_getAllLevels(false, true);
        // just to be sure - include only the ones that allow signups
        $invoices = $wpdb->get_results("SELECT *, UNIX_TIMESTAMP(timestamp) as timestamp FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '{$current_user->ID}' AND status NOT IN('refunded', 'review', 'token', 'error') ORDER BY timestamp DESC LIMIT 6");
        ?>
	
	<div id="pmpro_account">		
		<?php 
        if (in_array('membership', $sections) || in_array('memberships', $sections)) {
            ?>
			<div id="pmpro_account-membership" class="pmpro_box">
				
				<h3><?php 
            _e("My Memberships", "pmpro");
            ?>
</h3>
				<table width="100%" cellpadding="0" cellspacing="0" border="0">
					<thead>
						<tr>
							<th><?php 
            _e("Level", "pmpro");
            ?>
</th>
							<th><?php 
            _e("Billing", "pmpro");
            ?>
</th>
							<th><?php 
            _e("Expiration", "pmpro");
            ?>
</th>
						</tr>
					</thead>
					<tbody>
						<?php 
            foreach ($mylevels as $level) {
                ?>
						<tr>
							<td class="pmpro_account-membership-levelname">
								<?php 
                echo $level->name;
                ?>
								<div class="pmpro_actionlinks">
									<?php 
                do_action("pmpro_member_action_links_before");
                ?>
									
									<?php 
                if (array_key_exists($level->id, $pmpro_levels) && pmpro_isLevelExpiringSoon($level)) {
                    ?>
										<a href="<?php 
                    echo pmpro_url("checkout", "?level=" . $level->id, "https");
                    ?>
"><?php 
                    _e("Renew", "pmpro");
                    ?>
</a>
									<?php 
                }
                ?>

									<?php 
                if (isset($ssorder->status) && $ssorder->status == "success" && (isset($ssorder->gateway) && in_array($ssorder->gateway, array("authorizenet", "paypal", "stripe", "braintree", "payflow", "cybersource"))) && pmpro_isLevelRecurring($level)) {
                    ?>
										<a href="<?php 
                    echo pmpro_url("billing", "", "https");
                    ?>
"><?php 
                    _e("Update Billing Info", "pmpro");
                    ?>
</a>
									<?php 
                }
                ?>
									
									<?php 
                //To do: Only show CHANGE link if this level is in a group that has upgrade/downgrade rules
                if (count($pmpro_levels) > 1 && !defined("PMPRO_DEFAULT_LEVEL")) {
                    ?>
										<a href="<?php 
                    echo pmpro_url("levels");
                    ?>
"><?php 
                    _e("Change", "pmpro");
                    ?>
</a>
									<?php 
                }
                ?>
									<a href="<?php 
                echo pmpro_url("cancel", "?levelstocancel=" . $level->id);
                ?>
"><?php 
                _e("Cancel", "pmpro");
                ?>
</a>
									<?php 
                do_action("pmpro_member_action_links_after");
                ?>
								</div> <!-- end pmpro_actionlinks -->
							</td>
							<td class="pmpro_account-membership-levelfee">
								<p><?php 
                echo pmpro_getLevelCost($level, true, true);
                ?>
</p>
							</td>
							<td class="pmpro_account-membership-expiration">
							<?php 
                if ($level->enddate) {
                    echo date_i18n(get_option('date_format'), $level->enddate);
                } else {
                    echo "---";
                }
                ?>
							</td>
						</tr>
						<?php 
            }
            ?>
					</tbody>
				</table>
				<?php 
            //Todo: If there are multiple levels defined that aren't all in the same group defined as upgrades/downgrades
            ?>
				<div class="pmpro_actionlinks">
					<a href="<?php 
            echo pmpro_url("levels");
            ?>
"><?php 
            _e("View all Membership Options", "pmpro");
            ?>
</a>
				</div>

			</div> <!-- end pmpro_account-membership -->
		<?php 
        }
        ?>
		
		<?php 
        if (in_array('profile', $sections)) {
            ?>
			<div id="pmpro_account-profile" class="pmpro_box">	
				<?php 
            wp_get_current_user();
            ?>
 
				<h3><?php 
            _e("My Account", "pmpro");
            ?>
</h3>
				<?php 
            if ($current_user->user_firstname) {
                ?>
					<p><?php 
                echo $current_user->user_firstname;
                ?>
 <?php 
                echo $current_user->user_lastname;
                ?>
</p>
				<?php 
            }
            ?>
				<ul>
					<?php 
            do_action('pmpro_account_bullets_top');
            ?>
					<li><strong><?php 
            _e("Username", "pmpro");
            ?>
:</strong> <?php 
            echo $current_user->user_login;
            ?>
</li>
					<li><strong><?php 
            _e("Email", "pmpro");
            ?>
:</strong> <?php 
            echo $current_user->user_email;
            ?>
</li>
					<?php 
            do_action('pmpro_account_bullets_bottom');
            ?>
				</ul>
				<div class="pmpro_actionlinks">
					<a href="<?php 
            echo admin_url('profile.php');
            ?>
"><?php 
            _e("Edit Profile", "pmpro");
            ?>
</a>
					<a href="<?php 
            echo admin_url('profile.php');
            ?>
"><?php 
            _e('Change Password', 'pmpro');
            ?>
</a>
				</div>
			</div> <!-- end pmpro_account-profile -->
		<?php 
        }
        ?>
	
		<?php 
        if (in_array('invoices', $sections) && !empty($invoices)) {
            ?>
		
		<div id="pmpro_account-invoices" class="pmpro_box">
			<h3><?php 
            _e("Past Invoices", "pmpro");
            ?>
</h3>
			<table width="100%" cellpadding="0" cellspacing="0" border="0">
				<thead>
					<tr>
						<th><?php 
            _e("Date", "pmpro");
            ?>
</th>
						<th><?php 
            _e("Level", "pmpro");
            ?>
</th>
						<th><?php 
            _e("Amount", "pmpro");
            ?>
</th>
					</tr>
				</thead>
				<tbody>
				<?php 
            $count = 0;
            foreach ($invoices as $invoice) {
                if ($count++ > 4) {
                    break;
                }
                //get an member order object
                $invoice_id = $invoice->id;
                $invoice = new MemberOrder();
                $invoice->getMemberOrderByID($invoice_id);
                $invoice->getMembershipLevel();
                ?>
						<tr id="pmpro_account-invoice-<?php 
                echo $invoice->code;
                ?>
">
							<td><a href="<?php 
                echo pmpro_url("invoice", "?invoice=" . $invoice->code);
                ?>
"><?php 
                echo date_i18n(get_option("date_format"), $invoice->timestamp);
                ?>
</td>
							<td><?php 
                if (!empty($invoice->membership_level)) {
                    echo $invoice->membership_level->name;
                } else {
                    echo __("N/A", "pmpro");
                }
                ?>
</td>
							<td><?php 
                echo pmpro_formatPrice($invoice->total);
                ?>
</td>
						</tr>
						<?php 
            }
            ?>
				</tbody>
			</table>						
			<?php 
            if ($count == 6) {
                ?>
				<div class="pmpro_actionlinks"><a href="<?php 
                echo pmpro_url("invoice");
                ?>
"><?php 
                _e("View All Invoices", "pmpro");
                ?>
</a></div>
			<?php 
            }
            ?>
		</div> <!-- end pmpro_account-invoices -->
		<?php 
        }
        ?>
		
		<?php 
        if (in_array('links', $sections) && (has_filter('pmpro_member_links_top') || has_filter('pmpro_member_links_bottom'))) {
            ?>
		<div id="pmpro_account-links" class="pmpro_box">
			<h3><?php 
            _e("Member Links", "pmpro");
            ?>
</h3>
			<ul>
				<?php 
            do_action("pmpro_member_links_top");
            ?>
				
				<?php 
            do_action("pmpro_member_links_bottom");
            ?>
			</ul>
		</div> <!-- end pmpro_account-links -->		
		<?php 
        }
        ?>
	</div> <!-- end pmpro_account -->		
	<?php 
    }
    $content = ob_get_contents();
    ob_end_clean();
    return $content;
}