public static function activate($id, $pluginType)
    {
        try {
            Am_Di::getInstance()->db->query("CREATE TABLE ?_login_session (\n                login_session_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,\n                user_id INT UNSIGNED NOT NULL,\n                remote_addr varchar(39) NOT NULL,\n                session_id varchar(255) NOT NULL,\n                modified datetime NOT NULL,\n                need_logout TINYINT NOT NULL\n                ) CHARACTER SET utf8 COLLATE utf8_general_ci");
        } catch (Am_Exception_Db $e) {
        }
        try {
            Am_Di::getInstance()->db->query("CREATE INDEX user_id ON ?_login_session\n                (user_id)");
        } catch (Am_Exception_Db $e) {
        }
        $name = 'misc.single-login-session.notify_admin';
        $body = <<<CUT

Simultaneous login detected for the following user.

Login: %user.login%
Name: %user.name_f% %user.name_l%
Email: %user.email%

--
Best Regards,
%site_title%
%root_url%
CUT;
        $di = Am_Di::getInstance();
        $cnt = $di->db->selectCell("SELECT COUNT(*) AS cnt FROM ?_email_template WHERE name = ?", $name);
        if (!$cnt) {
            $di->db->query("INSERT INTO ?_email_template (name,lang,format,subject,txt) VALUES (?,?,?,?,?)", $name, 'en', 'text', 'Simultaneous login detected [%user.login%]', $body);
        }
    }
 protected function doBackup($stream, $tables, $gzip = false)
 {
     $db = Am_Di::getInstance()->db;
     $stream_filter = null;
     $hash = null;
     $len = 0;
     if ($gzip) {
         $hash = hash_init('crc32b');
         // gzip file header
         fwrite($stream, $this->getGzHeader());
         if (!($stream_filter = stream_filter_append($stream, "zlib.deflate", STREAM_FILTER_WRITE, self::COMPRESSION_LEVEL))) {
             throw new Am_Exception_InternalError("Could not attach gzencode filter to output stream");
         }
     }
     $this->out($stream, "### aMember Pro " . AM_VERSION . " database backup\n", $len, $hash);
     $this->out($stream, "### Created: " . date('Y-m-d H:i:s') . "\n", $len, $hash);
     foreach ($tables as $table) {
         $this->out($stream, "\n\nDROP TABLE IF EXISTS {$table};\n", $len, $hash);
         $r = $db->selectRow("SHOW CREATE TABLE {$table}");
         $this->out($stream, $r['Create Table'] . ";\n", $len, $hash);
         $q = $db->queryResultOnly("SELECT * FROM {$table}");
         while ($a = $db->fetchRow($q)) {
             $fields = join(',', array_keys($a));
             $values = join(',', array_map(array($db, 'escape'), array_values($a)));
             $this->out($stream, "INSERT INTO {$table} ({$fields}) VALUES ({$values});\n", $len, $hash);
         }
         $db->freeResult($q);
     }
     if ($stream_filter) {
         stream_filter_remove($stream_filter);
         fwrite($stream, $this->getGzFooter($len, $hash));
     }
     return $stream;
 }
    function init()
    {
        $this->addDataSource(new HTML_QuickForm2_DataSource_Array(array('_count' => 1, 'use_count' => 10, 'discount' => 10, 'discount_type' => '%', 'user_use_count' => 1, '_code_len' => 8)));
        if (!$this->record->isLoaded()) {
            $this->addElement('text', '_count', array('size' => 20))->setLabel(___("Coupons Count\nhow many coupons need to be generated"))->addRule('gt', 'Should be greater than 0', 0);
        }
        $this->addElement('text', 'use_count', array('size' => 20))->setLabel(___("Coupons Usage Count\n" . "how many times coupon can be used"));
        $discountGroup = $this->addElement('group')->setLabel(array('Discount'));
        $discountGroup->addElement('text', 'discount', array('size' => 5))->addRule('gt', 'must be greater than 0', 0);
        $discountGroup->addElement('select', 'discount_type')->loadOptions(array(Coupon::DISCOUNT_PERCENT => '%', Coupon::DISCOUNT_NUMBER => Am_Currency::getDefault()));
        $this->addElement('textarea', 'comment')->setLabel(___("Comment\nfor admin reference"));
        /// advanced settings
        $fs = $this->addAdvFieldset('advanced')->setLabel(___('Advanced Settings'));
        if (!$this->record->isLoaded()) {
            $fs->addElement('text', '_code_len', array('size' => 20))->setLabel(array(___("Code Length\ngenerated coupon code length\nbetween 5 and 32")))->addRule('gt', 'Should be greater than 4', 4)->addRule('lt', 'Should be less then 33', 33);
        }
        $fs->addElement('text', 'user_use_count', array('size' => 20))->setLabel(___("User Coupon Usage Count\nhow many times a coupon code can be used by customer"));
        $dateGroup = $fs->addElement('group')->setLabel(___("Dates\ndate range when coupon can be used"));
        $dateGroup->addCheckbox('_date-enable', array('class' => 'enable_date'));
        $begin = $dateGroup->addDate('begin_date');
        $expire = $dateGroup->addDate('expire_date');
        $fs->addElement('advcheckbox', 'is_recurring')->setLabel(___("Apply to recurring?\n" . "apply coupon discount to recurring rebills?"));
        $fs->addElement('advcheckbox', 'is_disabled')->setLabel(___("Is Disabled?\n" . "If you disable this coupons batch, it will\n" . "not be available for new purchases.\n" . "Existing invoices are not affected.\n"));
        $fs->addElement('select', 'product_ids', array('multiple' => 1, 'class' => 'magicselect'))->loadOptions(Am_Di::getInstance()->productTable->getOptions())->setLabel(___("Products\n" . "coupons can be used with selected products only.\n" . "if nothing selected, coupon can be used with any product"));
        $jsCode = <<<CUT
\$(".enable_date").prop("checked", \$("input[name=expire_date]").val() ? "checked" : "");   
\$(".enable_date").live("change", function(){
    var dates = \$(this).parent().find("input[type=text]");
    dates.prop('disabled', \$(this).prop("checked") ? '' : 'disabled');
}).trigger("change");
CUT;
        $fs->addScript('script')->setScript($jsCode);
    }
