Example #1
0
 public function execute()
 {
     $response = BlogApiService::instance()->getBlogPosts()->getResponse();
     if (!empty($response)) {
         Application::instance()->getCacheDriver()->save('recentblog', $response);
     }
 }
 /**
  * @Route ("/impersonate")
  * @HttpMethod ({"GET"})
  *
  * @param array $params
  * @param ViewModel $model
  * @throws Exception
  * @return string
  */
 public function impersonate(array $params, ViewModel $model)
 {
     $app = Application::instance();
     if (!Config::$a['allowImpersonation']) {
         throw new Exception('Impersonating is not allowed');
     }
     $userId = isset($params['userId']) && !empty($params['userId']) ? $params['userId'] : '';
     $username = isset($params['username']) && !empty($params['username']) ? $params['username'] : '';
     if (empty($userId) && empty($username)) {
         throw new Exception('[username] or [userId] required');
     }
     $authService = AuthenticationService::instance();
     $userService = UserService::instance();
     if (!empty($userId)) {
         $user = $userService->getUserById($userId);
     } else {
         if (!empty($username)) {
             $user = $userService->getUserByUsername($username);
         }
     }
     if (empty($user)) {
         throw new Exception('User not found. Try a different userId or username');
     }
     $credentials = $authService->getUserCredentials($user, 'impersonating');
     Session::start(Session::START_NOCOOKIE);
     Session::updateCredentials($credentials);
     ChatIntegrationService::instance()->setChatSession($credentials, Session::getSessionId());
     return 'redirect: /';
 }
 public function execute(AuthenticationCredentials $authCreds)
 {
     $authService = AuthenticationService::instance();
     // Make sure the creds are valid
     if (!$authCreds->isValid()) {
         Application::instance()->getLogger()->error(sprintf('Error validating auth credentials %s', var_export($authCreds, true)));
         throw new Exception('Invalid auth credentials');
     }
     // Account merge
     if (Session::set('accountMerge') === '1') {
         // Must be logged in to do a merge
         if (!Session::hasRole(UserRole::USER)) {
             throw new Exception('Authentication required for account merge');
         }
         $authService->handleAuthAndMerge($authCreds);
         return 'redirect: /profile/authentication';
     }
     // Follow url *notice the set, returning and clearing the var
     $follow = Session::set('follow');
     // If the user profile doesnt exist, go to the register page
     if (!$authService->getUserAuthProfileExists($authCreds)) {
         Session::set('authSession', $authCreds);
         $url = '/register?code=' . urlencode($authCreds->getAuthCode());
         if (!empty($follow)) {
             $url .= '&follow=' . urlencode($follow);
         }
         return 'redirect: ' . $url;
     }
     // User exists, handle the auth
     $authService->handleAuthCredentials($authCreds);
     if (!empty($follow) && substr($follow, 0, 1) == '/') {
         return 'redirect: ' . $follow;
     }
     return 'redirect: /profile';
 }
Example #4
0
 public function execute()
 {
     $app = Application::instance();
     $cacheDriver = $app->getCacheDriver();
     $twitterOAuthConf = Config::$a['oauth']['providers']['twitter'];
     $tmhOAuth = new \tmhOAuth(array('consumer_key' => $twitterOAuthConf['clientId'], 'consumer_secret' => $twitterOAuthConf['clientSecret'], 'token' => $twitterOAuthConf['token'], 'secret' => $twitterOAuthConf['secret'], 'curl_connecttimeout' => Config::$a['curl']['connecttimeout'], 'curl_timeout' => Config::$a['curl']['timeout'], 'curl_ssl_verifypeer' => Config::$a['curl']['verifypeer']));
     /** @noinspection PhpVoidFunctionResultUsedInspection */
     $code = $tmhOAuth->user_request(array('url' => $tmhOAuth->url('1.1/statuses/user_timeline.json'), 'params' => array('screen_name' => Config::$a['twitter']['user'], 'count' => 3, 'trim_user' => true)));
     if ($code == 200) {
         $result = json_decode($tmhOAuth->response['response'], true);
         $tweets = array();
         foreach ($result as $tweet) {
             $html = $tweet['text'];
             if (isset($tweet['entities']['user_mentions'])) {
                 foreach ($tweet['entities']['user_mentions'] as $ment) {
                     $l = '<a href="http://twitter.com/' . $ment['screen_name'] . '">' . $ment['name'] . '</a>';
                     $html = str_replace('@' . $ment['screen_name'], $l, $html);
                 }
             }
             if (isset($tweet['entities']) && isset($tweet['entities']['urls'])) {
                 foreach ($tweet['entities']['urls'] as $url) {
                     $l = '<a href="' . $url['url'] . '" rev="' . $url['expanded_url'] . '">' . $url['display_url'] . '</a>';
                     $html = str_replace($url['url'], $l, $html);
                 }
             }
             $tweet['user']['screen_name'] = Config::$a['twitter']['user'];
             $tweet['html'] = $html;
             $tweets[] = $tweet;
         }
         $cacheDriver->save('twitter', $tweets);
     }
 }
 public static function loadClass(ReflectionClass $refl, Reader $reader)
 {
     $router = Application::instance()->getRouter();
     $annotation = $reader->getClassAnnotation($refl, 'Destiny\\Common\\Annotation\\Controller');
     if (empty($annotation)) {
         return;
     }
     $methods = $refl->getMethods(ReflectionMethod::IS_PUBLIC);
     foreach ($methods as $method) {
         // Get all the route annotations
         $routes = array();
         $annotations = $reader->getMethodAnnotations($method);
         for ($i = 0; $i < count($annotations); ++$i) {
             if ($annotations[$i] instanceof \Destiny\Common\Annotation\Route) {
                 $routes[] = $annotations[$i];
             }
         }
         // No routes, continue
         if (count($routes) <= 0) {
             continue;
         }
         // We have 1 or many routes, add to the router
         $httpMethod = $reader->getMethodAnnotation($method, 'Destiny\\Common\\Annotation\\HttpMethod');
         $secure = $reader->getMethodAnnotation($method, 'Destiny\\Common\\Annotation\\Secure');
         $feature = $reader->getMethodAnnotation($method, 'Destiny\\Common\\Annotation\\Feature');
         for ($i = 0; $i < count($routes); ++$i) {
             $router->addRoute(new Route(array('path' => $routes[$i]->path, 'classMethod' => $method->name, 'class' => $refl->name, 'httpMethod' => $httpMethod ? $httpMethod->allow : null, 'secure' => $secure ? $secure->roles : null, 'feature' => $feature ? $feature->features : null)));
         }
     }
 }
