/** * @before _secure */ public function createinvoice() { $this->seo(array("title" => "Create Invoice")); $view = $this->getActionView(); $perfs = []; $start = RM::get("start"); $end = RM::get("end"); $user_id = RM::get("user_id", null); $view->set('user_id', $user_id)->set('start', $start)->set('end', $end); $query['created'] = Db::dateQuery($start, $end); $query['user_id'] = $user_id; $view->set("exists", false); if ($user_id) { $user = \User::first(['type = ?' => 'publisher', 'org_id = ?' => $this->org->_id, 'id = ?' => $user_id]); $view->set('affiliate', $user); $performances = Performance::all($query, ['clicks', 'impressions', 'conversions', 'created', 'revenue'], 'created', 'desc'); $perfs = array_values($performances); $view->set('performances', $perfs); $inv_exist = Invoice::exists($user_id, $start, $end); if ($inv_exist) { $view->set("message", "Invoice already exist for Date range from " . Framework\StringMethods::only_date($inv_exist->start) . " to " . Framework\StringMethods::only_date($inv_exist->end)); $view->set("exists", true); return; } } else { $affiliates = \User::all(['type = ?' => 'publisher', 'org_id' => $this->org->_id], ['id', 'name']); $view->set('affiliates', $affiliates); } if (RM::post("action") == "cinvoice" && RM::post("amount") > 0) { $invoice = new Invoice(["org_id" => $this->org->id, "user_id" => $user->id, "utype" => $user->type, "start" => end($perfs)->created, "end" => $perfs[0]->created, "amount" => RM::post("amount"), "live" => false]); $invoice->save(); Registry::get("session")->set('$flashMessage', 'Payment Saved!!'); $this->redirect("/billing/affiliates.html"); } }
/** * @before _secure */ public function manage() { $this->seo(array("title" => "Manage Account")); $view = $this->getActionView(); $users = User::all(['type' => Db::convertType('admin|adm|afm', 'regex'), "org_id" => $this->org->_id]); $view->set('users', $users); }
public static function exists($uid, $start = null, $end = null) { $uid = Db::convertType($uid); $dateQuery = Utils::dateQuery($start, $end); $inv_exist = self::first(['$or' => [["user_id" => $uid, "start" => ['$lte' => $dateQuery['start'], '$lte' => $dateQuery['end']], "end" => ['$gte' => $dateQuery['start'], '$gte' => $dateQuery['end']]], ["user_id" => $uid, "start" => Db::dateQuery($start, $end), "end" => ['$gte' => $dateQuery['start'], '$gte' => $dateQuery['end']]], ["user_id" => $uid, "start" => ['$lte' => $dateQuery['start'], '$lte' => $dateQuery['end']], "end" => Db::dateQuery($start, $end)], ["user_id" => $uid, "start" => Db::dateQuery($start, $end), "end" => Db::dateQuery($start, $end)]]]); return $inv_exist; }
public static function getStats($query, $dq = []) { if (count($dq) > 0) { $query['created'] = \Shared\Services\Db::dateQuery($dq['start'], $dq['end']); } $records = self::all($query, ['hits']); $total = 0; foreach ($records as $r) { $total += $r->hits; } return $total; }
public static function exists($oid, $opts = []) { $oid = Db::convertType($oid); $dateQuery = Utils::dateQuery($opts); $multiple = $opts['multiple'] ?? false; if ($multiple) { $query = "all"; } else { $query = "first"; } $inv_exist = self::$query(['$or' => [["org_id" => $oid, "start" => ['$lte' => $dateQuery['start'], '$lte' => $dateQuery['end']], "end" => ['$gte' => $dateQuery['start'], '$gte' => $dateQuery['end']]], ["org_id" => $oid, "start" => Db::dateQuery($start, $end), "end" => ['$gte' => $dateQuery['start'], '$gte' => $dateQuery['end']]], ["org_id" => $oid, "start" => ['$lte' => $dateQuery['start'], '$lte' => $dateQuery['end']], "end" => Db::dateQuery($start, $end)], ["org_id" => $oid, "start" => Db::dateQuery($start, $end), "end" => Db::dateQuery($start, $end)]]]); return $inv_exist; }
/** * Find the Performance of Affiliates|Advertisers of an organization * @param object $org \Organization * @param string $type Type of user * @return [type] [description] */ public static function perf($org, $type, $opts = []) { $start = $opts['start'] ?? RequestMethods::get('start', date('Y-m-d', strtotime("-5 day"))); $end = $opts['end'] ?? RequestMethods::get('end', date('Y-m-d', strtotime("-1 day"))); switch ($type) { case 'publisher': $perfFields = $opts['fields'] ?? ['clicks', 'impressions', 'conversions', 'revenue', 'created']; $meta = $opts['meta'] ?? false; if ($meta) { $perfFields[] = 'meta'; } $publishers = $opts['publishers'] ?? $org->users($type); $pubPerf = Perf::all(['user_id' => ['$in' => $publishers], 'created' => Db::dateQuery($start, $end)], $perfFields, 'created', 'asc'); $pubPerf = Perf::objectArr($pubPerf, $perfFields); return $pubPerf; case 'advertiser': $advertisers = $opts['advertisers'] ?? $org->users($type); $fields = $opts['fields'] ?? ['revenue', 'created']; $advertPerf = Perf::all(['user_id' => ['$in' => $advertisers], 'created' => Db::dateQuery($start, $end)], $fields, 'created', 'asc'); $advertPerf = Perf::objectArr($advertPerf, $fields); return $advertPerf; } return []; }
public static function total($dq = [], $user = null, $fields = []) { $name = __CLASS__; if (count($fields) === 0) { $fields = ['clicks', 'conversions', 'impressions', 'revenue']; } $project = ['user_id' => 1, '_id' => 0]; $group = ['_id' => '$user_id']; foreach ($fields as $f) { $project[$f] = 1; $group[$f] = ['$sum' => '$' . $f]; } $match = ['created' => Db::dateQuery($dq['start'], $dq['end'])]; if (is_array($user)) { $keys = ArrayMethods::arrayKeys($user, '_id'); $match['user_id'] = ['$in' => Db::convertType($keys)]; } else { $match['user_id'] = Db::convertType($user->_id); } $records = Db::collection($name)->aggregate([['$match' => $match], ['$project' => $project], ['$group' => $group]]); $result = []; foreach ($records as $r) { $obj = Utils::toArray($r); $add = []; foreach ($fields as $f) { $add[$f] = $obj[$f]; } ArrayMethods::add($add, $result); } return $result; }
/** * Converts the MongoDB result to an object of class * whose parent is \Shared\Model */ protected function _convert($record) { if (!$record) { return null; } $columns = $this->getColumns(); $record = (array) $record; $class = get_class($this); $c = new $class(); foreach ($record as $key => $value) { if (!property_exists($this, "_{$key}")) { continue; } $raw = "_{$key}"; if (is_object($value)) { if (Db::isType($value, 'id')) { $c->{$raw} = $this->getMongoID($value); } else { if (Db::isType($value, 'date')) { $v = $value->toDateTime(); $v->settimezone(new \DateTimeZone('Asia/Kolkata')); $c->{$raw} = $v; } else { if (Db::isType($value, 'document')) { $c->{$raw} = Utils::toArray($value); } else { // fallback case $c->{$raw} = (object) $value; } } } } else { $c->{$raw} = $value; } } return $c; }
public static function performance($id, $extra = []) { $stats = []; $start = $end = date('Y-m-d'); $match = ['adid' => Db::convertType($id), 'is_bot' => false]; $user_id = $extra['pid'] ?? null; if ($user_id) { $match["pid"] = Db::convertType($user_id); } if (isset($extra['start']) && isset($extra['end'])) { $start = $extra['start']; $end = $extra['end']; } $diff = date_diff(date_create($start), date_create($end)); $dateWise = $extra['meta'] ?? true; // by default datewise query if ($dateWise) { for ($i = 0; $i <= $diff->format("%a"); $i++) { $date = date('Y-m-d', strtotime($start . " +{$i} day")); $stats[$date] = ['clicks' => 0, 'meta' => []]; $match['created'] = Db::dateQuery($date, $date); $records = self::_perfQuery($match, $extra); self::_getStats($records, $stats, $date); } } else { $match['created'] = Db::dateQuery($start, $end); $stats[$start] = ['clicks' => 0, 'meta' => []]; $records = self::_perfQuery($match, $extra); self::_getStats($records, $stats, $start); } $records = self::earning($stats, $id, $user_id); $total = Performance::calTotal($records); return ['stats' => $records, 'total' => $total]; }
public static function hourly() { $today = date('Y-m-d'); $dq = Db::dateQuery(null, $today); // find all the ads whose expiry date is today $ads = self::all(['expiry' => $dq]); foreach ($ads as $a) { $a->live = false; // Make them disabled $a->save(); } }
/** * @before _admin */ public function manage() { $this->seo(array("title" => "Manage")); $view = $this->getActionView(); $page = RM::get("page", 1); $limit = RM::get("limit", 30); $query = ["type = ?" => "advertiser", "org_id = ?" => $this->org->_id]; $property = RM::get("property", "live"); $value = RM::get("value", 0); if (in_array($property, ["live", "id"])) { $query["{$property} = ?"] = $value; } else { if (in_array($property, ["email", "name", "phone"])) { $query["{$property} = ?"] = Db::convertType($value, 'regex'); } } $advertisers = \User::all($query, ['_id', 'name', 'live', 'email', 'created'], 'created', 'desc'); $count = \User::count($query); $active = \User::count(["type = ?" => "advertiser", "org_id = ?" => $this->org->_id, "live = ?" => 1]); $inactive = \User::count(["type = ?" => "advertiser", "org_id = ?" => $this->org->_id, "live = ?" => 0]); $view->set("advertisers", $advertisers)->set("property", $property)->set("value", $value)->set("active", $active)->set("inactive", $inactive)->set("count", $count)->set("limit", $limit)->set("page", $page); }
public function setUp() { // Connect to DB $this->mongoDB = Db::connect(); }
/** * @before _secure */ public function manage() { $this->seo(['title' => 'Campaign: List', 'description' => 'Manage campaigns']); $view = $this->getActionView(); $campaigns = []; $page = RM::get("page", 1); $limit = RM::get("limit", 10); $property = RM::get("property"); $value = RM::get("value"); switch (RM::get("sort")) { case 'trending': $start = RM::get("start", date("Y-m-d", strtotime('now'))); $end = RM::get("end", date("Y-m-d", strtotime('now'))); $q = ['start' => $start, 'end' => $end]; $view->set($q); // Only find the ads for this organizations $allAds = \Ad::all(['org_id' => $this->org->_id], ['_id']); $in = Db::convertType(array_keys($allAds)); $clickCol = Db::collection('Click'); $match = ['created' => Db::dateQuery($start, $end), 'is_bot' => false, 'adid' => ['$in' => $in]]; $records = $clickCol->aggregate([['$match' => $match], ['$project' => ['adid' => 1, '_id' => 0]], ['$group' => ['_id' => '$adid', 'count' => ['$sum' => 1]]], ['$sort' => ['count' => -1]], ['$limit' => (int) $limit]]); foreach ($records as $r) { $arr = Utils::toArray($r); $id = Utils::getMongoID($arr['_id']); $campaigns[] = Ad::first(["id = ?" => $id]); } $count = $limit; break; default: $query = ["org_id = ?" => $this->org->id]; if (in_array($property, ["user_id", "live", "id"])) { $query[$property] = $value; } else { if (in_array($property, ["url", "title"])) { $query[$property] = Utils::mongoRegex(preg_quote($value)); } } $campaigns = \Ad::all($query, [], 'created', 'desc', $limit, $page); $count = \Ad::count($query); break; } $categories = \Category::all(['org_id' => $this->org->_id], ['_id', 'name']); $active = \Ad::count(["org_id = ?" => $this->org->id, "live = ?" => 1]); $inactive = \Ad::count(["org_id = ?" => $this->org->id, "live = ?" => 0]); $view->set("campaigns", $campaigns)->set("count", $count)->set("active", $active)->set("inactive", $inactive)->set("limit", $limit)->set("page", $page)->set("property", $property)->set("value", $value)->set("categories", $categories); }
/** * @before _admin */ public function info($id = null) { $this->seo(array("title" => "Publisher Edit")); $view = $this->getActionView(); $publisher = User::first(["_id = ?" => $id, "type = ?" => "publisher", "org_id = ?" => $this->org->id]); if (!$publisher) { $this->_404(); } $platforms = Platform::all(["user_id = ?" => $publisher->id]); $view->set("platforms", $platforms); $view->set("errors", []); if (RM::type() == 'POST') { $action = RM::post('action', ''); switch ($action) { case 'account': $fields = ['name', 'email', 'phone', 'country', 'currency', 'username']; foreach ($fields as $f) { $publisher->{$f} = RM::post($f); } $publisher->save(); $view->set('message', 'Account Info updated!!'); break; case 'password': $old = RM::post('password'); $new = RM::post('npassword'); $view->set($publisher->updatePassword($old, $new)); break; case 'campaign': $publisher->getMeta()['campaign'] = ['model' => RM::post('model'), 'rate' => $this->currency(RM::post('rate'))]; $publisher->save(); $view->set('message', 'Payout Info Updated!!'); break; case 'trackingDomain': $tdomain = (array) RM::post('tdomain', ''); if ($tdomain && ArrayMethods::inArray($this->org->tdomains, $tdomain)) { $publisher->getMeta()['tdomain'] = $tdomain; $publisher->save(); $view->set('message', 'Added Tracking Domain for publisher'); } else { $view->set('message', 'Invalid Request!!'); } case 'commadd': case 'commedit': $comm_id = RM::post('comm_id'); if ($comm_id) { $comm = Commission::first(['_id' => $comm_id, 'user_id' => $publisher->_id]); } else { $comm = new Commission(['user_id' => $publisher->_id]); } $comm->model = RM::post('model'); $comm->description = RM::post('description'); $comm->rate = $this->currency(RM::post('rate')); $comm->coverage = RM::post('coverage', ['ALL']); $comm->save(); $view->set('message', "Multi Country Payout Saved!!"); break; } } if (RM::type() === 'DELETE') { $action = RM::get("action"); switch ($action) { case 'payoutdel': unset($publisher->getMeta()['campaign']); $publisher->save(); $view->set('message', 'Payout Deleted!!'); break; case 'commDel': $comm = Commission::first(['_id' => RM::get("comm_id"), 'user_id' => $publisher->_id]); if ($comm) { $comm->delete(); $view->set('message', 'Payout Deleted!!'); } else { $view->set('message', 'Invalid Request!!'); } break; case 'afields': $meta = $publisher->meta; $publisher->removeFields(); unset($meta['afields']); Db::updateRaw('users', ['_id' => Db::convertType($publisher->_id, 'id')], ['$set' => ['meta' => $meta]]); $view->set('message', 'Data Removed!!'); break; case 'defaultDomain': unset($publisher->getMeta()['tdomain']); $publisher->save(); $view->set('message', 'Removed tracking domain!!'); break; } } $afields = Meta::search('customField', $this->org); $view->set('afields', $afields)->set("publisher", $publisher)->set("commissions", Commission::all(["user_id = ?" => $publisher->id]))->set("start", strftime("%Y-%m-%d", strtotime('-7 day')))->set("end", strftime("%Y-%m-%d", strtotime('now')))->set("d", Performance::total(['start' => $start ?? $publisher->created->format('Y-m-d'), 'end' => $end ?? date('Y-m-d')], $publisher)); }
public static function toArray($object) { $arr = []; $obj = (array) $object; foreach ($obj as $key => $value) { if (Services\Db::isType($value, 'document')) { $arr[$key] = self::toArray($value); } else { $arr[$key] = $value; } } return $arr; }
/** * @before _secure * @after _displayData */ public function platforms($id = null) { $this->seo(["title" => "Platform wise click stats"]); $view = $this->getActionView(); $org = $this->org; $clickCol = Registry::get("MongoDB")->clicks; // find the platforms $platforms = \Platform::all(['user_id' => ['$in' => $org->users('advertisers')]], ['_id', 'url']); if (count($platforms) === 0) { return $view->set(['platforms' => [], 'publishers' => []]); } $key = array_rand($platforms); $url = RM::get('link', $platforms[$key]->url); // find ads having this url $ads = \Ad::all(['org_id' => $org->_id], ['_id', 'url']); $in = Utils::mongoObjectId(array_keys($ads)); $matched = []; foreach ($ads as $a) { $regex = preg_quote($url, '.'); if (preg_match('#^' . $regex . '#', $a->url)) { $matched[] = Utils::mongoObjectId($a->_id); } } if (count($matched) === 0) { $query['adid'] = ['$in' => $in]; } else { $query['adid'] = ['$in' => $matched]; } $query['is_bot'] = false; $query['created'] = Db::dateQuery($this->start, $this->end); $records = $clickCol->aggregate([['$match' => $query], ['$projection' => ['_id' => 1, 'pid' => 1]], ['$group' => ['_id' => '$pid', 'count' => ['$sum' => 1]]], ['$sort' => ['count' => -1]]]); $result = []; $publishers = []; foreach ($records as $r) { $obj = (object) $r; $id = Utils::getMongoID($obj->_id); $user = User::first(['_id' => $id], ['_id', 'name']); $result[$id] = (object) ['_id' => $user->_id, 'name' => $user->name, 'clicks' => $obj->count]; } $view->set(['platforms' => $platforms, 'link' => $url, 'publishers' => $result]); }
public static function hourly() { $halfHrAgo = date('Y-m-d H:i:s', time() - 1800); $now = date('Y-m-d H:i:s'); $created = ['$gte' => Db::time($halfHrAgo), '$lte' => Db::time($now)]; self::deleteAll(['created' => $created, 'is_bot' => true]); }
public function __construct($options = array()) { parent::__construct($options); Services\Db::connect(); // schedule: load user from session Events::add("framework.router.beforehooks.before", function ($name, $parameters) { $session = Registry::get("session"); $controller = Registry::get("controller"); $user = $session->get("user"); if ($user) { $controller->user = \User::first(array("id = ?" => $user)); } }); // schedule: save user to session Events::add("framework.router.afterhooks.after", function ($name, $parameters) { $session = Registry::get("session"); $controller = Registry::get("controller"); if ($controller->user) { $session->set("user", $controller->user->id); } // Set Flash Message to the Action View $flashMessage = $session->get('$flashMessage', null); if ($flashMessage) { $session->erase('$flashMessage'); $controller->actionView->set('message', $flashMessage); } }); }
/** * Gets the Rate based on the type of record i.e 'publisher', or 'advertiser' * @param array $commissions Array of Commissions to search for ad_id * @param String $type Advertiser | Publisher * @return array */ public static function campaignRate($adid, &$commissions = [], $country = null, $extra = []) { $commFetched = $extra['commFetched'] ?? false; if ($commFetched) { $comm = $commissions; } else { $comm = self::find($commissions, $adid); } $info = ['campaign' => 'cpc', 'rate' => 0, 'revenue' => 0, 'type' => $extra['type']]; if (!is_array($comm)) { return $info; } $commission = array_key_exists($country, $comm) ? $comm[$country] : @$comm['ALL']; // because commission might not exists if country is null if (!is_object($commission)) { return $info; } $query = ['adid' => $adid, 'created' => Db::dateQuery($extra['start'], $extra['end'])]; switch ($extra['type']) { case 'advertiser': $info['revenue'] = (double) $commission->revenue; break; case 'publisher': $info['rate'] = self::getPubRate($commission, $extra); $query['pid'] = $extra['publisher']->_id ?? null; break; case 'both': $info['revenue'] = (double) $commission->revenue; $info['rate'] = self::getPubRate($commission, $extra); if (isset($extra['publisher'])) { $query['pid'] = $extra['publisher']->_id; } break; } switch (strtolower($commission->model)) { case 'cpa': case 'cpi': $count = \Conversion::count($query); $info['conversions'] = $count; break; case 'cpm': $info['impressions'] = \Impression::getStats($query); break; } $info['campaign'] = strtolower($commission->model); return $info; }
public function delete() { $deleteList = ['Link', 'Platform', 'Ad', 'Performance', 'Invoice', 'Adaccess']; $query = ['user_id' => $this->_id]; $delete = false; switch ($this->_type) { case 'publisher': $clicks = Click::count(['pid' => $this->_id]); if ($clicks !== 0) { return false; } $delete = true; $this->removeFields(); break; case 'advertiser': $ads = Ad::all(['user_id' => $this->_id], ['_id']); if (count($ads) === 0) { $delete = true; } else { $in = array_keys($ads); $in = Db::convertType($in, 'id'); $clickCount = Click::count(['adid' => ['$in' => $in]]); if ($clickCount === 0) { Commission::deleteAll(['ad_id' => ['$in' => $in]]); $delete = true; } } break; } if ($delete) { parent::delete(); foreach ($deleteList as $table) { $table::deleteAll($query); } } return $delete; }
public static function customFields($user, $org) { $afields = \Meta::search('customField', $org); if (count($afields) > 0) { $meta = $user->meta ?? []; $extraFields = []; foreach ($afields as $value) { $key = $value['name']; $type = $value['type']; $message = $value['label'] . " is required!!"; switch ($type) { case 'file': $v = Utils::media($key, 'upload', ['extension' => 'jpe?g|gif|bmp|png|tif|pdf']); if (!$v) { $message = "Please Upload a valid image or pdf file"; } break; case 'text': $v = RequestMethods::post($key); break; case 'date': $d = RequestMethods::post($key, date('Y-m-d')); $v = Db::convertType($d, 'date'); break; default: $v = ''; break; } if (!$v && $value['required']) { return ["message" => $message, "success" => false]; } $extraFields[$key] = $v; } $meta['afields'] = $extraFields; $user->meta = $meta; } $user->save(); return ["success" => true]; }
protected function _login($org, $view) { $session = Registry::get("session"); $email = strtolower(trim(RM::post("email"))); $pass = RM::post("password"); $user = \User::first(["org_id = ?" => $org->_id, "email = ?" => $email]); if (!$user) { return $view->set('message', 'Invalid credentials'); } else { if (sha1($pass) != $user->password) { return $view->set('message', 'Invalid credentials'); } else { if (!$user->live) { return $view->set('message', 'User account deactivated!!'); } } } $session->erase('Auth\\Login:$token'); // erase login token $user->login = \Shared\Services\Db::time(); $user->save(); $this->_loginRedirect($user, $org); }