public function __call($methodName, $args)
 {
     $pluginId = filterId($this->_request->getUserParam('plugin_id'));
     $this->_request->setActionName(filterId($this->_request->getActionName()));
     if (!$pluginId) {
         throw new Am_Exception_InputError("Internal Error: wrong URL used - no plugin id");
     }
     switch ($type = $this->_request->getUserParam('type')) {
         case self::PAYMENT:
         case self::PROTECT:
         case self::MISC:
             break;
         default:
             throw new Am_Exception_InternalError("Wrong [type] requested");
     }
     $pluginMgr = $this->getDi()->plugins[$type];
     if (!$pluginMgr->isEnabled($pluginId)) {
         throw new Am_Exception_InputError("The [{$pluginId}] plugin is disabled");
     }
     $ps = $pluginMgr->loadGet($pluginId);
     if (!$ps->isConfigured()) {
         throw new Am_Exception_Configuration("The plugin [{$pluginId}] is not configured, directAction failed");
     }
     try {
         return $ps->directAction($this->_request, $this->_response, $this->_invokeArgs);
     } catch (Exception $e) {
         $this->getDi()->errorLogTable->log($e);
         throw $e;
     }
 }
Esempio n. 2
0
 function indexAction()
 {
     $this->getDi()->plugins_payment->loadEnabled()->getAllEnabled();
     $id = $this->_request->getFiltered('id');
     if (empty($id)) {
         $id = filterId(@$_GET['id']);
     }
     $this->invoice = null;
     if ($id) {
         $this->invoice = $this->getDi()->invoiceTable->findBySecureId($id, 'THANKS');
         if (!$this->invoice) {
             throw new Am_Exception_InputError("Invoice #{$id} not found");
         }
         $tm = max($this->invoice->tm_started, $this->invoice->tm_added);
         if ($this->getDi()->time - strtotime($tm) > 48 * 3600) {
             throw new Am_Exception_InputError("Link expired");
         }
         // Clean signup_member_login and signup_member_id to avoid duplicate signups with the same email address.
         $this->getSession()->signup_member_id = null;
         $this->getSession()->signup_member_login = null;
         $this->view->invoice = $this->invoice;
         foreach ($this->invoice->getPaymentRecords() as $p) {
             $this->view->payment = $p;
         }
         if (!$this->invoice->tm_started) {
             $this->view->show_waiting = true;
             $this->view->refreshTime = "<span id='am-countdown'>00:10</span> " . ___("seconds");
         }
         $this->view->script = $this->getJs(10);
     }
     $this->getDi()->hook->call(Am_Event::THANKS_PAGE, array('controller' => $this, 'invoice' => $this->invoice));
     $this->view->layoutNoMenu = true;
     $this->view->display('thanks.phtml');
 }
 public function load($keyOrTicketId, $throwExceptions = true)
 {
     if (preg_match('/^\\d+$/', trim($keyOrTicketId), $matches)) {
         return parent::load($matches[0], $throwExceptions);
     } else {
         $keyOrTicketId = filterId($keyOrTicketId);
         $found = $this->findFirstByTicketMask($keyOrTicketId);
         if (!$found && $throwExceptions) {
             throw new Am_Exception_InternalError("Ticket with mask [{$keyOrTicketId}] not found");
         }
         return $found;
     }
 }
Esempio n. 4
0
 public function splitPath($path)
 {
     if (ctype_digit((string) $path)) {
         return array('upload', $path, array());
     }
     list($id, $path) = explode('::', $path, 2);
     $id = filterId($id);
     @(list($path, $query) = explode('?', $path, 2));
     $path = preg_replace('|[^A-Za-z0-9 _:\\\\/._-]|', '', $path);
     if (strlen($query)) {
         parse_str($query, $q);
         $query = $q;
     }
     return array($id, $path, $query);
 }
