Example #1
0
 function addTo($date)
 {
     if ($this->isEmpty()) {
         throw new Am_Exception_InternalError("Could not do this operation on empty object " . __METHOD__);
     }
     if ($this->unit == self::FIXED) {
         return $this->count;
     }
     list($y, $m, $d) = explode('-', sqlDate($date));
     $tm = amstrtotime($date);
     switch ($this->unit) {
         case self::DAY:
             $tm2 = mktime(0, 0, 0, $m, $d + $this->count, $y);
             break;
         case self::MONTH:
             $tm2 = mktime(0, 0, 0, $m + $this->count, $d, $y);
             break;
         case self::YEAR:
             $tm2 = mktime(0, 0, 0, $m, $d, $y + $this->count);
             break;
         default:
             throw new Am_Exception_InternalError("Unknown period unit configured in " . $this->__toString());
     }
     if ($tm2 < $tm) {
         // overflow, assign fixed "lifetime" date
         return self::MAX_SQL_DATE;
     }
     return date('Y-m-d', $tm2);
 }
 function getYearMonthOptions($starttime)
 {
     $options = array();
     list($m, $y) = explode('-', date('m-Y', amstrtotime($starttime)));
     $end = date('Ym');
     do {
         $options[$key = sprintf("%04d%02d", $y, $m)] = date("F Y", mktime(1, 1, 1, $m, 1, $y));
         if (++$m >= 13) {
             $m = 1;
             $y++;
         }
     } while ($key < $end);
     return $options;
 }
Example #3
0
 public function getLabel($key)
 {
     list($start, $stop) = $this->getStartStop($key);
     $start = amstrtotime($start);
     $stop = amstrtotime($stop);
     $month = Am_Di::getInstance()->locale->getMonthNames('abbreviated', false);
     return $month[date('n', $start)] . date(' Y', $start) . '-' . $month[date('n', $stop)] . date(' Y', $stop);
 }
Example #4
0
function sqlTime($tm)
{
    if (!$tm instanceof DateTime && preg_match('/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/', $tm)) {
        return $tm;
    } else {
        return date('Y-m-d H:i:s', amstrtotime($tm));
    }
}
Example #5
0
 public function getFileName()
 {
     $filename = $this->getDi()->config->get('invoice_filename', 'amember-invoice-%public_id%.pdf');
     $filename = str_replace('%payment.date%', date('Y-m-d', amstrtotime($this->payment->dattm)), $filename);
     $tmp = new Am_SimpleTemplate();
     $tmp->assign('public_id', $this->invoice->public_id);
     $tmp->assign('receipt_id', $this->payment->receipt_id);
     $tmp->assign('payment', $this->payment);
     $tmp->assign('invoice', $this->invoice);
     $tmp->assign('user', $this->invoice->getUser());
     return $tmp->render($filename);
 }
Example #6
0
 public function getValue($lineParsed, $partialRecord = null)
 {
     $rawValue = $this->getRawValue($lineParsed, $partialRecord);
     return $rawValue ? date('Y-m-d', amstrtotime($rawValue)) : '';
 }
Example #7
0
 /**
  * Generate payout records for records on $date
  * @param date $date today's date
  */
 function runPayout($date)
 {
     $threseholdDate = sqlDate(amstrtotime($date) - 24 * 3600 * $this->getDi()->config->get('aff.payout_delay_days', 30));
     // now select all affiliates to pay with one query
     $q = $this->_db->queryResultOnly("\n            SELECT SUM(IF(c.record_type=?,-c.amount,c.amount)) AS _total,\n                a.*\n            FROM ?_aff_commission c RIGHT JOIN ?_user a ON a.user_id=c.aff_id\n            WHERE (c.record_type=? OR c.date<=?) AND (c.payout_detail_id IS NULL)\n            GROUP BY c.aff_id\n            HAVING _total > 0 AND _total >= ?  AND a.aff_payout_type > ''\n        ", AffCommission::VOID, AffCommission::VOID, $threseholdDate, (double) $this->getDi()->config->get('aff.payout_min', 0));
     // then do job
     $payouts = array();
     while ($row = $this->_db->fetchRow($q)) {
         $aff = $this->getDi()->userTable->createRecord($row);
         if (empty($payouts[$aff->aff_payout_type])) {
             $payout = $this->getDi()->affPayoutRecord;
             $payout->type = $aff->aff_payout_type;
             $payout->date = sqlDate($date);
             $payout->thresehold_date = $threseholdDate;
             $payout->insert();
             $payouts[$aff->aff_payout_type] = $payout;
         }
         $detail = $payouts[$aff->aff_payout_type]->addDetail($aff->pk(), $row['_total']);
         $this->_db->query("UPDATE ?_aff_commission c\n                SET c.payout_detail_id=?d\n                WHERE aff_id=?d AND (c.record_type=? OR c.date<=?) AND (c.payout_detail_id IS NULL)\n                ", $detail->pk(), $aff->pk(), AffCommission::VOID, $threseholdDate);
     }
     foreach ($payouts as $payout) {
         $payout->update();
     }
     // store totals
     if ($payouts) {
         $this->getDi()->hook->call(Bootstrap_Aff::AFF_PAYOUT, array('payouts' => $payouts));
         if ($et = Am_Mail_Template::load('aff.new_payouts')) {
             $et->setUrl(ROOT_SURL . '/aff/admin-payout')->sendAdmin();
         }
     }
 }
