/**
  * @param array $record         
  * @return array
  */
 public function __invoke(array $record)
 {
     // Real IP
     if (!empty($this->serverData['HTTP_CLIENT_IP'])) {
         // check ip from share internet
         $ipAddress = $this->serverData['HTTP_CLIENT_IP'];
     } elseif (!empty($this->serverData['HTTP_X_FORWARDED_FOR'])) {
         // to check ip is pass from proxy
         $ipAddress = $this->serverData['HTTP_X_FORWARDED_FOR'];
     } elseif (!empty($this->serverData['REMOTE_ADDR'])) {
         $ipAddress = $this->serverData['REMOTE_ADDR'];
     } else {
         $ipAddress = null;
     }
     $record['extra'] = array_merge($record['extra'], array('realIp' => $ipAddress));
     $session = Session::instance();
     if (!empty($session)) {
         $record['extra'] = array_merge($record['extra'], array('sessionId' => $session->getSessionId()));
         $credentials = $session->getCredentials()->getData();
         if (!empty($credentials)) {
             $record['extra'] = array_merge($record['extra'], array('credentials' => $credentials));
         }
     }
     return $record;
 }
 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';
 }
 /**
  * @Route ("/impersonate")
  * @HttpMethod ({"GET"})
  *
  * @param array $params
  * @throws Exception
  * @return string
  */
 public function impersonate(array $params)
 {
     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::updateCredentials($credentials);
     ChatIntegrationService::instance()->setChatSession($credentials, Session::getSessionId());
     return 'redirect: /';
 }
Example #4
0
 /**
  * Redirects the user to the auth provider
  *
  * @return void
  */
 public function getAuthenticationUrl()
 {
     $authConf = Config::$a['oauth']['providers'][$this->authProvider];
     $callback = sprintf(Config::$a['oauth']['callback'], $this->authProvider);
     $client = new \OAuth2\Client($authConf['clientId'], $authConf['clientSecret']);
     $client->setAccessTokenType(\OAuth2\Client::ACCESS_TOKEN_BEARER);
     return $client->getAuthenticationUrl('https://accounts.google.com/o/oauth2/auth', $callback, array('scope' => 'openid email', 'state' => 'security_token=' . Session::getSessionId()));
 }
Example #5
0
 /**
  * @Route ("/admin/chat/broadcast")
  * @Secure ({"ADMIN"})
  *
  * @param array $params         
  * @param ViewModel $model          
  * @throws Exception
  * @return string
  */
 public function adminChatBroadcast(array $params, ViewModel $model)
 {
     $model->title = 'Chat';
     FilterParams::required($params, 'message');
     $chatIntegrationService = ChatIntegrationService::instance();
     $chatIntegrationService->sendBroadcast($params['message']);
     Session::set('modelSuccess', sprintf('Sent broadcast: %s', $params['message']));
     return 'redirect: /admin/chat';
 }
Example #6
0
 /**
  * @Route ("/api/messages/unreadcount")
  *
  * @return Response
  */
 public function unreadCount()
 {
     $userId = Session::getCredentials()->getUserId();
     $response = array('success' => false);
     if ($userId) {
         $privateMessageService = PrivateMessageService::instance();
         $response['success'] = true;
         $response['unreadcount'] = (int) $privateMessageService->getUnreadMessageCount($userId);
     }
     $response = new Response(Http::STATUS_OK, json_encode($response));
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     return $response;
 }
Example #7
0
 /**
  * @Route ("/banned")
  * @Secure ({"USER"})
  *
  * @param array $params         
  * @param ViewModel $model          
  * @return string
  */
 public function banned(array $params, ViewModel $model, Request $request)
 {
     $userService = UserService::instance();
     $creds = Session::getCredentials();
     $model->ban = $userService->getUserActiveBan($creds->getUserId(), $request->ipAddress());
     $model->banType = 'none';
     if (!empty($model->ban)) {
         if (!$model->ban['endtimestamp']) {
             $model->banType = 'permanent';
         } else {
             $model->banType = 'temporary';
         }
     }
     $model->user = $creds->getData();
     return 'banned';
 }