Esempio n. 4
0
 protected function createAdapter()
 {
     $q = new Am_Query(Am_Di::getInstance()->newsletterListTable);
     $q->leftJoin('?_newsletter_user_subscription', 's', 's.list_id = t.list_id AND s.is_active > 0');
     $q->addField('COUNT(s.list_id)', 'subscribed_users');
     return $q;
 }
Esempio n. 5
0
 function addDefaultPages()
 {
     $this->addPage(array('id' => 'member', 'controller' => 'member', 'label' => ___('Dashboard'), 'order' => 0));
     $this->addPage(array('id' => 'add-renew', 'controller' => 'signup', 'action' => 'index', 'label' => ___('Add/Renew Subscription'), 'order' => 100));
     $this->addPage(array('id' => 'payment-history', 'controller' => 'member', 'action' => 'payment-history', 'label' => ___('Payments History'), 'order' => 200));
     $this->addPage(array('id' => 'profile', 'controller' => 'profile', 'label' => ___('Edit Profile'), 'order' => 300));
     try {
         $user = Am_Di::getInstance()->user;
     } catch (Am_Exception_Db_NotFound $e) {
         $user = null;
     }
     if ($user) {
         $tree = Am_Di::getInstance()->resourceCategoryTable->getAllowedTree($user);
         $pages = array();
         foreach ($tree as $node) {
             $pages[] = $this->getContentCategoryPage($node);
         }
         if (count($pages)) {
             $this->addPages($pages);
         }
     }
     Am_Di::getInstance()->hook->call(Am_Event::USER_MENU, array('menu' => $this, 'user' => $user));
     /// workaround against using the current route for generating urls
     foreach (new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST) as $child) {
         if ($child instanceof Zend_Navigation_Page_Mvc && $child->getRoute() === null) {
             $child->setRoute('default');
         }
     }
 }