Example #8
0
 public function renderTime($record, $fieldName)
 {
     return sprintf('<td><time title="%s" datetime="%s">%s</time></td>', amDatetime($record->{$fieldName}), date('c', amstrtotime($record->{$fieldName})), $this->getView()->getElapsedTime($record->{$fieldName}));
 }
Example #9
0
 function onBuildDemo(Am_Event $event)
 {
     $referrers = array('http://example.com/some/url.html', 'http://example.com/some/other/url.html', 'http://example.com/page/offer.html', 'http://example.com/very/very/long/referrer/url.html', 'http://example.com/referrer.html');
     static $banners = null;
     if (is_null($banners)) {
         $banners = $this->getDi()->affBannerTable->findBy();
         array_push($banners, null);
     }
     $user = $event->getUser();
     $user->is_affiliate = 1;
     $user->aff_payout_type = 'check';
     if (rand(0, 10) < 4) {
         $aff_id = $this->getDi()->db->selectCell("SELECT `id`\n                FROM ?_data\n                WHERE `table`='user' AND `key`='demo-id' AND `value`=?\n                LIMIT ?d, 1", $event->getDemoId(), rand(0, $event->getUsersCreated()));
         if ($aff_id) {
             $aff = $this->getDi()->userTable->load($aff_id);
             $banner = $banners[array_rand($banners)];
             $banner_id = $banner ? $banner->pk() : null;
             $user->aff_id = $aff_id;
             $user->aff_added = $user->added;
             $user->data()->set('aff-source', 'cookie');
             $server = $_SERVER;
             $_SERVER['REMOTE_ADDR'] = $user->remote_addr;
             $_SERVER['HTTP_REFERER'] = $referrers[array_rand($referrers)];
             $this->getDi()->setService('time', amstrtotime($user->added) - rand(5 * 60, 3600));
             $aff_click_id = $this->getDi()->affClickTable->log($aff, $banner);
             $this->getDi()->setService('time', amstrtotime($user->added));
             $this->getDi()->affLeadTable->log($aff_id, $banner_id, $user->pk(), $aff_click_id);
             $_SERVER = $server;
             $this->getDi()->setService('time', time());
         }
     }
 }