Example #8
0
 /**
  * @Route ("/embed/chat")
  *
  * @param array $params
  * @param ViewModel $model
  * @return string
  */
 public function embedChat(array $params, ViewModel $model)
 {
     $user = null;
     if (Session::hasRole(UserRole::USER)) {
         $creds = Session::getCredentials();
         $user = array();
         $user['username'] = $creds->getUsername();
         $user['features'] = $creds->getFeatures();
     }
     $model->options = $this->getChatOptionParams($params);
     $model->user = $user;
     // Login follow url
     if (isset($params['follow']) && !empty($params['follow']) && substr($params['follow'], 0, 1) == '/') {
         $model->follow = $params['follow'];
     }
     return 'embed/chat';
 }
Example #9
0
 /**
  * @Route ("/")
  * @Route ("/home")
  *
  * @param ViewModel $model
  * @return string
  */
 public function home(ViewModel $model)
 {
     if (Session::hasRole(UserRole::USER)) {
         $userid = $userId = Session::getCredentials()->getUserId();
         $privateMessageService = PrivateMessageService::instance();
         $model->unreadMessageCount = $privateMessageService->getUnreadMessageCount($userid);
     }
     $app = Application::instance();
     $cacheDriver = $app->getCacheDriver();
     $model->articles = $cacheDriver->fetch('recentblog');
     $model->summoners = $cacheDriver->fetch('summoners');
     $model->tweets = $cacheDriver->fetch('twitter');
     $model->music = $cacheDriver->fetch('recenttracks');
     $model->playlist = $cacheDriver->fetch('youtubeplaylist');
     $model->broadcasts = $cacheDriver->fetch('pastbroadcasts');
     $model->streamInfo = $cacheDriver->fetch('streaminfo');
     return 'home';
 }
Example #10
0
 /**
  * @Route ("/admin/user/{userId}/ban")
  * @Secure ({"ADMIN"})
  * @HttpMethod ({"POST"})
  *
  * @param array $params
  */
 public function insertBan(array $params, ViewModel $model)
 {
     if (!isset($params['userId']) || empty($params['userId'])) {
         throw new Exception('userId required');
     }
     $ban = array();
     $ban['reason'] = $params['reason'];
     $ban['userid'] = Session::getCredentials()->getUserId();
     $ban['ipaddress'] = '';
     $ban['targetuserid'] = $params['userId'];
     $ban['starttimestamp'] = Date::getDateTime($params['starttimestamp'])->format('Y-m-d H:i:s');
     if (!empty($params['endtimestamp'])) {
         $ban['endtimestamp'] = Date::getDateTime($params['endtimestamp'])->format('Y-m-d H:i:s');
     }
     $userService = UserService::instance();
     $ban['id'] = $userService->insertBan($ban);
     AuthenticationService::instance()->flagUserForUpdate($ban['targetuserid']);
     return 'redirect: /admin/user/' . $params['userId'] . '/ban/' . $ban['id'] . '/edit';
 }
Example #11
0
 /**
  * Checks the users current session status
  * Does a remember me login
  * @return void
  */
 public function init()
 {
     $app = Application::instance();
     $authService = AuthenticationService::instance();
     // If the session hasnt started, or the data is not valid (result from php clearing the session data), check the Remember me cookie
     if (!Session::isStarted() || !Session::getCredentials()->isValid()) {
         $userId = $authService->getRememberMe();
         if ($userId !== false) {
             $userManager = UserService::instance();
             $user = $userManager->getUserById($userId);
             if (!empty($user)) {
                 Session::start(Session::START_NOCOOKIE);
                 $credentials = $authService->getUserCredentials($user, 'rememberme');
                 Session::updateCredentials($credentials);
                 ChatIntegrationService::instance()->setChatSession($credentials, Session::getSessionId());
                 $authService->setRememberMe($user);
             }
         }
     }
 }