Esempio n. 6
0
 protected function getMember($user_id)
 {
     if (!isset(self::$cacheMembers[$user_id])) {
         self::$cacheMembers[$user_id] = Am_Di::getInstance()->userTable->load($user_id);
     }
     return self::$cacheMembers[$user_id];
 }
Esempio n. 7
0
 public function sendRequest($method, $params = array())
 {
     $this->vars = $params;
     $this->vars['api_key'] = $this->plugin->getConfig('api_key');
     $this->vars['api_user'] = $this->plugin->getConfig('api_user');
     $this->setUrl(self::API_URL . '/' . $method . '.json');
     foreach ($this->vars as $k => $v) {
         $this->addPostParameter($k, $v);
     }
     $ret = parent::send();
     if ($ret->getStatus() != '200') {
         throw new Am_Exception_InternalError("SendGrid  API Error:" . $ret->getBody());
     }
     $body = $ret->getBody();
     if (!$body) {
         return array();
     }
     $arr = json_decode($body, true);
     if (!$arr) {
         throw new Am_Exception_InternalError("SendGrid API Error - unknown response [" . $ret->getBody() . "]");
     }
     if (@$arr['message'] == 'error') {
         Am_Di::getInstance()->errorLogTable->log("Sendgrid API Error - [" . implode(', ', $arr['errors']) . "]");
         return false;
     }
     return $arr;
 }
Esempio n. 8
0
 /**
  * This function is likely never returns
  * but anyway handle result and exceptions
  * @return Am_Paysystem_Result
  */
 function process()
 {
     Am_Di::getInstance()->hook->call(Am_Event::INVOICE_BEFORE_PAYMENT, array('invoice' => $this->invoice, 'controller' => $this->controller));
     $plugin = Am_Di::getInstance()->plugins_payment->loadGet($this->invoice->paysys_id);
     $this->result = new Am_Paysystem_Result();
     $plugin->processInvoice($this->invoice, $this->controller->getRequest(), $this->result);
     if ($this->result->isSuccess() || $this->result->isFailure()) {
         if ($transaction = $this->result->getTransaction()) {
             $transaction->setInvoice($this->invoice);
             $transaction->process();
         }
     }
     if ($this->result->isSuccess()) {
         if (method_exists($this->controller, 'getForm')) {
             $this->controller->getForm()->getSessionContainer()->destroy();
         }
         $url = REL_ROOT_URL . "/thanks?id=" . $this->invoice->getSecureId('THANKS');
         $this->callback($this->onSuccess);
         $this->controller->redirectLocation($url);
         // no return
         // Am_Exception_Redirect only for APPLICATION_ENV = 'testing'
     } elseif ($this->result->isAction()) {
         if (method_exists($this->controller, 'getForm')) {
             $this->controller->getForm()->getSessionContainer()->destroy();
         }
         $this->callback($this->onAction);
         $this->result->getAction()->process($this->controller);
         // no return
         // Am_Exception_Redirect only for APPLICATION_ENV = 'testing'
     } else {
         //  ($result->isFailure()) {
         $this->callback($this->onFailure);
     }
     return $this->result;
 }
Esempio n. 9
0
 public function insertBrick(HTML_QuickForm2_Container $form)
 {
     $module = Am_Di::getInstance()->modules->loadGet('aff');
     if ($module->getConfig('payout_methods')) {
         Am_Di::getInstance()->modules->loadGet('aff')->addPayoutInputs($form);
     }
 }