Example #10
0
 function fetchByDate($date, $aff_id = null)
 {
     return $this->selectRecords("SELECT * FROM ?_aff_click WHERE time BETWEEN ? AND ? { AND aff_id=?d}", date('Y-m-d 00:00:00', amstrtotime($date)), date('Y-m-d 23:59:59', amstrtotime($date)), $aff_id === null ? DBSIMPLE_SKIP : $aff_id);
 }
    function init()
    {
        /* General Settings */
        $fieldSet = $this->addElement('fieldset', 'general', array('id' => 'general', 'label' => ___('General')));
        $login = $fieldSet->addText('login', array('class' => 'el-wide'))->setLabel(___('Username'))->setId('login');
        $login->addRule('required');
        $login->addRule('callback2', '-error-', array($this, 'checkUniqLogin'));
        if ($this->record->isLoaded()) {
            $countSameIp = Am_Di::getInstance()->userTable->countBy(array('remote_addr' => $this->record->remote_addr, 'user_id' => '<>' . $this->record->pk()));
            $ban = Am_Di::getInstance()->banTable->findBan(array('ip' => $this->record->remote_addr));
            $banInfoHtml = $ban ? sprintf('<strong>%s</strong>', Am_Controller::escape(___('This IP is Banned'))) : (Am_Di::getInstance()->authAdmin->getUser()->hasPermission(Am_Auth_Admin::PERM_BAN) ? sprintf('<a class="link" href="%s">%s</a>', REL_ROOT_URL . '/admin-ban?' . http_build_query(array('_ip_a' => 'insert', '_ip_b' => Am_Di::getInstance()->view->userUrl($this->record->pk()), 'value' => $this->record->remote_addr, 'comment' => sprintf('%s (%s %s)', $this->record->login, $this->record->name_f, $this->record->name_l))), Am_Controller::escape(___('Block This IP Address'))) : '');
            $fieldSet->addStatic('_signup_info', null, array('label' => ___('Signup Info')))->setContent(sprintf('<div>%s%s%s<time title="%s" datetime="%s">%s</time> %s</div>%s', $this->record->remote_addr, $this->record->user_agent ? sprintf(' (<span title="%s">%s&hellip;</span>)', Am_Controller::escape($this->record->user_agent), Am_Controller::escape(trim(substr($this->record->user_agent, 0, 12)))) : '', ___(' at '), Am_Di::getInstance()->view->getElapsedTime($this->record->added), date('c', amstrtotime($this->record->added)), amDatetime($this->record->added), $banInfoHtml, $countSameIp ? '<div>' . ___('There is %s users with same registration IP Address', '<a class="link" href="' . REL_ROOT_URL . '/admin-users?_u_filter=' . $this->record->remote_addr . '">' . $countSameIp . '</a>') . '</div>' : ''));
            $ban = Am_Di::getInstance()->banTable->findBan(array('ip' => $this->record->last_ip));
            $banInfoHtml = $ban ? sprintf(' <strong>%s</strong>', Am_Controller::escape(___('This IP is Banned'))) : (Am_Di::getInstance()->authAdmin->getUser()->hasPermission(Am_Auth_Admin::PERM_BAN) ? sprintf(' <a class="link" href="%s">%s</a>', REL_ROOT_URL . '/admin-ban?' . http_build_query(array('_ip_a' => 'insert', '_ip_b' => Am_Di::getInstance()->view->userUrl($this->record->pk()), 'value' => $this->record->last_ip, 'comment' => sprintf('%s (%s %s)', $this->record->login, $this->record->name_f, $this->record->name_l))), Am_Controller::escape(___('Block This IP Address'))) : '');
            $fieldSet->addStatic('_signin_info', null, array('label' => ___('Last Signin Info')))->setContent(sprintf("<div>%s</div>", $this->record->last_login ? sprintf('%s%s%s<time title="%s" datetime="%s">%s</time> %s', $this->record->last_ip, $this->record->last_user_agent ? sprintf(' (<span title="%s">%s&hellip;</span>)', Am_Controller::escape($this->record->last_user_agent), Am_Controller::escape(trim(substr($this->record->last_user_agent, 0, 12)))) : '', ___(' at '), Am_Di::getInstance()->view->getElapsedTime($this->record->last_login), date('c', amstrtotime($this->record->last_login)), amDatetime($this->record->last_login), $banInfoHtml) : ___('Never')));
        }
        $comment = $fieldSet->addTextarea('comment', array('class' => 'el-wide', 'id' => 'comment'), array('label' => ___('Comment')));
        $pass = $fieldSet->addElement('password', '_pass', array('size' => 20, 'autocomplete' => 'off'))->setLabel(___('New Password'));
        //$pass0 = $gr->addElement('password', '_pass0', array('size' => 20));
        //$pass0->addRule('eq', 'Password confirmation must be equal to Password', $pass);
        if (!$this->record->isLoaded()) {
            $pass->addRule('required');
        }
        $nameField = $fieldSet->addGroup('', array('id' => 'name'), array('label' => ___('Name')));
        $nameField->setSeparator(' ');
        $nameField->addElement('text', 'name_f', array('size' => 20));
        $nameField->addElement('text', 'name_l', array('size' => 20));
        $gr = $fieldSet->addGroup()->setLabel(___('E-Mail Address'));
        $gr->setSeparator(' ');
        $gr->addElement('text', 'email', array('size' => 40))->addRule('required');
        $gr->addRule('callback2', '-error-', array($this, 'checkUniqEmail'));
        if ($this->record && $this->record->isLoaded()) {
            $resendText = Am_Controller::escape(___('Resend Signup E-Mail'));
            $sending = Am_Controller::escape(___('sending'));
            $sent = Am_Controller::escape(___('sent successfully'));
            $id = $this->record->pk();
            $gr->addElement('static')->setContent(<<<CUT
<input type='button' value='{$resendText}' id='resend-signup-email' />
<script type='text/javascript'>
\$(function(){
\$("#resend-signup-email").click(function(){
    var btn = this;
    var txt = btn.value;
    btn.value += '...({$sending})...';
    \$.post(window.rootUrl + '/admin-users/resend-signup-email', {id: {$id}}, function(){
        btn.value = txt + '...({$sent})';
        setTimeout(function(){ btn.value = txt; }, 600);
    });
});
});
</script>
CUT
);
        }
        $isLocked = $fieldSet->addElement('advradio', 'is_locked', array('id' => 'is_locked'))->loadOptions(array('' => 'No', '1' => '<span class="red">' . ___('Yes, locked') . '</span>', '-1' => '<em>' . ___('Disable auto-locking for this customer') . '</em>'))->setLabel(___('Is Locked'));
        $fieldSet->addElement('advcheckbox', 'is_approved', array('id' => 'is_approved'))->setLabel(___('Is Approved'));
        $fieldSet->addElement('advradio', 'unsubscribed', array('id' => 'unsubscribed'))->setLabel(___("Is Unsubscribed?\nif enabled, this will\nunsubscribe the customer from:\n* messages that you send from aMember Cp,\n* autoresponder messages,\n* subscription expiration notices"))->loadOptions(array('' => ___('No'), '1' => ___('Yes, do not e-mail this customer for any reasons')));
        $fieldSet->addCategory('_groups', null, array('base_url' => 'admin-user-groups', 'link_title' => ___('Edit Groups'), 'title' => ___('User Groups'), 'options' => Am_Di::getInstance()->userGroupTable->getOptions()))->setLabel(___('User Groups'));
        $this->addElement('text', 'phone', array('size' => 20))->setLabel(___('Phone Number'));
        /* Address Info */
        $this->insertAddressFields();
        $this->insertAdditionalFields();
    }
