Exemplo n.º 1
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;
 }
Exemplo n.º 2
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';
 }
Exemplo n.º 3
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';
 }
Exemplo n.º 4
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';
 }
Exemplo n.º 5
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';
 }
Exemplo n.º 6
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);
             }
         }
     }
 }
Exemplo n.º 7
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';
 }
Exemplo n.º 8
0
 /**
  * @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;
 }
Exemplo n.º 9
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';
 }
Exemplo n.º 10
0
 /**
  * Handles the authentication and then merging of accounts
  * Merging of an account is basically connecting multiple authenticators to one user
  *
  * @param AuthenticationCredentials $authCreds
  * @throws Exception
  */
 public function handleAuthAndMerge(AuthenticationCredentials $authCreds)
 {
     $userService = UserService::instance();
     $user = $userService->getUserByAuthId($authCreds->getAuthId(), $authCreds->getAuthProvider());
     $sessAuth = Session::getCredentials()->getData();
     // We need to merge the accounts if one exists
     if (!empty($user)) {
         // If the profile userId is the same as the current one, the profiles are connceted, they shouldnt be here
         if ($user['userId'] == $sessAuth['userId']) {
             throw new Exception('These account are already connected');
         }
         // If the profile user is older than the current user, prompt the user to rather login using the other profile
         if (intval($user['userId']) < $sessAuth['userId']) {
             throw new Exception(sprintf('Your user profile for the %s account is older. Please login and use that account to merge.', $authCreds->getAuthProvider()));
         }
         // So we have a profile for a different user to the one logged in, we delete that user, and add a profile for the current user
         $userService->removeAuthProfile($user['userId'], $authCreds->getAuthProvider());
         // Set the user profile to Merged
         $userService->updateUser($user['userId'], array('userStatus' => 'Merged'));
     }
     $userService->addUserAuthProfile(array('userId' => $sessAuth['userId'], 'authProvider' => $authCreds->getAuthProvider(), 'authId' => $authCreds->getAuthId(), 'authCode' => $authCreds->getAuthCode(), 'authDetail' => $authCreds->getAuthDetail()));
 }
Exemplo n.º 11
0
 /**
  * Flag a user session for update
  * @param int $userId
  */
 public function flagUserForUpdate($userId)
 {
     $user = UserService::instance()->getUserById($userId);
     $credentials = $this->getUserCredentials($user, 'session');
     if (Session::instance() != null && Session::getCredentials()->getUserId() == $userId) {
         // Update the current session if the userId is the same as the credential user id
         Session::updateCredentials($credentials);
         // Init / create the current users chat session
         ChatIntegrationService::instance()->setChatSession($credentials, Session::getSessionId());
     } else {
         // Otherwise set a session variable which is picked up by the remember me service to update the session
         $cache = Application::instance()->getCacheDriver();
         $cache->save(sprintf('refreshusersession-%s', $userId), time(), intval(ini_get('session.gc_maxlifetime')));
     }
     ChatIntegrationService::instance()->refreshChatUserSession($credentials);
 }
Exemplo n.º 12
0
 /**
  * @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';
 }
Exemplo n.º 13
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);
 }
Exemplo n.º 14
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 
Exemplo n.º 15
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);
 }
Exemplo n.º 16
0
 /**
  * @param Request $request
  */
 public function executeRequest(Request $request)
 {
     $route = $this->router->findRoute($request);
     $conn = $this->getConnection();
     $model = new ViewModel();
     if ($route == null) {
         $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);
     }
     if ($route->isSecure()) {
         $creds = Session::getCredentials();
         if ($creds->isValid() && strcasecmp($creds->getUserStatus(), 'Active') !== 0) {
             $response = new Response(Http::STATUS_ERROR);
             $model->error = new Exception(sprintf('User status not active. Status: %s', $creds->getUserStatus()));
             $model->code = Http::STATUS_ERROR;
             $model->title = 'Inactive user';
             $response->setBody($this->template('errors/' . Http::STATUS_ERROR . '.php', $model));
             $this->handleResponse($response);
         }
         if (!$this->hasRouteSecurity($route, $creds)) {
             $response = new Response(Http::STATUS_UNAUTHORIZED);
             $model->title = Http::$HEADER_STATUSES[Http::STATUS_UNAUTHORIZED];
             $response->setBody($this->template('errors/' . Http::STATUS_UNAUTHORIZED . '.php', $model));
             $this->handleResponse($response);
         }
     }
     try {
         $className = $route->getClass();
         $classMethod = $route->getClassMethod();
         $classReflection = new \ReflectionClass($className);
         $classInstance = $classReflection->newInstance();
         // Order the controller arguments and invoke the controller
         $args = array();
         $methodReflection = $classReflection->getMethod($classMethod);
         $methodParams = $methodReflection->getParameters();
         foreach ($methodParams as $methodParam) {
             $paramType = $methodParam->getClass();
             if ($methodParam->isArray()) {
                 // the $params passed into the Controller classes. A merge of the _GET, _POST and variables generated from the route path (e.g. /dog/{id}/cat)
                 $args[] = array_merge($request->get(), $request->post(), $this->router->getRoutePathParams($route, $request->path()));
             } else {
                 if ($paramType->isInstance($model)) {
                     $args[] =& $model;
                 } else {
                     if ($paramType->isInstance($request)) {
                         $args[] =& $request;
                     }
                 }
             }
         }
         // Execute the controller
         $response = $methodReflection->invokeArgs($classInstance, $args);
         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));
         }
         if (!$response instanceof Response) {
             throw new Exception('Invalid response');
         }
     } catch (Exception $e) {
         $this->logger->error($e->getMessage() . PHP_EOL . $e->getTraceAsString());
         if ($conn->isTransactionActive()) {
             $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) {
         $this->logger->critical($e->getMessage() . PHP_EOL . $e->getTraceAsString());
         if ($conn->isTransactionActive()) {
             $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));
     }
     $this->handleResponse($response);
 }