Esempio n. 10
0
 function metacharge_get_period($period)
 {
     // For scheduled payments based upon this transaction, the interval between payments,
     // given as XY where X is a number (1-999) and Y is “D” for days, “W” for weeks or “M” for months.
     $days = strtolower(trim($days));
     if (preg_match('/^(\\d+)(d|w|m|y)$/', $period, $regs)) {
         $count = $regs[1];
         $period = $regs[2];
         if ($period == 'd') {
             return sprintf("%03d", $count) . "D";
         } elseif ($period == 'w') {
             return sprintf("%03d", $count) . "W";
         } elseif ($period == 'm') {
             return sprintf("%03d", $count) . "M";
         } elseif ($period == 'y') {
             return sprintf("%03d", $count * 12) . "M";
         } else {
             Am_Di::getInstance()->errorLogTable->log("METACHARGE. {$period} is not supported");
             throw new Am_Exception_InternalError();
         }
     } elseif (preg_match('/^\\d+$/', $days)) {
         return sprintf("%03d", $days) . "D";
     } else {
         Am_Di::getInstance()->errorLogTable->log("METACHARGE. {$period} is not supported");
         throw new Am_Exception_InternalError();
     }
 }
Esempio n. 11
0
 function addDefaultPages()
 {
     $separator = new Am_Navigation_Admin_Item_Separator();
     $this->addPage(array('id' => 'dashboard', 'controller' => 'admin', 'label' => ___('Dashboard')));
     $this->addPage(Zend_Navigation_Page::factory(array('id' => 'users', 'uri' => '#', 'label' => ___('Users'), 'resource' => 'grid_u', 'privilege' => 'browse', 'pages' => array_merge(array(array('id' => 'users-browse', 'controller' => 'admin-users', 'label' => ___('Browse Users'), 'resource' => 'grid_u', 'privilege' => 'browse', 'class' => 'bold'), array('id' => 'users-insert', 'uri' => REL_ROOT_URL . '/admin-users?_u_a=insert', 'label' => ___('Add User'), 'resource' => 'grid_u', 'privilege' => 'insert')), !Am_Di::getInstance()->config->get('manually_approve') ? array() : array(array('id' => 'user-not-approved', 'controller' => 'admin-users', 'action' => 'not-approved', 'label' => ___('Not Approved Users'), 'resource' => 'grid_u', 'privilege' => 'browse')), array(array('id' => 'users-email', 'controller' => 'admin-email', 'label' => ___('E-Mail Users'), 'resource' => Am_Auth_Admin::PERM_EMAIL), clone $separator, array('id' => 'users-import', 'controller' => 'admin-import', 'label' => ___('Import Users'), 'resource' => Am_Auth_Admin::PERM_IMPORT))))));
     $this->addPage(array('id' => 'reports', 'uri' => '#', 'label' => ___('Reports'), 'pages' => array(array('id' => 'reports-reports', 'controller' => 'admin-reports', 'label' => ___('Reports'), 'resource' => Am_Auth_Admin::PERM_REPORT), array('id' => 'reports-payments', 'type' => 'Am_Navigation_Page_Mvc', 'controller' => 'admin-payments', 'label' => ___('Payments'), 'resource' => array('grid_payment', 'grid_invoice')))));
     $this->addPage(array('id' => 'products', 'uri' => '#', 'label' => ___('Products'), 'pages' => array_filter(array(array('id' => 'products-manage', 'controller' => 'admin-products', 'label' => ___('Manage Products'), 'resource' => 'grid_product', 'class' => 'bold'), array('id' => 'products-coupons', 'controller' => 'admin-coupons', 'label' => ___('Coupons'), 'resource' => 'grid_coupon')))));
     /**
      *  Temporary disable this menu if user is on upgrade controller in order to avoid error: 
      *  Fatal error: Class Folder contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (ResourceAbstract::getAccessType)
      *  
      *   @todo Remove this in the future;
      * 
      */
     $content_pages = array();
     if (Zend_Controller_Front::getInstance()->getRequest()->getControllerName() != 'admin-upgrade') {
         foreach (Am_Di::getInstance()->resourceAccessTable->getAccessTables() as $t) {
             $k = $t->getPageId();
             $content_pages[] = array('id' => 'content-' . $k, 'module' => 'default', 'controller' => 'admin-content', 'action' => 'index', 'label' => $t->getAccessTitle(), 'resource' => 'grid_content', 'params' => array('page_id' => $k), 'route' => 'inside-pages');
         }
     }
     $this->addPage(array('id' => 'content', 'controller' => 'admin-content', 'label' => ___('Protect Content'), 'resource' => 'grid_content', 'class' => 'bold', 'pages' => $content_pages));
     $this->addPage(array('id' => 'configuration', 'uri' => '#', 'label' => ___('Configuration'), 'pages' => array_filter(array(array('id' => 'setup', 'controller' => 'admin-setup', 'label' => ___('Setup/Configuration'), 'resource' => Am_Auth_Admin::PERM_SETUP, 'class' => 'bold'), array('id' => 'saved-form', 'controller' => 'admin-saved-form', 'label' => ___('Forms Editor'), 'resource' => @constant('Am_Auth_Admin::PERM_FORM'), 'class' => 'bold'), array('id' => 'fields', 'controller' => 'admin-fields', 'label' => ___('Add User Fields'), 'resource' => @constant('Am_Auth_Admin::PERM_ADD_USER_FIELD')), array('id' => 'email-template-layout', 'controller' => 'admin-email-template-layout', 'label' => ___('Email Layouts'), 'resource' => Am_Auth_Admin::PERM_SETUP), array('id' => 'ban', 'controller' => 'admin-ban', 'label' => ___('Blocking IP/E-Mail'), 'resource' => @constant('Am_Auth_Admin::PERM_BAN')), array('id' => 'countries', 'controller' => 'admin-countries', 'label' => ___('Countries/States'), 'resource' => @constant('Am_Auth_Admin::PERM_COUNTRY_STATE')), array('id' => 'admins', 'controller' => 'admin-admins', 'label' => ___('Admin Accounts'), 'resource' => Am_Auth_Admin::PERM_SUPER_USER), array('id' => 'change-pass', 'controller' => 'admin-change-pass', 'label' => ___('Change Password'))))));
     $this->addPage(array('id' => 'utilites', 'uri' => '#', 'label' => ___('Utilities'), 'order' => 1000, 'pages' => array_filter(array(Am_Di::getInstance()->modules->isEnabled('cc') ? null : array('id' => 'backup', 'controller' => 'admin-backup', 'label' => ___('Backup'), 'resource' => Am_Auth_Admin::PERM_BACKUP_RESTORE), Am_Di::getInstance()->modules->isEnabled('cc') ? null : array('id' => 'restore', 'controller' => 'admin-restore', 'label' => ___('Restore'), 'resource' => Am_Auth_Admin::PERM_BACKUP_RESTORE), array('id' => 'rebuild', 'controller' => 'admin-rebuild', 'label' => ___('Rebuild Db'), 'resource' => @constant('Am_Auth_Admin::PERM_REBUILD_DB')), clone $separator, array('id' => 'logs', 'type' => 'Am_Navigation_Page_Mvc', 'controller' => 'admin-logs', 'label' => ___('Logs'), 'resource' => array(@constant('Am_Auth_Admin::PERM_LOGS'), @constant('Am_Auth_Admin::PERM_LOGS_ACCESS'), @constant('Am_Auth_Admin::PERM_LOGS_INVOICE'), @constant('Am_Auth_Admin::PERM_LOGS_MAIL'), @constant('Am_Auth_Admin::PERM_LOGS_ADMIN'))), array('id' => 'info', 'controller' => 'admin-info', 'label' => ___('System Info'), 'resource' => @constant('Am_Auth_Admin::PERM_SYSTEM_INFO')), clone $separator, array('id' => 'trans-global', 'controller' => 'admin-trans-global', 'label' => ___('Edit Messages'), 'resource' => @constant('Am_Auth_Admin::PERM_TRANSLATION')), array('id' => 'clear', 'controller' => 'admin-clear', 'label' => ___('Delete Old Records'), 'resource' => @constant('Am_Auth_Admin::PERM_CLEAR')), array('id' => 'build-demo', 'controller' => 'admin-build-demo', 'label' => ___('Build Demo'), 'resource' => @constant('Am_Auth_Admin::PERM_BUILD_DEMO'))))));
     $this->addPage(array('id' => 'help', 'uri' => '#', 'label' => ___('Help & Support'), 'order' => 1001, 'pages' => array_filter(array(array('id' => 'documentation', 'uri' => 'http://www.amember.com/docs/', 'target' => '_blank', 'label' => ___('Documentation')), array('id' => 'report-bugs', 'uri' => 'http://bt.amember.com/', 'target' => '_blank', 'label' => ___('Report Bugs'))))));
     Am_Di::getInstance()->hook->call(Am_Event::ADMIN_MENU, array('menu' => $this));
     /// workaround against using the current route for generating urls
     foreach (new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST) as $child) {
         if ($child instanceof Zend_Navigation_Page_Mvc && $child->getRoute() === null) {
             $child->setRoute('default');
         }
     }
 }