Example #6
0
 public function execute()
 {
     $app = Application::instance();
     $response = LastFMApiService::instance()->getLastFMTracks()->getResponse();
     if (!empty($response)) {
         $app->getCacheDriver()->save('recenttracks', $response);
     }
 }
Example #7
0
 public function execute(LoggerInterface $log)
 {
     $cacheDriver = Application::instance()->getCacheDriver();
     $response = TwitchApiService::instance()->getStreamInfo()->getResponse();
     if (!empty($response)) {
         $cacheDriver->save('streaminfo', $response);
     }
 }
Example #8
0
 public function execute()
 {
     $app = Application::instance();
     $response = YoutubeApiService::instance()->getYoutubePlaylist()->getResponse();
     if (!empty($response)) {
         $app->getCacheDriver()->save('youtubeplaylist', $response);
     }
 }
Example #9
0
 public function execute(LoggerInterface $log)
 {
     $app = Application::instance();
     $response = TwitchApiService::instance()->getPastBroadcasts()->getResponse();
     if (!empty($response)) {
         $app->getCacheDriver()->save('pastbroadcasts', $response);
     }
 }
Example #10
0
 /**
  * @Route ("/broadcasts.json")
  */
 public function broadcasts()
 {
     $app = Application::instance();
     $broadcasts = $app->getCacheDriver()->fetch('pastbroadcasts');
     $response = new Response(Http::STATUS_OK, json_encode($broadcasts));
     $response->addHeader(Http::HEADER_CACHE_CONTROL, 'private');
     $response->addHeader(Http::HEADER_PRAGMA, 'public');
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     return $response;
 }
