Пример #1
0
 function onAfterRender(Am_Event_AfterRender $event)
 {
     if ($this->done) {
         return;
     }
     if (preg_match('/thanks\\.phtml$/', $event->getTemplateName()) && $event->getView()->invoice && $event->getView()->payment) {
         $this->done += $event->replace("|</body>|i", $this->getHeader() . $this->getSaleCode($event->getView()->invoice, $event->getView()->payment) . "</body>", 1);
         if ($this->done) {
             $payment = $event->getView()->payment;
             $payment->data()->set(self::TRACKED_DATA_KEY, 1);
             $payment->save();
         }
     } elseif (preg_match('/signup\\/signup.*\\.phtml$/', $event->getTemplateName())) {
         $this->done += $event->replace("|</body>|i", $this->getHeader() . $this->getTrackingCode() . $this->getSignupCode() . "</body>", 1);
     } else {
         if ($user_id = $this->getDi()->auth->getUserId()) {
             $payments = $this->getDi()->invoicePaymentTable->findBy(array('user_id' => $user_id, 'dattm' => '>' . sqlTime('-5 days')));
             foreach ($payments as $payment) {
                 if ($payment->data()->get(self::TRACKED_DATA_KEY)) {
                     continue;
                 }
                 $this->done += $event->replace("|</body>|i", $this->getHeader() . $this->getSaleCode($payment->getInvoice(), $payment) . "</body>", 1);
                 if ($this->done) {
                     $payment->data()->set(self::TRACKED_DATA_KEY, 1);
                     $payment->save();
                 }
                 break;
             }
         }
         if (!$this->done && !(defined('AM_ADMIN') && AM_ADMIN) && !$this->getDi()->config->get("google_analytics_only_sales_code")) {
             $this->done += $event->replace("|</body>|i", $this->getHeader() . $this->getTrackingCode() . "</body>", 1);
         }
     }
 }
Пример #2
0
 protected function _set($key, $value, $colName, $expires = null)
 {
     if ($expires && !preg_match('/^\\d+$/', $expires)) {
         $expires = sqlTime($expires);
     }
     $this->db->query("INSERT INTO ?_store\n            SET name=?, `value`=?, blob_value=?, `expires`=?\n            ON DUPLICATE KEY UPDATE `value`=VALUES(`value`), `blob_value`=VALUES(`blob_value`),\n                `expires`=VALUES(`expires`)\n            ", $key, $colName == self::VALUE ? $value : null, $colName == self::BLOB_VALUE ? $value : null, $expires);
 }
Пример #3
0
 public function void($amount)
 {
     $record = $this->grid->getRecord();
     if (!$record->is_voided) {
         Am_Di::getInstance()->affCommissionTable->void($record, sqlTime('now'), $amount);
     }
     $this->log();
     $this->grid->redirectBack();
 }
Пример #4
0
 public function setArray($keyValues, $expires = null)
 {
     if ($expires && !preg_match('/^\\d+$/', $expires)) {
         $expires = sqlTime($expires);
     }
     $vals = array();
     foreach ($keyValues as $k => $v) {
         $vals[] = sprintf("(%s, %s, '%s')", $this->db->escape($k), $this->db->escape($v), $expires == null ? 'NULL' : $expires);
     }
     if ($vals) {
         $this->db->query("INSERT INTO ?_store (name, value, expires) VALUES " . implode(",", $vals) . "\n                ON DUPLICATE KEY UPDATE `value`=VALUES(`value`), `expires`=VALUES(`expires`)");
     }
 }
Пример #5
0
 public function setArray($rebuildName, $sessionId, $users, $expires = null)
 {
     if ($expires && !preg_match('/^\\d+$/', $expires)) {
         $expires = sqlTime($expires);
     }
     $vals = array();
     foreach ($users as $user_id) {
         $vals[] = sprintf("('%s', '%s', %d, '%s')", $rebuildName, $sessionId, $user_id, $expires == null ? 'NULL' : $expires);
     }
     if ($vals) {
         $this->db->query("INSERT INTO ?_store_rebuild (rebuild_name, session_id, user_id, expires) VALUES " . implode(",", $vals) . "\n                ON DUPLICATE KEY UPDATE `expires`=VALUES(`expires`)");
     }
 }
 public function doSignup(array $vars)
 {
     $vars['name'] = preg_replace('/[^\\w\\s]+/u', '', $vars['name']);
     $rand = substr(sha1(mt_rand()), 0, 10);
     $link = ROOT_SURL . "/newsletter/subscribe/confirm/k/" . $rand;
     $this->getDi()->store->setBlob(self::STORE_KEY . $rand, serialize($vars), sqlTime('+48 hours'));
     /// send confirmation e-mail
     $et = Am_Mail_Template::load('verify_guest');
     if (!$et) {
         throw new Am_Exception_Configuration("No e-mail template found for [verify_guest]");
     }
     $et->setName($vars['name'])->setLink($link)->setCode($rand);
     $et->send($vars['email']);
     $this->_redirect('newsletter/subscribe/confirm');
 }
 function process(User $user, array $r)
 {
     $times = unserialize($r['wp_optimizemember_paid_registration_times']);
     $max = max($times);
     foreach ($times as $level => $time) {
         if (!($pid = $this->_translateProduct($level))) {
             continue;
         }
         $bpId = Am_Di::getInstance()->productTable->load($pid)->default_billing_plan_id;
         $fisrtPeriod = Am_Di::getInstance()->billingPlanTable->load($bpId)->first_period;
         $period = new Am_Period($fisrtPeriod);
         $this->payment[$pid] = array('start' => sqlTime($time), 'stop' => $period->addTo(sqlTime($time)));
         if ($time == $max) {
             $lastProduct = $pid;
         }
     }
     $this->payment[$lastProduct]['subscr_id'] = $r['wp_optimizemember_subscr_id'];
     $this->user = $user;
     return $this->doWork();
 }
Пример #8
0
 public function validateInvoiceAndKey()
 {
     $invoiceId = $this->getFiltered('id');
     if (!$invoiceId) {
         throw new Am_Exception_InputError("invoice_id is empty - seems you have followed wrong url, please return back to continue");
     }
     $this->invoice = $this->getDi()->invoiceTable->findBySecureId($invoiceId, $this->plugin->getId());
     if (!$this->invoice) {
         throw new Am_Exception_InputError('You have used wrong link for payment page, please return back and try again');
     }
     if ($this->invoice->isCompleted()) {
         throw new Am_Exception_InputError(sprintf(___('Payment is already processed, please go to %sMembership page%s'), "<a href='" . htmlentities($this->getDi()->config->get('root_url')) . "/member'>", "</a>"));
     }
     if ($this->invoice->paysys_id != $this->plugin->getId()) {
         throw new Am_Exception_InputError("You have used wrong link for payment page, please return back and try again");
     }
     if ($this->invoice->tm_added < sqlTime('-1 days')) {
         throw new Am_Exception_InputError("Invoice expired - you cannot open invoice after 24 hours elapsed");
     }
 }
Пример #9
0
 function onBuildDemo(Am_Event $event)
 {
     $subjects = array('Please help', 'Urgent question', 'I have a problem', 'Important question', 'Pre-sale inquiry');
     $questions = array("My website is now working. Can you help?", "I have a problem with website script.\nWhere can I find documentation?", "I am unable to place an order, my credit card is not accepted.");
     $answers = array("Please call us to phone# 1-800-222-3334", "We are looking to your problem, and it will be resolved within 4 hours");
     $user = $event->getUser();
     /* @var $user User */
     while (rand(0, 10) < 4) {
         $ticket = $this->getDi()->helpdeskTicketRecord;
         $ticket->status = HelpdeskTicket::STATUS_AWAITING_ADMIN_RESPONSE;
         $ticket->subject = $subjects[rand(0, count($subjects) - 1)];
         $ticket->user_id = $user->pk();
         $ticket->created = sqlTime('now');
         $ticket->insert();
         //
         $msg = $this->getDi()->helpdeskMessageRecord;
         $msg->content = $questions[rand(0, count($questions) - 1)];
         $msg->type = 'message';
         $msg->ticket_id = $ticket->pk();
         $msg->dattm = $tm = sqlTime(time() - rand(3600, 3600 * 24 * 180));
         $msg->insert();
         //
         if (rand(0, 10) < 6) {
             $msg = $this->getDi()->helpdeskMessageRecord;
             $msg->content = $answers[rand(0, count($answers) - 1)];
             $msg->type = 'message';
             $msg->ticket_id = $ticket->pk();
             $msg->dattm = sqlTime(strtotime($tm) + rand(180, 3600 * 24));
             $msg->admin_id = $this->getDi()->adminTable->findFirstBy()->pk();
             $msg->insert();
             if (rand(0, 10) < 6) {
                 $ticket->status = HelpdeskTicket::STATUS_AWAITING_USER_RESPONSE;
             } else {
                 $ticket->status = HelpdeskTicket::STATUS_CLOSED;
             }
             $ticket->update();
         }
     }
 }