Esempio n. 12
0
    public function initConfigForm(Am_Form $form)
    {
        $el = $form->addSelect('type', array('id' => 'newsletter-type-select'))->setLabel(___('Type'));
        $el->addOption(___('Single Checkbox'), 'checkbox');
        $el->addOption(___('Checkboxes for Selected Lists'), 'checkboxes');
        $form->addAdvCheckbox('no_label', array('id' => 'newsletter-no-label'))->setLabel(___("Hide Label"));
        $form->addScript()->setScript(<<<CUT
\$(function(){
    \$('#newsletter-type-select').change(function(){
        \$('#newsletter-no-label').closest('.row').toggle(\$(this).val() == 'checkbox')
    }).change();
})
CUT
);
        $lists = $form->addSortableMagicSelect('lists', array('id' => 'newsletter-lists-select'))->setLabel(___("Lists\n" . 'All List will be displayed if none selected'));
        $lists->loadOptions(Am_Di::getInstance()->newsletterListTable->getAdminOptions());
        $form->addScript()->setScript(<<<CUT
jQuery(document).ready(function(\$) {
    \$("#newsletter-type-select").change(function(){
        var val = \$(this).val();
        \$("#row-newsletter-lists-select").toggle(val == 'checkboxes');
    }).change();
});
CUT
);
        $form->addAdvCheckbox('unchecked')->setLabel(___("Default unchecked\n" . 'Leave unchecked if you want newsletter default to be checked'));
    }
 /**
  * This function is likely never returns
  * but anyway handle result and exceptions
  * @return Am_Paysystem_Result
  */
 function process()
 {
     $err = $this->invoice->validate();
     if ($err) {
         throw new Am_Exception_InputError($err[0]);
     }
     $this->invoice->save();
     $plugin = Am_Di::getInstance()->plugins_payment->loadGet($this->invoice->paysys_id);
     $this->result = new Am_Paysystem_Result();
     $plugin->processInvoice($this->invoice, $this->controller->getRequest(), $this->result);
     if ($this->result->isSuccess() || $this->result->isFailure()) {
         if ($transaction = $this->result->getTransaction()) {
             $transaction->setInvoice($this->invoice);
             $transaction->process();
         }
     }
     if ($this->result->isSuccess()) {
         $url = REL_ROOT_URL . "/thanks?id=" . $this->invoice->getSecureId('THANKS');
         $this->callback($this->onSuccess);
         $this->controller->redirectLocation($url, ___("Invoice processed"), ___("Invoice processed successfully"));
         // no return Am_Exception_Redirect
     } elseif ($this->result->isAction()) {
         $this->callback($this->onAction);
         $this->result->getAction()->process($this->controller);
         // no return Am_Exception_Redirect
     } else {
         //  ($result->isFailure()) {
         $this->callback($this->onFailure);
     }
     return $this->result;
 }