Esempio n. 5
0
 public function setFromRequest(array $input)
 {
     if (@$input[$this->getId()]['val'] != '') {
         $id = $input[$this->getId()]['val'];
         if (is_integer($id)) {
             $user = Am_Di::getInstance()->userTable->load($id, false);
         } else {
             $user = Am_Di::getInstance()->userTable->findFirstByLogin(filterId($id));
         }
         if (!$user) {
             return false;
         }
         $this->reseller_id = $user->pk();
         $this->reseller_login = $user->login;
         return true;
     }
 }
Esempio n. 6
0
 public function directAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs)
 {
     if ($request->getActionName() == 'cancelpaysafecart') {
         // SEE par.3
         @(list($id, $code) = explode('-', filterId($request->getFiltered('id')), 2));
         $invoice = Am_Di::getInstance()->InvoiceTable->findFirstByPublicId(filterId($id));
         if (!$invoice) {
             throw new Am_Exception_InputError("No invoice found [{$id}]");
         }
         $invoice->setCancelled(true);
         $a = new Am_Paysystem_Action_HtmlTemplate_Paysafecard($this->getDir(), 'payment-paysafecard-cancel.phtml');
         $a->process(new Am_Controller($request, $response, $invokeArgs));
         // see par.3
     } else {
         parent::directAction($request, $response, $invokeArgs);
     }
 }
Esempio n. 7
0
 public function setRequest(Am_Request $request)
 {
     $this->completeRequest = $request;
     $arr = array();
     foreach ($request->toArray() as $k => $v) {
         if (strpos($k, $this->id . '_') === 0) {
             $k = substr($k, strlen($this->id) + 1);
             if (!strlen($k)) {
                 continue;
             }
             $arr[$k] = $v;
         }
     }
     $this->request = new Am_Request($arr);
     $sort = $this->request->get('sort');
     if (!empty($sort)) {
         $sort = explode(' ', $sort, 2);
         $this->getDataSource()->setOrder(filterId($sort[0]), !empty($sort[1]));
     }
 }
Esempio n. 8
0
 public function indexAction()
 {
     /* @var $invoice Invoice */
     $invoice = $this->getDi()->invoiceTable->findBySecureId($this->getParam('secure_id'), 'payment-link');
     if (!$invoice || $invoice->status != Invoice::PENDING) {
         throw new Am_Exception_InternalError(sprintf('Unknow invoice [%s] or invoice is already processed', filterId($this->getParam('secure_id'))));
     }
     if (!$invoice->due_date && sqlDate($invoice->tm_added) < sqlDate("-" . Invoice::DEFAULT_DUE_PERIOD . " days")) {
         throw new Am_Exception_InputError(___('Invoice is expired'));
     } elseif ($invoice->due_date && $invoice->due_date < sqlDate('now')) {
         throw new Am_Exception_InputError(___('Invoice is expired'));
     }
     $form = new Am_Form();
     if (!$invoice->paysys_id) {
         $psOptions = array();
         foreach (Am_Di::getInstance()->paysystemList->getAllPublic() as $ps) {
             $psOptions[$ps->getId()] = $this->renderPaysys($ps);
         }
         $paysys = $form->addAdvRadio('paysys_id')->setLabel(___('Payment System'))->loadOptions($psOptions);
         $paysys->addRule('required', ___('Please choose a payment system'));
         if (count($psOptions) == 1) {
             $paysys->toggleFrozen(true);
         }
     }
     $form->addSaveButton(___('Pay'));
     $this->view->invoice = $invoice;
     $this->view->form = $form;
     $form->setDataSources(array($this->getRequest()));
     if ($form->isSubmitted() && $form->validate()) {
         $vars = $form->getValue();
         if (!$invoice->paysys_id) {
             $invoice->setPaysystem($vars['paysys_id']);
             $invoice->save();
         }
         $payProcess = new Am_Paysystem_PayProcessMediator($this, $invoice);
         $result = $payProcess->process();
         throw new Am_Exception_InternalError(sprintf('Error occurred while trying proccess invoice [%s]', filterId($invoice->public_id)));
     }
     $this->view->layoutNoMenu = true;
     $this->view->display('pay.phtml');
 }