Example #11
0
 /**
  * Get the [userId, createdDate, expireDate] for the associated token
  *
  * @param string $token
  * @param string $tokenType
  * @return array
  */
 public function getRememberMe($token, $tokenType)
 {
     $conn = Application::instance()->getConnection();
     $stmt = $conn->prepare('
         SELECT u.userId,r.createdDate,r.expireDate FROM dfl_users_rememberme AS r
         INNER JOIN dfl_users AS u ON (u.userId = r.userId)
         WHERE r.token = :token AND r.tokenType = :tokenType AND r.expireDate > NOW() 
         LIMIT 0,1
     ');
     $stmt->bindValue('token', $token, \PDO::PARAM_STR);
     $stmt->bindValue('tokenType', $tokenType, \PDO::PARAM_STR);
     $stmt->execute();
     return $stmt->fetch();
 }
Example #12
0
 /**
  * @Route ("/admin/cron")
  * @Secure ({"ADMIN"})
  * @Transactional
  *
  * @param array $params         
  * @throws Exception
  */
 public function adminCron(array $params)
 {
     if (!isset($params['id']) || empty($params['id'])) {
         throw new Exception('Action id required.');
     }
     set_time_limit(180);
     $log = Application::instance()->getLogger();
     $response = array();
     $scheduler = new Scheduler(Config::$a['scheduler']);
     $scheduler->setLogger($log);
     $scheduler->loadSchedule();
     $scheduler->executeTaskByName($params['id']);
     $response['message'] = sprintf('Execute %s', $params['id']);
     $response = new Response(Http::STATUS_OK, json_encode($response));
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     return $response;
 }
Example #13
0
 private function sendResubscribeBroadcast(array $subscription)
 {
     $log = Application::instance()->getLogger();
     $userService = UserService::instance();
     $user = $userService->getUserById($subscription['userId']);
     if (!empty($user)) {
         try {
             // the subscription endDate has not been updated with the new subscription time
             $months = max(1, Date::getDateTime($subscription['createdDate'])->diff(Date::getDateTime($subscription['endDate']))->m);
             $months = $months > 1 ? $months . " months" : $months . " month";
             $chatIntegrationService = ChatIntegrationService::instance();
             $chatIntegrationService->sendBroadcast(sprintf("%s has resubscribed! Active for %s", $user['username'], $months));
         } catch (\Exception $e) {
             $log->critical('Could not send resubscribe broadcast', $subscription);
         }
     }
 }
Example #14
0
 /**
  * Return a cached list of countries
  *
  * @return array
  */
 public static function getCountries()
 {
     if (self::$countries == null) {
         $cacheDriver = Application::instance()->getCacheDriver();
         $countries = $cacheDriver->fetch('geodata');
         if (empty($countries)) {
             $countries = json_decode(file_get_contents(Config::$a['geodata']['json']), true);
             $cacheDriver->save('geodata', $countries);
         }
         if (is_array($countries)) {
             self::$countries = $countries;
         }
     }
     if (empty(self::$codeIndex)) {
         self::buildIndex();
     }
     return self::$countries;
 }
Example #15
0
 /**
  * @return ApiConsumer
  */
 public function getStreamInfo(array $options = array())
 {
     return new CurlBrowser(array_merge(array('url' => new String('https://api.twitch.tv/kraken/streams/{user}/', array('user' => Config::$a['twitch']['user'])), 'contentType' => MimeType::JSON, 'onfetch' => function ($json) {
         if (empty($json) || isset($json['status']) && $json['status'] == 503) {
             throw new Exception('Twitch api down');
         }
         // Last broadcast if the stream is offline
         // Called via static method, because we are in a closure
         $channel = TwitchApiService::instance()->getChannel()->getResponse();
         if (empty($channel) || !is_array($channel)) {
             throw new Exception(sprintf('Invalid stream channel response %s', $channel));
         }
         if (is_object($json) && isset($json['stream']) && $json['stream'] != null) {
             $json['stream']['channel']['updated_at'] = Date::getDateTime($json['stream']['channel']['updated_at'])->format(Date::FORMAT);
         }
         $json['lastbroadcast'] = Date::getDateTime($channel['updated_at'])->format(Date::FORMAT);
         $json['video_banner'] = $channel['video_banner'];
         $json['previousbroadcast'] = null;
         $json['status'] = $channel['status'];
         $json['game'] = $channel['game'];
         // Previous broadcast
         $app = Application::instance();
         $broadcasts = $app->getCacheDriver()->fetch('pastbroadcasts');
         if (!empty($broadcasts) && !empty($broadcasts['videos'])) {
             $broadcast = array();
             $broadcast['length'] = $broadcasts['videos'][0]['length'];
             $broadcast['preview'] = $broadcasts['videos'][0]['preview'];
             $broadcast['url'] = $broadcasts['videos'][0]['url'];
             $broadcast['recorded_at'] = $broadcasts['videos'][0]['recorded_at'];
             $broadcast['views'] = $broadcasts['videos'][0]['views'];
             $json['previousbroadcast'] = $broadcast;
             // If there are previous broadcasts, base the last broadcast time on it, twitch seems to update the channel at random
             $json['lastbroadcast'] = Date::getDateTime($broadcast['recorded_at'])->add(new \DateInterval('PT' . $broadcast['length'] . 'S'))->format(Date::FORMAT);
         }
         // Just some clean up
         if (isset($json['_links'])) {
             unset($json['_links']);
         }
         return $json;
     }), $options));
 }
 /**
  * Removes all of the bans and notifies the chat to refresh the bans
  * so it actually notices the bans being removed
  * @throws Exception
  */
 public function purgeBans()
 {
     $conn = Application::instance()->getConnection();
     $redis = Application::instance()->getRedis();
     $stmt = $conn->prepare("\r\n            TRUNCATE TABLE bans\r\n        ");
     $stmt->execute();
     return $redis->publish(sprintf('refreshbans-%s', Config::$a['redis']['database']), "doesnotmatter");
 }
Example #17
0
 public function __construct(array $args = null)
 {
     if (isset(Config::$a['curl'])) {
         Options::setOptions($this, Config::$a['curl']);
     }
     Options::setOptions($this, $args);
     if (empty($this->logger)) {
         $this->setLogger(Application::instance()->getLogger());
     }
     if (!empty($this->url)) {
         $this->response = $this->browse();
     }
 }
Example #18
0
 /**
  * Check if a user has a active subscription
  *
  * @param number $gifter userId
  * @param number $giftee userId
  * @return boolean
  */
 public function getCanUserReceiveGift($gifter, $giftee)
 {
     if ($gifter == $giftee) {
         return false;
     }
     // Make sure the the giftee accepts gifts
     $conn = Application::instance()->getConnection();
     $stmt = $conn->prepare('SELECT userId FROM dfl_users WHERE userId = :userId AND allowGifting = 1');
     $stmt->bindValue('userId', $giftee, \PDO::PARAM_INT);
     $stmt->execute();
     if ($stmt->rowCount() <= 0) {
         return false;
     }
     // make sure the giftee doesnt have an active subscription
     $subscription = $this->getUserActiveSubscription($giftee);
     if (!empty($subscription)) {
         return false;
     }
     return true;
 }
Example #19
0
 /**
  * @Route ("/bigscreen")
  *
  * @param array $params
  * @param ViewModel $model
  * @return string
  */
 public function bigscreen(array $params, ViewModel $model)
 {
     $model->streamInfo = Application::instance()->getCacheDriver()->fetch('streaminfo');
     return 'bigscreen';
 }
 /**
  * @param array $data
  * @throws Exception
  */
 public function publishPrivateMessages(array $data)
 {
     $redis = Application::instance()->getRedis();
     $chunked = array_chunk($data, 100);
     foreach ($chunked as $chunk) {
         $redis->multi();
         foreach ($chunk as $msgdata) {
             $this->publishPrivateMessage($msgdata);
         }
         $redis->exec();
     }
 }
Example #21
0
 public function getUserIdFromMinecraftName($name)
 {
     $conn = Application::instance()->getConnection();
     $stmt = $conn->prepare("\r\n      SELECT userId\r\n      FROM dfl_users\r\n      WHERE minecraftname = :name\r\n      LIMIT 1\r\n    ");
     $stmt->bindValue('name', $name, \PDO::PARAM_STR);
     $stmt->execute();
     return $stmt->fetchColumn();
 }
Example #22
0
 public function getActiveTwitchSubscriptions()
 {
     $conn = Application::instance()->getConnection();
     $stmt = $conn->prepare("\r\n      SELECT ua.authId\r\n      FROM\r\n        dfl_users AS u,\r\n        dfl_users_auth AS ua\r\n      WHERE\r\n        u.userId             = ua.userId AND\r\n        u.istwitchsubscriber = 1\r\n    ");
     $stmt->execute();
     $ret = array();
     while ($row = $stmt->fetch()) {
         $ret[] = $row['authId'];
     }
     return $ret;
 }
Example #23
0
 /**
  * @Route ("/admin/chart/{type}")
  * @Secure ({"ADMIN"})
  *
  * @param array $params
  * @return Response
  */
 public function chartData(array $params)
 {
     FilterParams::required($params, 'type');
     $statisticsService = StatisticsService::instance();
     $cacheDriver = Application::instance()->getCacheDriver();
     $data = array();
     switch (strtoupper($params['type'])) {
         case 'REVENUELASTXDAYS':
             FilterParams::required($params, 'days');
             $key = 'RevenueLastXDays ' . intval($params['days']);
             if (!$cacheDriver->contains($key)) {
                 $data = $statisticsService->getRevenueLastXDays(intval($params['days']));
                 $cacheDriver->save($key, $data, 30);
             } else {
                 $data = $cacheDriver->fetch($key);
             }
             break;
         case 'REVENUELASTXMONTHS':
             FilterParams::required($params, 'months');
             $key = 'RevenueLastXMonths ' . intval($params['months']);
             if (!$cacheDriver->contains($key)) {
                 $data = $statisticsService->getRevenueLastXMonths(intval($params['months']));
                 $cacheDriver->save($key, $data, 30);
             } else {
                 $data = $cacheDriver->fetch($key);
             }
             break;
         case 'REVENUELASTXYEARS':
             FilterParams::required($params, 'years');
             $key = 'RevenueLastXYears ' . intval($params['years']);
             if (!$cacheDriver->contains($key)) {
                 $data = $statisticsService->getRevenueLastXYears(intval($params['years']));
                 $cacheDriver->save($key, $data, 30);
             } else {
                 $data = $cacheDriver->fetch($key);
             }
             break;
         case 'NEWSUBSCRIBERSLASTXDAYS':
             FilterParams::required($params, 'days');
             $key = 'NewSubscribersLastXDays ' . intval($params['days']);
             if (!$cacheDriver->contains($key)) {
                 $data = $statisticsService->getNewSubscribersLastXDays(intval($params['days']));
                 $cacheDriver->save($key, $data, 30);
             } else {
                 $data = $cacheDriver->fetch($key);
             }
             break;
         case 'NEWSUBSCRIBERSLASTXMONTHS':
             FilterParams::required($params, 'months');
             $key = 'NewSubscribersLastXMonths ' . intval($params['months']);
             if (!$cacheDriver->contains($key)) {
                 $data = $statisticsService->getNewSubscribersLastXMonths(intval($params['months']));
                 $cacheDriver->save($key, $data, 30);
             } else {
                 $data = $cacheDriver->fetch($key);
             }
             break;
         case 'NEWSUBSCRIBERSLASTXYEARS':
             FilterParams::required($params, 'years');
             $key = 'NewSubscribersLastXYears ' . intval($params['years']);
             if (!$cacheDriver->contains($key)) {
                 $data = $statisticsService->getNewSubscribersLastXYears(intval($params['years']));
                 $cacheDriver->save($key, $data, 30);
             } else {
                 $data = $cacheDriver->fetch($key);
             }
             break;
         case 'NEWTIEREDSUBSCRIBERSLASTXDAYS':
             FilterParams::required($params, 'days');
             $key = 'NewTieredSubscribersLastXDays ' . intval($params['days']);
             if (!$cacheDriver->contains($key)) {
                 $data = $statisticsService->getNewTieredSubscribersLastXDays(intval($params['days']));
                 $cacheDriver->save($key, $data, 30);
             } else {
                 $data = $cacheDriver->fetch($key);
             }
             break;
     }
     $response = new Response(Http::STATUS_OK, json_encode($data));
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     return $response;
 }
 /**
  * @param int $userId
  * @return bool
  */
 protected function isUserFlaggedForUpdate($userId)
 {
     $cache = Application::instance()->getCacheDriver();
     $lastUpdated = $cache->fetch(sprintf('refreshusersession-%s', $userId));
     return !empty($lastUpdated);
 }
Example #25
0
 /**
  * @Route ("/profile/authtoken/create")
  * @HttpMethod ({"POST"})
  * @Secure ({"USER"})
  *
  * @param array $params
  * @param Request $request
  * @return string
  * @throws \Exception
  */
 public function profileAuthTokenCreate(array $params, Request $request)
 {
     if (!isset($params['g-recaptcha-response']) || empty($params['g-recaptcha-response'])) {
         throw new Exception('You must solve the recaptcha.');
     }
     $googleRecaptchaHandler = new GoogleRecaptchaHandler();
     $googleRecaptchaHandler->resolve(Config::$a['g-recaptcha']['secret'], $params['g-recaptcha-response'], $request->ipAddress());
     $apiAuthService = ApiAuthenticationService::instance();
     $userId = Session::getCredentials()->getUserId();
     $tokens = $apiAuthService->getAuthTokensByUserId($userId);
     if (count($tokens) >= 5) {
         throw new Exception('You have reached the maximum [5] allowed login keys.');
     }
     $log = Application::instance()->getLogger();
     $conn = Application::instance()->getConnection();
     $conn->beginTransaction();
     try {
         $token = $apiAuthService->createAuthToken($userId);
         $apiAuthService->addAuthToken($userId, $token);
         $conn->commit();
     } catch (\Exception $e) {
         $log->critical("Error creating auth token");
         $conn->rollBack();
         throw $e;
     }
     Session::set('modelSuccess', 'Auth token created!');
     return 'redirect: /profile/authentication';
 }
Example #26
0
 public function getNewSubscribersLastXYears($years)
 {
     $conn = Application::instance()->getConnection();
     $stmt = $conn->prepare('
         SELECT COUNT(*) `total`, DATE_FORMAT(createdDate, \'%Y-01-01\') `date` FROM `dfl_users_subscriptions` s
         WHERE s.createdDate BETWEEN CURDATE()-INTERVAL :years YEAR AND CURDATE() + INTERVAL 1 DAY
         AND s.status IN (\'Expired\',\'Active\',\'Cancelled\')
         GROUP BY DATE_FORMAT(s.createdDate, \'%Y\')
         ORDER BY s.createdDate ASC
     ');
     $stmt->bindValue('years', $years, \PDO::PARAM_INT);
     $stmt->execute();
     return $stmt->fetchAll();
 }
 /**
  * @Route ("/subscription/process")
  * @Secure ({"USER"})
  *
  * We were redirected here from PayPal after the buyer approved/cancelled the payment
  *
  * @param array $params
  * @return string
  * @throws Exception
  * @throws \Destiny\Common\Utils\FilterParamsException
  * TODO clean this method up
  */
 public function subscriptionProcess(array $params)
 {
     FilterParams::required($params, 'subscriptionId');
     FilterParams::required($params, 'token');
     FilterParams::declared($params, 'success');
     $userId = Session::getCredentials()->getUserId();
     $userService = UserService::instance();
     $ordersService = OrdersService::instance();
     $subscriptionsService = SubscriptionsService::instance();
     $payPalApiService = PayPalApiService::instance();
     $chatIntegrationService = ChatIntegrationService::instance();
     $authenticationService = AuthenticationService::instance();
     $log = Application::instance()->getLogger();
     $subscription = $subscriptionsService->getSubscriptionById($params['subscriptionId']);
     if (empty($subscription) || strcasecmp($subscription['status'], SubscriptionStatus::_NEW) !== 0) {
         throw new Exception('Invalid subscription record');
     }
     try {
         $subscriptionType = $subscriptionsService->getSubscriptionType($subscription['subscriptionType']);
         $user = $userService->getUserById($subscription['userId']);
         if ($user['userId'] != $userId && $subscription['gifter'] != $userId) {
             throw new Exception('Invalid subscription');
         }
         if ($params['success'] == '0' || $params['success'] == 'false' || $params['success'] === false) {
             throw new Exception('Order request failed');
         }
         if (!$payPalApiService->retrieveCheckoutInfo($params['token'])) {
             throw new Exception('Failed to retrieve express checkout details');
         }
         FilterParams::required($params, 'PayerID');
         // if the order status is an error, the payerID is not returned
         Session::set('subscriptionId');
         Session::set('token');
         // Create the payment profile
         // Payment date is 1 day before subscription rolls over.
         if ($subscription['recurring'] == 1 || $subscription['recurring'] == true) {
             $startPaymentDate = Date::getDateTime();
             $nextPaymentDate = Date::getDateTime();
             $nextPaymentDate->modify('+' . $subscriptionType['billingFrequency'] . ' ' . strtolower($subscriptionType['billingPeriod']));
             $nextPaymentDate->modify('-1 DAY');
             $reference = $subscription['userId'] . '-' . $subscription['subscriptionId'];
             $paymentProfileId = $payPalApiService->createRecurringPaymentProfile($params['token'], $reference, $user['username'], $nextPaymentDate, $subscriptionType);
             if (empty($paymentProfileId)) {
                 throw new Exception('Invalid recurring payment profileId returned from Paypal');
             }
             $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'paymentStatus' => PaymentStatus::ACTIVE, 'paymentProfileId' => $paymentProfileId, 'billingStartDate' => $startPaymentDate->format('Y-m-d H:i:s'), 'billingNextDate' => $nextPaymentDate->format('Y-m-d H:i:s')));
         }
         // Record the payments as well as check if any are not in the completed state
         // we put the subscription into "PENDING" state if a payment is found not completed
         $subscriptionStatus = SubscriptionStatus::ACTIVE;
         $DoECResponse = $payPalApiService->getECPaymentResponse($params['PayerID'], $params['token'], $subscriptionType['amount']);
         $payments = $payPalApiService->getResponsePayments($DoECResponse);
         foreach ($payments as $payment) {
             $payment['subscriptionId'] = $subscription['subscriptionId'];
             $payment['payerId'] = $params['PayerID'];
             $ordersService->addPayment($payment);
             // TODO: Payment provides no way of telling if the transaction with ALL payments was successful
             if ($payment['paymentStatus'] != PaymentStatus::COMPLETED) {
                 $subscriptionStatus = SubscriptionStatus::PENDING;
             }
         }
         // Update subscription status
         $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'status' => $subscriptionStatus));
     } catch (Exception $e) {
         $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'status' => SubscriptionStatus::ERROR));
         $log->critical($e->getMessage(), $subscription);
         return 'redirect: /subscription/' . urlencode($subscription['subscriptionId']) . '/error';
     }
     // only unban the user if the ban is non-permanent or the tier of the subscription is >= 2
     // we unban the user if no ban is found because it also unmutes
     $ban = $userService->getUserActiveBan($user['userId']);
     if (empty($ban) or (!empty($ban['endtimestamp']) or $subscriptionType['tier'] >= 2)) {
         $chatIntegrationService->sendUnban($user['userId']);
     }
     // Broadcast
     $randomEmote = Config::$a['chat']['customemotes'][array_rand(Config::$a['chat']['customemotes'])];
     if (!empty($subscription['gifter'])) {
         $gifter = $userService->getUserById($subscription['gifter']);
         $userName = $gifter['username'];
         $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! gifted by %s %s", $user['username'], $subscriptionType['tierLabel'], $gifter['username'], $randomEmote));
     } else {
         $userName = $user['username'];
         $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! %s", $user['username'], $subscriptionType['tierLabel'], $randomEmote));
     }
     $subMessage = Session::set('subMessage');
     if (!empty($subMessage)) {
         $chatIntegrationService->sendBroadcast(sprintf("%s: %s", $userName, $subMessage));
     }
     // Update the user
     $authenticationService->flagUserForUpdate($user['userId']);
     // Redirect to completion page
     return 'redirect: /subscription/' . urlencode($subscription['subscriptionId']) . '/complete';
 }