Esempio n. 14
0
 function assignStdVars()
 {
     $this->assign('site_title', Am_Di::getInstance()->config->get('site_title', 'aMember Pro'));
     $this->assign('root_url', ROOT_URL);
     $this->assign('root_surl', ROOT_SURL);
     return $this;
 }
Esempio n. 15
0
 function _getCrypt()
 {
     if (empty($this->_crypt)) {
         $this->_crypt = Am_Di::getInstance()->crypt;
     }
     return $this->_crypt;
 }
Esempio n. 16
0
 function init()
 {
     if (!class_exists('Am_Form_Brick', false)) {
         class_exists('Am_Form_Brick', true);
         Am_Di::getInstance()->hook->call(Am_Event::LOAD_BRICKS);
     }
     parent::init();
 }
Esempio n. 17
0
 protected function getData()
 {
     if (isset(self::$cache[$this->locale])) {
         return self::$cache[$this->locale];
     }
     $data = Am_Di::getInstance()->cacheFunction->call(array('Am_Locale', '_readData'), array($this->locale));
     return self::$cache[$this->locale] = $data;
 }
Esempio n. 18
0
 public function checkLogin($login)
 {
     $admin = Am_Di::getInstance()->adminTable->findFirstByLogin($login);
     if (!$admin) {
         $admin = Am_Di::getInstance()->adminTable->findFirstByEmail($login);
     }
     return (bool) $admin;
 }