Esempio n. 9
0
 public function __call($methodName, $args)
 {
     $pluginId = filterId($this->_request->getUserParam('plugin_id'));
     $this->_request->setActionName(filterId($this->_request->getActionName()));
     if (!$pluginId) {
         throw new Am_Exception_InputError("Internal Error: wrong URL used - no plugin id");
     }
     $type = $this->_request->getUserParam('type');
     if (!$this->getDi()->plugins->offsetGet($type)) {
         throw new Am_Exception_InternalError("Wrong [type] requested");
     }
     $pluginMgr = $this->getDi()->plugins[$type];
     if (!$pluginMgr->isEnabled($pluginId)) {
         throw new Am_Exception_InputError("The [{$pluginId}] plugin is disabled");
     }
     $ps = $pluginMgr->loadGet($pluginId);
     if (!$ps->isConfigured()) {
         throw new Am_Exception_Configuration("The plugin [{$pluginId}] is not configured, directAction failed");
     }
     return $ps->directAction($this->_request, $this->_response, $this->_invokeArgs);
 }
Esempio n. 10
0
 public function indexAction()
 {
     $this->_request->setParam('page', 'cart');
     $this->p = filterId($this->_request->getParam('page'));
     $this->initSetupForms();
     $this->form = $this->getForm($this->p, false);
     $this->form->prepare();
     if ($this->form->isSubmitted()) {
         $this->form->setDataSources(array($this->_request));
         if ($this->form->validate() && $this->form->saveConfig()) {
             Am_Controller::redirectLocation($this->getUrl());
         }
     } else {
         $this->form->setDataSources(array(new HTML_QuickForm2_DataSource_Array($this->getConfigValues()), new HTML_QuickForm2_DataSource_Array($this->form->getDefaults())));
     }
     $this->view->assign('p', $this->p);
     $this->form->replaceDotInNames();
     $this->view->assign('pageObj', $this->form);
     $this->view->assign('form', $this->form);
     $this->view->display('admin/cart/config.phtml');
 }