Пример #10
0
 protected function ccActionValidateSetInvoice(Am_Request $request, array $invokeArgs)
 {
     $invoiceId = $request->getFiltered('cc_id');
     if (!$invoiceId) {
         throw new Am_Exception_InputError("invoice_id is empty - seems you have followed wrong url, please return back to continue");
     }
     $invoice = $this->getDi()->invoiceTable->findBySecureId($invoiceId, $this->getId());
     if (!$invoice) {
         throw new Am_Exception_InputError('You have used wrong link for payment page, please return back and try again');
     }
     if ($invoice->isCompleted()) {
         throw new Am_Exception_InputError(sprintf(___('Payment is already processed, please go to %sMembership page%s'), "<a href='" . htmlentities($this->getDi()->config->get('root_url')) . "/member'>", "</a>"));
     }
     if ($invoice->paysys_id != $this->getId()) {
         throw new Am_Exception_InputError("You have used wrong link for payment page, please return back and try again");
     }
     if ($invoice->tm_added < sqlTime('-30 days')) {
         throw new Am_Exception_InputError("Invoice expired - you cannot open invoice after 30 days elapsed");
     }
     $this->invoice = $invoice;
     // set for reference
 }
Пример #11
0
 public function lock(Admin $admin)
 {
     $this->updateQuick(array('lock_until' => sqlTime('+2 minutes'), 'lock_admin_id' => $admin->pk(), 'lock_admin' => sprintf('%s (%s %s)', $admin->login, $admin->name_f, $admin->name_l)));
 }
