<?php
 class vB_Library_ReferUser extends vB_Library { protected $assertor = null; protected function __construct() { parent::__construct(); $this->assertor = vB::getDbAssertor(); } public function getReferralCode() { $currentUserId = vB::getCurrentSession()->get('userid'); $limit = 10; while(true AND $limit--) { $referralCode = (new vB_Utility_Random())->hex(40); $check = $this->assertor->getRow('vBForum:userreferral', ['referralcode' => $referralCode]); if (!$check) { break; } } $values = [ 'userid' => $currentUserId, 'dateline' => vB::getRequest()->getTimeNow(), 'referralcode' => $referralCode, ]; $this->assertor->insert('vBForum:userreferral', $values); return $referralCode; } public function validateReferralCode($referralCode) { $result = $this->validateReferralCodeInternal($referralCode); if ($result) { return $result['referralcode']; } return false; } function getUseridFromReferralCode($referralCode) { $result = $this->validateReferralCodeInternal($referralCode); if ($result) { return $result['userid']; } return false; } protected function validateReferralCodeInternal($referralCode) { if (!is_string($referralCode)) { return false; } $cleaner = vB::getCleaner(); $referralCode = $cleaner->clean($referralCode, vB_Cleaner::TYPE_STR); if (strlen($referralCode) == 40) { $check = $this->assertor->getRow('vBForum:userreferral', ['referralcode' => $referralCode]); if ($check) { $vboptions = vB::getDatastore()->getValue('options'); $now = vB::getRequest()->getTimeNow(); $validForSeconds = 86400 * $vboptions['user_referral_expire_days']; $validUntil = $check['dateline'] + $validForSeconds; if ($now <= $validUntil) { $referringUserContext = vB::getUserContext($check['userid']); if ($referringUserContext->hasPermission('genericpermissions2', 'canreferusers')) { return [ 'referralcode' => $referralCode, 'userid' => $check['userid'], ]; } } } } return false; } public function deleteExpiredReferralCodes() { $vboptions = vB::getDatastore()->getValue('options'); $now = vB::getRequest()->getTimeNow(); $cutoff = $now - (86400 * $vboptions['user_referral_expire_days']); $conditions = [ ['field' => 'dateline', 'value' => $cutoff, vB_dB_Query::OPERATOR_KEY => vB_dB_Query::OPERATOR_LT], ]; $this->assertor->delete('vBForum:userreferral', $conditions); } public function fetchReferrers($startdate, $enddate) { $keys = ['hour', 'minute', 'second', 'month', 'day', 'year']; $inputs = ['start' => $startdate, 'end' => $enddate]; foreach ($inputs AS $k => $date) { $clean = []; foreach ($keys AS $key) { $clean[$key] = ($date[$key] ?? 0); } $inputs[$k] = $clean; } $startdate = $inputs['start']; $enddate = $inputs['end']; $start = 0; if (!empty($startdate['month'])) { $start = vbmktime_array($startdate); } $end = 0; if (!empty($enddate['month'])) { $end = vbmktime_array($enddate); } $users = $this->assertor->getRows('userReferrers', [ 'startdate' => $start, 'enddate' => $end, ]); return $users; } } 