Example #28
0
 /**
  * @param int $limit
  * @param int $start
  * @return array
  * @throws \Doctrine\DBAL\DBALException
  */
 public function getLastBroadcasts($limit = 1, $start = 0)
 {
     $conn = Application::instance()->getConnection();
     $stmt = $conn->prepare('
         SELECT
             u.username,
             u2.username AS target,
             l.event,
             l.data,
             l.timestamp
         FROM
             chatlog AS l
             LEFT JOIN dfl_users AS u ON u.userId = l.userid
             LEFT JOIN dfl_users AS u2 ON u2.userId = l.targetuserid
         WHERE
             l.event IN(\'BROADCAST\')
         ORDER BY l.id DESC
         LIMIT :start,:limit
     ');
     $stmt->bindValue('start', $start, \PDO::PARAM_INT);
     $stmt->bindValue('limit', $limit, \PDO::PARAM_INT);
     $stmt->execute();
     return $stmt->fetchAll();
 }
Example #29
0
 /**
  * Remove a feature from a user
  *
  * @param int $userId
  * @param string $feature
  */
 public function removeAllUserFeatures($userId)
 {
     $conn = Application::instance()->getConnection();
     $conn->delete('dfl_users_features', array('userId' => $userId));
 }
 /**
  * @Route ("/subscription/process")
  * @Secure ({"USER"})
  * @Transactional
  *
  * We were redirected here from PayPal after the buyer approved/cancelled the payment
  *
  * @param array $params
  */
 public function subscriptionProcess(array $params, ViewModel $model)
 {
     FilterParams::isRequired($params, 'orderId');
     FilterParams::isRequired($params, 'token');
     FilterParams::isThere($params, 'success');
     $ordersService = OrdersService::instance();
     $userService = UserService::instance();
     $subscriptionsService = SubscriptionsService::instance();
     $payPalApiService = PayPalApiService::instance();
     $chatIntegrationService = ChatIntegrationService::instance();
     $authenticationService = AuthenticationService::instance();
     $userId = Session::getCredentials()->getUserId();
     // Get the order
     $order = $ordersService->getOrderByIdAndUserId($params['orderId'], $userId);
     if (empty($order) || strcasecmp($order['state'], OrderStatus::_NEW) !== 0) {
         throw new Exception('Invalid order record');
     }
     try {
         // If we got a failed response URL
         if ($params['success'] == '0' || $params['success'] == 'false' || $params['success'] === false) {
             throw new Exception('Order request failed');
         }
         // Get the subscription from the order
         $orderSubscription = $subscriptionsService->getSubscriptionByOrderId($order['orderId']);
         $subscriptionUser = $userService->getUserById($orderSubscription['userId']);
         // Make sure the subscription is valid
         if (empty($orderSubscription)) {
             throw new Exception('Invalid order subscription');
         }
         // Make sure the subscription is either owned or gifted by the user
         if ($subscriptionUser['userId'] != $userId && $orderSubscription['gifter'] != $userId) {
             throw new Exception('Invalid order subscription');
         }
         $subscriptionType = $subscriptionsService->getSubscriptionType($orderSubscription['subscriptionType']);
         $paymentProfile = $ordersService->getPaymentProfileByOrderId($order['orderId']);
         // Get the checkout info
         $ecResponse = $payPalApiService->retrieveCheckoutInfo($params['token']);
         if (!isset($ecResponse) || $ecResponse->Ack != 'Success') {
             throw new Exception('Failed to retrieve express checkout details');
         }
         // Moved this down here, as if the order status is error, the payerID is not returned
         FilterParams::isRequired($params, 'PayerID');
         // Point of no return - we only every want a person to get here if their order was a successful sequence
         Session::set('token');
         Session::set('orderId');
         // Recurring payment
         if (!empty($paymentProfile)) {
             $createRPProfileResponse = $payPalApiService->createRecurringPaymentProfile($paymentProfile, $params['token'], $subscriptionType);
             if (!isset($createRPProfileResponse) || $createRPProfileResponse->Ack != 'Success') {
                 throw new Exception('Failed to create recurring payment request');
             }
             $paymentProfileId = $createRPProfileResponse->CreateRecurringPaymentsProfileResponseDetails->ProfileID;
             $paymentStatus = $createRPProfileResponse->CreateRecurringPaymentsProfileResponseDetails->ProfileStatus;
             if (empty($paymentProfileId)) {
                 throw new Exception('Invalid recurring payment profileId returned from Paypal');
             }
             // Set the payment profile to active, and paymetProfileId
             $ordersService->updatePaymentProfileId($paymentProfile['profileId'], $paymentProfileId, $paymentStatus);
             // Update the payment profile
             $subscriptionsService->updateSubscriptionPaymentProfile($orderSubscription['subscriptionId'], $paymentProfile['profileId'], true);
         }
         // Complete the checkout
         $DoECResponse = $payPalApiService->getECPaymentResponse($params['PayerID'], $params['token'], $order);
         if (isset($DoECResponse) && $DoECResponse->Ack == 'Success') {
             if (isset($DoECResponse->DoExpressCheckoutPaymentResponseDetails->PaymentInfo)) {
                 $payPalApiService->recordECPayments($DoECResponse, $params['PayerID'], $order);
                 $ordersService->updateOrderState($order['orderId'], $order['state']);
             } else {
                 throw new Exception('No payments for express checkout order');
             }
         } else {
             throw new Exception($DoECResponse->Errors[0]->LongMessage);
         }
         // If the user already has a subscription and ONLY if this subscription was NOT a gift
         if (!isset($orderSubscription['gifter']) || empty($orderSubscription['gifter'])) {
             $activeSubscription = $subscriptionsService->getUserActiveSubscription($subscriptionUser['userId']);
             if (!empty($activeSubscription)) {
                 // Cancel any attached payment profiles
                 $ordersService = OrdersService::instance();
                 $paymentProfile = $ordersService->getPaymentProfileById($activeSubscription['paymentProfileId']);
                 if (!empty($paymentProfile)) {
                     $payPalApiService->cancelPaymentProfile($activeSubscription, $paymentProfile);
                     $subscriptionsService->updateSubscriptionRecurring($activeSubscription['subscriptionId'], false);
                 }
                 // Cancel the active subscription
                 $subscriptionsService->updateSubscriptionState($activeSubscription['subscriptionId'], SubscriptionStatus::CANCELLED);
             }
         }
         // Check if this is a gift, check that the giftee is still eligable
         if (!empty($orderSubscription['gifter']) && !$subscriptionsService->getCanUserReceiveGift($userId, $subscriptionUser['userId'])) {
             // Update the state to ERROR and log a critical error
             Application::instance()->getLogger()->critical('Duplicate subscription attempt, Gifter: %d GifteeId: %d, OrderId: %d', $userId, $subscriptionUser['userId'], $order['orderId']);
             $subscriptionsService->updateSubscriptionState($orderSubscription['subscriptionId'], SubscriptionStatus::ERROR);
         } else {
             // Unban the user if a ban is found
             $ban = $userService->getUserActiveBan($subscriptionUser['userId']);
             // only unban the user if the ban is non-permanent or the tier of the subscription is >= 2
             // we unban the user if no ban is found because it also unmutes
             if (empty($ban) or (!empty($ban['endtimestamp']) or $orderSubscription['subscriptionTier'] >= 2)) {
                 $chatIntegrationService->sendUnban($subscriptionUser['userId']);
             }
             // Activate the subscription (state)
             $subscriptionsService->updateSubscriptionState($orderSubscription['subscriptionId'], SubscriptionStatus::ACTIVE);
             // Flag the user for 'update'
             $authenticationService->flagUserForUpdate($subscriptionUser['userId']);
             // Random emote
             $randomEmote = Config::$a['chat']['customemotes'][array_rand(Config::$a['chat']['customemotes'])];
             // Broadcast
             if (!empty($orderSubscription['gifter'])) {
                 $gifter = $userService->getUserById($orderSubscription['gifter']);
                 $userName = $gifter['username'];
                 $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! gifted by %s %s", $subscriptionUser['username'], $subscriptionType['tierLabel'], $gifter['username'], $randomEmote));
             } else {
                 $userName = $subscriptionUser['username'];
                 $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! %s", $subscriptionUser['username'], $subscriptionType['tierLabel'], $randomEmote));
             }
             // Get the subscription message, and remove it from the session
             $subMessage = Session::set('subMessage');
             if (!empty($subMessage)) {
                 $chatIntegrationService->sendBroadcast(sprintf("%s: %s", $userName, $subMessage));
             }
         }
         // Redirect to completion page
         return 'redirect: /subscription/' . urlencode($order['orderId']) . '/complete';
     } catch (Exception $e) {
         if (!empty($order)) {
             $ordersService->updateOrderState($order['orderId'], OrderStatus::ERROR);
         }
         if (!empty($paymentProfile)) {
             $ordersService->updatePaymentStatus($paymentProfile['paymentId'], PaymentStatus::ERROR);
         }
         if (!empty($orderSubscription)) {
             $subscriptionsService->updateSubscriptionState($orderSubscription['subscriptionId'], SubscriptionStatus::ERROR);
         }
         $log = Application::instance()->getLogger();
         $log->error($e->getMessage(), $order);
         return 'redirect: /subscription/' . urlencode($order['orderId']) . '/error';
     }
 }