Пример #12
0
 private function sendSecurityCode(Admin $admin)
 {
     $security_code = $this->getDi()->app->generateRandomString(16);
     $securitycode_expire = sqlTime(time() + self::EXPIRATION_PERIOD * 60 * 60);
     $et = Am_Mail_Template::load('send_security_code_admin', null, true);
     $et->setUser($admin);
     $et->setUrl(sprintf('%s/admin-auth/change-pass/?s=%s', $this->getDi()->config->get('root_url'), $security_code));
     $et->setHours(self::EXPIRATION_PERIOD);
     $et->send($admin);
     $this->getDi()->store->set(self::SECURITY_CODE_STORE_PREFIX . $security_code, $admin->pk(), $securitycode_expire);
 }
    public function addInvoiceAction()
    {
        $this->getDi()->authAdmin->getUser()->checkPermission('grid_invoice', 'insert');
        $form = new Am_Form_Admin('add-invoice');
        $tm_added = $form->addDate('tm_added')->setLabel(___('Date'));
        $tm_added->setValue($this->getDi()->sqlDate);
        $tm_added->addRule('required');
        $comment = $form->addText('comment', array('class' => 'el-wide'))->setLabel(___("Comment\nfor your reference"));
        $form->addElement(new Am_Form_Element_ProductsWithQty('product_id'))->setLabel(___('Products'))->loadOptions($this->getDi()->billingPlanTable->selectAllSorted())->addRule('required');
        $form->addSelect('paysys_id')->setLabel(___('Payment System'))->setId('add-invoice-paysys_id')->loadOptions(array('' => '') + $this->getDi()->paysystemList->getOptions());
        $couponEdit = $form->addText('coupon')->setLabel(___('Coupon'))->setId('p-coupon');
        $action = $form->addAdvRadio('_action')->setLabel(___('Action'))->setId('add-invoice-action')->loadOptions(array('pending' => ___('Just Add Pending Invoice'), 'pending-payment' => ___('Add Invoice and Payment/Access Manually'), 'pending-send' => ___('Add Pending Invoice and Send Link to Pay It to Customer')))->setValue('pending');
        $receipt = $form->addText('receipt')->setLabel(___('Receipt#'))->setId('add-invoice-receipt');
        $tm_due = $form->addDate('tm_due')->setLabel(___('Due Date'));
        $tm_due->setValue(sqlDate('+7 days'));
        $tm_due->setId('add-invoice-due');
        $message = $form->addTextarea('message', array('class' => 'el-wide'))->setLabel(___("Message\nwill be included to email to user"));
        $message->setId('add-invoice-message');
        $form->addElement('email_link', 'invoice_pay_link')->setLabel(___('Email Template with Payment Link'));
        $form->addScript()->setScript('
            $("[name=_action]").change(function(){
                var val = $("[name=_action]:checked").val();
                $("#add-invoice-receipt").closest("div.row").toggle(val == "pending-payment")
                $("#add-invoice-due").closest("div.row").toggle(val == "pending-send")
                $("#add-invoice-message").closest("div.row").toggle(val == "pending-send")
                $("[name=invoice_pay_link]").closest("div.row").toggle(val == "pending-send")
            }).change();

        ');
        $script = <<<CUT
        \$("input#p-coupon").autocomplete({
                minLength: 2,
                source: window.rootUrl + "/admin-coupons/autocomplete"
        });
CUT;
        $form->addScript('script')->setScript($script);
        $form->addSaveButton();
        $form->setDataSources(array($this->getRequest()));
        do {
            if ($form->isSubmitted() && $form->validate()) {
                $vars = $form->getValue();
                $invoice = $this->getDi()->invoiceRecord;
                $invoice->setUser($this->getDi()->userTable->load($this->user_id));
                $invoice->tm_added = sqlTime($vars['tm_added']);
                if ($vars['coupon']) {
                    $invoice->setCouponCode($vars['coupon']);
                    $error = $invoice->validateCoupon();
                    if ($error) {
                        $couponEdit->setError($error);
                        break;
                    }
                }
                foreach ($vars['product_id'] as $plan_id => $qty) {
                    $p = $this->getDi()->billingPlanTable->load($plan_id);
                    $pr = $p->getProduct();
                    try {
                        $invoice->add($pr, $qty);
                    } catch (Am_Exception_InputError $e) {
                        $form->setError($e->getMessage());
                        break 2;
                    }
                }
                $invoice->comment = $vars['comment'];
                $invoice->calculate();
                switch ($vars['_action']) {
                    case 'pending':
                        if (!$this->_addPendingInvoice($invoice, $form, $vars)) {
                            break 2;
                        }
                        break;
                    case 'pending-payment':
                        if (!$this->_addPendingInvoiceAndPayment($invoice, $form, $vars)) {
                            break 2;
                        }
                        break;
                    case 'pending-send':
                        if (!$this->_addPendingInvoiceAndSend($invoice, $form, $vars)) {
                            break 2;
                        }
                        break;
                    default:
                        throw new Am_Exception_InternalError(sprintf('Unknown action [%s] as %s::%s', $vars['_action'], __CLASS__, __METHOD__));
                }
                $this->getDi()->adminLogTable->log("Add Invoice (#{$invoice->invoice_id}/{$invoice->public_id}, Billing Terms: " . new Am_TermsText($invoice) . ")", 'invoice', $invoice->invoice_id);
                return $this->redirectLocation(REL_ROOT_URL . '/admin-user-payments/index/user_id/' . $this->user_id);
            }
            // if
        } while (false);
        $this->view->content = '<h1>' . ___('Add Invoice') . ' (<a href="' . REL_ROOT_URL . '/admin-user-payments/index/user_id/' . $this->user_id . '">' . ___('return') . '</a>)</h1>' . (string) $form;
        $this->view->display('admin/user-layout.phtml');
    }
Пример #14
0
 /**
  * Return commission stats
  * @param type $startTm
  * @param type $endTm 
  * @return array with keys: count and amount
  */
 function getAffStats($aff_id, $startTm, $endTm)
 {
     // return sales count of this affiliate for period
     return $this->_db->selectRow("\n            SELECT \n                COUNT(DISTINCT(invoice_id)) AS `count`, \n                SUM((SELECT COUNT(*) FROM ?_invoice_item WHERE \n                    invoice_id=inv.invoice_id AND (first_total>0 OR second_total>0)))\n                    AS `items_count`,\n                SUM(p.amount) as `amount`\n            FROM ?_invoice inv\n                INNER JOIN ?_user u USING (user_id)\n                LEFT JOIN ?_invoice_payment p USING (invoice_id)\n            WHERE u.aff_id=?d \n                AND inv.tm_started BETWEEN ? AND ?\n        ", $aff_id, sqlTime($startTm), sqlTime($endTm . ' 23:59:59'));
 }
Пример #15
0
 public function setCancelled($cancelled = true)
 {
     $this->updateQuick(array('tm_cancelled' => $cancelled ? sqlTime('now') : null, 'rebill_date' => null));
     if (!$cancelled) {
         $this->updateRebillDate();
     }
     $this->updateStatus();
     return $this;
 }
Пример #16
0
 protected function handleEmail(SavedForm $form, &$vars)
 {
     /* @var $user User */
     $user = $this->user;
     $bricks = $form->getBricks();
     foreach ($bricks as $brick) {
         if ($brick->getClass() == 'email' && $brick->getConfig('validate') && $vars['email'] != $user->email) {
             $code = $this->getDi()->app->generateRandomString(self::EMAIL_CODE_LEN);
             $data = array('security_code' => $code, 'email' => $vars['email']);
             $this->getDi()->store->setBlob(self::SECURITY_CODE_STORE_PREFIX . $this->user_id, serialize($data), sqlTime(Am_Di::getInstance()->time + self::SECURITY_CODE_EXPIRE * 3600));
             $tpl = Am_Mail_Template::load('verify_email_profile', get_first($user->lang, Am_Di::getInstance()->app->getDefaultLocale(false)), true);
             $cur_email = $user->email;
             $user->email = $vars['email'];
             $tpl->setUser($user);
             $tpl->setCode($code);
             $tpl->setUrl($this->getDi()->config->get('root_surl') . '/profile/confirm-email?em=' . $user->pk() . ':' . $code);
             $tpl->send($user);
             $user->email = $cur_email;
             unset($vars['email']);
             return true;
         }
     }
     return false;
 }
Пример #17
0
 function _getWhere(Am_Query $db)
 {
     $where = '';
     switch ($this->op) {
         case 'never':
             $where = '(last_login IS NULL)';
             break;
         case 'between':
             $from = $this->from ? date('Y-m-d 00:00:00', amstrtotime($this->from)) : sqlTime('- 10 years');
             $to = $this->to ? date('Y-m-d 23:59:59', amstrtotime($this->to)) : sqlTime('tommorow');
             $where = sprintf('(last_login BETWEEN %s AND %s)', $db->escape($from), $db->escape($to));
             break;
         default:
             new Am_Exception_InputError("Unknown operation type [{$this->op}]");
     }
     return $where;
 }
Пример #18
0
 public function clearExpired($date)
 {
     // this function deletes only 500 records at time, to do not work over limits
     $q = $this->_db->queryResultOnly("SELECT u.* \n            FROM ?_user u\n                LEFT JOIN ?_access a ON a.user_id = u.user_id\n                LEFT JOIN ?_invoice_payment ip ON ip.user_id = u.user_id\n            WHERE u.status = 2 \n                AND IFNULL(u.is_affiliate,0)=0 \n            GROUP BY u.user_id\n            HAVING GREATEST(\n                IFNULL(MAX(ip.dattm), '2000-01-01'), \n                IFNULL(MAX(a.expire_date), '2000-01-01')) < ?\n            LIMIT 500 \n        ", sqlTime($date), sqlTime($date));
     while ($r = $this->_db->fetchRow($q)) {
         $u = $this->createRecord($r);
         $u->delete();
     }
 }
Пример #19
0
 /**
  *
  * @param User
  * @param Am_Paysystem_Abstract $payplugin
  * @param array $product_ids array of product_id to use for generation
  * @param int $invCnt count of invoices per user
  * @param int $invVar variation of count of invoices per user
  * @param int $prdCnt count of products per invoice
  * @param int $prdVar variation of products per invoice
  * @param int $start timestamp period begin
  * @param int $end timestamp period end
  */
 public function createInvoices($user, $payplugin, $product_ids, $invCnt, $invVar, $prdCnt, $prdVar, $start, $end, $coupons = array())
 {
     $invoiceLimit = $this->getLimit($invCnt, $invVar);
     for ($j = 1; $j <= $invoiceLimit; $j++) {
         $tm = mt_rand($start, $end);
         /* @var $invoice Invoice */
         $invoice = $this->getDi()->invoiceTable->createRecord();
         $productLimit = max(1, $this->getLimit($prdCnt, $prdVar));
         for ($k = 1; $k <= $productLimit; $k++) {
             try {
                 $product = Am_Di::getInstance()->productTable->load(array_rand($product_ids));
                 if (!($err = $invoice->isProductCompatible($product))) {
                     $invoice->add($product, 1);
                 }
             } catch (Am_Exception_InputError $e) {
             }
         }
         if (!count($invoice->getItems())) {
             continue;
         }
         if (count($coupons) && rand(1, 5) == 5) {
             $invoice->setCouponCode($coupons[array_rand($coupons)]);
             $invoice->validateCoupon();
         }
         $invoice->tm_added = sqlTime($tm);
         $invoice->setUser($user);
         $invoice->calculate();
         $invoice->setPaysystem($payplugin->getId());
         $invoice->save();
         $this->getDi()->setService('dateTime', new DateTime('@' . $tm));
         if ($invoice->isZero()) {
             $tr = new Am_Paysystem_Transaction_Free($this->getDi()->plugins_payment->loadGet('free'));
             $tr->setInvoice($invoice)->setTime(new DateTime('@' . $tm))->process();
         } else {
             $tr = new Am_Paysystem_Transaction_Manual($payplugin);
             $tr->setAmount($invoice->first_total)->setInvoice($invoice)->setTime(new DateTime('@' . $tm))->setReceiptId('demo-' . substr(sprintf('%.4f', microtime(true)), -7))->process();
             //recurring payments
             $i = 1;
             while ((double) $invoice->second_total && $invoice->rebill_date < sqlDate($end) && $invoice->rebill_times >= $i && !$invoice->isCancelled()) {
                 $this->getDi()->setService('dateTime', new DateTime('@' . amstrtotime($invoice->rebill_date)));
                 $tr = new Am_Paysystem_Transaction_Manual($payplugin);
                 $tr->setAmount($invoice->second_total)->setInvoice($invoice)->setTime(new DateTime('@' . amstrtotime($invoice->rebill_date)))->setReceiptId('demo-rebill-' . $i++ . '-' . substr(sprintf('%.4f', microtime(true)), -7))->process();
                 if (rand(1, 5) == 5) {
                     //20% probability
                     $invoice->setCancelled(true);
                 }
             }
             //            $cc = $this->createCcRecord($user);
             //
             //            Am_Paysystem_Transaction_CcDemo::_setTime(new DateTime('-'.rand(0,200).' days'));
             //            $payplugin->doBill($invoice, true, $cc);
         }
         $tr = null;
         unset($tr);
         $invoice = null;
         unset($invoice);
     }
 }
Пример #20
0
 /**
  * @param Am_Event_UserBeforeInsert $event
  */
 function onUserBeforeInsert(Am_Event_UserBeforeInsert $event)
 {
     // skip this code if running from aMember CP
     if (defined('AM_ADMIN') && AM_ADMIN) {
         return;
     }
     $aff_id = $this->findAffId($aff_source);
     $e = new Am_Event(self::AFF_BIND_AFFILIATE, array('user' => $event->getUser()));
     $e->setReturn($aff_id);
     $this->getDi()->hook->call($e);
     $aff_id = $e->getReturn();
     // remember for usage in onUserAfterInsert
     $this->last_aff_id = $aff_id;
     if ($aff_id > 0) {
         $event->getUser()->aff_id = intval($aff_id);
         $event->getUser()->aff_added = sqlTime('now');
         if ($aff_source) {
             $event->getUser()->data()->set('aff-source', $aff_source);
         }
     }
     if (empty($event->getUser()->is_affiliate)) {
         $event->getUser()->is_affiliate = $this->getDi()->config->get('aff.signup_type') == 1 ? 1 : 0;
     }
 }
 function doWork(&$context)
 {
     if (!$this->session->addFieldDef3) {
         $this->session->addFieldDef3 = $this->importAddFieldDefs();
     }
     $maxImported = (int) $this->getDi()->db->selectCell("SELECT `value` FROM ?_data\n                WHERE `table`='user' AND `key`='am3:id'\n                ORDER BY `id` DESC LIMIT 1");
     $count = @$this->options['count'];
     if ($count) {
         $count -= $context;
     }
     if ($count < 0) {
         return true;
     }
     $q = $this->db3->queryResultOnly("SELECT *\n            FROM ?_members\n            WHERE member_id > ?d\n            { AND (IFNULL(status,?d) > 0 OR IFNULL(is_affiliate,0) > 0) }\n            ORDER BY member_id\n            LIMIT ?d ", $maxImported, @$this->options['exclude_pending'] ? 0 : DBSIMPLE_SKIP, $count ? $count : $this->chunkSize + 1);
     while ($r = $this->db3->fetchRow($q)) {
         if (!$this->checkLimits()) {
             return false;
         }
         $r['data'] = unserialize($r['data']);
         $u = $this->getDi()->userRecord;
         foreach (array('login', 'email', 'name_f', 'name_l', 'street', 'city', 'state', 'country', 'state', 'zip', 'remote_addr', 'added', 'unsubscribed', 'phone', 'is_affiliate', 'aff_payout_type') as $k) {
             if (strlen(@$r[$k])) {
                 $u->set($k, $r[$k]);
             } elseif (!empty($r['data'][$k])) {
                 $u->set($k, $r[$k]);
             }
         }
         if ($r['aff_id'] > 0) {
             $u->aff_id = $this->getDi()->db->selectCell("SELECT `id` FROM ?_data\n                    WHERE `table`='user' AND `key`='am3:id' AND value=?d", $r['aff_id']);
             $u->aff_added = $r['added'];
         }
         if ($r['is_affiliate']) {
             foreach ($r['data'] as $k => $v) {
                 if (strpos($k, 'aff_') === 0) {
                     $u->data()->set($k, $v);
                 }
             }
         }
         $u->setPass($r['pass'], true);
         // do not salt passwords heavily to speed-up
         $u->data()->set('am3:id', $r['member_id']);
         $u->data()->set('signup_email_sent', 1);
         // do not send signup email second time
         //import additional fields
         foreach ($this->session->addFieldDef3 as $def) {
             $value = $def['additional_fields']['sql'] ? $r[$def['name']] : $r['data'][$def['name']];
             $u->setForInsert(array($def['name'] => $value));
         }
         if (@$this->options['keep_user_id']) {
             $u->disableInsertPkCheck(true);
             $u->user_id = $r['member_id'];
         }
         try {
             if (@$this->options['keep_user_id']) {
                 $u->insert(false)->refresh();
             } else {
                 $u->insert();
             }
             if (!empty($r['data']['cc-hidden']) && class_exists('CcRecord', true)) {
                 $cc = $this->getDi()->ccRecordRecord;
                 $cc->user_id = $u->pk();
                 foreach (array('cc_country', 'cc_street', 'cc_city', 'cc_company', 'cc_state', 'cc_zip', 'cc_name_f', 'cc_name_l', 'cc_phone', 'cc_type') as $k) {
                     if (!empty($r['data'][$k])) {
                         $cc->set($k, $r['data'][$k]);
                     }
                 }
                 $ccnum = $this->getCryptCompat()->decrypt($r['data']['cc-hidden']);
                 $cc->cc_number = $ccnum;
                 $cc->cc_expire = $r['data']['cc-expire'];
                 $cc->insert();
             }
             $this->insertPayments($r['member_id'], $u, $r);
             $context++;
         } catch (Am_Exception_Db_NotUnique $e) {
             echo "Could not import user: "******"<br />\n";
         }
         // downloads & credits hystory
         $sql_credits = array();
         $sql_downloads = array();
         if (!empty($r['data']['downloads'])) {
             $db = Am_Di::getInstance()->db;
             $db->query("\n                    CREATE TABLE IF NOT EXISTS ?_credit (\n                        credit_id int not null auto_increment PRIMARY KEY,\n                        dattm datetime not null,\n                        user_id int not null,\n                        value int not null comment 'positive value: credit, negavive value: debit',\n                        comment varchar(255) not null comment 'useful for debit comments',\n                        access_id int null comment 'will be set to related access_id for credit records',\n                        reference_id varchar(255) null comment 'you can set it to your internal operation reference# to link, is not used in aMember',\n                        INDEX (user_id, dattm)\n                    )  DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci\n                ");
             $db->query("\n                    CREATE TABLE IF NOT EXISTS ?_history_downloads (\n                        downloads_id int(11) NOT NULL AUTO_INCREMENT,\n                        filename varchar(255) NOT NULL,\n                        cost int(11) NOT NULL,\n                        user_id int(11) NOT NULL,\n                        dattm datetime NOT NULL,\n                        remote_addr varchar(15) DEFAULT NULL,\n                        PRIMARY KEY (`downloads_id`)\n                    ) DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci\n                ");
             foreach ($r['data']['downloads'] as $d) {
                 $sql_credits[] = "('" . sqlTime($d['time']) . "', " . $u->pk() . ", -" . $d['cost'] . ", 'For download file [" . $d['filename'] . "]')";
                 $sql_downloads[] = "('" . $d['filename'] . "', " . $d['cost'] . ", " . $u->pk() . ", '" . sqlTime($d['time']) . "')";
             }
             $db->query("\n                    INSERT INTO ?_credit\n                        (dattm, user_id, value, comment)\n                    VALUES\n                " . join(',', $sql_credits));
             $db->query("\n                    INSERT INTO ?_history_downloads\n                        (filename, cost, user_id, dattm)\n                    VALUES\n                " . join(',', $sql_downloads));
         }
         if (isset($r['data']['download_credits'])) {
             $db = Am_Di::getInstance()->db;
             $db->query("CREATE TABLE IF NOT EXISTS ?_credit (\n                    credit_id int not null auto_increment PRIMARY KEY,\n                    dattm datetime not null,\n                    user_id int not null,\n                    value int not null comment 'positive value: credit, negavive value: debit',\n                    comment varchar(255) not null comment 'useful for debit comments',\n                    access_id int null comment 'will be set to related access_id for credit records',\n                    reference_id varchar(255) null comment 'you can set it to your internal operation reference# to link, is not used in aMember',\n                    INDEX (user_id, dattm)\n                )");
             // insert records with no related "credit"
             $db->query("\n                    INSERT INTO ?_credit \n                    SELECT \n                        null as credit_id,\n                        IFNULL(p.dattm, a.begin_date) as dattm,\n                        a.user_id,\n                        d.`value`*it.qty as `value`,\n                        pr.title as comment,\n                        a.access_id,\n                        null as reference_id\n                    FROM ?_access a \n                        LEFT JOIN ?_credit c ON a.access_id = c.access_id\n                        INNER JOIN ?_data d ON d.`table`='product' \n                            AND d.`id`=a.product_id AND d.`key`='credit' AND d.`value` > 0\n                        LEFT JOIN ?_invoice_payment p ON a.invoice_payment_id=p.invoice_payment_id\n                        LEFT JOIN ?_invoice_item it ON it.invoice_id = a.invoice_id and it.item_id=a.product_id\n                        LEFT JOIN ?_product pr ON a.product_id = pr.product_id\n                    WHERE a.user_id=?d AND c.credit_id IS NULL\n                ", $u->pk());
             $balance = $db->selectCell("SELECT SUM(`value`) FROM ?_credit\n                    WHERE user_id=?d\n                    ", $u->pk());
             if ($r['data']['download_credits'] != $balance) {
                 $db->query("INSERT INTO ?_credit\n                        SET ?a\n                    ", array('dattm' => '1970-01-01', 'user_id' => $u->pk(), 'value' => $r['data']['download_credits'] - $balance, 'comment' => 'import'));
             }
         }
         // subusers
         if (in_array('subusers', $this->getDi()->modules->getEnabled())) {
             if (!empty($r['data']['parent_id'])) {
                 $u->subusers_parent_id = intval($r['data']['parent_id']);
                 $u->update();
             }
             if (!empty($r['data']['subusers_groups_id'])) {
                 if (!is_array($subusers_groups_id = $r['data']['subusers_groups_id'])) {
                     $subusers_groups_id = unserialize($subusers_groups_id);
                 }
                 if (!empty($subusers_groups_id)) {
                     $sql = array();
                     foreach ($this->getDi()->db->selectCol("\n                                SELECT `id` FROM ?_data WHERE `table`='product' AND `key`='subusers_groups' AND `value` IN (?a)\n                            ", $subusers_groups_id) as $masterProductId) {
                         if ($prId = $this->getDi()->productTable->load($masterProductId)->subusers_product_id) {
                             $sql[] = "(" . $prId . "," . $u->pk() . ")";
                         }
                     }
                     if (!empty($sql)) {
                         try {
                             $this->getDi()->db->query("INSERT INTO ?_subusers_subscription\n                                        (product_id, user_id) VALUES " . join(',', $sql));
                         } catch (Am_Exception_Db_NotUnique $e) {
                             echo "Could not import subusers subscription: " . $e->getMessage() . "<br />\n";
                         }
                     }
                 }
             }
         }
     }
     return true;
 }
Пример #22
0
 public function clearPending($date)
 {
     $ids = $this->_db->selectCol("SELECT i.invoice_id\n            FROM ?_invoice i\n                LEFT JOIN ?_invoice_payment p ON p.invoice_id = i.invoice_id\n                LEFT JOIN ?_access a ON a.invoice_id = i.invoice_id\n            WHERE i.status = 0 AND p.invoice_payment_id IS NULL AND a.access_id IS NULL\n             AND i.tm_added < ?\n             AND (due_date IS NULL OR due_date < ?)\n            GROUP BY i.invoice_id\n            ", sqlTime($date), $this->getDi()->sqlDate);
     if (!$ids) {
         return;
     }
     $tables = array('?_invoice', '?_invoice_item', '?_invoice_log', '?_invoice_refund');
     foreach ($tables as $t) {
         $this->_db->query("DELETE FROM {$t} WHERE invoice_id IN (?a)", $ids);
     }
     $this->_db->query("DELETE FROM ?_data WHERE `table`='invoice' AND `id` IN (?a)", $ids);
     return count($ids);
 }
Пример #23
0
 static function checkCron()
 {
     if (defined('AM_TEST') && AM_TEST) {
         return;
     }
     // do not run during unit-testing
     // get lock
     if (!Am_Di::getInstance()->db->selectCell("SELECT GET_LOCK(?, 0)", self::getLockId())) {
         Am_Di::getInstance()->errorLogTable->log("Could not obtain MySQL's GET_LOCK() to update cron run time. Probably attempted to execute two cron processes simultaneously. ");
         return;
     }
     $needRun = self::needRun();
     if ($needRun) {
         Am_Di::getInstance()->db->query("REPLACE INTO ?_store (name, `value`) VALUES (?, ?)", self::KEY, time());
     }
     Am_Di::getInstance()->db->query("SELECT RELEASE_LOCK(?)", self::getLockId());
     if (!$needRun) {
         return;
     }
     // Load all payment plugins here. ccBill plugin require hourly cron to be executed;
     Am_Di::getInstance()->plugins_payment->loadEnabled()->getAllEnabled();
     @ignore_user_abort(true);
     @set_time_limit(0);
     @ini_set('memory_limit', '256M');
     if (!empty($_GET['log'])) {
         Am_Di::getInstance()->errorLogTable->log("cron.php started");
     }
     $out = "";
     if ($needRun & self::HOURLY) {
         Am_Di::getInstance()->hook->call(Am_Event::HOURLY, array('date' => sqlDate('now'), 'datetime' => sqlTime('now')));
         $out .= "hourly.";
     }
     if ($needRun & self::DAILY) {
         Am_Di::getInstance()->hook->call(Am_Event::DAILY, array('date' => sqlDate('now'), 'datetime' => sqlTime('now')));
         $out .= "daily.";
     }
     if ($needRun & self::WEEKLY) {
         Am_Di::getInstance()->hook->call(Am_Event::WEEKLY, array('date' => sqlDate('now'), 'datetime' => sqlTime('now')));
         $out .= "weekly.";
     }
     if ($needRun & self::MONTHLY) {
         Am_Di::getInstance()->hook->call(Am_Event::MONTHLY, array('date' => sqlDate('now'), 'datetime' => sqlTime('now')));
         $out .= "monthly.";
     }
     if ($needRun & self::YEARLY) {
         Am_Di::getInstance()->hook->call(Am_Event::YEARLY, array('date' => sqlDate('now'), 'datetime' => sqlTime('now')));
         $out .= "yearly.";
     }
     if (!empty($_GET['log'])) {
         Am_Di::getInstance()->errorLogTable->log("cron.php finished ({$out})");
     }
 }
Пример #24
0
 function process(Am_Form $f)
 {
     $vars = $f->getValue();
     $user = Am_Di::getInstance()->userTable->findFirstByLogin($vars['user']);
     if (!$user) {
         list($el) = $f->getElementsByName('user');
         $el->setError(___('User %s not found', $vars['user']));
         return false;
     }
     $aff = Am_Di::getInstance()->userTable->findFirstByLogin($vars['aff']);
     if (!$aff) {
         list($el) = $f->getElementsByName('aff');
         $el->setError(___('Affiliate %s not found', $vars['user']));
         return false;
     }
     $couponAff = null;
     if ($vars['coupon']) {
         $coupon = Am_DI::getInstance()->couponTable->findFirstByCode($vars['coupon']);
         if ($coupon && ($coupon->aff_id || $coupon->getBatch()->aff_id)) {
             $couponAff = Am_Di::getInstance()->userTable->load($coupon->aff_id ? $coupon->aff_id : $coupon->getBatch()->aff_id, false);
         }
     }
     /* @var $invoice Invoice */
     $invoice = Am_Di::getInstance()->invoiceTable->createRecord();
     $invoice->setUser($user);
     if ($vars['coupon']) {
         $invoice->setCouponCode($vars['coupon']);
         $error = $invoice->validateCoupon();
         if ($error) {
             throw new Am_Exception_InputError($error);
         }
     }
     $user->aff_id = $aff->pk();
     foreach ($vars['product_id'] as $plan_id => $qty) {
         $p = Am_Di::getInstance()->billingPlanTable->load($plan_id);
         $pr = $p->getProduct();
         $invoice->add($pr, $qty);
     }
     $invoice->calculate();
     $invoice->setPaysystem($vars['paysys_id'], false);
     $invoice->invoice_id = '00000';
     $invoice->public_id = 'TEST';
     $invoice->tm_added = sqlTime('now');
     echo "<pre>";
     echo $invoice->render();
     echo "\nBilling Terms: " . $invoice->getTerms() . "\n" . str_repeat("-", 70) . "\n";
     $helper = new Am_View_Helper_UserUrl();
     $helper->setView(new Am_View());
     printf("User Ordering the subscription: <a target='_blank' class='link' href='%s'>%d/%s &quot;%s&quot; &lt;%s&gt</a>\n", $helper->userUrl($user->pk()), $user->pk(), Am_Controller::escape($user->login), Am_Controller::escape($user->name_f . ' ' . $user->name_l), Am_Controller::escape($user->email));
     printf("Reffered Affiliate: <a target='_blank' class='link' href='%s'>%d/%s &quot;%s&quot; &lt;%s&gt</a>\n", $helper->userUrl($aff->pk()), $aff->pk(), Am_Controller::escape($aff->login), Am_Controller::escape($aff->name_f . ' ' . $aff->name_l), Am_Controller::escape($aff->email));
     if ($couponAff) {
         printf("Affiliate Detected by Coupon (will get commision): <a target='_blank' class='link' href='%s'>%d/%s &quot;%s&quot; &lt;%s&gt</a>\n", $helper->userUrl($couponAff->pk()), $couponAff->pk(), Am_Controller::escape($couponAff->login), Am_Controller::escape($couponAff->name_f . ' ' . $couponAff->name_l), Am_Controller::escape($couponAff->email));
     }
     $max_tier = Am_Di::getInstance()->affCommissionRuleTable->getMaxTier();
     //COMMISSION FOR FREE SIGNUP
     if (!(double) $invoice->first_total && !(double) $invoice->second_total && $vars['is_first']) {
         echo "\n<strong>FREE SIGNUP</strong>:\n";
         list($item, ) = $invoice->getItems();
         echo sprintf("* ITEM: %s\n", Am_Controller::escape($item->item_title));
         foreach (Am_Di::getInstance()->affCommissionRuleTable->findRules($invoice, $item, $aff, 0, 0) as $rule) {
             echo $rule->render('*   ');
         }
         $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 0, 0);
         echo "* AFFILIATE WILL GET FOR THIS ITEM: " . Am_Currency::render($to_pay) . "\n";
         for ($i = 1; $i <= $max_tier; $i++) {
             $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 0, $i, $to_pay);
             $tier = $i + 1;
             echo "* {$tier}-TIER AFFILIATE WILL GET FOR THIS ITEM: " . Am_Currency::render($to_pay) . "\n";
         }
         echo str_repeat("-", 70) . "\n";
     }
     //COMMISSION FOR FIRST PAYMENT
     $price_field = (double) $invoice->first_total ? 'first_total' : 'second_total';
     if ((double) $invoice->{$price_field}) {
         echo "\n<strong>FIRST PAYMENT ({$invoice->currency} {$invoice->{$price_field}})</strong>:\n";
         $payment = Am_Di::getInstance()->invoicePaymentTable->createRecord();
         $payment->invoice_id = @$invoice->invoice_id;
         $payment->dattm = sqlTime('now');
         $payment->amount = $invoice->{$price_field};
         echo str_repeat("-", 70) . "\n";
         foreach ($invoice->getItems() as $item) {
             if (!(double) $item->{$price_field}) {
                 continue;
             }
             //do not calculate commission for free items within invoice
             echo sprintf("* ITEM: %s ({$invoice->currency} {$item->{$price_field}})\n", Am_Controller::escape($item->item_title));
             foreach (Am_Di::getInstance()->affCommissionRuleTable->findRules($invoice, $item, $aff, 1, 0, $payment->dattm) as $rule) {
                 echo $rule->render('*   ');
             }
             $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 1, 0, $payment->amount, $payment->dattm);
             echo "* AFFILIATE WILL GET FOR THIS ITEM: <strong>" . Am_Currency::render($to_pay) . "</strong>\n";
             for ($i = 1; $i <= $max_tier; $i++) {
                 $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 1, $i, $to_pay, $payment->dattm);
                 $tier = $i + 1;
                 echo "* {$tier}-TIER AFFILIATE WILL GET FOR THIS ITEM: <strong>" . Am_Currency::render($to_pay) . "</strong>\n";
             }
             echo str_repeat("-", 70) . "\n";
         }
     }
     //COMMISSION FOR SECOND AND SUBSEQUENT PAYMENTS
     if ((double) $invoice->second_total) {
         echo "\n<strong>SECOND AND SUBSEQUENT PAYMENTS ({$invoice->second_total} {$invoice->currency})</strong>:\n";
         $payment = Am_Di::getInstance()->invoicePaymentTable->createRecord();
         $payment->invoice_id = @$invoice->invoice_id;
         $payment->dattm = sqlTime('now');
         $payment->amount = $invoice->second_total;
         echo str_repeat("-", 70) . "\n";
         foreach ($invoice->getItems() as $item) {
             if (!(double) $item->second_total) {
                 continue;
             }
             //do not calculate commission for free items within invoice
             echo sprintf("* ITEM:  %s ({$item->second_total} {$invoice->currency})\n", Am_Controller::escape($item->item_title));
             foreach (Am_Di::getInstance()->affCommissionRuleTable->findRules($invoice, $item, $aff, 2, 0, $payment->dattm) as $rule) {
                 echo $rule->render('*   ');
             }
             $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 2, 0, $payment->amount, $payment->dattm);
             echo "* AFFILIATE WILL GET FOR THIS ITEM: <strong>" . Am_Currency::render($to_pay) . "</strong>\n";
             for ($i = 1; $i <= $max_tier; $i++) {
                 $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 2, $i, $to_pay, $payment->dattm);
                 $tier = $i + 1;
                 echo "* {$tier}-TIER AFFILIATE WILL GET FOR THIS ITEM: <strong>" . Am_Currency::render($to_pay) . "</strong>\n";
             }
             echo str_repeat("-", 70) . "\n";
         }
     }
     echo "</pre>";
     return true;
 }
