setJsOptions($jsOptions);
$upload_id->addRule('required');
$size = $form->addElement('group', 'size')
->setLabel(___("Size\nWidth × Height"));
$size->setSeparator(' × ');
$width = $size->addElement('text', 'width', array('size' => 4));
$height = $size->addElement('text', 'height', array('size' => 4));
}
function valuesFromForm()
{
$values = parent::valuesFromForm();
$values['height'] = $values['size']['height'];
$values['width'] = $values['size']['width'];
unset($values['size']);
return $values;
}
function valuesToForm()
{
$values = parent::valuesToForm();
$values['size']['height'] = @$values['height'];
$values['size']['width'] = @$values['width'];
return $values;
}
}
class Am_Grid_Editable_TextLinks extends Am_Grid_Editable_AffBannersAbstract
{
protected $affBannerType = AffBanner::TYPE_TEXTLINK;
protected function getGridTitle()
{
return ___('Text Links');
}
protected function _initForm($form) {}
}
class Am_Grid_Editable_Custom extends Am_Grid_Editable_AffBannersAbstract
{
protected $affBannerType = AffBanner::TYPE_CUSTOM;
protected function getGridTitle()
{
return ___('Custom HTML');
}
protected function _initForm($form)
{
$form->addTextarea('html', array('rows' => 10, 'class' => 'el-wide'))
->setLabel(___("HTML Code\n%url% will be replaced with actual url of affilate link"))
->addRule('required');
}
}
class Am_Grid_Editable_LightBoxes extends Am_Grid_Editable_AffBannersAbstract
{
protected $affBannerType = AffBanner::TYPE_LIGHTBOX;
protected function getGridTitle()
{
return ___('Light Boxes');
}
protected function _initForm($form)
{
$upload_id = $form->addElement(new Am_Form_Element_Upload('upload_id', array(), array('prefix' => 'banners')))
->setLabel(___('Lightbox Thumbnail Image'))
->setId('lightboxes-upload_id')
->setAllowedMimeTypes(array(
'image/png', 'image/jpeg', 'image/tiff', 'image/gif',
));
$upload_id->addRule('required');
$upload_big_id = $form->addElement(new Am_Form_Element_Upload('upload_big_id', array(), array('prefix' => 'banners')))
->setLabel(___('Lightbox Main Image'))
->setId('lightboxes-upload_big_id')
->setAllowedMimeTypes(array(
'image/png', 'image/jpeg', 'image/tiff', 'image/gif',
));
$upload_big_id->addRule('required');
}
function valuesFromForm()
{
$values = parent::valuesFromForm();
$values['height'] = $values['size']['height'];
$values['width'] = $values['size']['width'];
unset($values['size']);
return $values;
}
function valuesToForm()
{
$values = parent::valuesToForm();
$values['size']['height'] = @$values['height'];
$values['size']['width'] = @$values['width'];
return $values;
}
}
class Am_Grid_Editable_AffBannersAll extends Am_Grid_Editable
{
protected $permissionId = Bootstrap_Aff::ADMIN_PERM_ID;
public function __construct(Am_Mvc_Request $request, Am_View $view)
{
$id = explode('_', get_class($this));
$id = strtolower(array_pop($id));
parent::__construct('_' . $id, $this->getGridTitle(), $this->createDs(), $request, $view);
}
public function initActions()
{
$this->actionAdd(new Am_Grid_Action_AffBannersAllEdit('edit', ___('Edit')));
$this->actionAdd(new Am_Grid_Action_Delete);
$this->actionAdd(new Am_Grid_Action_Sort_AffBanners());
}
function renderUGroup($b)
{
$res = array();
$options = $this->getDi()->userGroupTable->getSelectOptions();
foreach (explode(',', $b->user_group_id) as $ug_id) {
if (isset($options[$ug_id]))
$res[] = $options[$ug_id];
}
return $this->renderTd($res ? implode(", ", $res) : ___('All'));
}
protected function getGridTitle()
{
return ___('All Banners');
}
protected function initGridFields()
{
$this->addField(new Am_Grid_Field_Enum('type', ___('Type'), true))
->setTranslations(array(
AffBanner::TYPE_TEXTLINK => ___('Text Link'),
AffBanner::TYPE_BANNER => ___('Banner'),
AffBanner::TYPE_PAGEPEEL => ___('Page Peel'),
AffBanner::TYPE_LIGHTBOX => ___('Light Box'),
AffBanner::TYPE_CUSTOM => ___('Custom HTML')
));
$this->addField(new Am_Grid_Field('title', ___('Title'), true, '', null, '25%'));
$this->addField(new Am_Grid_Field('url', ___('URL'), true, '', null, '35%'));
$this->addField(new Am_Grid_Field('category', ___('Category'), true));
$this->addField(new Am_Grid_Field('available', ___('Available'), false))->setRenderFunction(array($this, 'renderUGroup'));
$this->addField(new Am_Grid_Field_IsDisabled());
parent::initGridFields();
}
protected function createDs()
{
$query = new Am_Query(Am_Di::getInstance()->affBannerTable);
$query->setOrder('sort_order');
return $query;
}
}
class Am_Grid_Editable_AffBannersCategory extends Am_Grid_Editable
{
protected $permissionId = Bootstrap_Aff::ADMIN_PERM_ID;
public function __construct(Am_Mvc_Request $request, Am_View $view)
{
$id = explode('_', get_class($this));
$id = strtolower(array_pop($id));
parent::__construct('_' . $id, $this->getGridTitle(), $this->createDs(), $request, $view);
}
public function initActions()
{
$this->actionAdd(new Am_Grid_Action_LiveEdit('name'));
}
protected function getGridTitle()
{
return ___('Banner Categories');
}
protected function initGridFields()
{
$this->addField(new Am_Grid_Field('name', ___('Title')));
parent::initGridFields();
}
protected function createDs()
{
$ret = array();
foreach (Am_Di::getInstance()->affBannerTable->getCategories() as $category) {
$cat = new stdClass();
$cat->name = $category;
$ret[] = $cat;
}
return new Am_Grid_DataSource_AffBannerCategory($ret);
}
}
class Am_Grid_DataSource_AffBannerCategory extends Am_Grid_DataSource_Array
{
public function updateRecord($record, $valuesFromForm)
{
Am_Di::getInstance()->db->query('UPDATE ?_aff_banner SET category=? WHERE category=?',
$valuesFromForm['name'],
$record->name);
}
}
class Am_Grid_Action_Upload extends Am_Grid_Action_Abstract
{
protected $type = self::NORECORD;
public function __construct($id = null, $title = null)
{
$this->title = ___('Upload');
parent::__construct($id, $title);
}
public function run()
{
$form = $this->grid->getForm();
$form->setAttribute('target', '_top');
$upload = new Am_Upload(Am_Di::getInstance());
$upload->setPrefix($this->grid->getCompleteRequest()->getParam('prefix'));
$upload->loadFromStored();
$ids_before = $this->getUploadIds($upload);
if ($form->isSubmitted() && $upload->processSubmit('upload')) {
//find currently uploaded file
$upload_id = array_pop(array_diff($this->getUploadIds($upload), $ids_before));
$upload = Am_Di::getInstance()->uploadTable->load($upload_id);
$upload->desc = $this->grid->getCompleteRequest()->getParam('desc');
$upload->save();
return $this->grid->redirectBack();
}
echo $this->renderTitle();
echo $form;
}
protected function getUploadIds(Am_Upload $upload)
{
$upload_ids = array();
foreach ($upload->getUploads() as $upload) {
$upload_ids[] = $upload->pk();
}
return $upload_ids;
}
}
class Am_Grid_Action_AffBannersAllEdit extends Am_Grid_Action_Abstract
{
protected $privilege = 'edit';
public function __construct($id, $title)
{
$this->id = $id;
$this->title = $title;
parent::__construct();
$this->setTarget('_top');
}
public function getUrl($record = null, $id = null)
{
$id = $record->pk();
switch ($record->type) {
case AffBanner::TYPE_TEXTLINK:
$prefix = 'textlinks';
break;
case AffBanner::TYPE_BANNER:
$prefix = 'banners';
break;
case AffBanner::TYPE_PAGEPEEL:
$prefix = 'pagepeel';
break;
case AffBanner::TYPE_LIGHTBOX:
$prefix = 'lightboxs';
break;
case AffBanner::TYPE_CUSTOM:
$prefix = 'custom';
break;
default:
throw new Am_Exception_InternalError(sprintf('Unknown banner type [%s] in %s::%s',
$record->type, __CLASS__, __METHOD__));
}
$back_url = Am_Html::escape($this->grid->getBackUrl());
return $this->grid->getDi()->url("aff/admin-banners/p/$prefix/index?_{$prefix}_a=edit&_{$prefix}_b=$back_url&_{$prefix}_id=$id", false);
}
public function run()
{
}
}
class Am_Grid_Action_Sort_AffBanners extends Am_Grid_Action_Sort_Abstract
{
protected function setSortBetween($item, $after, $before)
{
$this->_simpleSort(Am_Di::getInstance()->affBannerTable, $item, $after, $before);
}
}
class Aff_AdminGeneralLinkController extends Am_Mvc_Controller
{
public function checkAdminPermissions(Admin $admin)
{
return $admin->hasPermission(Bootstrap_Aff::ADMIN_PERM_ID);
}
function indexAction()
{
$form = $this->createForm();
$form->setDataSources(array($this->getRequest()));
if ($this->getRequest()->isPost() && $form->validate()) {
$v = $form->getValue();
$this->getDi()->config->saveValue('aff.general_link_url', $v['general_link_url']);
}
echo $form;
}
function createForm()
{
$form = new Am_Form_Admin('aff-general-link');
$form->addElement('text', 'general_link_url', array('class' => 'el-wide'))
->setLabel(___("General Affiliate Link Redirect URL\n" .
'It is url of landing page for default affiliate link (which does not related to any banner), ' .
'home page will be used if you keep it empty'))
->setValue($this->getDi()->config->get('aff.general_link_url', ''));
$form->addSaveButton();
return $form;
}
}
class Aff_AdminBannersController extends Am_Mvc_Controller_Pages
{
public function checkAdminPermissions(Admin $admin)
{
return $admin->hasPermission(Bootstrap_Aff::ADMIN_PERM_ID);
}
public function preDispatch()
{
parent::preDispatch();
$this->setActiveMenu('affiliates-banners');
}
public function initPages()
{
$this->addPage(array($this, 'createController'), 'general', ___('General Link'))
->addPage('Am_Grid_Editable_Banners', 'banners', ___('Banners'))
->addPage('Am_Grid_Editable_TextLinks', 'textlinks', ___('Text Links'))
//->addPage('Am_Grid_Editable_PagePeels', 'pagePeels', ___('Page Peels'))
->addPage('Am_Grid_Editable_LightBoxes', 'lightboxes', ___('Light Boxes'))
->addPage('Am_Grid_Editable_Custom', 'custom', ___('Custom HTML'))
->addPage('Am_Grid_Editable_AffBannersAll', 'all', ___('All Banners'))
->addPage('Am_Grid_Editable_AffBannersCategory', 'category', ___('Banner Categories'))
->addPage('Am_Grid_Editable_Downloads', 'downloads', ___('Marketing Materials'));
}
public function createController($id, $title, $grid)
{
return new Aff_AdminGeneralLinkController($grid->getRequest(), $grid->getResponse(), $this->_invokeArgs);
}
}PK \4 4 MemberController.phpnu [ getDi()->auth->requireLogin($this->getDi()->url('aff/member', null, false));
$this->user = $this->getDi()->user;
if (!$this->user->is_affiliate) {
//throw new Am_Exception_InputError("Sorry, this page is opened for affiliates only");
$this->_redirect('member');
}
}
function indexAction()
{
$this->_redirect('aff/aff');
}
function statsAction()
{
class_exists('Am_Report_Standard', true);
include_once AM_APPLICATION_PATH . '/aff/library/Reports.php';
if ($this->getDi()->config->get('aff.affiliate_can_view_details') && $detailDate = $this->getFiltered('detailDate')) {
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $detailDate))
throw new Am_Exception_InputError("Wrong date passed");
$c = 0;
foreach ($this->getDi()->affCommissionTable->fetchByDate($detailDate, $this->user->user_id) as $c) {
$c++;
$p = $c->getPayment();
if (!$p)
continue;
$u = $p->getUser();
$i = $p->getInvoice();
$product = $c->getProduct();
$s = sprintf('%s (%s) – %s %s', $this->escape($u->name_f . ' ' . $u->name_l),
___($product->title), Am_Currency::render($c->amount),
($c->tier ? sprintf(' (%d-tier)', $c->tier+1) : ''));
if ($c->record_type == AffCommission::VOID)
$s = "$s (void)
";
echo $s . " \n";
}
if (!$c)
echo ___('No commissions on this date');
return;
}
$rs = new Am_Report_AffStats();
$rs->setAffId($this->user->user_id);
$rc = new Am_Report_AffClicks();
$rc->setAffId($this->user->user_id);
$rn = new Am_Report_AffSales();
$rn->setAffId($this->user->user_id);
$this->view->monthyear = $this->getInt('monthyear', '');
if (!$this->getInt('monthyear')) {
$firstDate[] = $this->getDi()->db->selectCell("SELECT MIN(date) FROM ?_aff_commission WHERE aff_id=?d", $this->user->user_id);
$firstDate[] = current(explode(' ', $this->getDi()->db->selectCell("SELECT MIN(`time`) FROM ?_aff_click WHERE aff_id=?d", $this->user->user_id)));
$rs->setInterval(min($firstDate), 'now')->setQuantity(new Am_Report_Quant_Month());
} else {
$ym = $this->getInt('monthyear');
if (!$ym || strlen($ym) != 6)
$ym = date('Ym');
$start = mktime(0, 0, 0, substr($ym, 4, 2), 1, substr($ym, 0, 4));
$rs->setInterval(date('Y-m-d 00:00:00', $start), date('Y-m-t 23:59:59', $start))->setQuantity(new Am_Report_Quant_Day());
$this->view->period = array(date('Y-m-d 00:00:00', $start), date('Y-m-t 23:59:59', $start));
}
$rc->setInterval($rs->getStart(), $rs->getStop())->setQuantity(clone $rs->getQuantity());
$rn->setInterval($rs->getStart(), $rs->getStop())->setQuantity(clone $rs->getQuantity());
$result = $rs->getReport();
$rc->getReport($result);
$rn->getReport($result);
$output = new Am_Report_Graph_Line($result);
$output->setSize('100%', 300);
$this->view->report = $output->render();
/* extract data from report to show it in view */
$rows = array();
$totals = array();
$lines = $result->getLines();
foreach ($result->getPointsWithValues() as $r) {
/* @var $r Am_Report_Point */
if ($result->getQuantity()->getId() == 'month') {
$hasValue = false;
foreach ($lines as $line) {
if ($r->getValue($line->getKey())) {
$hasValue = true;
break;
}
}
$href = $hasValue ? $this->view->overrideUrl(array("monthyear"=>$r->getKey())) : '';
} elseif ($this->getModule()->getConfig('affiliate_can_view_details')) {
$href = "javascript: showAffDetails('{$r->getKey()}')";
} else {
$href = "";
}
$rows[$r->getKey()]['date'] = $r->getLabel();
$rows[$r->getKey()]['date_href'] = $href;
foreach ($lines as $i=>$line){
list($start, $stop) = $result->getQuantity()->getStartStop($r->getKey());
$href = $r->getValue($line->getKey()) > 0 ?
sprintf("javascript:affDetail('%s', '%s', '%s')", $start, $stop, $r->getLabel()) :
null;
$rows[$r->getKey()][$line->getKey() . '_href'] = $href;
$rows[$r->getKey()][$line->getKey()] = $r->getValue($line->getKey());
@$totals[$line->getKey()] = $totals[$line->getKey()]+$r->getValue($line->getKey());
}
}
if ($this->getParam('csv')) {
$filename = sprintf("aff-stat-%s-%s.csv",
$this->user->login, $this->getInt('monthyear') ?: 'full');
return $this->sendReportFile($rows, $filename);
}
$this->view->canViewDetails = $this->getModule()->getConfig('affiliate_can_view_details');
$this->view->totals = $totals;
$this->view->rows = $rows;
$this->view->result = $result;
$this->view->display('aff/stats.phtml');
}
public function exportDetailsAction()
{
if (!$this->getModule()->getConfig('affiliate_can_view_details')) {
throw new Am_Exception_AccessDenied;
}
$q = new Am_Query($this->getDi()->affCommissionTable);
$q->addWhere('t.aff_id=?', $this->user->pk())
->leftJoin('?_invoice_item', 'ii', 't.invoice_item_id = ii.invoice_item_id')
->leftJoin('?_invoice', 'i', 'ii.invoice_id = i.invoice_id')
->leftJoin('?_user', 'u', 'i.user_id = u.user_id')
->addField("CONCAT(u.name_f, ' ', u.name_l)", 'u_name')
->addField("ii.item_title");
if ($ym = $this->getInt('monthyear', '')) {
$start = mktime(0, 0, 0, substr($ym, 4, 2), 1, substr($ym, 0, 4));
$begin = date('Y-m-d 00:00:00', $start);
$end = date('Y-m-t 23:59:59', $start);
$q->addWhere('date BETWEEN ? AND ?', $begin, $end);
}
$filename = sprintf("aff-details-%s-%s.csv",
$this->user->login, $this->getInt('monthyear') ?: 'full');
$this->sendDetailsReportFile($q->selectAllRecords(), $filename);
}
public function sendReportFile($rows, $filename)
{
$delimiter = ',';
$data = array();
$data[] = array(
___('Date'), ___('Transactions'), ___('Commission'), ___('Clicks (All)'), ___('Clicks (Unique)')
);
foreach ($rows as $r) {
$data[] = array(
$r['date'], $r['sales'], $r['commission'], $r['clicks_all'], $r['clicks']
);
}
foreach ($data as & $r) {
$out = "";
foreach ($r as $s) {
$out .= ( $out ? $delimiter : "") . amEscapeCsv($s, $delimiter);
}
$r = $out;
}
$this->_helper->sendFile->sendData(implode("\r\n", $data), 'text/csv', $filename);
}
public function sendDetailsReportFile($rows, $filename)
{
$delimiter = ',';
$data = array();
$data[] = array(
___('Date'), ___('User'), ___('Product'), ___('Type'), ___('Amount'), ___('Tier')
);
foreach ($rows as $r) {
$data[] = array(
$r->date, $r->u_name, $r->item_title, $r->record_type, $r->amount, $r->tier
);
}
foreach ($data as & $r) {
$out = "";
foreach ($r as $s) {
$out .= ( $out ? $delimiter : "") . amEscapeCsv($s, $delimiter);
}
$r = $out;
}
$this->_helper->sendFile->sendData(implode("\r\n", $data), 'text/csv', $filename);
}
public function payoutInfoAction()
{
$form = new Am_Form;
$form->addCsrf();
$form->setAction($this->getUrl());
$this->getModule()->addPayoutInputs($form);
$form->addSubmit('_save', array('value' => ___('Save')));
$form->addDataSource(new Am_Mvc_Request($d = $this->user->toArray()));
if ($form->isSubmitted() && $form->validate()) {
foreach ($form->getValue() as $k => $v) {
if ($k[0] == '_')
continue;
if ($k == 'aff_payout_type')
$this->user->set($k, $v);
else
$this->user->data()->set($k, $v);
}
$this->user->update();
}
$this->view->form = $form;
$this->view->display('aff/payout-info.phtml');
}
public function payoutAction()
{
$query = new Am_Query($this->getDi()->affPayoutDetailTable);
$query->leftJoin('?_aff_payout', 'p', 'p.payout_id=t.payout_id');
$query->addField('p.*')
->addWhere('aff_id=?', $this->user->pk());
$this->view->payouts = $query->selectAllRecords();
$this->view->display('aff/payout.phtml');
}
public function clicksDetailAction()
{
$date_from = $this->getFiltered('from');
$date_to = $this->getFiltered('to');
$this->view->clicks = $this->getDi()->affClickTable->fetchByDateInterval($date_from, $date_to, $this->getDi()->auth->getUserId());
$this->view->display('/aff/clicks-detail.phtml');
}
public function getKeywordsReport($uid)
{
$db = $this->getDi()->db;
$db->query('DROP TEMPORARY TABLE IF EXISTS ?_aff_keywords_tmp');
$db->query("CREATE TEMPORARY TABLE ?_aff_keywords_tmp (
keyword_id int not null DEFAULT 0,
keyword varchar(64) not null DEFAULT '',
clicks_count int not null DEFAULT 0,
leads_count int not null DEFAULT 0,
sales_count int not null DEFAULT 0,
sales_amount int not null DEFAULT 0,
PRIMARY KEY (`keyword_id`)
)");
//clicks
$db->query("INSERT into ?_aff_keywords_tmp (keyword_id, clicks_count)
SELECT keyword_id, count(*) from ?_aff_click where keyword_id is not null and aff_id = ? group by keyword_id", $uid);
//leads
$db->query("INSERT into ?_aff_keywords_tmp (keyword_id, leads_count)
SELECT keyword_id, cnt from (SELECT keyword_id, count(*) as cnt from ?_aff_lead
where keyword_id is not null and aff_id = ? group by keyword_id) s
ON DUPLICATE KEY UPDATE leads_count = s.cnt", $uid);
//sales_count
$db->query("INSERT into ?_aff_keywords_tmp (keyword_id, sales_count)
SELECT keyword_id, cnt from (SELECT keyword_id, sum(if(record_type='commission', 1, 0)) as cnt from ?_aff_commission
where keyword_id is not null and aff_id = ? group by keyword_id) s
ON DUPLICATE KEY UPDATE sales_count = s.cnt", $uid);
//sales_amount
$db->query("INSERT into ?_aff_keywords_tmp (keyword_id, sales_amount)
SELECT keyword_id, cnt from (SELECT keyword_id, sum(if(record_type='commission', amount, -amount)) as cnt from ?_aff_commission
where keyword_id is not null and aff_id = ? group by keyword_id) s
ON DUPLICATE KEY UPDATE sales_amount = s.cnt", $uid);
//keyword
$db->query("UPDATE ?_aff_keywords_tmp t set keyword = (SELECT value from ?_aff_keyword s where s.keyword_id = t.keyword_id)");
$res = array();
$q = $db->queryResultOnly("select * from ?_aff_keywords_tmp");
while ($row = $db->fetchRow($q))
{
$res[] = json_decode(json_encode($row), FALSE);
}
return $res;
}
public function keywordsAction()
{
$values = $this->getDi()->cacheFunction->call(array($this, 'getKeywordsReport'),array($this->getDi()->auth->getUserId()), array(), 120);
$ds = new Am_Grid_DataSource_Array($values);
$grid = new Am_Grid_ReadOnly('_aff_keywords', 'Keywords', $ds, $this->getRequest(), $this->getView());
$grid->addField('keyword', ___('Keyword'));
$grid->addField('clicks_count', ___('Clicks'));
$grid->addField('leads_count', ___('Leads'));
$grid->addField('sales_count', ___('Sales'));
$grid->addField('sales_amount', ___('Commissions'))->setRenderFunction(
function($record){
return "". Am_Currency::render($record->sales_amount)." ";
}
);
$grid->runWithLayout('aff/keywords.phtml');
}
}PK \TMLְ AffPayoutsController.phpnu [ array('class' => 'Aff_AffPayoutDetailsController', 'file' => 'aff/controllers/AffPayoutDetailsController.php'),
);
protected $_defaultNested = array(
'aff-payout-details'
);
public function createTable()
{
return $this->getDi()->affPayoutTable;
}
}
PK \i}u u ! AdminCommissionRuleController.phpnu [ getDi()->affCommissionRuleTable->getMaxTier();
$next_tier = ++$max_tier;
$comm = $this->getDi()->affCommissionRuleRecord;
$comm->tier = $next_tier;
$comm->type = AffCommissionRule::TYPE_GLOBAL;
$comm->sort_order = ($next_tier + 1) * 10000;
$comm->comment = ($next_tier + 1) . '-Tier Affiliates Commission';
$comm->save();
$this->grid->redirectBack();
}
/**
* @return Am_Di
*/
protected function getDi()
{
return $this->grid->getDi();
}
}
class Am_Grid_Action_RemoveLastTier extends Am_Grid_Action_Abstract
{
protected $type = Am_Grid_Action_Abstract::NORECORD;
protected $title = 'Remove Last Tier';
public function run()
{
$max_tier = $this->getDi()->affCommissionRuleTable->getMaxTier();
if ($max_tier) {
$this->getDi()->affCommissionRuleTable->findFirstByTier($max_tier)->delete();
}
$this->grid->redirectBack();
}
/**
*
* @return Am_Di
*/
protected function getDi()
{
return $this->grid->getDi();
}
}
class Am_Grid_Action_TestAffCommissionRule extends Am_Grid_Action_Abstract
{
protected $type = Am_Grid_Action_Abstract::NORECORD;
protected $title = 'Test Commission Rules';
protected $cssClass = 'link';
public function run()
{
$f = $this->createForm();
$f->setDataSources(array($this->grid->getCompleteRequest()));
echo $this->renderTitle();
if ($f->isSubmitted() && $f->validate() && $this->process($f))
return;
echo $f;
}
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 "";
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: %d/%s "%s" <%s> \n",
$helper->userUrl($user->pk()),
$user->pk(), Am_Html::escape($user->login),
Am_Html::escape($user->name_f . ' ' . $user->name_l),
Am_Html::escape($user->email));
printf("Reffered Affiliate: %d/%s "%s" <%s> \n",
$helper->userUrl($aff->pk()),
$aff->pk(),
Am_Html::escape($aff->login),
Am_Html::escape($aff->name_f . ' ' . $aff->name_l),
Am_Html::escape($aff->email));
if ($couponAff) {
printf("Affiliate Detected by Coupon (will get commision): %d/%s "%s" <%s> \n",
$helper->userUrl($couponAff->pk()),
$couponAff->pk(),
Am_Html::escape($couponAff->login),
Am_Html::escape($couponAff->name_f . ' ' . $couponAff->name_l),
Am_Html::escape($couponAff->email));
}
$max_tier = Am_Di::getInstance()->affCommissionRuleTable->getMaxTier();
//COMMISSION FOR FREE SIGNUP
if (!(float)$invoice->first_total
&& !(float)$invoice->second_total
&& $vars['is_first']) {
echo "\nFREE SIGNUP :\n";
list($item,) = $invoice->getItems();
echo sprintf("* ITEM: %s\n", Am_Html::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 = (float)$invoice->first_total ? 'first_total' : 'second_total';
if ((float)($invoice->$price_field)) {
echo "\nFIRST PAYMENT ($invoice->currency {$invoice->$price_field}) :\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 (!(float)($item->$price_field)) continue; //do not calculate commission for free items within invoice
echo sprintf("* ITEM: %s ($invoice->currency {$item->$price_field})\n", Am_Html::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: " . Am_Currency::render($to_pay) . " \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: " . Am_Currency::render($to_pay) . " \n";
}
echo str_repeat("-", 70) . "\n";
}
}
//COMMISSION FOR SECOND AND SUBSEQUENT PAYMENTS
if ((float)$invoice->second_total)
{
echo "\nSECOND AND SUBSEQUENT 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 (!(float)$item->second_total) continue; //do not calculate commission for free items within invoice
echo sprintf("* ITEM: %s ($item->second_total $invoice->currency)\n", Am_Html::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: " . Am_Currency::render($to_pay) . " \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: " . Am_Currency::render($to_pay) . " \n";
}
echo str_repeat("-", 70) . "\n";
}
}
echo " ";
return true;
}
protected function createForm()
{
$f = new Am_Form_Admin;
$f->addText('user')->setLabel('Enter username of existing user')
->addRule('required', 'This field is required');
$f->addText('aff')->setLabel('Enter username of existing affiliate')
->addRule('required', 'This field is required');
$f->addText('coupon')->setLabel('Enter coupon code or leave field empty');
$f->addCheckbox('is_first')->setLabel('Is first user invoice?');
$f->addElement(new Am_Form_Element_ProductsWithQty('product_id'))
->setLabel(___('Choose products to include into test invoice'))
->loadOptions(Am_Di::getInstance()->billingPlanTable->selectAllSorted())
->addRule('required');
$f->addSelect('paysys_id')
->setLabel(___('Payment System'))
->loadOptions(Am_Di::getInstance()->paysystemList->getOptions());
$f->addSubmit('', array('value' => 'Test'));
$f->addScript()->setScript(<<grid->getVariablesList() as $k)
{
$kk = $this->grid->getId() . '_' . $k;
if ($v = @$_REQUEST[$kk])
$f->addHidden($kk)->setValue($v);
}
return $f;
}
}
class Am_Grid_Editable_AffCommissionRule extends Am_Grid_Editable
{
protected $permissionId = Bootstrap_Aff::ADMIN_PERM_ID;
public function renderTable()
{
$url = $this->getDi()->url('admin-setup/aff');
return parent::renderTable() .
___('For each item in purchase, aMember will look through all rules, from top to bottom. ' .
'If it finds a matching multiplier, it will be remembered. ' .
'If it finds a matching custom rule, it takes commission rates from it. ' .
'If no matching custom rule was found, it uses "Default" commission settings.
' .
'For n-tier affiliates, no rules are used, you can just define percentage of commission earned by previous level.
') .
'' . ___('Check other Affiliate Program Settings') . '
';
}
public function __construct(Am_Mvc_Request $request, Am_View $view)
{
parent::__construct('_affcommconf',
___('Affiliate Commission Rules'), Am_Di::getInstance()->affCommissionRuleTable->createQuery(),
$request, $view);
$this->setEventId('gridAffCommissionRule');
$this->setRecordTitle('Commission Rule');
$this->addField('comment', 'Comment')->setRenderFunction(array($this, 'renderComment'));
$this->addField('sort_order', 'Sort')->setRenderFunction(array($this, 'renderSort'));
$this->addField('_commission', 'Commission', false)->setRenderFunction(array($this, 'renderCommission'));
$this->addField('_conditions', 'Conditions', false)->setRenderFunction(array($this, 'renderConditions'));
$this->actionGet('edit')->setTarget('_top');
$this->actionGet('insert')->setTitle('New Custom %s')->setTarget('_top');
$this->actionAdd(new Am_Grid_Action_AddTier());
if ($this->getDi()->affCommissionRuleTable->getMaxTier()) {
$this->actionAdd(new Am_Grid_Action_RemoveLastTier());
}
$this->actionAdd(new Am_Grid_Action_TestAffCommissionRule());
$this->setForm(array($this,'createConfigForm'));
$this->addCallback(Am_Grid_Editable::CB_VALUES_TO_FORM, array($this, '_valuesToForm'));
$this->addCallback(Am_Grid_Editable::CB_VALUES_FROM_FORM, array($this, '_valuesFromForm'));
}
public function renderSort(AffCommissionRule $rule)
{
$v = $rule->isGlobal() ? '-' : $rule->sort_order;
return $this->renderTd($v);
}
public function renderCommission(AffCommissionRule $rule, $fieldName)
{
return $this->renderTd($rule->renderCommission(), false);
}
public function renderConditions(AffCommissionRule $rule, $fieldName)
{
return $this->renderTd($rule->renderConditions(), true);
}
public function renderComment(AffCommissionRule $rule)
{
if ($rule->isGlobal())
$text = ''.$rule->comment.' ';
else
$text = $this->escape($rule->comment);
return "$text \n";
}
public function _valuesToForm(& $values, AffCommissionRule $record)
{
$values['_conditions'] = json_decode(@$values['conditions'], true);
foreach ((array)$values['_conditions'] as $k => $v) {
$values['_conditions_status'][$k] = 1; //enabled
}
}
public function _valuesFromForm(& $values, AffCommissionRule $record)
{
$values['free_signup_t'] = '$';
$conditions = array();
foreach ($values['_conditions_status'] as $k => $v) {
if ($v) {
$conditions[$k] = $values['_conditions'][$k];
}
}
$this->cleanUpConditions($conditions);
if (!empty($conditions)) {
$values['conditions'] = json_encode($conditions);
}
}
/**
* Remove incomplete conditions
*
* @param array $conditions
*/
protected function cleanUpConditions(& $conditions)
{
foreach ($conditions as $type => $vars) {
switch ($type) {
case AffCommissionRule::COND_PRODUCT_ID :
case AffCommissionRule::COND_PRODUCT_CATEGORY_ID :
case AffCommissionRule::COND_AFF_PRODUCT_ID :
case AffCommissionRule::COND_AFF_PRODUCT_CATEGORY_ID :
if (empty($vars)) unset($conditions[$type]);
break;
case AffCommissionRule::COND_AFF_SALES_AMOUNT:
case AffCommissionRule::COND_AFF_ITEMS_COUNT:
case AffCommissionRule::COND_AFF_SALES_COUNT:
if (empty($vars['count']) || empty($vars['days']))
unset($conditions[$type]);
break;
case AffCommissionRule::COND_COUPON :
if (($vars['type'] == 'batch' && !$vars['batch_id'])
|| ($vars['type'] == 'coupon' && !$vars['code']))
unset($conditions[$type]);
break;
}
}
}
public function createConfigForm(Am_Grid_Editable $grid)
{
$form = new Am_Form_Admin;
$record = $grid->getRecord($grid->getCurrentAction());
if (empty($record->type)) $record->type = null;
if (empty($record->tier)) $record->tier = 0;
$globalOptions = AffCommissionRule::getTypes();
($record->type && !isset($globalOptions[$record->type])) && $globalOptions[$record->type] = $record->getTypeTitle();
$cb = $form->addSelect('type')->setLabel('Type')->loadOptions($globalOptions);
if ($record->isGlobal())
$cb->toggleFrozen(true);
$form->addScript()->setScript(<<X ");
});
jQuery(document).on('click',"a.hide-row",function(){
var row = jQuery(this).closest(".row");
var id = row.hide().attr("id");
var val = /row-(.*)/i.exec(id).pop();
jQuery('input[name="_conditions_status[' + val + ']"]').val(0);
jQuery("#condition-select option[value='"+val+"']").prop("disabled", false);
});
jQuery('#used-type').change(function(){
jQuery('#used-batch_id, #used-code').hide();
switch (jQuery(this).val()) {
case 'batch' :
jQuery('#used-batch_id').show();
break;
case 'coupon' :
jQuery('#used-code').show();
break;
}
}).change()
});
CUT
);
$comment = $form->addText('comment', array('size' => 40))
->setLabel('Rule title - for your own reference');
if ($record->isGlobal()) {
$comment->toggleFrozen(true);
} else {
$comment->addRule('required', 'This field is required');
}
if (!$record->isGlobal())
$form->addInteger('sort_order')
->setLabel('Sort order - rules with lesser values executed first');
if (!$record->isGlobal()) // add conditions
{
$set = $form->addFieldset('', array('id'=>'conditions'))->setLabel('Conditions');
$set->addSelect('', array('id' => 'condition-select'))->setLabel('Add Condition')->loadOptions(array(
'' => ___('Select Condition...'),
___('User') => array(
'first_time' => ___('First Time Purchase of Product'),
'first_time_payment' => ___('First Time Purchase'),
),
___('Invoice') => array(
'coupon' => ___('By Used Coupon'),
'paysys_id' => ___('By Used Payment System'),
'product_id' => ___('By Product'),
'product_category_id' => ___('By Product Category'),
'not_product_id' => ___('Not Product'),
'not_product_category_id' => ___('Not Product Category'),
'upgrade' => ___('Upgrade Invoice'),
),
___('Affiliate') => array(
'aff_group_id' => ___('By Affiliate Group Id'),
'aff_sales_count' => ___('By Affiliate Sales Count'),
'aff_items_count' => ___('By Affiliate Item Sales Count'),
'aff_sales_amount' => ___('By Affiliate Sales Amount'),
'aff_product_id' => ___('By Affiliate Active Product'),
'aff_product_category_id' => ___('By Affiliate Active Product Category'),
)
));
$set->addHidden('_conditions_status[product_id]');
$set->addMagicSelect('_conditions[product_id]', array('id' => 'product_id'))
->setLabel(___("This rule is for particular products\n" .
'if none specified, rule works for all products'))
->loadOptions(Am_Di::getInstance()->productTable->getOptions());
$set->addHidden('_conditions_status[product_category_id]');
$el = $set->addMagicSelect('_conditions[product_category_id]', array('id' => 'product_category_id'))
->setLabel(___("This rule is for particular product categories\n" .
"if none specified, rule works for all product categories"));
$el->loadOptions(Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions());
$set->addHidden('_conditions_status[not_product_id]');
$set->addMagicSelect('_conditions[not_product_id]', array('id' => 'not_product_id'))
->setLabel(___("Product is not\n" .
'if none specified, rule works for all products'))
->loadOptions(Am_Di::getInstance()->productTable->getOptions());
$set->addHidden('_conditions_status[not_product_category_id]');
$el = $set->addMagicSelect('_conditions[not_product_category_id]', array('id' => 'not_product_category_id'))
->setLabel(___("Product is not included to Category\n" .
"if none specified, rule works for all product categories"));
$el->loadOptions(Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions());
$set->addHidden('_conditions_status[aff_group_id]');
$el = $set->addMagicSelect('_conditions[aff_group_id]', array('id' => 'aff_group_id'))
->setLabel(___("This rule is for particular affiliate groups\n" .
"you can add user groups and assign it to customers in User editing form"));
$el->loadOptions(Am_Di::getInstance()->userGroupTable->getSelectOptions());
$set->addHidden('_conditions_status[aff_sales_count]');
$gr = $set->addGroup('_conditions[aff_sales_count]', array('id' => 'aff_sales_count'))
->setLabel(___("Affiliate sales count\n" .
"trigger this commission if affiliate made more than ... sales within ... days before the current date\n" .
"(only count of new invoices is calculated)"
));
$gr->addStatic()->setContent('use only if affiliate referred ');
$gr->addInteger('count', array('size'=>4));
$gr->addStatic()->setContent(' invoices within last ');
$gr->addInteger('days', array('size'=>4));
$gr->addStatic()->setContent(' days');
$set->addHidden('_conditions_status[aff_items_count]');
$gr = $set->addGroup('_conditions[aff_items_count]', array('id' => 'aff_items_count'))
->setLabel(___("Affiliate items count\n" .
"trigger this commission if affiliate made more than ... item sales within ... days before the current date\n" .
"(only count of items in new invoices is calculated"
));
$gr->addStatic()->setContent('use only if affiliate made ');
$gr->addInteger('count', array('size'=>4));
$gr->addStatic()->setContent(' item sales within last ');
$gr->addInteger('days', array('size'=>4));
$gr->addStatic()->setContent(' days');
$set->addHidden('_conditions_status[aff_sales_amount]');
$gr = $set->addGroup('_conditions[aff_sales_amount]', array('id' => 'aff_sales_amount'))
->setLabel(___("Affiliate sales amount\n" .
"trigger this commission if affiliate made more than ... sales within ... days before the current date\n" .
"(only new invoices calculated)"
));
$gr->addStatic()->setContent('use only if affiliate made ');
$gr->addInteger('count', array('size'=>4));
$gr->addStatic()->setContent(' ' .Am_Currency::getDefault(). ' in total sales amount within last ');
$gr->addInteger('days', array('size'=>4));
$gr->addStatic()->setContent(' days');
$set->addHidden('_conditions_status[coupon]');
$gr = $set->addGroup('_conditions[coupon]', array('id' => 'coupon'))
->setLabel(___('Used coupon'));
$gr->setSeparator(' ');
$gr->addSelect('used')
->loadOptions(array(
'1' => 'Used',
'0' => "Didn't Use"
));
$gr->addSelect('type')
->setId('used-type')
->loadOptions(array(
'any' => ___('Any Coupon'),
'batch' => ___("Coupon From Batch"),
'coupon' => ___("Specific Coupon")
));
$gr->addSelect('batch_id')
->setId('used-batch_id')
->loadOptions(
$this->getDi()->couponBatchTable->getOptions()
);
$gr->addText('code', array('size'=>10))
->setId('used-code');
$set->addHidden('_conditions_status[paysys_id]');
$set->addMagicSelect('_conditions[paysys_id]', array('id' => 'paysys_id'))
->setLabel(___('This rule is for particular payment system'))
->loadOptions(Am_Di::getInstance()->paysystemList->getOptions());
$set->addHidden('_conditions_status[first_time]');
$set->addStatic('_conditions[first_time]', array('id' => 'first_time'))
->setLabel(___("First Time Purchase of Product"))
->setContent("✓
");
$set->addHidden('_conditions_status[first_time_payment]');
$set->addSelect('_conditions[first_time_payment]', array('id' => 'first_time_payment'))
->setLabel(___("First Time Purchase"))
->loadOptions(array(
0 => ___('No'),
1 => ___('Yes')
));
$set->addHidden('_conditions_status[upgrade]');
$set->addStatic('_conditions[upgrade]', array('id' => 'upgrade'))
->setLabel(___("Upgrade Invoice"))
->setContent("✓
");
$set->addHidden('_conditions_status[aff_product_id]');
$set->addMagicSelect('_conditions[aff_product_id]', array('id' => 'aff_product_id'))
->setLabel(___("Apply this rule if affiliate has active access to"))
->loadOptions(Am_Di::getInstance()->productTable->getOptions());
$set->addHidden('_conditions_status[aff_product_category_id]');
$el = $set->addMagicSelect('_conditions[aff_product_category_id]', array('id' => 'aff_product_category_id'))
->setLabel(___("Apply this rule if affiliate has active access to"));
$el->loadOptions(Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions());
}
$set = $form->addFieldset('', array('id' => 'commission'))->setLabel('Commission');
if ($record->tier == 0)
{
$set->addElement(new Am_Form_Element_AffCommissionSize(null, null, 'first_payment'))
->setLabel(___("Commission for First Payment\ncalculated for first payment in each invoice"));
$set->addElement(new Am_Form_Element_AffCommissionSize(null, null, 'recurring'))
->setLabel(___("Commission for Rebills"));
$group = $set->addGroup('')
->setLabel(___("Commission for Free Signup\ncalculated for first customer invoice only"));
$group->addText('free_signup_c', array('size'=>5));
$group->addStatic()->setContent(' ' . Am_Currency::getDefault());
;//->addRule('gte', 'Value must be a valid number > 0, or empty (no text)', 0);
} else {
$set->addText('first_payment_c')
->setLabel(___("Commission\n% of commission received by referred affiliate"));
}
if (!$record->isGlobal())
{
$set = $form->addFieldset('', array('id' => 'multiplier'))->setLabel('Multipier');
$set->addText('multi', array('size' => 5, 'placeholder' => '1.0'))
->setLabel(___("Multiply commission calculated by the following rules\n" .
"to number specified in this field. To keep commission untouched, enter 1 or delete this rule"))
;//->addRule('gt', 'Values must be greater than 0.0', 0.0);
}
return $form;
}
}
class Aff_AdminCommissionRuleController extends Am_Mvc_Controller_Grid
{
public function checkAdminPermissions(Admin $admin)
{
return $admin->hasPermission(Bootstrap_Aff::ADMIN_PERM_ID);
}
public function createGrid()
{
return new Am_Grid_Editable_AffCommissionRule($this->getRequest(), $this->getView());
}
}PK \Gv9 9 AdminController.phpnu [ hasPermission(Bootstrap_Webhooks::ADMIN_PERM_ID);
}
function createGrid()
{
$ds = new Am_Query($this->getDi()->webhookTable);
$grid = new Am_Grid_Editable('_w', ___('Browse Webhooks'), $ds, $this->getRequest(), $this->getView(), $this->getDi());
$grid->setPermissionId(Bootstrap_Webhooks::ADMIN_PERM_ID);
$grid->addCallback(Am_Grid_ReadOnly::CB_TR_ATTRIBS, array($this, 'getTrAttribs'));
$grid->addField(new Am_Grid_Field('webhook_id', '#', true, '', null, '1%'));
$grid->addField('event_id', ___('Event'));
$grid->addField('url', ___('Url'));
$grid->setForm(array($this, 'createForm'));
$grid->setRecordTitle('WebHook');
$grid->addCallback(Am_Grid_Editable::CB_RENDER_CONTENT, function(& $out, Am_Grid_Editable $grid) {
$cron_url = $this->getDi()->url('webhooks/cron',null,true,2);
$out = '' . "It is required to setup a cron job to run each minute to trigger sending of webhooks
* * * * * /usr/bin/curl $cron_url " . '
' . $out;
});
return $grid;
}
public function getTrAttribs(& $ret, $record)
{
if ($record->is_disabled) {
$ret['class'] = isset($ret['class']) ? $ret['class'] . ' disabled' : 'disabled';
}
}
function renderStatus(Webhook $webhook)
{
return $webhook->is_disabled ? 'Disabled' : 'Active';
}
function createForm()
{
$keys = array_keys($this->getModule()->getTypes());
$form = new Am_Form_Admin('webhooks');
$gr = $form->addGroup()->setLabel(___('Event'));
$sel = $gr->addSelect('event_id');
$sel->setLabel(___('Event'))
->loadOptions(array_merge(array('' => ___('-- Please select --')),array_combine($keys,$keys)));
$sel->addRule('required');
$gr->addElement('static')->setContent('
');
$js_ = '';
foreach ($this->getModule()->getTypes() as $k => $v)
{
$desc = array($v['title']);
if(isset($v['description']))
$desc[] = $v['description'];
$params = array();
if(!is_array($v['params']))
$params = array($v['params']);
else
$params = $v['params'];
if(isset($v['nested']))
{
if(!is_array($v['nested']))
$params = array_merge($params,array($v['nested']));
else
$params = array_merge($params,$v['nested']);
}
$desc[] = 'List of parameters:['.implode(',', $params).']';
$js_.="webhooksCache.{$k} = '". implode(' ', $desc) ."';
";
}
$id_ = $sel->getId();
$gr->addElement('static')->setContent(
<<
var webhooksCache = {"" : {} };
$js_
jQuery(document).ready(function($) {
function onWebhookChange() {
$("#webhook_info").html(webhooksCache[$(this).val()]);
}
$("#$id_").change(onWebhookChange);
});
EOF
);
$form->addText('url',array('class'=>'el-wide'))->setLabel(___("Url\n" .
'url of the page POST data will be sent to'))->addRule('required');
$form->addAdvcheckbox('is_disabled')->setLabel(___('Is Disabled?'));
return $form;
}
}
PK \ ClickJsController.phpnu [ getParam('r'));
if (is_numeric($id)) {
$aff = $this->getDi()->userTable->load($id, false);
if ($aff) return $aff;
}
if (strlen($id)) {
$aff = $this->getDi()->userTable->findFirstByLogin($id);
if ($aff) return $aff;
}
return null;
}
function findKeyword()
{
if($keyword = $this->getParam('keyword'))
{
return substr($keyword, 0, Bootstrap_Aff::KEYWORD_MAX_LEN);
}
return null;
}
function indexAction(){
if(!Am_Di::getInstance()->config->get('aff.tracking_code'))
{
$this->log('Click logging disabled in config');
}
elseif ($this->aff = $this->findAff())
{
$keyword = $this->findKeyword();
$aff_click_id = $this->getDi()->affClickTable->log($this->aff, null, $this->getParam('s'), $this->getModule()->findKeywordId($this->aff->pk(), $keyword));
$this->getModule()->setCookie($this->aff, null, $aff_click_id);
$this->log('Click Logged');
}
}
function log($text){
if (constant('AM_APPLICATION_ENV') != 'debug') return;
echo 'console.log("'.$text.'")';
}
}
PK \sQ$ Q$ AdminConvertController.phpnu [ isSuper();
}
/**
*
* @return Am_Crypt
*/
function getCurrentCryptObject()
{
$cname = $this->getDi()->getCryptClass();
return (new $cname);
}
/**
*
* @return Am_Crypt
*/
function getOldCryptObject()
{
$crypt = $this->getCurrentCryptObject();
$oldCrypt = $crypt;
$oldSig = $oldCrypt->loadKeySignature();
$cname = Am_Crypt::getClassByMethod($oldSig);
if (get_class($oldCrypt) != $cname)
{
$oldCrypt = new $cname;
}
if ($oldCrypt->getKeySignature() != $oldSig)
{
// Now try to load old key file;
$path = APPLICATION_PATH . '/configs/key-old.php';
if (!file_exists($path))
throw new Am_Exception_Crypt_Key(___('Unable to find old keyfile. '
. 'Please upload it to %s '
. 'Then refresh page', $path)); // @todo comment
$key = include $path;
if (!strlen($key))
throw new Am_Exception_Crypt_Key('Key file has incorrect format or the key is empty'); // @todo comment
if ($key == 'REPLACE THIS STRING TO YOUR KEYSTRING')
throw new Am_Exception_Crypt_Key("You must define a valid key in the file [$path] instead of default");
$oldCrypt = new $cname($key);
}
return $oldCrypt;
}
function createBackup()
{
try
{
$this->getDi()->db->query("CREATE TABLE ?_cc_backup LIKE ?_cc");
$this->getDi()->db->query("INSERT INTO ?_cc_backup SELECT * FROM ?_cc");
$this->getDi()->db->query("CREATE TABLE ?_config_backup LIKE ?_config");
$this->getDi()->db->query("INSERT INTO ?_config_backup SELECT * FROM ?_config");
}
catch (Exception $ex)
{
$this->getDi()->errorLogTable->logException($ex);
throw new Am_Exception_InputError(
___('Unable to backup cc and config tables. '
. 'Check "aMember CP -> Error Log " for more info', $this->getDi()->url('admin-logs'))
);
}
}
function dropBackup()
{
try
{
$this->getDi()->db->query('DROP TABLE ?_config_backup');
$this->getDi()->db->query('DROP TABLE ?_cc_backup');
}
catch (Exception $ex)
{
$this->getDi()->errorLogTable->logException($ex);
throw new Am_Exception_InputError(
___('Unable to delete backup tables. '
. 'Please delete cc_backup and config_backup tables manually '
. 'Check "aMember CP -> Error Log " for more info ', $this->getDi()->url('admin-logs'))
);
}
}
function restoreBackup()
{
try
{
$this->getDi()->db->query('TRUNCATE TABLE ?_config');
$this->getDi()->db->query("INSERT INTO ?_config SELECT * FROM ?_config_backup");
$this->getDi()->db->query('TRUNCATE TABLE ?_cc');
$this->getDi()->db->query("INSERT INTO ?_cc SELECT * FROM ?_cc_backup");
}
catch (Exception $ex)
{
$this->getDi()->errorLogTable->logException($ex);
throw new Am_Exception_InputError(
___('Unable to restore back in cc_backup and config_backup tables'
. 'Please restore it manually. '
. 'Check "aMember CP -> Error Log " for more info ', $this->getDi()->url('admin-logs'))
);
}
}
function indexAction()
{
$crypt = $this->getCurrentCryptObject();
$oldCrypt = $this->getOldCryptObject();
$this->view->title = "Convert CC Database";
$startUrl = $this->getDi()->url('cc/admin-convert/do');
if (get_class($oldCrypt) != get_class($crypt))
{
$this->view->content = <<
Encryption method was changed. You have to encrypt database using new encryption method.
You must backup your database before you'll run this tool. GGI-Central is not responsible for any damage
this script may result to. If you have no backup saved, you may loose your data.
Make backup first, then return to this page.
CUT1;
}
else if ($crypt->getKeySignature() != $crypt->loadKeySignature())
{
$path = $path = APPLICATION_PATH . '/configs/key-old.php';
$this->view->content = <<
Encryption key file was changed. Please upload old key file to {$path} and re-encrypt CC table.
You must backup your database before you'll run this tool. GGI-Central is not responsible for any damage
this script may result to. If you have no backup saved, you may loose your data.
Make backup first, then return to this page.
CUT2;
}
else
{
$this->view->content = <<Key signature stored in database and key signature that was generated are equal. No further actions are required.
CUT;
}
$this->view->display('admin/layout.phtml');
}
function doAction()
{
$this->crypt = $this->getCurrentCryptObject();
$this->oldCrypt = $this->getOldCryptObject();
$this->context = $this->getParam('context');
if (!$this->context)
$this->createBackup();
$batch = new Am_BatchProcessor(array($this, 'doWork'));
$breaked = !$batch->run($this->context);
$breaked ? $this->convertRedirect() : $this->convertComplete();
}
function doWork(& $context, Am_BatchProcessor $batch)
{
$db = $this->getDi()->db;
try
{
$this->done = $db->selectCell("select count(*) from ?_cc where cc_idtotal = $db->selectCell("select count(*) from ?_cc");
$q = $db->queryResultOnly("SELECT * FROM ?_cc WHERE cc_id > ?d", (int) $context);
while ($r = $db->fetchRow($q))
{
$context = $r['cc_id'];
$ccRecord = $this->getDi()->CcRecordRecord;
$ccRecord->getTable()->setCrypt($this->oldCrypt);
$ccRecord->fromRow($r);
if (preg_match('/[^\s\d-]/', $ccRecord->cc_number)) {
throw new Am_Exception_InternalError(
"Problem with converting to new encryption key. "
. "cc record# {$ccRecord->cc_id} could not be converted, "
. "it seems the old key has been specified incorrectly. Conversion cancelled.");
return;
}
$ccRecord->getTable()->setCrypt($this->crypt);
$ccRecord->update();
$this->done++;
if (!$batch->checkLimits())
return;
}
}
catch (Exception $ex)
{
$this->getDi()->errorLogTable->logException($ex);
$this->restoreBackup();
$this->dropBackup();
throw new Am_Exception_InputError(
___('Got an error when attempting to re-encode CC record. '
. 'CC and config tables were restored from backup. '
. 'Check "aMember CP -> Error Log " for more info ', $this->getDi()->url('admin-logs'))
);
}
return true;
}
function convertRedirect()
{
$done = $this->done;
$total = $this->total;
$url = $this->getUrl('admin-convert', 'do', 'cc', array('context' => $this->context));
$text = $total > 0 ? (___('Converting CC info (%d from %d)', $done, $total) . '. ' . ___('Please wait')) :
___('Converting started');
$text .= '...';
$this->redirectHtml($url, $text, ___('Converting') . '...', false, $done, $total);
}
function convertComplete()
{
$this->crypt->saveKeySigunature();
$this->view->assign('title', ___('Done'));
ob_start();
print '';
print 'Records were re-encoded using new key/encryption method';
print '. ';
$url = $this->getUrl('admin-convert', 'index', 'cc');
print '
' . ___('Back') . ' ';
$this->view->assign('content', ob_get_clean());
$this->view->display('admin/layout.phtml');
$this->getDi()->db->query("OPTIMIZE TABLE ?_cc");
$this->dropBackup();
}
}
PK \h*0 *0 AdminRebillsController.phpnu [ hasPermission('cc');
}
public function init()
{
parent::init();
$this->view->headScript()->appendScript($this->getJs());
$this->view->placeholder('after-content')->append(
"
");
}
public function renderStatus($obj, $fieldname, $grid, $field)
{
return $obj->{$fieldname} ?
$this->renderTd(sprintf('%d - %s ', $obj->{$fieldname}, Am_Currency::render($obj->{$fieldname . '_amt'})), false) :
$this->renderTd('');
}
protected function createAdapter()
{
$q = new Am_Query($this->getDi()->ccRebillTable);
$q->leftJoin('?_invoice', 'i', 't.invoice_id=i.invoice_id');
$q->clearFields();
$q->groupBy('rebill_date');
$q->addField('t.rebill_date');
$q->addField('(1)', 'is_log');
$q->addField('COUNT(t.rebill_date)', 'total');
$q->addField('SUM(i.second_total/i.base_currency_multi)', 'total_amt');
$q->addField('SUM(IF(t.status=0, 1, 0))', 'status_0');
$q->addField('SUM(IF(t.status=1, 1, 0))', 'status_1');
$q->addField('SUM(IF(t.status=2, 1, 0))', 'status_2');
$q->addField('SUM(IF(t.status=3, 1, 0))', 'status_3');
$q->addField('SUM(IF(t.status=4, 1, 0))', 'status_4');
$q->addField('SUM(IF(t.status=0, i.second_total/i.base_currency_multi, 0))', 'status_0_amt');
$q->addField('SUM(IF(t.status=1, i.second_total/i.base_currency_multi, 0))', 'status_1_amt');
$q->addField('SUM(IF(t.status=2, i.second_total/i.base_currency_multi, 0))', 'status_2_amt');
$q->addField('SUM(IF(t.status=3, i.second_total/i.base_currency_multi, 0))', 'status_3_amt');
$q->addField('SUM(IF(t.status=4, i.second_total/i.base_currency_multi, 0))', 'status_4_amt');
$u = new Am_Query($this->getDi()->invoiceTable, 'i');
$u->addWhere('i.paysys_id IN (?a)', array_merge(array('avoid-sql-error'), $this->getPlugins()));
$u->groupBy('rebill_date');
$u->clearFields()->addField('i.rebill_date');
$u->addField('(0)', 'is_log');
$u->addField('COUNT(i.invoice_id)', 'total');
$u->addField('SUM(i.second_total/i.base_currency_multi)', 'total_amt');
for ($i = 1; $i < 11; $i++)
$u->addField('(NULL)');
$u->leftJoin('?_cc_rebill', 't', 't.rebill_date=i.rebill_date');
$u->addWhere('i.rebill_date IS NOT NULL');
$u->addWhere('t.rebill_date IS NULL');
$q->addUnion($u);
$q->addOrder('rebill_date', true);
return $q;
}
public function createGrid()
{
$grid = new Am_Grid_ReadOnly('_r', 'Rebills by Date', $this->createAdapter(), $this->_request, $this->view);
$grid->setPermissionId('cc');
$grid->addField('rebill_date', 'Date')->setRenderFunction(array($this, 'renderDate'));
$grid->addField('status_0', 'Processing Not Finished')->setRenderFunction(array($this, 'renderStatus'));
$grid->addField('status_1', 'No CC Saved')->setRenderFunction(array($this, 'renderStatus'));
$grid->addField('status_2', 'Error')->setRenderFunction(array($this, 'renderStatus'));
$grid->addField('status_3', 'Success')->setRenderFunction(array($this, 'renderStatus'));
$grid->addField('status_4', 'Exception!')->setRenderFunction(array($this, 'renderStatus'));
$grid->addField('total', 'Total')->setRenderFunction(array($this, 'renderTotal'));
$grid->addField('_action', '')->setRenderFunction(array($this, 'renderLink'));
$grid->addCallback(Am_Grid_ReadOnly::CB_TR_ATTRIBS, array($this, 'getTrAttribs'));
return $grid;
}
public function getPlugins()
{
$this->getDi()->plugins_payment->loadEnabled();
$ret = array();
foreach ($this->getDi()->plugins_payment->getAllEnabled() as $ps)
if ($ps instanceof Am_Paysystem_CreditCard || $ps instanceof Am_Paysystem_Echeck)
$ret[] = $ps->getId();
return $ret;
}
public function renderDate(CcRebill $obj)
{
$raw = $obj->rebill_date;
$d = amDate($raw);
return $this->renderTd("$d ", false);
}
public function getTrAttribs(& $ret, $record)
{
if ($record->rebill_date > sqlDate('now')) {
$ret['class'] = isset($ret['class']) ? $ret['class'] . ' disabled' : 'disabled';
}
}
public function renderTotal(CcRebill $obj)
{
if ($obj->is_log) {
return $this->renderTd(sprintf('%d - %s', $obj->total, Am_Currency::render($obj->total_amt)), false);
} else {
$url = $this->getDi()->url('default/admin-payments/p/invoices/index' , array(
'_invoice_filter' => array(
'datf' => 'rebill_date',
'dat1' => amDate($obj->rebill_date),
'dat2' => amDate($obj->rebill_date)
),
'_invoice_sort' => 'rebill_date'
));
return $this->renderTd(sprintf('%d - %s ',
$url, $obj->total, Am_Currency::render($obj->total_amt)), false);
}
}
public function renderLink(CcRebill $obj)
{
$linkRun = $linkDetail = '';
if ($obj->rebill_date <= sqlDate('now')) {
if ($obj->status_3 < $obj->total) {
$iconRun = $this->getDi()->view->icon('retry', ___('Run'));
$back_url = $this->grid->makeUrl();
$linkRun = "$iconRun ";
}
if ($obj->is_log) {
$iconDetail = $this->getDi()->view->icon('view', ___('Details'));
$linkDetail = "$iconDetail ";
}
}
return "$linkRun $linkDetail ";
}
public function renderInvoiceLink($record)
{
return 'user_id . "#invoice-" . $record->invoice_id) . '" target=_top >' . $record->invoice_id . '/' . $record->public_id . ' ';
}
public function getJs()
{
$title = ___('Run Rebill Manually');
$title_details = ___('Details');
return <<');
div.load(amUrl("/cc/admin-rebills/detail?_r_d_date=") + date , function(){
div.dialog({
autoOpen: true
,width: 800
,buttons: {}
,closeOnEscape: true
,title: "$title_details"
,modal: true
,open: function(){
div.ngrid();
}
});
});
});
});
jQuery(function(){
jQuery(document).on('submit',"#run-form form", function(){
jQuery(this).ajaxSubmit({target: '#run-form'});
return false;
});
});
CUT;
}
public function createRunForm()
{
$form = new Am_Form;
$form->setAction($this->getUrl(null, 'run'));
$s = $form->addSelect('paysys_id')->setLabel(___('Choose a plugin'));
$s->addRule('required');
foreach ($this->getModule()->getPlugins() as $p)
$s->addOption($p->getTitle(), $p->getId());
$form->addDate('date')->setLabel(___('Run Rebill Manually'))->addRule('required');
$form->addHidden('back_url');
$form->addSubmit('run', array('value' => ___('Run')));
return $form;
}
public function detailAction()
{
$date = $this->getFiltered('_r_d_date');
if (!$date)
throw new Am_Exception_InputError('Wrong date');
$grid = $this->createDetailGrid($date);
$grid->isAjax(false);
$grid->runWithLayout('admin/layout.phtml');
}
protected function createDetailGrid($date)
{
$q = new Am_Query($this->getDi()->ccRebillTable);
$q->addWhere('t.rebill_date=?', $date);
$q->leftJoin('?_invoice', 'i', 'i.invoice_id=t.invoice_id');
$q->leftJoin('?_user', 'u', 'u.user_id=i.user_id');
$q->addField('i.public_id');
$q->addField('u.name_f');
$q->addField('u.name_l');
$q->addField('u.email');
$q->addField('i.user_id');
$q->addField('i.second_total');
$q->addField('i.currency');
$grid = new Am_Grid_ReadOnly('_r_d', ___('Detailed Rebill Report for %s', amDate($date)), $q, $this->_request, $this->view);
$grid->setPermissionId('cc');
$grid->addField(new Am_Grid_Field_Date('tm_added', 'Started', true));
$grid->addField('invoice_id', 'Invoice#', true, '', array($this, 'renderInvoiceLink'));
$grid->addField('user', 'User')->setRenderFunction(function($obj, $fieldname, $grid, $field){
return sprintf("%s %s (%s)> ",
$this->getDi()->url('admin-users',array('_u_a'=>'edit','_u_id'=>$obj->user_id)),
$obj->name_f, $obj->name_l, $obj->email);
});
$grid->addField('paysys_id', ___('Payment System'));
$grid->addField('second_total', ___('Amount'))->setRenderFunction(function($obj, $fieldname, $grid, $field){
return $grid->renderTd(Am_Currency::render($obj->second_total, $obj->currency), false);
});
$grid->addField(new Am_Grid_Field_Date('rebill_date', 'Date', true))->setFormatDate();
$grid->addField('status', 'Status', true)->setFormatFunction(array('CcRebill', 'getStatusText'));
$grid->addField('status_msg', 'Message');
$grid->setCountPerPage(10);
return $grid;
}
public function runAction()
{
$date = $this->getFiltered('date');
if (!$date)
throw new Am_Exception_InputError("Wrong date");
$form = $this->createRunForm();
if ($form->isSubmitted() && $form->validate()) {
$value = $form->getValue();
$this->doRun($value['paysys_id'], $value['date']);
echo sprintf('%s
', ___('Rebill Operation Completed for %s', amDate($value['date'])));
} else {
echo $form;
}
}
public function doRun($paysys_id, $date)
{
$this->getDi()->plugins_payment->load($paysys_id);
$p = $this->getDi()->plugins_payment->get($paysys_id);
// Delete all previous failed attempts for this date in order to rebill these invoices again.
$this->getDi()->db->query("
DELETE FROM ?_cc_rebill
WHERE rebill_date = ? AND paysys_id = ? AND status <> ?
", $date, $paysys_id, ccRebill::SUCCESS);
$p->ccRebill($date);
}
}PK \}0 AdminFieldsController.phpnu [ hasPermission(Bootstrap_Helpdesk::ADMIN_PERM_CATEGORY);
}
protected function getTable()
{
return $this->getDi()->helpdeskTicketTable;
}
public function createGrid()
{
$grid = parent::createGrid();
$grid->addCallback(Am_Grid_Editable::CB_AFTER_DELETE, array($this, 'afterDelete'));
$grid->setPermissionId(Bootstrap_Helpdesk::ADMIN_PERM_CATEGORY);
return $grid;
}
public function createForm()
{
$form = new Am_Form_Admin_CustomField_Ticket($this->grid->getRecord());
$form->setTable($this->getTable());
return $form;
}
public function afterDelete($record)
{
foreach ($this->getDi()->helpdeskCategoryTable->findBy(array()) as $c) {
$fields = $c->unserializeList($c->fields);
if (in_array($record->name, $fields)) {
$fields = array_diff($fields, array($record->name));
$c->fields = $c->serializeList($fields);
$c->save();
}
}
}
}PK \LEE AdminMyController.phpnu [ addWhere('t.owner_id=?d', Am_Di::getInstance()->authAdmin->getUserId());
$q->addWhere('t.status<>?', HelpdeskTicket::STATUS_CLOSED);
return $q;
}
public function getGridTitle()
{
return ___('Tickets Assigned to Me');
}
public function initGridFields()
{
parent::initGridFields();
$this->removeField('owner_id');
}
public function initActions()
{
parent::initActions();
$this->actionAdd(new Am_Grid_Action_Delete());
}
}
class Helpdesk_AdminMyController extends Am_Mvc_Controller_Pages
{
public function checkAdminPermissions(Admin $admin)
{
return $admin->hasPermission(Bootstrap_Helpdesk::ADMIN_PERM_ID);
}
function preDispatch()
{
$this->view->headLink()->appendStylesheet($this->view->_scriptCss('helpdesk-admin.css'));
$this->setActiveMenu('helpdesk-ticket-my');
parent::preDispatch();
}
public function initPages()
{
$this->addPage('Am_Helpdesk_Grid_My', 'index', ___('Tickets'))
->addPage(array($this, 'createController'), 'view', ___('Conversation'));
}
public function renderTabs()
{
return '';
}
public function createController($id, $title, $grid)
{
return new Am_Helpdesk_Controller($grid->getRequest(), $grid->getResponse(), $this->_invokeArgs);
}
}PK \'ʀ
FaqController.phpnu [ getModule()->getConfig('does_not_require_login')) {
$this->getDi()->auth->requireLogin($this->getDi()->url('helpdesk/faq',null,false,2));
}
$this->view->headLink()->appendStylesheet($this->view->_scriptCss('helpdesk-user.css'));
if ($this->getDi()->auth->getUser() && ($page = $this->getDi()->navigationUser->findOneBy('id', 'helpdesk-faq'))) {
$page->setActive(true);
}
parent::preDispatch();
}
public function indexAction()
{
$this->view->categories = $this->getDi()->helpdeskFaqTable->getCategories();
$this->view->catActive = $this->getParam('cat');
$this->view->faq = $this->getDi()->helpdeskFaqTable->findBy(array(
'category' => $this->getParam('cat', null)), null, null, 'sort_order');
if ($this->getParam('cat')) {
$this->view->getHelper('breadcrumbs')->setPath(array($this->getDi()->url('helpdesk/faq',null,false) => ___('FAQ')));
}
$this->view->display('helpdesk/faq.phtml');
}
public function itemAction()
{
$path = array($this->getDi()->url('helpdesk/faq',null,false) => ___('FAQ'));
$faq = $this->getDi()->helpdeskFaqTable->findFirstByTitle($this->getParam('title'));
if ($faq->category) {
$path[$this->getDi()->url('helpdesk/faq/c/' . urldecode($faq->category),null,false)] = $faq->category;
}
$this->view->getHelper('breadcrumbs')->setPath($path);
$this->view->faq = $faq;
$this->view->display('helpdesk/faq-item.phtml');
}
public function searchAction()
{
$result = $this->getDi()->db->selectPage($total, "SELECT * FROM ?_helpdesk_faq WHERE MATCH(`title`,`content`)
AGAINST (? IN NATURAL LANGUAGE MODE)
LIMIT 10", $this->getParam('q'));
$items = array();
foreach ($result as $row)
$items[] = $this->getDi()->helpdeskFaqTable->createRecord($row);
$this->view->items = $items;
$this->view->display('helpdesk/_search-result.phtml');
}
public function suggestAction()
{
$result = $this->getDi()->db->selectPage($total, "SELECT * FROM ?_helpdesk_faq WHERE MATCH(`title`,`content`)
AGAINST (? IN NATURAL LANGUAGE MODE)
LIMIT 10", $this->getParam('q'));
$items = array();
foreach ($result as $row)
$items[] = $this->getDi()->helpdeskFaqTable->createRecord($row);
$this->view->items = $items;
$this->view->display('helpdesk/_suggest.phtml');
}
}PK \-a AdminFaqController.phpnu [ helpdeskFaqTable->getCategories());
$catoptions = array_merge(array('' => ___('-- Without A Category --')), $catoptions);
$this->addSelect('category', array(),
array('intrinsic_validation' => false, 'options' => $catoptions))
->setLabel('Category');
$label_add_category = ___('add category');
$label_title_error = ___('Enter title for your new category');
$this->addScript()
->setScript(<< $label_add_category "));
jQuery("select[name='category']").change(function(){
jQuery(this).toggle(jQuery(this).find('option').length > 1);
}).change();
jQuery(document).on('click',"a#add-category", function(){
var ret = prompt("$label_title_error", "");
if (!ret) return;
var \$sel = jQuery("select#category").append(
jQuery(" ").val(ret).html(ret));
\$sel.val(ret).change();
});
})
CUT
);
$this->addText('title', array('class' => 'el-wide'))
->setLabel(___('Title'));
$this->addHtmlEditor('content')
->setLabel(___('Content'));
}
}
class Am_Grid_Filter_HelpdeskFaq extends Am_Grid_Filter_Abstract
{
public function getTitle()
{
return ___('Filter By Title or Category');
}
protected function applyFilter()
{
if ($this->isFiltered()) {
$q = $this->grid->getDataSource();
/* @var $q Am_Query */
$q->addWhere('title LIKE ? OR category LIKE ?',
'%' . $this->vars['filter'] . '%',
'%' . $this->vars['filter'] . '%');
}
}
public function renderInputs()
{
return $this->renderInputText();
}
}
class Am_Grid_Action_EditFaqCategory extends Am_Grid_Action_Abstract
{
protected $type = self::NORECORD;
protected $url;
protected $attributes = array(
'target' => '_top'
);
public function getUrl($record = null, $id = null)
{
return Am_Di::getInstance()->url('helpdesk/admin-faq/category',null,false);
}
public function run()
{
//nop
}
}
class Am_Grid_Action_Back extends Am_Grid_Action_Abstract
{
protected $type = self::NORECORD;
protected $url;
protected $attributes = array(
'target' => '_top'
);
public function getUrl($record = null, $id = null)
{
return Am_Di::getInstance()->url('helpdesk/admin-faq',null,false);
}
public function run()
{
//nop
}
}
class Am_Grid_DataSource_FaqCategory extends Am_Grid_DataSource_Array
{
public function updateRecord($record, $valuesFromForm)
{
Am_Di::getInstance()->db->query('UPDATE ?_helpdesk_faq SET category=? WHERE category=?',
$valuesFromForm['name'],
$record->name);
}
}
class Helpdesk_AdminFaqController extends Am_Mvc_Controller_Grid
{
public function checkAdminPermissions(Admin $admin)
{
return $admin->hasPermission(Bootstrap_Helpdesk::ADMIN_PERM_FAQ);
}
public function createGrid()
{
$ds = new Am_Query($this->getDi()->helpdeskFaqTable);
$ds->setOrder('sort_order');
$grid = new Am_Grid_Editable('_helpdesk_faq', ___('FAQ'), $ds, $this->_request, $this->view);
$grid->addField(new Am_Grid_Field('title', ___('Title'), true, '', null, '50%'));
$grid->addField(new Am_Grid_Field('category', ___('Category')));
$grid->addField('_link', ___('Link'), false)->setRenderFunction(array($this, 'renderLink'));
$grid->setForm('Am_Form_Admin_HelpdeskFaq');
$grid->setFilter(new Am_Grid_Filter_HelpdeskFaq());
$grid->addCallback(Am_Grid_Editable::CB_VALUES_FROM_FORM, array($this, 'valuesFromForm'));
$grid->setPermissionId(Bootstrap_Helpdesk::ADMIN_PERM_FAQ);
$grid->actionAdd(new Am_Grid_Action_Sort_HelpdeskFaq());
if ($this->getDi()->helpdeskFaqTable->getCategories()) {
$grid->actionAdd(new Am_Grid_Action_EditFaqCategory('faq-edit-category', ___('Edit Categories')))
->setCssClass('link');
}
return $grid;
}
public function categoryAction()
{
$ret = array();
foreach ($this->getDi()->helpdeskFaqTable->getCategories() as $category) {
$cat = new stdClass();
$cat->name = $category;
$ret[] = $cat;
}
$ds = new Am_Grid_DataSource_FaqCategory($ret);
$grid = new Am_Grid_Editable('_helpdesk_faq_category', ___('Categories'), $ds, $this->_request, $this->view);
$grid->setPermissionId(Bootstrap_Helpdesk::ADMIN_PERM_FAQ);
$grid->addField(new Am_Grid_Field('name', ___('Title')));
$grid->actionsClear();
$grid->actionAdd(new Am_Grid_Action_Back('faq-edit-category-back', ___('Back to FAQ List')))
->setCssClass('link');
$grid->actionAdd(new Am_Grid_Action_LiveEdit('name'));
$grid->runWithLayout('admin/layout.phtml');
}
public function valuesFromForm(& $ret, HelpdeskFaq $record)
{
if (!isset($ret['category']) || !$ret['category'])
$ret['category'] = null;
}
public function renderLink(Am_Record $record)
{
$url = Am_Di::getInstance()->url('helpdesk/faq/i/'.urlencode($record->title));
return $this->renderTd(sprintf('%s ',
$url, ___('link')), false);
}
}
class Am_Grid_Action_Sort_HelpdeskFaq extends Am_Grid_Action_Sort_Abstract
{
protected function setSortBetween($item, $after, $before)
{
$this->_simpleSort(Am_Di::getInstance()->helpdeskFaqTable, $item, $after, $before);
}
}PK \8z AdminCategoryController.phpnu [ addText('title', array('size' => 40))
->setLabel(___('Title'));
$options = array();
foreach (Am_Di::getInstance()->adminTable->findBy() as $admin) {
$options[$admin->pk()] = sprintf('%s (%s %s)', $admin->login, $admin->name_f, $admin->name_l);
}
$this->addSelect('owner_id')
->setLabel(___("Owner\n".
'set the following admin as owner of ticket'))
->loadOptions(array('' => '') + $options);
$this->addMagicSelect('watcher_ids')
->setLabel(___("Watchers\n" .
'notify the following admins ' .
'about new messages in this category'))
->loadOptions($options);
$options = array();
foreach(Am_Di::getInstance()->helpdeskTicketTable->customFields()->getAll()
as $f) {
$options[$f->getName()] = $f->title;
}
$url = Am_Di::getInstance()->url('helpdesk/admin-fields');
$this->addSortableMagicSelect('fields')
->setLabel(___("Fields\n" .
"You can add new fields %shere%s",
'', ' '))
->loadOptions($options);
$this->addElement(new Am_Form_Element_ResourceAccess)
->setName('_access')
->setLabel(___("Access Permissions\n" .
'this category will be available only for users ' .
'with proper access permission'))
->setAttribute('without_free_without_login', 'true');
}
}
class Am_Grid_Action_Sort_HelpdeskCategory extends Am_Grid_Action_Sort_Abstract
{
protected function setSortBetween($item, $after, $before)
{
$this->_simpleSort(Am_Di::getInstance()->helpdeskCategoryTable, $item, $after, $before);
}
}
class Helpdesk_AdminCategoryController extends Am_Mvc_Controller_Grid
{
public function checkAdminPermissions(Admin $admin)
{
return $admin->hasPermission(Bootstrap_Helpdesk::ADMIN_PERM_CATEGORY);
}
public function preDispatch()
{
parent::preDispatch();
$this->view->headScript()->appendFile($this->view->_scriptJs("resourceaccess.js"));
}
public function createGrid()
{
$ds = new Am_Query($this->getDi()->helpdeskCategoryTable);
$ds->leftJoin('?_admin', 'a', 't.owner_id=a.admin_id')
->addField("CONCAT(a.login, ' (',a.name_f, ' ', a.name_l, ')')", 'owner');
$ds->setOrder('sort_order');
$grid = new Am_Grid_Editable('_helpdesk_category', ___("Ticket Categories"), $ds, $this->_request, $this->view);
$grid->addField(new Am_Grid_Field('title', ___('Title')));
$grid->addField(new Am_Grid_Field('fields', ___('Fields')))
->setGetFunction(function($r, $grid, $fieldname, $field){
return implode(', ', $r->unserializeList($r->{$fieldname}));
});
$grid->addField(new Am_Grid_Field('owner_id', ___('Owner'), true, '', array($this, 'renderOwner')));
$grid->addField(new Am_Grid_Field_IsDisabled);
$grid->setForm('Am_Form_Admin_HelpdeskCategory');
$grid->addCallback(Am_Grid_Editable::CB_BEFORE_SAVE, array($this, 'beforeSave'));
$grid->setPermissionId(Bootstrap_Helpdesk::ADMIN_PERM_CATEGORY);
$grid->actionAdd(new Am_Grid_Action_Sort_HelpdeskCategory());
$grid->setFormValueCallback('watcher_ids', array('RECORD', 'unserializeIds'), array('RECORD', 'serializeIds'));
$grid->setFormValueCallback('fields', array('RECORD', 'unserializeList'), array('RECORD', 'serializeList'));
$grid->addCallback(Am_Grid_Editable::CB_AFTER_DELETE, array($this, 'afterDelete'));
$grid->addCallback(Am_Grid_Editable::CB_AFTER_SAVE, array($this, 'afterSave'));
$grid->addCallback(Am_Grid_Editable::CB_VALUES_TO_FORM, array($this, 'valuesToForm'));
return $grid;
}
public function renderOwner($record)
{
return $record->owner_id ?
sprintf('%s ', Am_Html::escape($record->owner)) :
' ';
}
public function beforeSave(& $values, $record)
{
$values['owner_id'] = $values['owner_id'] ? $values['owner_id'] : null;
}
public function valuesToForm(& $ret, $record)
{
$ret['_access'] = $record->isLoaded() ?
$this->getDi()->resourceAccessTable->getAccessList($record->pk(), HelpdeskCategory::ACCESS_TYPE) :
array(
ResourceAccess::FN_FREE => array(
json_encode(array(
'start' => null,
'stop' => null,
'text' => ___('Free Access')
))));
}
public function afterSave(array & $values, $record)
{
$this->getDi()->resourceAccessTable->setAccess($record->pk(), HelpdeskCategory::ACCESS_TYPE, $values['_access']);
}
public function afterDelete($record)
{
$this->getDi()->resourceAccessTable->clearAccess($record->pk(), HelpdeskCategory::ACCESS_TYPE);
}
}PK \a AdminUserController.phpnu [ user_id = $this->getCompleteRequest()->get('user_id', 0);
if ($this->user_id) {
$this->getDataSource()->getDataSourceQuery()->addWhere('t.user_id=?d', $this->user_id);
}
}
public function initActions()
{
parent::initActions();
$this->actionAdd(new Am_Grid_Action_Ticket());
}
}
class Helpdesk_AdminUserController extends Am_Mvc_Controller_Pages
{
protected $layout = 'admin/user-layout.phtml';
public function checkAdminPermissions(Admin $admin)
{
return $admin->hasPermission(Bootstrap_Helpdesk::ADMIN_PERM_ID);
}
function preDispatch()
{
$this->getDi()->navigationUserTabs->setActive('helpdesk');
$this->getDi()->helpdeskStrategy->setUserId(
$this->getRequest()->getParam('user_id', 0)
);
$this->view->headLink()->appendStylesheet($this->view->_scriptCss('helpdesk-admin.css'));
$this->setActiveMenu('users-browse');
parent::preDispatch();
}
public function initPages()
{
$this->addPage('Am_Helpdesk_Grid_UserTab', 'index', ___('Tickets'))
->addPage(array($this, 'createController'), 'view', ___('Conversation'));
}
public function renderTabs()
{
return '';
}
public function createController($id, $title, $grid)
{
return new Am_Helpdesk_Controller($grid->getRequest(), $grid->getResponse(), $this->_invokeArgs);
}
}PK \v v IndexController.phpnu [ addCallback(Am_Grid_ReadOnly::CB_TR_ATTRIBS, function(&$attrs, $r){
if ($r->has_new) {
$attrs['class'] = isset($attrs['class']) ? $attrs['class'] . ' emphase' : 'emphase';
}
});
$uid = $this->getDi()->auth->getUserId();
if ($this->getDi()->helpdeskTicketTable->countByUserId($uid) < 10) {
$this->addCallback(Am_Grid_ReadOnly::CB_RENDER_CONTENT, function(&$out, $g){
$out = preg_replace('/.*?/is', '', $out);
});
}
parent::init();
}
public function initGridFields()
{
$this->addField(new Am_Grid_Field('subject', ___('Subject'), true, '', array($this, 'renderSubject')));
$this->addField(new Am_Grid_Field('updated', ___('Updated'), true, '', array($this, 'renderTime')));
$this->addField(new Am_Grid_Field('ticket_mask', '#', true));
$this->addField(new Am_Grid_Field('status', ___('Status'), true, '', array($this, 'renderStatus'), '1%'));
$this->addCallback(Am_Grid_ReadOnly::CB_TR_ATTRIBS, array($this, 'cbGetTrAttribs'));
}
protected function createFilter()
{
return new Am_Grid_Filter_Helpdesk;
}
public function getStatusIconId($id, $record)
{
return $id == 'awaiting' && $record->status == HelpdeskTicket::STATUS_AWAITING_USER_RESPONSE ?
$id . '-me' : $id;
}
protected function isNotImportant($record)
{
return $record->status == HelpdeskTicket::STATUS_CLOSED;
}
public function initActions()
{
parent::initActions();
$this->actionAdd(new Am_Grid_Action_Ticket());
}
public function createDs()
{
$query = parent::createDS();
$query->addWhere('t.user_id=?',
Am_Di::getInstance()->auth->getUserId()
);
return $query;
}
}
class Helpdesk_IndexController extends Am_Mvc_Controller_Pages
{
protected $layout = 'member/layout.phtml';
function preDispatch()
{
$this->getDi()->auth->requireLogin($this->getDi()->url('helpdesk',null,false,2));
$this->view->headLink()->appendStylesheet($this->view->_scriptCss('helpdesk-user.css'));
$this->view->headScript()->appendFile($this->view->_scriptJs('jquery/jquery.form.js'));
if ($page = $this->getDi()->navigationUser->findOneBy('id', 'helpdesk')) {
$page->setActive(true);
}
parent::preDispatch();
}
public function initPages()
{
$this->addPage('Am_Helpdesk_Grid_User', 'index', ___('Tickets'))
->addPage(array($this, 'createController'), 'view', ___('Conversation'));
}
public function renderTabs()
{
$intro = $this->getDi()->config->get('helpdesk.intro');
return $intro ? sprintf('%s
', $intro) : '';
}
public function createController($id, $title, $grid)
{
return new Am_Helpdesk_Controller($grid->getRequest(), $grid->getResponse(), $this->_invokeArgs);
}
}PK 3\b٧܁
AdminQueueController.phpnu [ hasPermission(Bootstrap_Webhooks::ADMIN_PERM_ID);
}
function createGrid()
{
$ds = new Am_Query($this->getDi()->webhookQueueTable);
$grid = new Am_Grid_Editable('_w', ___('Webhooks Queue'), $ds, $this->getRequest(), $this->getView(), $this->getDi());
$grid->setPermissionId(Bootstrap_Webhooks::ADMIN_PERM_ID);
$grid->actionDelete('edit');
$grid->actionDelete('insert');
$grid->actionAdd(new Am_Grid_Action_Group_Delete);
$grid->addField(new Am_Grid_Field_Date('added', ___('Added')));
$grid->addField(new Am_Grid_Field_Date('sent', ___('Sent')));
$grid->addField('event_id', ___('Event'));
$grid->addField('url', ___('Url'));
$grid->addField('failures', ___('Failures'));
$grid->addField('last_error', ___('Last Error'));
$grid->addField(new Am_Grid_Field_Expandable('params', ___('Params'), false))
->setAjax($this->getDi()->url('webhooks/admin-queue/get-queue-details?id={webhook_queue_id}',null,false));
$grid->setFilter(new Am_Grid_Filter_WebhookQueue);
return $grid;
}
function getQueueDetailsAction()
{
$log = $this->getDi()->webhookQueueTable->load($this->getParam('id'));
echo $this->renderQueueDetails($log);
}
public function renderQueueDetails(WebhookQueue $obj)
{
$ret = "";
$ret .= "\n";
if (empty($obj->params)) {
$rows = array();
} else {
$rows = unserialize($obj->params);
}
$open = count($rows) == 1 ? 'open' : '';
foreach ($rows as $name => $array)
{
$ret .= "\t
\n";
$ret .= "\t\t
$name
\n";
$ret .= "\t\t
\n";
$ret .= "\t
\n";
}
$ret .= "
\n\n";
return $ret;
}
}
class Am_Grid_Filter_WebhookQueue extends Am_Grid_Filter_Abstract
{
protected $title = "Filter by Event";
function applyFilter()
{
$this->grid->getDataSource()
->getDataSourceQuery()
->addWhere('event_id=?', $this->getParam('filter'));
}
function renderInputs()
{
$k = array_keys($this->grid->getDi()->modules->loadGet('webhooks')->getTypes());
return $this->renderInputSelect('filter', array(''=>'') + array_combine($k, $k));
}
}PK 3\Y Y CronController.phpnu [ getDi()->db->selectCell("SELECT GET_LOCK(?, 0)", self::getLockId())) {
$this->getDi()->errorLogTable->log("Could not obtain MySQL's GET_LOCK() to run webhooks cron. Probably attempted to execute two cron processes simultaneously. ");
return;
}
$start = time();
foreach($this->getDi()->webhookQueueTable->findBy(array('sent' => null)) as $webhook_queue)
{
if(time() - $start >= $time_limit) break;
try{
$req = new Am_HttpRequest($webhook_queue->url, Am_HttpRequest::METHOD_POST);
$params = unserialize($webhook_queue->params);
foreach($params as $name => $data) {
if (is_array($data)) {
unset($params[$name]);
foreach($data as $k => $v) {
$params[$name . '[' . $k . ']'] = $v;
}
}
}
$req->addPostParameter($params);
$res = $req->send();
$st = $res->getStatus();
if($st == 200) {
$webhook_queue->updateQuick(array('sent' => $this->getDi()->time));
} else {
$webhook_queue->updateQuick(array('last_error'=>$st, 'failures'=>$webhook_queue->failures + 1));
}
} catch(Exception $e) {
$this->getDi()->errorLogTable->logException($e);
}
}
//release lock
$this->getDi()->db->query("SELECT RELEASE_LOCK(?)", self::getLockId());
}
static function getLockId()
{
return 'webhooks-cron-lock-' . md5(__FILE__);
}
}PK a\+f AjaxController.phpnu [ getFiltered('s')) && ($e = $this->getParam('e')) &&
Am_Mail::validateUnsubscribeLink($e, $s))
{
$user = $this->getDi()->userTable->findFirstByEmail($e);
} else {
$user = $this->getDi()->user;
}
if (!$user) throw new Am_Exception_InputError(___('You must be logged-in to use this function'));
$allowed = array();
foreach ($this->getDi()->newsletterListTable->getAllowed($user) as $r)
$allowed[$r->pk()] = $r;
$subs = array();
foreach ($this->getDi()->newsletterUserSubscriptionTable->findByUserId($user->pk()) as $s)
$subs[$s->list_id] = $s;
$post = $this->getRequest()->getPost();
$ret = array('status' => 'OK');
foreach ($post as $k => $v)
{
if (!is_int($k)) continue;
switch ($v)
{
case 0:
if (!empty($subs[$k]))
$subs[$k]->unsubscribe();
$ret[(int)$k] = (int)$v;
break;
case 1:
$this->getDi()->newsletterUserSubscriptionTable->add($user,
$this->getDi()->newsletterListTable->load($k),
NewsletterUserSubscription::TYPE_USER);
$ret[(int)$k] = (int)$v;
break;
default:
throw new Am_Exception_InputError(___('Wrong value submitted'));
}
}
$this->_response->ajaxResponse($ret);
}
}PK \xq AffPayoutDetailsController.phpnu [ PK \yKX SignupController.phpnu [ PK \4ð1 1 AffController.phpnu [ PK \+ + / GoController.phpnu [ PK \̩ @ BannerController.phpnu [ PK \HrJ J @W AdminCommissionController.phpnu [ PK \i~:3 :3 L AdminPayoutController.phpnu [ PK \P P AdminBannersController.phpnu [ PK \4 4 ' MemberController.phpnu [ PK \TMLְ [ AffPayoutsController.phpnu [ PK \i}u u ! ] AdminCommissionRuleController.phpnu [ PK \Gv9 9 AdminController.phpnu [ PK \ u ClickJsController.phpnu [ PK \sQ$ Q$ { AdminConvertController.phpnu [ PK \h*0 *0
AdminRebillsController.phpnu [ PK \}0 = AdminFieldsController.phpnu [ PK \LEE C AdminMyController.phpnu [ PK \'ʀ
J FaqController.phpnu [ PK \-a T AdminFaqController.phpnu [ PK \8z l AdminCategoryController.phpnu [ PK \a AdminUserController.phpnu [ PK \v v IndexController.phpnu [ PK 3\b٧܁
N AdminQueueController.phpnu [ PK 3\Y Y CronController.phpnu [ PK a\+f AjaxController.phpnu [ PK v