function payready_rebill()
{
    global $config, $db, $t;
    if (!$config['use_cron']) {
        fatal_error("PayReady rebill can be run only with external cron");
    }
    $dat = date('Y-m-d');
    $tomorrow = date('Y-m-d', time() + 3600 * 24);
    $payments = $db->get_expired_payments($dat, $dat, 'payready');
    $renewed = array();
    $log = "PayReady Rebill\n";
    foreach ($payments as $p) {
        if ($p['data']['CANCELLED']) {
            continue;
        }
        $member_id = $p['member_id'];
        $member = $db->get_user($member_id);
        $product_id = $p['product_id'];
        if ($renewed[$member_id][$product_id]++) {
            continue;
        }
        $product =& get_product($product_id);
        if (!$product->config['is_recurring']) {
            continue;
        }
        if ($product->config['rebill_times'] && !payready_check_rebill_times($product->config['rebill_times'], $p)) {
            continue;
        }
        $vars = array('RENEWAL_ORIG' => "RENEWAL_ORIG: {$p['payment_id']}");
        $payment_id = $db->add_waiting_payment($member_id, $product_id, 'payready', $product->config['price'], $dat, $product->get_expire($dat), $vars);
        list($err, $errno) = payready_payment($payment_id, $member_id);
        if ($errno > 1) {
            mail_rebill_failed_member($member, $payment_id, $product, "{$err} ({$errno})");
        } elseif (!$errno) {
            $db->log_error("no return from PayReady, payment #{$payment_id}");
        } elseif ($errno == 1) {
            $err = "COMPLETED";
            mail_rebill_success_member($member, $payment_id, $product);
        }
        $log .= "login: {$p['member_login']} payment#: {$payment_id}: {$err} ({$errno})\n";
    }
    #    print $log;
}
function cc_core_rebill($plugin, $dat = '', $running_from_cron = true, $repeat_declined = false)
{
    global $config, $db, $t;
    if (!$config['use_cron'] && $running_from_cron) {
        $db->log_error("{$plugin} rebill can be run only with external cron");
    }
    $amDb =& amDb();
    if ($dat == '') {
        $dat = date('Y-m-d');
    }
    $tomorrow = date('Y-m-d', strtotime($dat) + 3600 * 24);
    $pl =& instantiate_plugin('payment', $plugin);
    if (!method_exists($pl, 'cc_bill')) {
        fatal_error("This plugin ({$plugin}) is not handled by cc_core!");
    }
    // check if another rebilling process is active
    // last status_tm / added_tm in rebill_log is < 5 minutes ago
    // to avoiding starting new process while a PHP rebill script runned
    // less than 10 minutes ago is still running
    if ($running_from_cron) {
        if ($last_rebill_log_id = $amDb->selectCell("SELECT MAX(rebill_log_id) FROM ?_rebill_log")) {
            $last_tm_diff = $amDb->selectCell("SELECT UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(IFNULL(status_tm, added_tm)) \n\t\t\t\tFROM ?_rebill_log WHERE rebill_log_id=?", $last_rebill_log_id);
            if ($last_tm_diff < 5 * 60) {
                $db->log_error("[Notice] cc_core_rebill({$plugin}, {$dat}) skipped because previous rebilling process still working ({$last_tm_diff} seconds ago)");
                return;
            }
        }
        print ".\n";
        // to avoid Apache's timeout
    }
    $payments = $db->get_expired_payments($dat, $dat, $plugin);
    $renewed = array();
    $log = "{$plugin} Rebill\n";
    foreach ($payments as $p) {
        if ($p['data']['CANCELLED']) {
            continue;
        }
        $member_id = $p['member_id'];
        $member = $db->get_user($member_id);
        $product_id = $p['product_id'];
        if ($renewed[$member_id][$product_id]++) {
            continue;
        }
        $product =& get_product($product_id);
        if (!$product->config['is_recurring']) {
            continue;
        }
        if ($product->config['rebill_times'] && !cc_core_check_rebill_times($product->config['rebill_times'], $p)) {
            continue;
        }
        // check if we've already tried to rebill the customer today
        $check = $repeat_declined ? "SUM(status = 0)" : "MAX(status IS NOT NULL)";
        if ($amDb->selectCell("SELECT {$check} FROM ?_rebill_log\n\t\t\tWHERE payment_id = ? AND payment_date = ? ", $p['payment_id'], $dat)) {
            // retry on payment processor failure? todo, real tests needed
            continue;
        }
        $vars = array('RENEWAL_ORIG' => "RENEWAL_ORIG: {$p['payment_id']}");
        $pc =& new PriceCalculator();
        $pc->setTax(get_member_tax($member_id));
        $coupon_code = $p['data'][0]['COUPON_CODE'];
        if ($config['use_coupons'] && $coupon_code != '') {
            $coupon = $db->coupon_get($coupon_code, null, 1);
            if ($coupon['coupon_id'] && $coupon['is_recurring']) {
                $pc->setCouponDiscount($coupon['discount'], split(',', trim($coupon['product_id'])));
                $vars['COUPON_CODE'] = $coupon_code;
            }
        }
        $pc->addProduct($product_id);
        $terms =& $pc->calculate();
        $additional_values = array();
        $additional_values['COUPON_DISCOUNT'] = $terms->discount;
        $additional_values['TAX_AMOUNT'] = $terms->tax;
        $payment_id = $db->add_waiting_payment($member_id, $product_id, $plugin, $terms->total, $dat, $product->get_expire($dat), $vars, $additional_values);
        $rebill_log_id = $amDb->query("INSERT INTO ?_rebill_log \n\t\t(payment_id, added_tm, payment_date, amount, rebill_payment_id)\n\t\tVALUES\n\t\t(?d, ?, ?, ?f, ?d)", $p['payment_id'], date('Y-m-d H:i:s'), $dat, $terms->total, $payment_id);
        $payment = $db->get_payment($payment_id);
        $cc_info = $member['data'];
        $cc_info['cc_number'] = amember_decrypt($cc_info['cc-hidden']);
        $x = list($res, $err_msg, $receipt_id, $log) = $pl->cc_bill($cc_info, $member, $payment['amount'], $product->config[$payment['paysys_id'] . '_currency'], $product->config['title'], CC_CHARGE_TYPE_RECURRING, $payment['payment_id'], $payment);
        foreach ($log as $v) {
            $payment['data'][] = $v;
        }
        $db->update_payment($payment['payment_id'], $payment);
        $amDb->query("UPDATE ?_rebill_log \n        \tSET status = ?, status_tm = ?, status_msg = ? \n        \tWHERE rebill_payment_id = ?d", $res, date('Y-m-d H:i:s'), $err_msg, $payment_id);
        switch ($res) {
            case CC_RESULT_SUCCESS:
                $err = $db->finish_waiting_payment($payment['payment_id'], $payment['paysys_id'], $receipt_id, $payment['amount'], '', cc_core_get_payer_id($vars, $member));
                if ($err) {
                    $db->log_error($err . ": payment_id = {$payment['payment_id']} (rebilling)");
                }
                if ($config['cc_rebill_success']) {
                    mail_rebill_success_member($member, $payment_id, $product);
                }
                break;
            case CC_RESULT_INTERNAL_ERROR:
            case CC_RESULT_DECLINE_TEMP:
                if ($pl->config['reattempt'] != '') {
                    $new_expire = cc_core_prorate_subscription($p['payment_id'], $pl->config['reattempt'], $dat);
                }
                if ($config['cc_rebill_failed']) {
                    mail_rebill_failed_member($member, $payment_id, $product, "{$err_msg}", $new_expire);
                }
                if ($config['cc_rebill_failed_admin']) {
                    mail_rebill_failed_admin($member, $payment_id, $product, "{$err_msg}", $new_expire);
                }
                break;
            case CC_RESULT_DECLINE_PERM:
                if ($pl->config['reattempt'] != '') {
                    $new_expire = cc_core_prorate_subscription($p['payment_id'], $pl->config['reattempt'], $dat);
                }
                if ($config['cc_rebill_failed']) {
                    mail_rebill_failed_member($member, $payment_id, $product, "{$err_msg}", $new_expire);
                }
                if ($config['cc_rebill_failed_admin']) {
                    mail_rebill_failed_admin($member, $payment_id, $product, "{$err_msg}", $new_expire);
                }
                //            clean_cc_info($member);
                break;
            case CC_RESULT_IGNORE:
                break;
            default:
                $db->log_error("Unknown return from plugin_bill: {$res}");
        }
    }
}