Esempio n. 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);
     }
 }
Esempio n. 20
0
 public function void()
 {
     $record = $this->grid->getRecord();
     if (!$record->is_voided) {
         Am_Di::getInstance()->affCommissionTable->void($record);
     }
     $this->log();
     $this->grid->redirectBack();
 }
Esempio n. 21
0
 function init()
 {
     if (!class_exists('Am_Form_Brick', false)) {
         class_exists('Am_Form_Brick', true);
         Am_Di::getInstance()->hook->call(Am_Event::LOAD_BRICKS);
     }
     parent::init();
     $this->msg = ___('We review all affiliates manually, so your affiliate account status is pending. ' . 'You will receive email when your account will be approved. Thank you for your patience.');
 }
Esempio n. 22
0
 public function validateSource()
 {
     $str = $this->request->getFiltered("fp_paidto") . ":" . $this->request->getFiltered("fp_paidby") . ":" . $this->request->get("fp_store") . ":" . $this->request->get("fp_amnt") . ":" . $this->request->getFiltered("fp_batchnumber") . ":" . $this->request->getFiltered("fp_currency") . ":" . $this->getPlugin()->getConfig('security_word');
     $hash = hash('sha256', $str);
     if ($hash == $this->request->getFiltered("fp_hash")) {
         return true;
     }
     Am_Di::getInstance()->errorLogTable->log("[Fasapay-incoming]: Transaction HASH [{$this->request->getFiltered("fp_hash")}] does not match expected [{$hash}]");
 }
Esempio n. 23
0
 public function validate()
 {
     $event = new Am_Event_ValidateSavedForm($this->getValue(), $this);
     Am_Di::getInstance()->hook->call($event);
     if ($errors = $event->getErrors()) {
         $this->setError($errors[0]);
         return false;
     }
     return parent::validate();
 }
Esempio n. 24
0
 public function onAfterInsertMessage($message)
 {
     if (Am_Di::getInstance()->config->get('helpdesk.notify_new_message_admin', 1)) {
         $et = Am_Mail_Template::load('helpdesk.notify_new_message_admin');
         if ($et) {
             $et->setUrl(sprintf('%s/helpdesk/admin/p/view/view/ticket/%s', Am_Di::getInstance()->config->get('root_surl'), $message->getTicket()->ticket_mask));
             $et->send(Am_Mail_Template::TO_ADMIN);
         }
     }
 }
Esempio n. 25
0
 function indexAction()
 {
     if (!Am_Di::getInstance()->config->get('aff.tracking_code')) {
         $this->log('Click logging disabled in config');
     } elseif ($this->aff = $this->findAff()) {
         $aff_click_id = $this->getDi()->affClickTable->log($this->aff, null, $this->getParam('s'));
         $this->getModule()->setCookie($this->aff, null, $aff_click_id);
         $this->log('Click Logged');
     }
 }