Example #12
0
 /**
  * @param array $params
  * @return string
  * @throws Exception
  */
 public function authenticate(array $params)
 {
     if (!isset($params['oauth_token']) || empty($params['oauth_token']) || !isset($params['oauth_verifier']) || empty($params['oauth_verifier'])) {
         throw new Exception('Authentication failed');
     }
     $oauth = Session::set('oauth');
     if ($params['oauth_token'] !== $oauth['oauth_token']) {
         throw new Exception('Invalid login session');
     }
     $twitterOAuthConf = Config::$a['oauth']['providers']['twitter'];
     $tmhOAuth = new \tmhOAuth(array('consumer_key' => $twitterOAuthConf['clientId'], 'consumer_secret' => $twitterOAuthConf['clientSecret'], 'token' => $oauth['oauth_token'], 'secret' => $oauth['oauth_token_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('method' => 'POST', 'url' => $tmhOAuth->url('oauth/access_token', ''), 'params' => array('oauth_verifier' => trim($params['oauth_verifier']))));
     if ($code != 200) {
         throw new Exception('Failed to retrieve user data');
     }
     $data = $tmhOAuth->extract_params($tmhOAuth->response['response']);
     $authCreds = $this->getAuthCredentials($oauth['oauth_token'], $data);
     $authCredHandler = new AuthenticationRedirectionFilter();
     return $authCredHandler->execute($authCreds);
 }
Example #13
0
 /**
  * @Route ("/login")
  * @HttpMethod ({"POST"})
  *
  * @param array $params         
  * @param ViewModel $model          
  * @return string
  */
 public function loginPost(array $params, ViewModel $model)
 {
     $userService = UserService::instance();
     $authProvider = isset($params['authProvider']) && !empty($params['authProvider']) ? $params['authProvider'] : '';
     $rememberme = isset($params['rememberme']) && !empty($params['rememberme']) ? true : false;
     if (empty($authProvider)) {
         $model->title = 'Login error';
         $model->rememberme = $rememberme;
         $model->error = new Exception('Please select a authentication provider');
         return 'login';
     }
     Session::start(Session::START_NOCOOKIE);
     if ($rememberme) {
         Session::set('rememberme', 1);
     }
     if (isset($params['follow']) && !empty($params['follow'])) {
         Session::set('follow', $params['follow']);
     }
     switch (strtoupper($authProvider)) {
         case 'TWITCH':
             $authHandler = new TwitchAuthHandler();
             return 'redirect: ' . $authHandler->getAuthenticationUrl();
         case 'GOOGLE':
             $authHandler = new GoogleAuthHandler();
             return 'redirect: ' . $authHandler->getAuthenticationUrl();
         case 'TWITTER':
             $authHandler = new TwitterAuthHandler();
             return 'redirect: ' . $authHandler->getAuthenticationUrl();
         case 'REDDIT':
             $authHandler = new RedditAuthHandler();
             return 'redirect: ' . $authHandler->getAuthenticationUrl();
         default:
             $model->title = 'Login error';
             $model->rememberme = $rememberme;
             $model->error = new Exception('Authentication type not supported');
             return 'login';
     }
 }
Example #14
0
 /**
  * @Route ("/admin")
  * @Secure ({"ADMIN"})
  * @HttpMethod ({"GET","POST"})
  *
  * @param array $params         
  * @param ViewModel $model          
  * @return string
  */
 public function admin(array $params, ViewModel $model)
 {
     if (empty($params['page'])) {
         $params['page'] = 1;
     }
     if (empty($params['size'])) {
         $params['size'] = 20;
     }
     if (empty($params['search'])) {
         $params['search'] = '';
     }
     $model->title = 'Administration';
     $model->user = Session::getCredentials()->getData();
     if (empty($params['search'])) {
         $model->users = UserService::instance()->listUsers(intval($params['size']), intval($params['page']));
     } else {
         $model->users = UserService::instance()->searchUsers(intval($params['size']), intval($params['page']), $params['search']);
     }
     $model->size = $params['size'];
     $model->page = $params['page'];
     $model->search = $params['search'];
     return 'admin/admin';
 }
Example #15
0
use Destiny\Common\Session;
use Destiny\Common\User\UserRole;
?>
<div class="modal fade message-composition" id="compose" tabindex="-1" role="dialog" aria-labelledby="composeLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="composeLabel">New message</h4>
            </div>
            <div id="compose-form">
                <div class="modal-recipients">
                    <div class="modal-user-groups" class="clearfix">
                        <?php 
if (Session::hasRole(UserRole::ADMIN)) {
    ?>
                        <div class="btn-group pull-right">
                            <button type="button" class="btn btn-xs btn-primary">Add group</button>
                            <button type="button" class="btn btn-xs btn-primary dropdown-toggle" data-toggle="dropdown">
                                <span class="caret"></span>
                                <span class="sr-only">Toggle Dropdown</span>
                            </button>
                            <ul class="groups dropdown-menu dropdown-menu-right" role="menu">
                                <li><a href="#">T4 Subscribers</a></li>
                                <li><a href="#">T3 Subscribers</a></li>
                                <li><a href="#">T2 Subscribers</a></li>
                                <li><a href="#">T1 Subscribers</a></li>
                            </ul>
                        </div>
                        <?php 
Example #16
0
 /**
  * @Route ("/admin/user/{id}/subscription/{subscriptionId}/save")
  * @Route ("/admin/user/{id}/subscription/save")
  * @Secure ({"ADMIN"})
  * @HttpMethod ({"POST"})
  *
  * @param array $params         
  * @param ViewModel $model          
  * @throws Exception
  * @return string
  */
 public function subscriptionSave(array $params, ViewModel $model)
 {
     FilterParams::required($params, 'subscriptionType');
     FilterParams::required($params, 'status');
     FilterParams::required($params, 'createdDate');
     FilterParams::required($params, 'endDate');
     $subscriptionsService = SubscriptionsService::instance();
     $subscriptionType = $subscriptionsService->getSubscriptionType($params['subscriptionType']);
     $subscription = array();
     $subscription['subscriptionType'] = $subscriptionType['id'];
     $subscription['subscriptionTier'] = $subscriptionType['tier'];
     $subscription['status'] = $params['status'];
     $subscription['createdDate'] = $params['createdDate'];
     $subscription['endDate'] = $params['endDate'];
     $subscription['userId'] = $params['id'];
     $subscription['subscriptionSource'] = isset($params['subscriptionSource']) && !empty($params['subscriptionSource']) ? $params['subscriptionSource'] : Config::$a['subscriptionType'];
     if (isset($params['subscriptionId']) && !empty($params['subscriptionId'])) {
         $subscription['subscriptionId'] = $params['subscriptionId'];
         $subscriptionId = $subscription['subscriptionId'];
         $subscriptionsService->updateSubscription($subscription);
         Session::set('modelSuccess', 'Subscription updated!');
     } else {
         $subscriptionId = $subscriptionsService->addSubscription($subscription);
         Session::set('modelSuccess', 'Subscription created!');
     }
     $authService = AuthenticationService::instance();
     $authService->flagUserForUpdate($params['id']);
     return 'redirect: /admin/user/' . urlencode($params['id']) . '/subscription/' . urlencode($subscriptionId) . '/edit';
 }
 /**
  * @Route ("/gift/check")
  * @Secure ({"USER"})
  *
  * @param array $params
  * @return Response
  */
 public function giftCheckUser(array $params)
 {
     FilterParams::required($params, 's');
     $userService = UserService::instance();
     $subscriptionService = SubscriptionsService::instance();
     $userId = Session::getCredentials()->getUserId();
     $data = array('valid' => false, 'cangift' => false, 'username' => $params['s']);
     $user = $userService->getUserByUsername($params['s']);
     if (!empty($user)) {
         $data['cangift'] = $subscriptionService->getCanUserReceiveGift($userId, $user['userId']);
         $data['valid'] = true;
     }
     $response = new Response(Http::STATUS_OK);
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     $response->setBody(json_encode($data));
     return $response;
 }
Example #18
0
include Tpl::file('seg/google.tracker.php');
?>
</head>
<body id="subscribe">

  <?php 
include Tpl::file('seg/top.php');
?>
  <?php 
include Tpl::file('seg/headerband.php');
?>
  
  <section class="container">
  
    <?php 
if (Session::hasRole(UserRole::USER)) {
    ?>
    <div id="giftSubscriptionSelect" class="alert alert-info" style="text-align: center;">
        Would you like to gift someone a subscription? 
        <button class="btn btn-primary" data-toggle="modal" data-target="#userSearchModal">Yes, gift a subscription <span class="glyphicon glyphicon-gift"></span></button>
    </div>

    <div id="giftSubscriptionConfirm" class="alert alert-info hidden" style="text-align: center;">
        You are gifting your subscription to <strong id="subscriptionGiftUsername"></strong>!
        <button class="btn btn-primary" id="selectGiftSubscription" data-toggle="modal" data-target="#userSearchModal">Change <span class="glyphicon glyphicon-gift"></span></button>
        <button class="btn btn-default" id="cancelGiftSubscription">Abort!</button>
    </div>
    <?php 
}
?>
Example #19
0
 /**
  * Update/add a address
  *
  * @Route ("/profile/address/update")
  * @HttpMethod ({"POST"})
  * @Secure ({"USER"})
  *
  * @param array $params
  * @return string
  */
 public function updateAddress(array $params)
 {
     FilterParams::required($params, 'fullName');
     FilterParams::required($params, 'line1');
     FilterParams::declared($params, 'line2');
     FilterParams::required($params, 'city');
     FilterParams::required($params, 'region');
     FilterParams::required($params, 'zip');
     FilterParams::required($params, 'country');
     $userService = UserService::instance();
     $userId = Session::getCredentials()->getUserId();
     $address = $userService->getAddressByUserId($userId);
     if (empty($address)) {
         $address = array();
         $address['userId'] = $userId;
     }
     $address['fullName'] = $params['fullName'];
     $address['line1'] = $params['line1'];
     $address['line2'] = $params['line2'];
     $address['city'] = $params['city'];
     $address['region'] = $params['region'];
     $address['zip'] = $params['zip'];
     $address['country'] = $params['country'];
     if (!isset($address['id']) || empty($address['id'])) {
         $userService->addAddress($address);
     } else {
         $userService->updateAddress($address);
     }
     Session::set('modelSuccess', 'Your address has been updated');
     return 'redirect: /profile';
 }
Example #20
0
 /**
  * Returns the remember me record for the current cookie
  *
  * @return array
  */
 protected function getRememberMe()
 {
     $rememberMeService = RememberMeService::instance();
     $cookie = Session::instance()->getRememberMeCookie();
     $token = $cookie->getValue();
     $rememberMe = null;
     // throw back to when I used a json string in the rememberme cookie
     // this is here so no-ones remember me cookie failed after upgrade.
     if (!empty($token) && $token[0] == "{") {
         $cookieData = @json_decode($token, true);
         if (!empty($cookieData) && isset($cookieData['token'])) {
             $token = $cookieData['token'];
         }
     }
     // If the token is not empty query the DB for the remember me record
     if (!empty($token)) {
         $rememberMe = $rememberMeService->getRememberMe($token, 'rememberme');
     }
     return $rememberMe;
 }
Example #21
0
 /**
  * Executes the action if a route is found
  */
 public function executeRequest(Request $request)
 {
     $route = $this->router->findRoute($request);
     $model = new ViewModel();
     $response = null;
     // No route found
     if (!$route) {
         $model->title = Http::$HEADER_STATUSES[Http::STATUS_NOT_FOUND];
         $response = new Response(Http::STATUS_NOT_FOUND);
         $response->setBody($this->template('errors/' . Http::STATUS_NOT_FOUND . '.php', $model));
         $this->handleResponse($response);
     }
     // Security checks
     if (!$this->hasRouteSecurity($route, Session::getCredentials())) {
         $model->title = Http::$HEADER_STATUSES[Http::STATUS_UNAUTHORIZED];
         $response = new Response(Http::STATUS_UNAUTHORIZED);
         $response->setBody($this->template('errors/' . Http::STATUS_UNAUTHORIZED . '.php', $model));
         $this->handleResponse($response);
     }
     try {
         // Parameters
         $params = array_merge($_GET, $_POST, $route->getPathParams($request->path()));
         // Get and init action class
         $className = $route->getClass();
         $classMethod = $route->getClassMethod();
         // Init the action class instance
         $classInstance = new $className();
         // Check for @Transactional annotation
         $annotationReader = $this->getAnnotationReader();
         $transactional = $annotationReader->getMethodAnnotation(new \ReflectionMethod($classInstance, $classMethod), 'Destiny\\Common\\Annotation\\Transactional');
         $transactional = empty($transactional) ? false : true;
         // If transactional begin a DB transaction before the action begins
         if ($transactional) {
             $conn = $this->getConnection();
             $conn->beginTransaction();
         }
         // Execute the class method
         $response = $classInstance->{$classMethod}($params, $model, $request);
         // Log any errors on the model
         // @TODO neaten this implementation up - better than logging everywhere else
         ///if (! empty ( $model->error ) && is_a ( $model->error, 'Exception' )) {
         /// $this->logger->error ( $model->error->getMessage () );
         //}
         // Check if the response is valid
         if (empty($response)) {
             throw new Exception('Invalid action response');
         }
         // Redirect response
         if (is_string($response) && substr($response, 0, 10) === 'redirect: ') {
             $redirect = substr($response, 10);
             $response = new Response(Http::STATUS_OK);
             $response->setLocation($redirect);
         }
         // Template response
         if (is_string($response)) {
             $tpl = $response . '.php';
             $response = new Response(Http::STATUS_OK);
             $response->setBody($this->template($tpl, $model));
         }
         // Check the response type
         if (!$response instanceof Response) {
             throw new Exception('Invalid response');
         }
         // Commit the DB transaction
         if ($transactional) {
             $conn->commit();
         }
     } catch (Exception $e) {
         // Destiny\Exceptions are caught and displayed
         $this->logger->error($e->getMessage());
         if ($transactional) {
             $conn->rollback();
         }
         $response = new Response(Http::STATUS_ERROR);
         $model->error = new Exception($e->getMessage());
         $model->code = Http::STATUS_ERROR;
         $model->title = 'Error';
         $response->setBody($this->template('errors/' . Http::STATUS_ERROR . '.php', $model));
     } catch (\Exception $e) {
         // \Exceptions are caught and generic message is shown
         $this->logger->critical($e->getMessage());
         if ($transactional) {
             $conn->rollback();
         }
         $response = new Response(Http::STATUS_ERROR);
         $model->error = new Exception('Maximum over-rustle has been achieved');
         $model->code = Http::STATUS_ERROR;
         $model->title = 'Error';
         $response->setBody($this->template('errors/' . Http::STATUS_ERROR . '.php', $model));
     }
     // Handle the request response
     $this->handleResponse($response);
 }
Example #22
0
    ?>
                  <a href="#togglemute">
                    <span class="fa fa-ban"></span> Mute
                  </a> 
                  <a href="#toggleban">
                    <span class="fa fa-remove"></span> Ban
                  </a> 
                  <a href="#clearmessages"><span class="fa fa-fire"></span> Clear messages</a> 
                  <?php 
}
?>
            
                </div>
            
                <?php 
if (Session::hasFeature(UserFeature::MODERATOR) || Session::hasFeature(UserFeature::ADMIN)) {
    ?>
                <!-- mute -->
                <form id="user-mute-form">
                  <div class="form-group">
                    <select id="banTimeLength" class="select form-control input-sm">
                      <option value="0">Length of time</option>
                      <option value="10">10 minutes</option>
                      <option value="30">30 minutes</option>
                      <option value="60">1 hr</option>
                      <option value="720">12 hrs</option>
                      <option value="1440">24 hrs</option>
                    </select>
                  </div>
                  <div class="form-group">
                    <button type="submit" class="btn btn-xs btn-primary">Confirm</button>
Example #23
0
<?php

namespace Destiny;

use Destiny\Common\Utils\Tpl;
use Destiny\Common\Session;
?>

<h2 class="page-title" style="margin-left: 20px;">
	<span><?php 
echo Tpl::out(Session::getCredentials()->getUsername());
?>
</span>
	<small><i class="fa fa-envelope-o" title="<?php 
echo Tpl::out(Session::getCredentials()->getEmail());
?>
"></i></small>
</h2>

<section class="container">
    <ol class="breadcrumb" style="margin-bottom:0;">
      	<li><a href="/profile" title="Your account details">Account</a></li>
      	<li><a href="/profile/messages" title="Your private messages">Messages</a></li>
        <li><a href="/profile/authentication" title="Your login methods">Authentication</a></li>
    </ol>
</section><?php 
Example #24
0
 /**
  * Create a Paypal recurring payment profile
  *
  * @param array $order          
  * @param string $token         
  * @param array $subscriptionType         
  * @return \PayPalAPI\CreateRecurringPaymentsProfileResponseType
  */
 public function createRecurringPaymentProfile(array $paymentProfile, $token, array $subscriptionType)
 {
     $billingStartDate = Date::getDateTime($paymentProfile['billingStartDate']);
     $RPProfileDetails = new RecurringPaymentsProfileDetailsType();
     $RPProfileDetails->SubscriberName = Session::getCredentials()->getUsername();
     // This should be passed in
     $RPProfileDetails->BillingStartDate = $billingStartDate->format(\DateTime::ATOM);
     $RPProfileDetails->ProfileReference = $paymentProfile['userId'] . '-' . $paymentProfile['orderId'];
     $paymentBillingPeriod = new BillingPeriodDetailsType();
     $paymentBillingPeriod->BillingFrequency = $paymentProfile['billingFrequency'];
     $paymentBillingPeriod->BillingPeriod = $paymentProfile['billingPeriod'];
     $paymentBillingPeriod->Amount = new BasicAmountType($paymentProfile['currency'], $paymentProfile['amount']);
     $scheduleDetails = new ScheduleDetailsType();
     $scheduleDetails->Description = $subscriptionType['agreement'];
     $scheduleDetails->PaymentPeriod = $paymentBillingPeriod;
     $createRPProfileRequestDetail = new CreateRecurringPaymentsProfileRequestDetailsType();
     $createRPProfileRequestDetail->Token = $token;
     $createRPProfileRequestDetail->ScheduleDetails = $scheduleDetails;
     $createRPProfileRequestDetail->RecurringPaymentsProfileDetails = $RPProfileDetails;
     $createRPProfileRequest = new CreateRecurringPaymentsProfileRequestType();
     $createRPProfileRequest->CreateRecurringPaymentsProfileRequestDetails = $createRPProfileRequestDetail;
     $createRPProfileReq = new CreateRecurringPaymentsProfileReq();
     $createRPProfileReq->CreateRecurringPaymentsProfileRequest = $createRPProfileRequest;
     $paypalService = new PayPalAPIInterfaceServiceService();
     return $paypalService->CreateRecurringPaymentsProfile($createRPProfileReq);
 }
 /**
  * Delete the session for the chat user
  */
 public function deleteChatSession()
 {
     $redis = Application::instance()->getRedis();
     $redis->delete(sprintf('CHAT:session-%s', Session::getSessionId()));
 }
Example #26
0
                <li class="divider-vertical visible-xs"></li>
                <?php 
}
?>

                <li><a title="Blog @ destiny.gg" href="//blog.destiny.gg">Blog</a></li>
                <li><a title="twitter.com" href="//twitter.com/Steven_Bonnell/">Twitter</a></li>
                <li><a title="youtube.com" href="//www.youtube.com/user/Destiny">Youtube</a></li>
                <li><a title="reddit.com" href="//www.reddit.com/r/Destiny/">Reddit</a></li>
                <li><a title="facebook.com" href="//www.facebook.com/Steven.Bonnell.II">Facebook</a></li>

                <?php 
if (!Session::hasRole(UserRole::SUBSCRIBER)) {
    ?>
                <li class="subscribe"><a href="/subscribe" rel="subscribe" title="Get your own destiny.gg subscription"><span>Subscribe Now!</span></a></li>
                <?php 
}
?>

                <?php 
if (Session::hasRole(UserRole::SUBSCRIBER)) {
    ?>
                <li class="subscribed"><a href="/subscribe" rel="subscribe" title="You have an active subscription!"><span>Subscribe</span></a></li>
                <?php 
}
?>

            </ul>
        </div>
    </div>
</div><?php 
 /**
  * Returns the user record associated with a remember me cookie
  *
  * @return array
  * @throws \Exception
  */
 protected function getRememberMe()
 {
     $cookie = Session::instance()->getRememberMeCookie();
     $rawData = $cookie->getValue();
     $user = null;
     if (empty($rawData)) {
         goto end;
     }
     if (strlen($rawData) < 64) {
         goto cleanup;
     }
     $data = unserialize(Crypto::decrypt($rawData));
     if (!$data) {
         goto cleanup;
     }
     if (!isset($data['expires']) or !isset($data['userId'])) {
         goto cleanup;
     }
     $expires = Date::getDateTime($data['expires']);
     if ($expires <= Date::getDateTime()) {
         goto cleanup;
     }
     $user = UserService::instance()->getUserById(intval($data['userId']));
     goto end;
     cleanup:
     $cookie->clearCookie();
     end:
     return $user;
 }
Example #28
0
 /**
  * Updates the session last updated time to match the cache time
  *
  * @param int $userId
  * @param int $lastUpdated
  * @return boolean
  */
 private function clearUserUpdateFlag($userId, $lastUpdated)
 {
     Session::set('lastUpdated', $lastUpdated);
 }
 /**
  * @Route ("/profile/messages/{targetuserid}")
  * @Secure ({"USER"})
  * @HttpMethod ({"GET"})
  *
  * @param array $params
  * @return Response
  */
 public function message(array $params, ViewModel $viewModel)
 {
     FilterParams::required($params, 'targetuserid');
     $privateMessageService = PrivateMessageService::instance();
     $userService = UserService::instance();
     $userId = Session::getCredentials()->getUserId();
     $username = Session::getCredentials()->getUsername();
     $targetuser = $userService->getUserById($params['targetuserid']);
     if (empty($targetuser)) {
         throw new Exception('Invalid user');
     }
     $messages = $privateMessageService->getMessagesBetweenUserIdAndTargetUserId($userId, $params['targetuserid'], 0, 1000);
     $privateMessageService->markMessagesRead($userId, $params['targetuserid']);
     $viewModel->targetuser = $targetuser;
     $viewModel->messages = $messages;
     $viewModel->username = $username;
     $viewModel->userId = $userId;
     $viewModel->title = 'Message';
     return 'profile/message';
 }
Example #30
0
 /**
  * @Route ("/register")
  * @HttpMethod ({"POST"})
  * @Transactional
  *
  * Handle the confirmation request
  * @param array $params
  * @throws Exception
  */
 public function registerProcess(array $params, ViewModel $model, Request $request)
 {
     $userService = UserService::instance();
     $authService = AuthenticationService::instance();
     $authCreds = $this->getSessionAuthenticationCredentials($params);
     $username = isset($params['username']) && !empty($params['username']) ? $params['username'] : '';
     $email = isset($params['email']) && !empty($params['email']) ? $params['email'] : '';
     $country = isset($params['country']) && !empty($params['country']) ? $params['country'] : '';
     $rememberme = isset($params['rememberme']) && !empty($params['rememberme']) ? true : false;
     $authCreds->setUsername($username);
     $authCreds->setEmail($email);
     try {
         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());
         $authService->validateUsername($username);
         $authService->validateEmail($email);
         if (!empty($country)) {
             $countryArr = Country::getCountryByCode($country);
             if (empty($countryArr)) {
                 throw new Exception('Invalid country');
             }
             $country = $countryArr['alpha-2'];
         }
         $user = array();
         $user['username'] = $username;
         $user['email'] = $email;
         $user['userStatus'] = 'Active';
         $user['country'] = $country;
         $user['userId'] = $userService->addUser($user);
         $userService->addUserAuthProfile(array('userId' => $user['userId'], 'authProvider' => $authCreds->getAuthProvider(), 'authId' => $authCreds->getAuthId(), 'authCode' => $authCreds->getAuthCode(), 'authDetail' => $authCreds->getAuthDetail()));
         Session::set('authSession');
         $authCredHandler = new AuthenticationRedirectionFilter();
         return $authCredHandler->execute($authCreds);
     } catch (Exception $e) {
         $model->title = 'Register Error';
         $model->username = $username;
         $model->email = $email;
         $model->follow = isset($params['follow']) ? $params['follow'] : '';
         $model->authProvider = $authCreds->getAuthProvider();
         $model->code = $authCreds->getAuthCode();
         $model->error = $e;
         return 'register';
     }
 }