Esempio n. 11
0
 /**
  * Find out locale from the request, settings or session
  * if language choice enabled, try the following:
  *      - REQUEST parameter "lang"
  *      - SESSION parameter "lang"
  *      - Am_App::getUser->lang
  *      - default in App
  *      - en_US
  * else use latter 2
  */
 static function initLocale(Am_Di $di)
 {
     if (defined('AM_ADMIN') && AM_ADMIN) {
         Zend_Locale::setDefault('en_US');
     } else {
         $possibleLang = array();
         if ($di->config->get('lang.display_choice')) {
             $auth = $di->auth;
             $user = $auth->getUserId() ? $auth->getUser() : null;
             if (!empty($_REQUEST['_lang'])) {
                 $possibleLang[] = filterId($_REQUEST['_lang']);
             } elseif (!empty($di->session->lang)) {
                 $possibleLang[] = $di->session->lang;
             } elseif ($user && $user->lang) {
                 $possibleLang[] = $user->lang;
             }
             $br = Zend_Locale::getBrowser();
             arsort($br);
             $possibleLang = array_merge($possibleLang, array_keys($br));
         }
         $possibleLang[] = $di->config->get('lang.default', 'en_US');
         $possibleLang[] = 'en_US';
         // last but not least
         // now choose the best candidate
         $enabledLangs = $di->config->get('lang.enabled', array());
         $checked = array();
         foreach ($possibleLang as $lc) {
             list($lang) = explode('_', $lc, 2);
             if (!in_array($lc, $enabledLangs) && !in_array($lang, $enabledLangs)) {
                 continue;
             }
             if ($lc == $lang) {
                 // we have not got entire locale,guess it
                 if ($lc == 'en') {
                     $lc = 'en_US';
                 } elseif ($lc == 'sv') {
                     $lc = 'sv_SE';
                 } elseif ($lc == 'et') {
                     $lc = 'et_EE';
                 } elseif ($lc == 'vi') {
                     $lc = 'vi_VN';
                 } else {
                     $lc = Zend_Locale::getLocaleToTerritory($lang);
                 }
                 if (!$lc && $lang == 'ko') {
                     $lc = 'ko_KR';
                 }
                 if (!$lc && $lang == 'ja') {
                     $lc = 'ja_JP';
                 }
                 if (!$lc && $lang == 'nb') {
                     $lc = 'nb_NO';
                 }
                 if (!$lc && $lang == 'zh') {
                     $lc = 'zh_Hans';
                 }
                 if (!$lc && $lang == 'el') {
                     $lc = 'el_GR';
                 }
                 if (!$lc && $lang == 'he') {
                     $lc = 'he_IL';
                 }
                 if (!$lc && $lang == 'da') {
                     $lc = 'da_DK';
                 }
                 if (!$lc && $lang == 'cs') {
                     $lc = 'cs_CZ';
                 }
                 if (!$lc && $lang == 'sq') {
                     $lc = 'sq_AL';
                 }
                 if (!$lc) {
                     continue;
                 }
             }
             if (isset($checked[$lc])) {
                 continue;
             }
             $checked[$lc] = true;
             // check if locale file is exists
             $lc = preg_replace('/[^A-Za-z0-9_]/', '', $lc);
             if (!Zend_Locale::isLocale($lc)) {
                 continue;
             }
             Zend_Locale::setDefault($lc);
             // then update user if it was request
             // and set to session
             break;
         }
         if ($di->config->get('lang.display_choice') && !empty($_REQUEST['_lang'])) {
             if (($_REQUEST['_lang'] == $lang || $_REQUEST['_lang'] == $lc) && $user && $user->lang != $lang) {
                 $user->updateQuick('lang', $lc);
             }
             // set to session
             $di->session->lang = $lc;
         }
     }
     Zend_Registry::set('Zend_Locale', new Zend_Locale());
     $amLocale = new Am_Locale();
     Zend_Registry::set('Am_Locale', $amLocale);
     $di->locale = $amLocale;
     Zend_Locale_Format::setOptions(array('date_format' => $amLocale->getDateFormat()));
 }
 /** @return Am_Form_Setup */
 function getFormByTitle($title)
 {
     foreach ($this->forms as $f) {
         if ($f->getTitle() == $title) {
             return $f;
         }
     }
     $form = new Am_Form_Setup(strtolower(filterId($title)));
     $form->setTitle($title);
     $this->addForm($form);
     return $form;
 }
Esempio n. 13
0
 function setCvv($code)
 {
     $this->_cc_code = filterId($code);
 }
Esempio n. 14
0
 /**
  * Filter key value
  */
 function filterId($id)
 {
     return $this->_keyIsInt ? intval($id) : filterId($id);
 }
Esempio n. 15
0
 function loadGet($name, $throwExceptions = true)
 {
     $name = filterId($name);
     if ($this->isEnabled($name) && $this->load($name)) {
         return $this->get($name);
     }
     if ($throwExceptions) {
         throw new Am_Exception_InternalError("Could not loadGet([{$name}])");
     }
 }
Esempio n. 16
0
 public function getPage($id)
 {
     $id = filterId($id);
     if (!array_key_exists($id, $this->pages)) {
         throw new Am_Exception_InternalError("Could not find page[{$id}]");
     }
     return $this->pages[$id];
 }
Esempio n. 17
0
 /**
  * Get Session ID from Cookie;
  * @return string
  */
 function getSessionIdFromCookie()
 {
     return ($session_id = filterId($this->getDi()->request->getCookie($this->getSessionCookieName()))) ? $session_id : null;
 }
Esempio n. 18
0
 public function sendRequest($method, $params)
 {
     $this->vars = $params;
     $this->vars['apikey'] = $this->plugin->getConfig('api_key');
     $this->vars['method'] = $method;
     list($_, $server) = explode('-', $this->plugin->getConfig('api_key'), 2);
     $server = filterId($server);
     if (empty($server)) {
         throw new Am_Exception_Configuration("Wrong API Key set for MailChimp");
     }
     $url = sprintf('http://%s.api.mailchimp.com/1.3/', $server);
     $url .= '?' . http_build_query($this->vars, '', '&');
     $this->setUrl($url);
     $ret = parent::send();
     if ($ret->getStatus() != '200') {
         throw new Am_Exception_InternalError("MailChimp API Error, is configured API Key is wrong");
     }
     $arr = json_decode($ret->getBody(), true);
     if (!$arr) {
         throw new Am_Exception_InternalError("MailChimp API Error - unknown response [" . $ret->getBody() . "]");
     }
     if (isset($arr['error'])) {
         Am_Di::getInstance()->errorLogTable->log("MailChimp API Error - [" . $arr['error'] . "]");
         return false;
     }
     return $arr;
 }