Esempio n. 26
0
 public function calculate(Invoice $invoiceBill)
 {
     $user = $invoiceBill->getUser();
     if (!$user) {
         $user = Am_Di::getInstance()->userRecord;
     }
     $this->tax_rate = $this->getTaxRate($user);
     $invoiceBill->tax_rate = $this->tax_rate;
     parent::calculate($invoiceBill);
 }
Esempio n. 27
0
 function process()
 {
     try {
         parent::process();
     } catch (Am_Exception_Paysystem_TransactionAlreadyHandled $e) {
         // do nothing if transaction is already handled
     }
     if (Am_Di::getInstance()->config->get('auto_login_after_signup')) {
         Am_Di::getInstance()->auth->setUser($this->invoice->getUser(), $this->request->getClientIp());
     }
 }
Esempio n. 28
0
    function getJs()
    {
        $countries = json_encode(Am_Di::getInstance()->countryTable->getOptions());
        $states = array();
        foreach (Am_Di::getInstance()->db->select("SELECT country, state, title FROM ?_state") as $r) {
            $states[$r['country']][$r['state']] = $r['title'];
        }
        $states = json_encode($states);
        $name = $this->getName();
        $remove = ___('Remove');
        return <<<CUT
<script type='text/javascript'>
\$(function(){
    var countries = {$countries};
    var states = {$states};
    \$("#regional-tax-country").change(function(){
        var sel = \$("#regional-tax-state");
        sel.find('option').remove();
        var options = states[ \$(this).val() ];
        sel.append(\$('<option>'));
        if (!options) return;
        \$.each(options, function(key, value) {   
            sel.append(\$('<option>', { value : key })
                .text(value)); 
        });
    });
    \$("#regional-tax-add-button").click(function(){
        var c = \$("#regional-tax-country").val();
        var r = \$("#regional-tax-rate").val();
        if (!c || !r) {
            flashError("Country and Tax Rate fields are required");
            return;
        }
        var s = \$("#regional-tax-state").val();
        var z = \$("#regional-tax-zip").val();
        //
        var row = \$("<tr />");
        row.append(\$("<td />").text(countries[c]));
        row.append(\$("<td />").text(states[c][s] ? states[c][s] : ''));
        row.append(\$("<td />").text(z));
        row.append(\$("<td />").text(r));
        var hidden = \$("<input type='hidden' name='{$name}[]'/>").val(c+'|'+s+'|'+z+'|'+r);
        row.append(\$("<td><a href='javascript:' class='regional-tax-remove'>{$remove}</a></td>").append(hidden));
        \$("#regional-tax-zip").val("");
        \$("#regional-tax-state").val("");
        \$("#regional-tax-table").append(row);
    });
    \$(document).on('click',"a.regional-tax-remove", function(){
        \$(this).closest("tr").remove();
    });
});
</script>
CUT;
    }
 function validateSignedLink($id)
 {
     @(list($rec_id, $time, $hash) = explode('-', $id, 3));
     if ($rec_id <= 0) {
         throw new Am_Exception_InputError("Wrong video id#");
     }
     if ($time < Am_Di::getInstance()->time) {
         throw new Am_Exception_InputError("Video Link Expired");
     }
     if ($hash != $this->getDi()->app->hash("am-video-{$rec_id}-{$time}", 10)) {
         throw new Am_Exception_InputError("Video Link Error - Wrong Sign");
     }
 }
Esempio n. 30
0
 static function getAvailableOptions()
 {
     $ret = array();
     foreach (get_declared_classes() as $className) {
         if (strpos($className, __CLASS__ . '_') === 0) {
             $o = new $className();
             $ret[$o->getId()] = $o->getTitle();
         }
     }
     $event = new Am_Event(Bootstrap_Aff::AFF_GET_PAYOUT_OPTIONS);
     $event->setReturn($ret);
     Am_Di::getInstance()->hook->call($event);
     return $event->getReturn();
 }