Example #12
0
 /**
  * run payouts when scheduled
  */
 function onDaily(Am_Event $event)
 {
     $delay = $this->getConfig('payout_day');
     if (!$delay) {
         return;
     }
     list($count, $unit) = preg_split('/(\\D)/', $delay, 2, PREG_SPLIT_DELIM_CAPTURE);
     switch ($unit) {
         case 'd':
             if ($count != (int) date('d', amstrtotime($event->getDatetime()))) {
                 return;
             }
             break;
         case 'w':
             $w = date('w', amstrtotime($event->getDatetime()));
             if ($count != $w) {
                 return;
             }
             break;
         default:
             return;
             // wtf?
     }
     $this->getDi()->affCommissionTable->runPayout(sqlDate($event->getDatetime()));
 }
Example #13
0
 function indexAction()
 {
     $this->view->title = ___('Build Demo');
     $this->session->unsetAll();
     $form = new Am_Form_Admin_BuildDemoForm();
     if ($form->isSubmitted()) {
         $form->setDataSources(array($this->getRequest()));
     }
     if ($form->isSubmitted() && $form->validate()) {
         $values = $form->getValue();
         $this->session->params = array();
         $this->session->params['email_domain'] = $values['email_domain'];
         $this->session->params['users_count'] = $values['users_count'];
         $this->session->params['products_count'] = $values['products_count'];
         $this->session->params['invoices_per_user'] = $values['invoices_per_user'];
         $this->session->params['invoices_per_user_variation'] = $values['invoices_per_user_variation'];
         $this->session->params['products_per_invoice'] = $values['products_per_invoice'];
         $this->session->params['products_per_invoice_variation'] = $values['products_per_invoice_variation'];
         $this->session->params['product_ids'] = isset($values['product_ids']) ? $values['product_ids'] : null;
         $this->session->params['date_begin'] = amstrtotime($values['date_begin']);
         $this->session->params['date_end'] = amstrtotime($values['date_end']);
         $this->session->proccessed = 0;
         $this->updateDemoHistory();
         if (@$values['do_not_generate_products']) {
             $this->session->params['products_count'] = 0;
             $this->readProductsToSession();
         } else {
             $this->generateProducts();
         }
         $this->sendRedirect();
     }
     $this->view->form = $form;
     $this->view->content = (string) $form . $this->createDemoHistoryGrid()->render();
     $this->view->display('admin/layout.phtml');
 }
Example #14
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);
     }
 }
Example #15
0
 function fetchByDateInterval($from, $to, $aff_id = null)
 {
     return $this->selectObjects("SELECT * FROM ?_aff_click WHERE time BETWEEN ? AND ? { AND aff_id=?d}", date('Y-m-d 00:00:00', amstrtotime($from)), date('Y-m-d 23:59:59', amstrtotime($to)), $aff_id === null ? DBSIMPLE_SKIP : $aff_id);
 }
Example #16
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;
 }
Example #17
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();
     $now = $this->getDi()->time;
     $added = amstrtotime($user->added);
     /* @var $user User */
     while (rand(0, 10) < 4) {
         $created = min($now, $added + rand(60, $now - $added));
         $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($created);
         $ticket->updated = sqlTime($created);
         $ticket->insert();
         //
         $msg = $this->getDi()->helpdeskMessageRecord;
         $msg->content = $questions[rand(0, count($questions) - 1)];
         $msg->type = 'message';
         $msg->ticket_id = $ticket->pk();
         $msg->dattm = sqlTime($created);
         $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(min($created + rand(60, 3600 * 24), $now));
             $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->updated = $msg->dattm;
             $ticket->update();
         }
     }
 }