Пример #25
0
 function onGridUserOnBeforeRun(Am_Event $event)
 {
     /* @var $grid Am_Grid_Editable */
     $grid = $event->getGrid();
     /* @var $query Am_Query_User */
     $query = $grid->getDataSource();
     $date = sqlTime(sprintf('-%d minutes', $this->getConfig('timeout', 5)));
     $query->leftJoin('?_login_session', 'ls', 'u.user_id=ls.user_id')->addField("SUM(IF(modified>'{$date}' AND need_logout=0, 1, 0))", 'login_session_cnt');
     $loginIndicator = new Am_Grid_Field('login_indicator', ___('Login Indicator'), false);
     $loginIndicator->setRenderFunction(array($this, 'renderLoginIndicator'));
     $action = $grid->actionGet('customize');
     $action->addField($loginIndicator);
 }
 function doWork()
 {
     foreach ($this->groups as $group_id => $list) {
         $txn_types = array();
         $currency = "";
         $product_ids = array();
         foreach ($list as $p) {
             $signup_params = array();
             foreach ($p['data'] as $k => $d) {
                 if (is_int($k) && !empty($d['txn_type'])) {
                     @$txn_types[$d['txn_type']]++;
                 }
                 if (is_int($k) && !empty($d['mc_currency'])) {
                     $currency = $d['mc_currency'];
                 }
                 if (@$d['txn_type'] == 'subscr_signup') {
                     $signup_params = $d;
                 } elseif (@$d['txn_type'] == 'web_accept') {
                     $signup_params = $d;
                 }
             }
             @$product_ids[$p['product_id']]++;
         }
         $invoice = $this->getDi()->invoiceRecord;
         $invoice->user_id = $this->user->pk();
         foreach ($product_ids as $pid => $count) {
             $newP = $this->_translateProduct($pid);
             if ($newP) {
                 $item = $invoice->createItem(Am_Di::getInstance()->productTable->load($newP));
             } else {
                 $item = $invoice->createItem(new ImportedProduct($pid));
             }
             $item->_calculateTotal();
             $invoice->addItem($item);
         }
         $invoice->paysys_id = 'paypal';
         $invoice->tm_added = $list[0]['tm_added'];
         $invoice->tm_started = $list[0]['tm_completed'];
         $invoice->public_id = $signup_params['invoice'] ? $signup_params['invoice'] : $list[0]['payment_id'];
         $invoice->currency = $currency ? $currency : $item->currency;
         // Set currency;
         if (!empty($txn_types['web_accept'])) {
             $invoice->first_total = $signup_params['mc_gross'];
             $item = current($invoice->getItems());
             $invoice->first_period = $item->first_period;
             $invoice->status = Invoice::PAID;
         } else {
             // recurring
             if ($signup_params) {
                 $invoice->first_period = $invoice->second_period = strtolower(str_replace(' ', '', $signup_params['period3']));
                 $invoice->first_total = $invoice->second_total = $signup_params['mc_amount3'];
                 if (!empty($signup_params['mc_amount1'])) {
                     $invoice->first_total = $signup_params['mc_amount1'];
                     $invoice->first_period = strtolower(str_replace(' ', '', $signup_params['period1']));
                 }
                 if (!$signup_params['recurring']) {
                     $invoice->rebill_times = 1;
                 } elseif ($signup_params['recur_times']) {
                     $invoice->rebill_times = $signup_params['recur_times'];
                 } else {
                     $invoice->rebill_times = IProduct::RECURRING_REBILLS;
                 }
             } else {
                 // get terms from products
                 foreach ($product_ids as $pid => $count) {
                     $newPid = $this->_translateProduct($pid);
                     if (!$newPid) {
                         continue;
                     }
                     $pr = Am_Di::getInstance()->productTable->load($newPid);
                     $invoice->first_total += $pr->getBillingPlan()->first_price;
                     $invoice->first_period = $pr->getBillingPlan()->first_period;
                     $invoice->second_total += $pr->getBillingPlan()->second_price;
                     $invoice->second_period = $pr->getBillingPlan()->second_period;
                     $invoice->rebill_times = max(@$invoice->rebill_times, $pr->getBillingPlan()->rebill_times);
                 }
                 $invoice->rebill_times = IProduct::RECURRING_REBILLS;
             }
             if (@$txn_types['subscr_eot']) {
                 $invoice->status = Invoice::RECURRING_FINISHED;
             } elseif (@$txn_types['subscr_cancel']) {
                 $invoice->status = Invoice::RECURRING_CANCELLED;
                 foreach ($list as $p) {
                     if (!empty($p['data']['CANCELLED_AT'])) {
                         $invoice->tm_cancelled = sqlTime($p['data']['CANCELLED_AT']);
                     }
                 }
             } elseif (@$txn_types['subscr_payment']) {
                 $invoice->status = Invoice::RECURRING_ACTIVE;
             }
             $invoice->data()->set('paypal_subscr_id', $group_id);
         }
         foreach ($list as $p) {
             $pidlist[] = $p['payment_id'];
         }
         $invoice->data()->set('am3:id', implode(',', $pidlist));
         $invoice->insert();
         // insert payments and access
         foreach ($list as $p) {
             $newP = $this->_translateProduct($p['product_id']);
             $tm = null;
             $txnid = null;
             foreach ($p['data'] as $k => $d) {
                 if (is_int($k) && !empty($d['payment_date'])) {
                     $tm = $d['payment_date'];
                 }
                 if (is_int($k) && !empty($d['txn_id'])) {
                     $txnid = $d['txn_id'];
                 }
             }
             $tm = new DateTime(get_first(urldecode($tm), urldecode($p['tm_completed']), urldecode($p['tm_added']), urldecode($p['begin_date'])));
             $payment = $this->getDi()->invoicePaymentRecord;
             $payment->user_id = $this->user->user_id;
             $payment->invoice_id = $invoice->pk();
             $payment->amount = $p['amount'];
             $payment->paysys_id = 'paypal';
             $payment->dattm = $tm->format('Y-m-d H:i:s');
             if ($txnid) {
                 $payment->receipt_id = $txnid;
             }
             $payment->transaction_id = $txnid ? $txnid : 'import-paypal-' . mt_rand(10000, 99999);
             $payment->insert();
             $this->getDi()->db->query("INSERT INTO ?_data SET\n                    `table`='invoice_payment',`id`=?d,`key`='am3:id',`value`=?", $payment->pk(), $p['payment_id']);
             if ($newP) {
                 $a = $this->getDi()->accessRecord;
                 $a->user_id = $this->user->user_id;
                 $a->setDisableHooks();
                 $a->begin_date = $p['begin_date'];
                 /// @todo handle payments that were cancelled but still active in amember 3.  Calculate expire date in this case.
                 if (($p['expire_date'] == self::AM3_RECURRING_DATE || $p['expire_date'] == self::AM3_LIFETIME_DATE) && array_key_exists('subscr_cancel', $txn_types)) {
                     $a->expire_date = $invoice->calculateRebillDate(count($list));
                 } else {
                     $a->expire_date = $p['expire_date'];
                 }
                 $a->invoice_id = $invoice->pk();
                 $a->invoice_payment_id = $payment->pk();
                 $a->product_id = $newP;
                 $a->insert();
             }
         }
     }
 }