Esempio n. 19
0
 protected function autoCreate()
 {
     try {
         $invoiceId = $this->findInvoiceId();
         if ($invoiceId === null) {
             throw new Am_Exception_Paysystem_TransactionEmpty("Looks like an invalid IPN post - no Invoice# passed");
         }
         $invoiceId = filterId($invoiceId);
         if (!strlen($invoiceId)) {
             throw new Am_Exception_Paysystem_TransactionInvalid("Could not load Invoice related to this transaction, passed id is not a valid Invoice#[{$invoiceId}]");
         }
         if (!($this->invoice = $this->loadInvoice($invoiceId))) {
             throw new Am_Exception_Paysystem_TransactionUnknown("Unknown transaction: related invoice not found #[{$invoiceId}]");
         }
     } catch (Am_Exception_Paysystem $e) {
         if (!$this->plugin->getConfig('auto_create')) {
             throw $e;
         }
         // try auto-create invoice
         $invoice = $this->autoCreateInvoice();
         if ($invoice) {
             $this->invoice = $invoice;
         } else {
             throw $e;
         }
     }
     $this->time = $this->findTime();
 }
Esempio n. 20
0
 public function cancelPaymentAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs)
 {
     $id = $request->getFiltered('id');
     if (!$id && isset($_GET['id'])) {
         $id = filterId($_GET['id']);
     }
     $invoice = $this->getDi()->invoiceTable->findFirstByPublicId($id);
     if (!$invoice) {
         throw new Am_Exception_InputError("No invoice found [{$id}]");
     }
     if ($invoice->user_id != $this->getDi()->auth->getUserId()) {
         throw new Am_Exception_InternalError("User tried to access foreign invoice: [{$id}]");
     }
     $this->invoice = $invoice;
     // find invoice and redirect to default "cancel" page
     $response->setRedirect($this->getCancelUrl());
 }
Esempio n. 21
0
 /** @return Invoice|null */
 function findBySecureId($invoiceId, $prefix)
 {
     if (!preg_match('/(.*)-([a-z0-9]*)$/', filterId($invoiceId), $matches)) {
         return;
     }
     $id = $matches[1];
     $code = $matches[2];
     $id = filterId($id);
     if (!strlen($id)) {
         return;
     }
     $invoice = $this->findFirstByPublicId($id);
     if (!$invoice) {
         return;
     }
     if ($invoice->getUniqId($prefix) != $code) {
         return;
     }
     return $invoice;
 }
Esempio n. 22
0
 /** @return Invoice|null */
 function findBySecureId($invoiceId, $prefix)
 {
     @(list($id, $code) = explode('-', filterId($invoiceId), 2));
     $id = filterId($id);
     if (!strlen($id)) {
         return;
     }
     $invoice = $this->findFirstByPublicId($id);
     if (!$invoice) {
         return;
     }
     if ($invoice->getUniqId($prefix) != $code) {
         return;
     }
     return $invoice;
 }