Пример #27
0
 /**
  * Find affililate by IP address if cookie is empty
  * @param type $ip 
  * @return last aff_id in record with matching IP 
  */
 function findAffIdByIp($ip)
 {
     $startTm = sqlTime($this->getDi()->time - $this->getDi()->config->get('aff.cookie_lifetime', 365) * 24 * 3600);
     return $this->_db->selectCell("SELECT CONCAT(aff_id, '-', IFNULL(banner_id, ''))\n            FROM {$this->_table}\n            WHERE time >= ? AND remote_addr=? AND aff_id>0\n            ORDER BY time DESC\n            LIMIT 1", $startTm, $ip);
 }
Пример #28
0
 function getSignupsCount($start, $stop)
 {
     return $this->getDi()->db->selectCell("\n            SELECT \n                COUNT(*) AS cnt\n            FROM ?_user\n            WHERE added BETWEEN ? AND ?\n            ", sqlTime(strtotime($start)), sqlTime(strtotime($stop)));
 }
Пример #29
0
 /**
  * Process invoice and insert necessary commissions for it
  *
  * External code should guarantee that this method with $payment = null will be called
  * only once for each user for First user invoice
  */
 public function processPayment(Invoice $invoice, InvoicePayment $payment = null)
 {
     $aff_id = $invoice->aff_id;
     /* @var $coupon Coupon */
     try {
         if (!$aff_id && ($coupon = $invoice->getCoupon())) {
             // try to find affiliate by coupon
             $aff_id = $coupon->aff_id ? $coupon->aff_id : $coupon->getBatch()->aff_id;
         }
     } catch (Am_Exception_Db_NotFound $e) {
         //coupon not found
     }
     if (empty($aff_id)) {
         $aff_id = $invoice->getUser()->aff_id;
     }
     if ($aff_id && empty($invoice->aff_id)) {
         // set aff_id to invoice for quick access next time
         $invoice->updateQuick('aff_id', $aff_id);
     }
     // run event to get plugins chance choose another affiliate
     $event = new Am_Event(Bootstrap_Aff::AFF_FIND_AFFILIATE, array('invoice' => $invoice, 'payment' => $payment));
     $event->setReturn($aff_id);
     $this->getDi()->hook->call($event);
     $aff_id = $event->getReturn();
     if (empty($aff_id)) {
         return;
     }
     // no affiliate id registered
     if ($aff_id == $invoice->getUser()->pk()) {
         return;
     }
     //strange situation
     // load affiliate and continue
     $aff = $this->getDi()->userTable->load($aff_id, false);
     if (!$aff || !$aff->is_affiliate) {
         return;
     }
     // affiliate not found
     $user = $invoice->getUser();
     if (!$user->aff_id) {
         $user->aff_id = $aff->pk();
         $user->aff_added = sqlTime('now');
         $user->data()->set('aff-source', 'invoice-' . $invoice->pk());
         $user->save();
     }
     // try to load other tier affiliate
     $aff_tier = $aff;
     $aff_tiers = array();
     $aff_tiers_exists = array($aff->pk());
     for ($tier = 1; $tier <= $this->getMaxTier(); $tier++) {
         if (!$aff_tier->aff_id || $aff_tier->pk() == $invoice->getUser()->pk()) {
             break;
         }
         $aff_tier = $this->getDi()->userTable->load($aff_tier->aff_id, false);
         if (!$aff_tier || !$aff_tier->is_affiliate || $aff_tier->pk() == $invoice->getUser()->pk() || in_array($aff_tier->pk(), $aff_tiers_exists)) {
             //already in chain
             break;
         }
         $aff_tiers[$tier] = $aff_tier;
         $aff_tiers_exists[] = $aff_tier->pk();
     }
     $isFirst = !$payment || $payment->isFirst();
     //to define price field
     $paymentNumber = is_null($payment) ? 0 : $invoice->getPaymentsCount();
     if (!$payment) {
         $tax = 0;
     } else {
         $tax = $this->getDi()->config->get('aff.commission_include_tax', false) ? 0 : doubleval($payment->tax);
     }
     $amount = $payment ? $payment->amount - $tax : 0;
     $date = $payment ? $payment->dattm : 'now';
     // now calculate commissions
     $items = is_null($payment) ? array_slice($invoice->getItems(), 0, 1) : $invoice->getItems();
     foreach ($items as $item) {
         //we do not calculate commission for free items in invoice
         $prefix = $isFirst ? 'first' : 'second';
         if (!is_null($payment) && !(double) $item->get("{$prefix}_total")) {
             continue;
         }
         $comm = $this->getDi()->affCommissionRecord;
         $comm->date = sqlDate($date);
         $comm->record_type = AffCommission::COMMISSION;
         $comm->invoice_id = $invoice->invoice_id;
         $comm->invoice_item_id = $item->invoice_item_id;
         $comm->invoice_payment_id = $payment ? $payment->pk() : null;
         $comm->receipt_id = $payment ? $payment->receipt_id : null;
         $comm->product_id = $item->item_id;
         $comm->is_first = $paymentNumber <= 1;
         $comm->_setPayment($payment);
         $comm->_setInvoice($invoice);
         $comm_tier = clone $comm;
         $rules = array();
         $topay_this = $topay = $this->calculate($invoice, $item, $aff, $paymentNumber, 0, $amount, $date, $rules);
         if ($topay > 0) {
             $comm->aff_id = $aff->pk();
             $comm->amount = $topay;
             $comm->tier = 0;
             $comm->_setAff($aff);
             $comm->insert();
             $comm->setCommissionRules(array_map(create_function('$el', 'return $el->pk();'), $rules));
         }
         foreach ($aff_tiers as $tier => $aff_tier) {
             $rules = array();
             $topay_this = $this->calculate($invoice, $item, $aff_tier, $paymentNumber, $tier, $topay_this, $date, $rules);
             if ($topay_this > 0) {
                 $comm_this = clone $comm_tier;
                 $comm_this->aff_id = $aff_tier->pk();
                 $comm_this->amount = $topay_this;
                 $comm_this->tier = $tier;
                 $comm_this->_setAff($aff_tier);
                 $comm_this->insert();
                 $comm_this->setCommissionRules(array_map(create_function('$el', 'return $el->pk();'), $rules));
             }
         }
     }
 }
 function process(array $vars)
 {
     $vars['user'] = filterId($vars['user']);
     $vars['aff'] = filterId($vars['aff']);
     $user = Am_Di::getInstance()->userTable->findFirstByLogin($vars['user']);
     if (!$user) {
         throw new Am_Exception_InputError("User {$vars['user']} not found");
     }
     $aff = Am_Di::getInstance()->userTable->findFirstByLogin($vars['aff']);
     if (!$aff) {
         throw new Am_Exception_InputError("Affiliate {$vars['aff']} not found");
     }
     $invoice = Am_Di::getInstance()->invoiceTable->createRecord();
     $invoice->setUser($user);
     $user->aff_id = $aff->pk();
     foreach (Am_Di::getInstance()->productTable->loadIds($vars['product_ids']) as $pr) {
         $invoice->add($pr);
     }
     $invoice->paysys_id = 'manual';
     $invoice->calculate();
     $firstPayment = Am_Di::getInstance()->invoicePaymentTable->createRecord();
     $firstPayment->amount = $invoice->first_total;
     $firstPayment->currency = $invoice->currency;
     $firstPayment->dattm = sqlTime('now');
     $firstPayment->discount = $invoice->first_discount;
     $firstPayment->paysys_id = $invoice->paysys_id;
     $firstPayment->shipping = $invoice->first_shipping;
     $firstPayment->tax = $invoice->first_tax;
     $firstPayment->_setInvoice($invoice);
     $secondPayment = Am_Di::getInstance()->invoicePaymentTable->createRecord();
     $secondPayment->amount = $invoice->second_total;
     $secondPayment->currency = $invoice->currency;
     $secondPayment->dattm = sqlTime('tomorrow');
     $secondPayment->discount = $invoice->second_discount;
     $secondPayment->paysys_id = $invoice->paysys_id;
     $secondPayment->shipping = $invoice->second_shipping;
     $secondPayment->tax = $invoice->second_tax;
     $secondPayment->_setInvoice($invoice);
     // Am_Di::getInstance()->affCommissionRuleTable->getRules($firstPayment);
     // Am_Di::getInstance()->affCommissionRuleTable->getRules($secondPayment);
     $invoice->invoice_id = '00000';
     $invoice->public_id = 'TEST';
     $invoice->tm_added = sqlTime('now');
     echo "<pre>";
     echo $invoice->render();
     echo "\nBilling Terms: " . $invoice->getTerms() . "\n" . str_repeat("-", 70) . "\n";
     $helper = new Am_View_Helper_UserUrl();
     $helper->setView(new Am_View());
     printf("User Ordering the subscription: <a target='_blank' href='%s'>%d/%s &quot;%s&quot; &lt;%s&gt</a>\n", $helper->userUrl($user->pk()), $user->pk(), Am_Controller::escape($user->login), Am_Controller::escape($user->name_f . ' ' . $user->name_l), Am_Controller::escape($user->email));
     printf("Reffered Affiliate:             <a target='_blank' href='%s'>%d/%s &quot;%s&quot; &lt;%s&gt</a>\n", $helper->userUrl($aff->pk()), $aff->pk(), Am_Controller::escape($aff->login), Am_Controller::escape($aff->name_f . ' ' . $aff->name_l), Am_Controller::escape($aff->email));
     echo "\nFIRST PAYMENT ({$invoice->currency} {$invoice->first_total}):\n";
     $payment = Am_Di::getInstance()->invoicePaymentTable->createRecord();
     $payment->invoice_id = @$invoice->invoice_id;
     $payment->dattm = sqlTime('now');
     $payment->amount = $invoice->first_total;
     echo str_repeat("-", 70) . "\n";
     foreach ($invoice->getItems() as $item) {
         echo "* ITEM: {$item->item_title} ({$invoice->currency} {$item->first_total})\n";
         foreach (Am_Di::getInstance()->affCommissionRuleTable->findRules($invoice, $item, $aff, 0, 0, $payment->dattm) as $rule) {
             echo $rule->render('*   ');
         }
         echo "* AFFILIATE WILL GET FOR THIS ITEM: " . Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 0, 0, $payment->amount, $payment->dattm) . " {$invoice->currency} \n";
         echo "* " . str_repeat("-", 70) . "\n";
     }
     if ($invoice->second_total) {
         echo "\nSECOND AND THE FOLLOWING PAYMENTS ({$invoice->second_total} {$invoice->currency}):\n";
         $payment = Am_Di::getInstance()->invoicePaymentTable->createRecord();
         $payment->invoice_id = @$invoice->invoice_id;
         $payment->dattm = sqlTime('now');
         $payment->amount = $invoice->second_total;
         echo str_repeat("-", 70) . "\n";
         foreach ($invoice->getItems() as $item) {
             if (!$item->second_total) {
                 continue;
             }
             echo "* ITEM:  {$item->item_title} ({$item->second_total} {$invoice->currency})\n";
             foreach (Am_Di::getInstance()->affCommissionRuleTable->findRules($invoice, $item, $aff, 1, 0, $payment->dattm) as $rule) {
                 echo $rule->render('*   ');
             }
             echo "* AFFILIATE WILL GET FOR THIS ITEM: " . Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 1, 0, $payment->amount, $payment->dattm) . " {$invoice->currency} \n";
             echo "* " . str_repeat("-", 70) . "\n";
         }
     }
     echo "</pre>";
     return true;
 }