Esempio n. 23
0
    protected function displayHostedPage($cancelUrl)
    {
        $id = $this->invoice->getUser()->data()->get(Am_Paysystem_AuthorizeCim::PAYMENT_PROFILE_KEY);
        if ($id) {
            $method = 'editPayment';
            $id = filterId($id);
        } else {
            $method = 'addPayment';
            $id = null;
        }
        $token = $this->plugin->getHostedProfilePageToken();
        $domain = $this->plugin->getConfig('testing') ? 'test' : 'secure';
        $cancelUrl = json_encode($cancelUrl);
        $popupTitle = json_encode(___('Credit Card Info'));
        $plzwt = ___('Please wait while we process your order...');
        $plzwt2 = ___('Click here if you do not want to wait any longer (or if your browser does not automatically forward you).');
        $this->view->content .= <<<CUT
<div id="AuthorizeNetPopupInner" style='display:none'>
  <iframe width=440 height=520 name="iframeAuthorizeNet" id="iframeAuthorizeNet" src="about:blank" frameborder="0" scrolling="no"></iframe>
</div>
            
<form method="post" action="https://{$domain}.authorize.net/profile/{$method}" 
       id="formAuthorizeNetPopup" name="formAuthorizeNetPopup" 
       target="iframeAuthorizeNet" style=''>
    <input type="hidden" name="token" value="{$token}" />
    <input type="hidden" name="PaymentProfileId" value="{$id}" />
</form>

<script type="text/javascript">
jQuery(function () {
\tif (!window.AuthorizeNetPopup) window.AuthorizeNetPopup = {};
\tif (!AuthorizeNetPopup.options) AuthorizeNetPopup.options = {
\t\tonPopupClosed: null
\t};
\tAuthorizeNetPopup.onReceiveCommunication = function (querystr) {
\t\tvar params = parseQueryString(querystr);
\t\tswitch(params["action"]) {
\t\t\tcase "successfulSave":
                jQuery("#AuthorizeNetPopupInner").amPopup("close");
                var href = window.location.href;
                if (href.match(/\\?/))
                    href = href + '&result=success';
                else
                    href = href + '?result=success';
                jQuery("body").append('<div style="position:fixed; top:0px; left:0px; width:100%; background:#cccccc; opacity:0.5; height:100%;z-index:1000"></div><div style="position:absolute; top:40%; left:50%; margin-left:-295px; width:600px; height:60px; background:#000; padding:0px 15px; color:#ffffff; line-height:30px; text-align:center; border-radius:10px;z-index:1002;box-shadow:0px 0px 5px #000;">{$plzwt}<br><a href="' + href + '">{$plzwt2}</a></div>');
                window.location.href = href;
\t\t\t\tbreak;
\t\t\tcase "cancel":
                jQuery("#AuthorizeNetPopupInner").amPopup("close");
                window.location.href = {$cancelUrl};
\t\t\t\tbreak;
\t\t\tcase "resizeWindow":
\t\t\t\tvar w = parseInt(params["width"]);
\t\t\t\tvar h = parseInt(params["height"]);
\t\t\t\tvar ifrm = document.getElementById("iframeAuthorizeNet");
\t\t\t\tifrm.style.width = w.toString() + "px";
\t\t\t\tifrm.style.height = h.toString() + "px";
\t\t\t\tbreak;
\t\t}
\t};
\tfunction parseQueryString(str) {
\t\tvar vars = [];
\t\tvar arr = str.split('&');
\t\tvar pair;
\t\tfor (var i = 0; i < arr.length; i++) {
\t\t\tpair = arr[i].split('=');
\t\t\tvars.push(pair[0]);
\t\t\tvars[pair[0]] = unescape(pair[1]);
\t\t}
\t\treturn vars;
\t}

    jQuery("#AuthorizeNetPopupInner").amPopup({
        title: {$popupTitle}
    });
    jQuery("form#formAuthorizeNetPopup").submit();
});
</script>

CUT;
        $this->_response->setBody($this->view->render('layout.phtml'));
    }
Esempio n. 24
0
 public function run()
 {
     $prefix = $this->fieldName . '-';
     $ds = $this->grid->getDataSource();
     foreach ($this->grid->getRequest()->getPost() as $k => $v) {
         if (strpos($k, $prefix) === false) {
             continue;
         }
         $id = filterId(substr($k, strlen($prefix)));
         $record = $ds->getRecord($id);
         if (!$record) {
             throw new Am_Exception_InputError("Record [{$id}] not found");
         }
         $ds->updateRecord($record, array($this->fieldName => $v));
         $newValue = $v;
         $this->log('LiveEdit [' . $this->fieldName . ']');
     }
     $resp = array('ok' => true, 'message' => ___("Field Updated"), 'newValue' => $newValue);
     if ($this->callback) {
         $resp['callback'] = $this->callback;
     }
     Am_Controller::ajaxResponse($resp);
 }
Esempio n. 25
0
 public function expressCheckoutAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs)
 {
     $invoiceLog = $this->_logDirectAction($request, $response, $invokeArgs);
     $token = $request->getFiltered('token');
     if (!$token) {
         throw new Am_Exception_InputError("No required [token] provided, internal error");
     }
     $log = $this->getDi()->invoiceLogRecord;
     $log->title = "";
     $log->paysys_id = $this->getId();
     if ($request->getInt('do')) {
         $invoice = current($this->getDi()->invoiceTable->findByData(self::PAYPAL_EXPRESS_TOKEN, $token));
         if (!$invoice) {
             throw new Am_Exception_InternalError("Could not find invoice by token [{$token}]");
         }
         $invoiceLog->setInvoice($invoice);
         $this->_setInvoice($invoice);
         $log->setInvoice($invoice);
         if ($invoice->first_total > 0) {
             // bill initial amount @todo free trial
             $log->title .= " doExpressCheckout";
             $apireq = new Am_Paysystem_PaypalApiRequest($this);
             $apireq->doExpressCheckout($invoice, $token, $request->getFiltered('PayerID'));
             $vars = $apireq->sendRequest($log);
             $transaction = new Am_Paysystem_Transaction_PayPalExpress_DoExpressCheckout($this, $vars);
             $transaction->setInvoice($invoice);
             $transaction->process();
         }
         if ($invoice->rebill_times) {
             $log->title .= " createRecurringPaymentProfile";
             $apireq = new Am_Paysystem_PaypalApiRequest($this);
             $apireq->createRecurringPaymentProfile($invoice, null, $token, $request->getFiltered('PayerID'));
             $vars = $apireq->sendRequest($log);
             if (!in_array($vars['ACK'], array('Success', 'SuccessWithWarning'))) {
                 $this->logError("Not Success response to CreateRecurringPaymentProfile request", $vars);
             } else {
                 $invoice->data()->set(self::PAYPAL_PROFILE_ID, $vars['PROFILEID'])->update();
                 if ($invoice->first_total <= 0) {
                     $transaction = new Am_Paysystem_Transaction_PayPalExpress_CreateRecurringPaymentProfile($this, $vars);
                     $transaction->setInvoice($invoice);
                     $transaction->process();
                 }
             }
         }
         return Am_Controller::redirectLocation($this->getReturnUrl());
     } else {
         $log->title .= " getExpressCheckoutDetails";
         $apireq = new Am_Paysystem_PaypalApiRequest($this);
         $apireq->getExpressCheckoutDetails($token);
         $vars = $apireq->sendRequest($log);
         $invoiceId = filterId(get_first(@$vars['INVNUM'], @$vars['L_PAYMENTREQUEST_0_INVNUM'], $this->getDi()->session->paypal_invoice_id));
         if (!$invoiceId || !($invoice = $this->getDi()->invoiceTable->findBySecureId($invoiceId, 'paypal'))) {
             throw new Am_Exception_InputError("Could not find invoice related to given payment. Internal error. Your account was not billed, please try again");
         }
         $invoiceLog->setInvoice($invoice);
         $log->setInvoice($invoice);
         $log->update();
         $this->_setInvoice($invoice);
         /* @var $invoice Invoice */
         if ($invoice->isPaid()) {
             return Am_Controller::redirectLocation($this->getReturnUrl());
         }
         $invoice->data()->set(self::PAYPAL_EXPRESS_TOKEN, $token)->update();
         $view = new Am_View();
         $view->invoice = $invoice;
         $view->url = $this->getPluginUrl(self::PAYPAL_EXPRESS_CHECKOUT);
         $view->hidden = array('do' => '1', 'token' => $request->getFiltered('token'), 'PayerID' => $request->getFiltered('PayerID'));
         $view->display("payment-confirm.phtml");
     }
 }
 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;
 }