Example #1
0
 /**
  * @Route ("/admin/user/{id}/edit")
  * @Secure ({"ADMIN"})
  * @HttpMethod ({"GET"})
  *
  * @param array $params         
  * @param ViewModel $model          
  * @throws Exception
  * @return string
  */
 public function adminUserEdit(array $params, ViewModel $model)
 {
     $model->title = 'User';
     FilterParams::required($params, 'id');
     $user = UserService::instance()->getUserById($params['id']);
     if (empty($user)) {
         throw new Exception('User was not found');
     }
     $userService = UserService::instance();
     $userFeaturesService = UserFeaturesService::instance();
     $apiAuthenticationService = ApiAuthenticationService::instance();
     $chatlogService = ChatlogService::instance();
     $subscriptionsService = SubscriptionsService::instance();
     $user['roles'] = $userService->getUserRolesByUserId($user['userId']);
     $user['features'] = $userFeaturesService->getUserFeatures($user['userId']);
     $user['ips'] = $userService->getIPByUserId($user['userId']);
     $model->user = $user;
     $model->smurfs = $userService->findSameIPUsers($user['userId']);
     $model->features = $userFeaturesService->getDetailedFeatures();
     $ban = $userService->getUserActiveBan($user['userId']);
     $banContext = array();
     if (!empty($ban)) {
         $banContext = $chatlogService->getChatLogBanContext($user['userId'], Date::getDateTime($ban['starttimestamp']), 18);
     }
     $model->banContext = $banContext;
     $model->ban = $ban;
     $model->authSessions = $apiAuthenticationService->getAuthSessionsByUserId($user['userId']);
     $model->address = $userService->getAddressByUserId($user['userId']);
     $model->subscriptions = $subscriptionsService->getUserSubscriptions($user['userId']);
     if (Session::get('modelSuccess')) {
         $model->success = Session::get('modelSuccess');
         Session::set('modelSuccess');
     }
     return 'admin/user';
 }
Example #2
0
 /**
  * @return void
  */
 public function execute()
 {
     foreach ($this->schedule as $i => $action) {
         $task = $this->getTask($this->schedule[$i]['action']);
         if (empty($task)) {
             $this->schedule[$i]['lastExecuted'] = date(\DateTime::ATOM);
             $this->schedule[$i]['executeCount'] = 0;
             $this->insertTask($this->schedule[$i]);
         } else {
             $this->schedule[$i] = array_merge($this->schedule[$i], $task);
         }
     }
     $startTime = microtime(true);
     try {
         $this->logger->debug('Schedule starting');
         foreach ($this->schedule as $i => $action) {
             $nextExecute = Date::getDateTime($this->schedule[$i]['lastExecuted']);
             $nextExecute->modify('+' . $this->schedule[$i]['frequency'] . ' ' . $this->schedule[$i]['period']);
             if (time() > $nextExecute->getTimestamp()) {
                 $this->schedule[$i]['executeCount'] = intval($this->schedule[$i]['executeCount']) + 1;
                 $this->schedule[$i]['lastExecuted'] = date(\DateTime::ATOM);
                 $this->updateTask($this->schedule[$i]);
                 $this->executeTask($this->schedule[$i]);
             }
         }
         $this->logger->debug('Schedule complete');
     } catch (Exception $e) {
         $this->logger->error($e->getMessage());
     } catch (\Exception $e) {
         $this->logger->critical($e->getMessage());
     }
     $this->logger->debug('Completed in ' . (microtime(true) - $startTime) . ' seconds');
 }
Example #3
0
 /**
  * Get a the latest playlist from google
  *
  * @param array $options
  * @param array $params
  * @throws Exception
  * @return \Destiny\CurlBrowser
  */
 public function getYoutubePlaylist(array $options = array(), array $params = array())
 {
     // Get the channel ID's from a specific person
     // GET https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=StevenBonnell&key={YOUR_API_KEY}
     $params['limit'] = isset($params['limit']) ? intval($params['limit']) : 4;
     return new CurlBrowser(array_merge(array('url' => new String('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={playlistId}&key={apikey}&maxResults={limit}', array('playlistId' => Config::$a['youtube']['playlistId'], 'apikey' => Config::$a['youtube']['apikey'], 'limit' => $params['limit'])), 'contentType' => MimeType::JSON, 'onfetch' => function ($json) {
         if (is_array($json['items'])) {
             foreach ($json['items'] as $i => $item) {
                 $item['snippet']['publishedAt'] = Date::getDateTime($item['snippet']['publishedAt'], Date::FORMAT);
             }
         } else {
             throw new Exception('Youtube API Down');
         }
         return $json;
     }), $options));
 }
Example #4
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 #5
0
 /**
  * @Route ("/chat/history")
  *
  * @param array $params            
  * @param ViewModel $model            
  */
 public function history(array $params, ViewModel $model)
 {
     $chatLogService = ChatlogService::instance();
     $chatlog = $chatLogService->getChatLog(Config::$a['chat']['backlog']);
     $broadcasts = $chatLogService->getBroadcasts(Date::getDateTime(strtotime('5 minutes ago')));
     $b = '';
     $lines = array();
     $suppress = array();
     foreach ($chatlog as &$line) {
         if ($line['event'] == 'MUTE' or $line['event'] == 'BAN') {
             $suppress[$line['target']] = true;
         }
         if (isset($suppress[$line['username']])) {
             continue;
         }
         if (!empty($line['features'])) {
             $line['features'] = explode(',', $line['features']);
         } else {
             $line['features'] = array();
         }
         if ($line['subscriber'] == 1) {
             $line['features'][] = UserFeature::SUBSCRIBER;
             if ($line['istwitchsubscriber']) {
                 $line['features'][] = UserFeature::SUBSCRIBERT0;
             }
             if ($line['subscriptionTier'] == 2) {
                 $line['features'][] = UserFeature::SUBSCRIBERT2;
             }
             if ($line['subscriptionTier'] == 3) {
                 $line['features'][] = UserFeature::SUBSCRIBERT3;
             }
             if ($line['subscriptionTier'] == 4) {
                 $line['features'][] = UserFeature::SUBSCRIBERT4;
             }
         }
         unset($line['istwitchsubscriber']);
         // do not leak the abstraction
         $lines[] = $line;
     }
     $b .= 'var backlog = ' . json_encode($lines) . ';' . PHP_EOL;
     $b .= 'var broadcasts = ' . json_encode($broadcasts) . ';' . PHP_EOL;
     $response = new Response(Http::STATUS_OK, $b);
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JAVASCRIPT);
     return $response;
 }
Example #6
0
 /**
  * @param array $options
  * @return CurlBrowser
  */
 public function getLastFMTracks(array $options = array())
 {
     return new CurlBrowser(array_merge(array('url' => 'http://ws.audioscrobbler.com/2.0/?api_key=' . Config::$a['lastfm']['apikey'] . '&user='******'lastfm']['user'] . '&method=user.getrecenttracks&limit=3&format=json', 'contentType' => MimeType::JSON, 'onfetch' => function ($json) {
         if (!$json || isset($json['error']) && $json['error'] > 0 || count($json['recenttracks']['track']) <= 0) {
             throw new Exception('Error fetching tracks');
         }
         foreach ($json['recenttracks']['track'] as $i => $track) {
             // Timezone DST = -1
             if (!isset($track['@attr']) || $track['@attr']['nowplaying'] != true) {
                 if (!empty($track['date'])) {
                     $json['recenttracks']['track'][$i]['date']['uts]'] = $track['date']['uts'];
                     $json['recenttracks']['track'][$i]['date_str'] = Date::getDateTime($track['date']['uts'])->format(Date::FORMAT);
                 }
             } else {
                 $json['recenttracks']['track'][$i]['date_str'] = '';
             }
         }
         return $json;
     }), $options));
 }
Example #7
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));
 }
Example #8
0
 /**
  * @Route ("/admin/user/{userId}/ban/{id}/update")
  * @Secure ({"ADMIN"})
  * @HttpMethod ({"POST"})
  * @Transactional
  *
  * @param array $params
  */
 public function updateBan(array $params, ViewModel $model)
 {
     if (!isset($params['id']) || empty($params['id'])) {
         throw new Exception('id required');
     }
     if (!isset($params['userId']) || empty($params['userId'])) {
         throw new Exception('userId required');
     }
     $userService = UserService::instance();
     $authenticationService = AuthenticationService::instance();
     $eBan = $userService->getBanById($params['id']);
     $ban = array();
     $ban['id'] = $eBan['id'];
     $ban['reason'] = $params['reason'];
     $ban['userid'] = $eBan['userid'];
     $ban['ipaddress'] = $eBan['ipaddress'];
     $ban['targetuserid'] = $eBan['targetuserid'];
     $ban['starttimestamp'] = Date::getDateTime($params['starttimestamp'])->format('Y-m-d H:i:s');
     $ban['endtimestamp'] = '';
     if (!empty($params['endtimestamp'])) {
         $ban['endtimestamp'] = Date::getDateTime($params['endtimestamp'])->format('Y-m-d H:i:s');
     }
     $userService->updateBan($ban);
     $authenticationService->flagUserForUpdate($ban['targetuserid']);
     return 'redirect: /admin/user/' . $params['userId'] . '/ban/' . $params['id'] . '/edit';
 }
Example #9
0
		<div id="broadcasts" class="stream">
			<h3 class="title clearfix">
				<span>Broadcasts</span> <a href="http://www.twitch.tv/<?php 
echo Config::$a['twitch']['user'];
?>
/profile/pastBroadcasts" class="twitch-title">twitch.tv</a>
			</h3>
			<ul class="thumbnails">
			<?php 
if (isset($model->broadcasts) && !empty($model->broadcasts['videos'])) {
    ?>
			<?php 
    foreach ($model->broadcasts['videos'] as $broadcast) {
        ?>
				<?php 
        $time = Date::getElapsedTime(Date::getDateTime($broadcast['recorded_at']));
        ?>
				<li>
					<div class="thumbnail" data-placement="bottom" data-toggle="tooltip" title="<?php 
        echo $time;
        ?>
">
						<a href="<?php 
        echo $broadcast['url'];
        ?>
"> <img alt="<?php 
        echo $time;
        ?>
" src="<?php 
        echo Config::cdn();
        ?>
 /**
  * @Route ("/subscription/create")
  * @Secure ({"USER"})
  * @Transactional
  *
  * Create and send the order
  *
  * @param array $params
  */
 public function subscriptionCreate(array $params, ViewModel $model)
 {
     FilterParams::isRequired($params, 'subscription');
     $userService = UserService::instance();
     $subscriptionsService = SubscriptionsService::instance();
     $ordersService = OrdersService::instance();
     $payPalApiService = PayPalApiService::instance();
     $userId = Session::getCredentials()->getUserId();
     $subscriptionType = $subscriptionsService->getSubscriptionType($params['subscription']);
     $recurring = isset($params['renew']) && $params['renew'] == '1';
     $giftReceiverUsername = isset($params['gift']) && !empty($params['gift']) ? $params['gift'] : null;
     $giftReceiver = null;
     if (isset($params['sub-message']) and !empty($params['sub-message'])) {
         Session::set('subMessage', mb_substr($params['sub-message'], 0, 250));
     }
     try {
         if (!empty($giftReceiverUsername)) {
             // make sure the receiver is valid
             $giftReceiver = $userService->getUserByUsername($giftReceiverUsername);
             if (empty($giftReceiver)) {
                 throw new Exception('Invalid giftee (user not found)');
             }
             if ($userId == $giftReceiver['userId']) {
                 throw new Exception('Invalid giftee (cannot gift yourself)');
             }
             if (!$subscriptionsService->getCanUserReceiveGift($userId, $giftReceiver['userId'])) {
                 throw new Exception('Invalid giftee (user does not accept gifts)');
             }
         }
         // Create NEW order
         $order = $ordersService->createSubscriptionOrder($subscriptionType, $userId);
         // Create the subscription
         $start = Date::getDateTime();
         $end = Date::getDateTime();
         $end->modify('+' . $subscriptionType['billingFrequency'] . ' ' . strtolower($subscriptionType['billingPeriod']));
         $subscription = array('userId' => $userId, 'orderId' => $order['orderId'], 'subscriptionSource' => Config::$a['subscriptionType'], 'subscriptionType' => $subscriptionType['id'], 'subscriptionTier' => $subscriptionType['tier'], 'createdDate' => $start->format('Y-m-d H:i:s'), 'endDate' => $end->format('Y-m-d H:i:s'), 'recurring' => 0, 'status' => SubscriptionStatus::_NEW);
         // If this is a gift, change the user and the gifter
         if (!empty($giftReceiver)) {
             $subscription['userId'] = $giftReceiver['userId'];
             $subscription['gifter'] = $userId;
         }
         // Insert subscription
         $subscriptionId = $subscriptionsService->addSubscription($subscription);
         // Add payment profile
         $paymentProfile = null;
         if ($recurring) {
             $billingStartDate = Date::getDateTime(date('m/d/y'));
             $billingStartDate->modify('+' . $subscriptionType['billingFrequency'] . ' ' . strtolower($subscriptionType['billingPeriod']));
             $paymentProfile = $ordersService->createPaymentProfile($userId, $order, $subscriptionType, $billingStartDate);
         }
         $setECResponse = $payPalApiService->createECResponse('/subscription/process', $order, $subscriptionType, $recurring);
         if (empty($setECResponse) || $setECResponse->Ack != 'Success') {
             throw new Exception($setECResponse->Errors->ShortMessage);
         }
         return 'redirect: ' . Config::$a['paypal']['api']['endpoint'] . urlencode($setECResponse->Token);
     } catch (Exception $e) {
         if (!empty($order)) {
             $ordersService->updateOrderState($order['orderId'], OrderStatus::ERROR);
         }
         if (!empty($paymentProfile)) {
             $ordersService->updatePaymentStatus($paymentProfile['paymentId'], PaymentStatus::ERROR);
         }
         if (!empty($subscriptionId)) {
             $subscriptionsService->updateSubscriptionState($subscriptionId, SubscriptionStatus::ERROR);
         }
         $log = Application::instance()->getLogger();
         $log->error($e->getMessage(), $order);
         return 'redirect: /subscription/' . urlencode($order['orderId']) . '/error';
     }
 }
Example #11
0
 /**
  * Record the payments from a EC payment response
  * 
  * @param PayPalAPI\DoExpressCheckoutPaymentResponseType $DoECResponse
  * @param string $payerId
  * @param array $order
  * @return array
  */
 public function recordECPayments(DoExpressCheckoutPaymentResponseType $DoECResponse, $payerId, array &$order)
 {
     $payments = array();
     $orderService = OrdersService::instance();
     $orderStatus = OrderStatus::COMPLETED;
     for ($i = 0; $i < count($DoECResponse->DoExpressCheckoutPaymentResponseDetails->PaymentInfo); ++$i) {
         $paymentInfo = $DoECResponse->DoExpressCheckoutPaymentResponseDetails->PaymentInfo[$i];
         $payment = array();
         $payment['orderId'] = $order['orderId'];
         $payment['payerId'] = $payerId;
         $payment['amount'] = $paymentInfo->GrossAmount->value;
         $payment['currency'] = $paymentInfo->GrossAmount->currencyID;
         $payment['transactionId'] = $paymentInfo->TransactionID;
         $payment['transactionType'] = $paymentInfo->TransactionType;
         $payment['paymentType'] = $paymentInfo->PaymentType;
         $payment['paymentStatus'] = $paymentInfo->PaymentStatus;
         $payment['paymentDate'] = Date::getDateTime($paymentInfo->PaymentDate)->format('Y-m-d H:i:s');
         $orderService->addOrderPayment($payment);
         $payments[] = $payment;
         if ($paymentInfo->PaymentStatus != PaymentStatus::COMPLETED) {
             $orderStatus = OrderStatus::PENDING;
         }
     }
     $order['state'] = $orderStatus;
     return $order;
 }
Example #12
0
      <div class="content">

        <?php foreach ($model->gifts as $gift): ?>
        <div class="content-dark clearfix">
          <div class="ds-block">
            <div>

              <?php if($gift['recurring'] == 1): ?>
              <a class="btn btn-danger pull-right cancel-gift" href="/subscription/<?= $gift['subscriptionId'] ?>/cancel">Cancel</a>
              <?php endif; ?>

              <h3><?= Tpl::out( $gift['type']['tierLabel'] ) ?> <small>Gifted to <span class="label label-primary"><?= $gift['username'] ?></span></small></h3>
              <p>
                <span class="sub-amount">$<?=$gift['type']['amount']?></span> 
                <span>(<?=$gift['type']['billingFrequency']?> <?=strtolower($gift['type']['billingPeriod'])?><?php if($gift['recurring'] == 1): ?> recurring<?php endif; ?>)</span>
                <small>started on <?=Tpl::moment(Date::getDateTime($gift['createdDate']), Date::FORMAT)?></small>
              </p>
              
            </div>
          </div>
        </div>
        <?php endforeach; ?>

      </div>
    </section>
    <?php endif; ?>
    
    <section class="container collapsible">
      <h3><span class="fa fa-fw fa-chevron-right expander"></span> Account</h3>
      
      <div class="content content-dark clearfix">
Example #13
0
        echo Tpl::out($ban['banningusername']);
        ?>
 with reason: <?php 
        echo Tpl::out($ban['reason']);
        ?>
</td>
          <td><?php 
        echo Tpl::moment(Date::getDateTime($ban['starttimestamp']), Date::STRING_FORMAT);
        ?>
</td>
          <td>
            <?php 
        if (!$ban['endtimestamp']) {
            echo "Permanent";
        } else {
            echo Tpl::moment(Date::getDateTime($ban['endtimestamp']), Date::STRING_FORMAT);
        }
        ?>
          </td>
          <td><a class="btn btn-danger btn-xs" href="/admin/user/<?php 
        echo $ban['targetuserid'];
        ?>
/ban/remove?follow=<?php 
        echo rawurlencode($_SERVER['REQUEST_URI']);
        ?>
">Remove</a>
        </tr>
        <?php 
    }
    ?>
        </tbody>
Example #14
0
 /**
  * Returns the current userId of the remember me cookie
  * Also performs validation on the cookie and the record in the Db
  * Does not touch the DB unless there is a valid remember me cookie
  *
  * @return int false
  */
 public function getRememberMe()
 {
     $cookie = $this->getRememberMeCookie();
     if (!empty($cookie) && isset($cookie['created']) && isset($cookie['expire']) && isset($cookie['token'])) {
         $rememberMeService = RememberMeService::instance();
         $rememberMe = $rememberMeService->getRememberMe($cookie['token'], 'rememberme');
         if (!empty($rememberMe)) {
             try {
                 if (Date::getDateTime($rememberMe['createdDate']) != Date::getDateTime($cookie['created'])) {
                     throw new Exception('Token invalid [createdDate] does not match');
                 }
                 if (Date::getDateTime($rememberMe['expireDate']) != Date::getDateTime($cookie['expire'])) {
                     throw new Exception('Token invalid [expireDate] does not match');
                 }
                 if ($cookie['token'] != md5($rememberMe['userId'] . Date::getDateTime($rememberMe['createdDate'])->getTimestamp() . Date::getDateTime($rememberMe['expireDate'])->getTimestamp() . $this->remembermeSalt)) {
                     throw new Exception('Token invalid [token] does not match');
                 }
             } catch (Exception $e) {
                 $this->clearRememberMe($rememberMe['userId']);
                 Application::instance()->getLogger()->error(sprintf('Remember-me: %s', $e->getMessage()));
                 return false;
             }
             return $rememberMe['userId'];
         }
     }
     return false;
 }
Example #15
0
if (!empty($model->streamInfo)) {
    ?>
                    <?php 
    if (!isset($model->streamInfo['stream']) || empty($model->streamInfo['stream'])) {
        ?>
                    <span class="glyphicon glyphicon-time"></span> 
                    <span>Last broadcast ended <?php 
        echo Date::getElapsedTime(Date::getDateTime($model->streamInfo['lastbroadcast']));
        ?>
</span>
                    <?php 
    } else {
        ?>
                    <span class="glyphicon glyphicon-time"></span> 
                    <span>Started <?php 
        echo Date::getElapsedTime(Date::getDateTime($model->streamInfo['lastbroadcast']));
        ?>
</span>
                    <?php 
        if (intval($model->streamInfo['stream']['channel']['delay']) > 1) {
            ?>
                    - <?php 
            echo intval($model->streamInfo['stream']['channel']['delay']) / 60;
            ?>
m delay
                    <?php 
        }
        ?>
                    <?php 
    }
    ?>
Example #16
0
        echo $article['title'];
        ?>
</a>
						</div>
						<div>
							<?php 
        foreach ($article['categories'] as $categories) {
            ?>
							<span><small>Posted in</small> <?php 
            echo Tpl::out($categories['title']);
            ?>
</span>
							<?php 
        }
        ?>
						</div>
						<?php 
        echo Tpl::moment(Date::getDateTime($article['date']), Date::FORMAT);
        ?>
					</div>
				</div>
				<?php 
    }
    ?>
			</div>
		</div>

	</div>
</section>
<?php 
}
Example #17
0
function buildSubscribersTier(array $tier = null, $num)
{
    ?>
  <?php 
    if (!empty($tier)) {
        ?>
  <section class="container">
    <h3>T<?php 
        echo $num;
        ?>
 Subscribers</h3>
    <div class="content content-dark clearfix">
      <table class="grid">
        <thead>
          <tr>
            <td style="width: 20px;"></td>
            <td style="width: 200px;">User</td>
            <td style="width: 100px;">Recurring</td>
            <td style="width: 80px;">Created on</td>
            <td>Ends on</td>
          </tr>
        </thead>
        <tbody>
        <?php 
        $i = 1;
        ?>
        <?php 
        foreach ($tier as $sub) {
            ?>
        <tr>
          <td><?php 
            echo $i;
            ?>
</td>
          <td>
            <a href="/admin/user/<?php 
            echo $sub['userId'];
            ?>
/edit"><?php 
            echo Tpl::out($sub['username']);
            ?>
</a>
            <?php 
            if (!empty($sub['gifter'])) {
                ?>
              &nbsp; (<a title="Gifted by" href="/admin/user/<?php 
                echo $sub['gifter'];
                ?>
/edit"><span class="fa fa-gift" title="Gift"></span> <?php 
                echo Tpl::out($sub['gifterUsername']);
                ?>
</a>)
            <?php 
            }
            ?>
          </td>
          <td><?php 
            echo $sub['recurring'] == 1 ? 'Yes' : 'No';
            ?>
</td>
          <td><?php 
            echo Tpl::moment(Date::getDateTime($sub['createdDate']), Date::STRING_FORMAT);
            ?>
</td>
          <td><?php 
            echo Tpl::moment(Date::getDateTime($sub['endDate']), Date::STRING_FORMAT);
            ?>
</td>
        </tr>
        <?php 
            $i++;
        }
        ?>
        </tbody>
      </table>
    </div>
  </section>
  <?php 
    }
    ?>
  <?php 
}
Example #18
0
 /**
  * @param string $txnId
  * @param string $txnType
  * @param array $data
  * @throws Exception
  */
 protected function handleIPNTransaction($txnId, $txnType, array $data)
 {
     $log = Application::instance()->getLogger();
     $orderService = OrdersService::instance();
     $subscriptionsService = SubscriptionsService::instance();
     switch (strtoupper($txnType)) {
         // This is sent when a express checkout has been performed by a user
         // We need to handle the case where orders go through, but have pending payments.
         case 'EXPRESS_CHECKOUT':
             $payment = $orderService->getPaymentByTransactionId($txnId);
             if (!empty($payment)) {
                 // Make sure the payment values are the same
                 if (number_format($payment['amount'], 2) != number_format($data['mc_gross'], 2)) {
                     throw new Exception('Amount for payment do not match');
                 }
                 // Update the payment status
                 $orderService->updatePayment(array('paymentId' => $payment['paymentId'], 'paymentStatus' => $data['payment_status']));
                 // Update the subscription paymentStatus to active (may have been pending)
                 // TODO we set the paymentStatus to active without checking it because we get the opportunity to check it after subscription completion
                 $subscription = $subscriptionsService->getSubscriptionById($payment['subscriptionId']);
                 if (!empty($subscription)) {
                     $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'paymentStatus' => PaymentStatus::ACTIVE));
                 }
             } else {
                 $log->info(sprintf('Express checkout IPN called, but no payment found [%s]', $txnId));
             }
             break;
             // This is sent from paypal when a recurring payment is billed
         // This is sent from paypal when a recurring payment is billed
         case 'RECURRING_PAYMENT':
             if (!isset($data['payment_status'])) {
                 throw new Exception('Invalid payment status');
             }
             if (!isset($data['next_payment_date'])) {
                 throw new Exception('Invalid next_payment_date');
             }
             $nextPaymentDate = Date::getDateTime($data['next_payment_date']);
             $subscription = $this->getSubscriptionByPaymentProfileData($data);
             $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'billingNextDate' => $nextPaymentDate->format('Y-m-d H:i:s'), 'paymentStatus' => PaymentStatus::ACTIVE));
             $orderService->addPayment(array('subscriptionId' => $subscription['subscriptionId'], 'payerId' => $data['payer_id'], 'amount' => $data['mc_gross'], 'currency' => $data['mc_currency'], 'transactionId' => $txnId, 'transactionType' => $txnType, 'paymentType' => $data['payment_type'], 'paymentStatus' => $data['payment_status'], 'paymentDate' => Date::getDateTime($data['payment_date'])->format('Y-m-d H:i:s')));
             $log->notice(sprintf('Added order payment %s status %s', $data['recurring_payment_id'], $data['profile_status']));
             break;
         case 'RECURRING_PAYMENT_SKIPPED':
             $subscription = $this->getSubscriptionByPaymentProfileData($data);
             $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'paymentStatus' => PaymentStatus::SKIPPED));
             $log->debug(sprintf('Payment skipped %s', $data['recurring_payment_id']));
             break;
         case 'RECURRING_PAYMENT_PROFILE_CANCEL':
             $subscription = $this->getSubscriptionByPaymentProfileData($data);
             $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'paymentStatus' => PaymentStatus::CANCELLED));
             $log->debug(sprintf('Payment profile cancelled %s status %s', $data['recurring_payment_id'], $data['profile_status']));
             break;
         case 'RECURRING_PAYMENT_FAILED':
             $subscription = $this->getSubscriptionByPaymentProfileData($data);
             $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'paymentStatus' => PaymentStatus::FAILED));
             $log->debug(sprintf('Payment profile cancelled %s status %s', $data['recurring_payment_id'], $data['profile_status']));
             break;
             // Sent on first post-back when the user subscribes
         // Sent on first post-back when the user subscribes
         case 'RECURRING_PAYMENT_PROFILE_CREATED':
             $subscription = $this->getSubscriptionByPaymentProfileData($data);
             $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'paymentStatus' => PaymentStatus::ACTIVE));
             $log->debug(sprintf('Updated payment profile %s status %s', $data['recurring_payment_id'], $data['profile_status']));
             break;
     }
 }
Example #19
0
include Tpl::file('seg/google.tracker.php');
?>
</head>
<body id="agreement">

  <?php 
include Tpl::file('seg/top.php');
?>
  <?php 
include Tpl::file('seg/headerband.php');
?>
  
  <section class="container">
    <h1 class="title">
      <small class="subtle pull-right" style="font-size:14px; margin-top:20px;">Last update: <?php 
echo Date::getDateTime(filemtime(__FILE__))->format(Date::STRING_FORMAT);
?>
</small>
      <span>User agreement</span>
    </h1>
    <div class="content content-dark clearfix">
      <div class="ds-block">
        <p>There is no user agreement.</p>
      </div>
    </div>
  </section>
  
  <?php 
include Tpl::file('seg/panel.ads.php');
?>
  <?php 
Example #20
0
">
                                        <?php 
        echo Tpl::out($thread['othernick']);
        ?>
                                    </a>
                                    <span class="count">(<?php 
        echo $thread['count'];
        ?>
)</span>
                                </td>
                                <td class="message"><span><?php 
        echo Tpl::formatTextForDisplay($thread['message']);
        ?>
</span></td>
                                <td class="timestamp"><?php 
        echo Tpl::calendar(Date::getDateTime($thread['timestamp']));
        ?>
</td>
                            </tr>
                            <?php 
    }
    ?>
                        </tbody>
                    </table>
                    <?php 
} else {
    ?>
                    <table id="read" class="grid messages">
                        <tbody>
                            <tr>
                                <td><span class="subtle">You have no read messages</span></td>
Example #21
0
        foreach ($model->usersByIp as $user) {
            ?>
  				<tr>
  					<td><a href="/admin/user/<?php 
            echo $user['userId'];
            ?>
/edit"><?php 
            echo Tpl::out($user['username']);
            ?>
</a></td>
  					<td><?php 
            echo Tpl::out($user['email']);
            ?>
</td>
  					<td><?php 
            echo Tpl::moment(Date::getDateTime($user['createdDate']), Date::STRING_FORMAT_YEAR);
            ?>
</td>
  				</tr>
  			<?php 
        }
        ?>
  			</tbody>
  		</table>
		<?php 
    } else {
        ?>
  		<div class="ds-block">
  			<p>No users with the IP "<?php 
        echo Tpl::out($model->searchIp);
        ?>
Example #22
0
    echo Tpl::out($model->subscription['subscriptionSource']);
    ?>
</dd>
                <dt>Created date:</dt>
                <dd><?php 
    echo Tpl::moment(Date::getDateTime($model->subscription['createdDate']), Date::STRING_FORMAT_YEAR);
    ?>
</dd>
                <dt>End date:</dt>
                <dd><?php 
    echo Tpl::moment(Date::getDateTime($model->subscription['endDate']), Date::STRING_FORMAT_YEAR);
    ?>
</dd>
                <dt>Time remaining:</dt>
                <dd><?php 
    echo Date::getRemainingTime(Date::getDateTime($model->subscription['endDate']));
    ?>
</dd>

                <?php 
    if (!empty($model->giftee)) {
        ?>
                <dt>Gifted to:</dt>
                <dd><?php 
        echo Tpl::out($model->giftee['username']);
        ?>
</dd>
                <?php 
    }
    ?>
Example #23
0
                <div class="message-summary clearfix">
                    <span class="message-from">
                        <span alt="<?php 
    echo Tpl::out($msg['from']);
    ?>
"><?php 
    echo !$isme ? Tpl::out($msg['from']) : 'Me';
    ?>
</span>
                    </span>
                    <span class="message-snippet"><?php 
    echo Tpl::formatTextForDisplay($msg['message']);
    ?>
</span>
                    <span class="message-date"><?php 
    echo Tpl::calendar(Date::getDateTime($msg['timestamp']));
    ?>
</span>
                </div>
                <div class="speech-arrow"></div>
            </div>
            <?php 
}
?>
            <div class="clearfix"></div>
            <div class="message-reply content content-dark clearfix" style="">
                <div class="clearfix">
                    <span class="pull-left">
                        <a accesskey="r" id="reply-toggle" href="#reply" data-replyto="<?php 
echo Tpl::out($model->targetuser['username']);
?>
Example #24
0
 public static function fromNow(\DateTime $date, $format, $momentFormat = 'MMMM Do, h:mm:ss a, YYYY')
 {
     return sprintf('<time title="%s" data-moment="true" data-moment-fromnow="true" datetime="%s" data-format="%s">%s</time>', $date->format(Date::STRING_FORMAT), $date->format(Date::FORMAT), $momentFormat, Date::getElapsedTime($date));
 }
Example #25
0
 /**
  * @Route ("/profile/update")
  * @HttpMethod ({"POST"})
  * @Secure ({"USER"})
  *
  * @param array $params
  * @return string
  * @throws Exception
  * @throws \Doctrine\DBAL\DBALException
  * @throws \Exception
  */
 public function profileSave(array $params)
 {
     // Get user
     $userService = UserService::instance();
     $authenticationService = AuthenticationService::instance();
     $userId = Session::getCredentials()->getUserId();
     $user = $userService->getUserById($userId);
     if (empty($user)) {
         throw new Exception('Invalid user');
     }
     $username = isset($params['username']) && !empty($params['username']) ? $params['username'] : $user['username'];
     $email = isset($params['email']) && !empty($params['email']) ? $params['email'] : $user['email'];
     $country = isset($params['country']) && !empty($params['country']) ? $params['country'] : $user['country'];
     $allowGifting = isset($params['allowGifting']) ? $params['allowGifting'] : $user['allowGifting'];
     $minecraftname = isset($params['minecraftname']) && !empty($params['minecraftname']) ? $params['minecraftname'] : $user['minecraftname'];
     try {
         $authenticationService->validateUsername($username, $user);
         $authenticationService->validateEmail($email, $user);
         if (!empty($country)) {
             $countryArr = Country::getCountryByCode($country);
             if (empty($countryArr)) {
                 throw new Exception('Invalid country');
             }
             $country = $countryArr['alpha-2'];
         }
     } catch (Exception $e) {
         Session::set('modelError', $e->getMessage());
         return 'redirect: /profile';
     }
     // Date for update
     $userData = array('username' => $username, 'country' => $country, 'email' => $email, 'minecraftname' => $minecraftname, 'allowGifting' => $allowGifting);
     // Is the user changing their name?
     if (strcasecmp($username, $user['username']) !== 0) {
         $nameChangeCount = intval($user['nameChangedCount']);
         // have they hit their limit
         if ($nameChangeCount >= Config::$a['profile']['nameChangeLimit']) {
             throw new Exception('You have reached your name change limit');
         } else {
             $userData['nameChangedDate'] = Date::getDateTime('NOW')->format('Y-m-d H:i:s');
             $userData['nameChangedCount'] = $nameChangeCount + 1;
         }
     }
     try {
         // Update user
         $userService->updateUser($user['userId'], $userData);
     } catch (\Doctrine\DBAL\DBALException $e) {
         // get PDO exception, extract info
         $info = $e->getPrevious()->errorInfo;
         // a unique key constraint failure
         if ($info[0] === "23000") {
             // extract key name
             if (!preg_match("/^Duplicate entry '.+' for key '(.+)'\$/iu", $info[2], $match)) {
                 throw $e;
             }
             // WELL F**K I GUESS ITS NOT MYSQL
             $key = $match[1];
             $keyToField = array('minecraftname' => '"Minecraft name"');
             throw new Exception('Duplicate value for ' . $keyToField[$key]);
         }
     }
     $authenticationService->flagUserForUpdate($user['userId']);
     Session::set('modelSuccess', 'Your profile has been updated');
     return 'redirect: /profile';
 }
Example #26
0
echo Tpl::out('{"height":"500","width":"420"}');
?>
">Pop-out chat</a>
              <a target="_blank" href="http://www.twitch.tv/destiny/popout" class="popup btn btn-xs btn-link" data-options="<?php 
echo Tpl::out('{"height":"420","width":"720"}');
?>
">Pop-out stream</a>
            </div>
            <h1>Stream currently offline</h1>
            <div id="live-info">
              <span class="offline-status"><?php 
echo Tpl::out($model->streamInfo['status']);
?>
</span><br />
              Last broadcast ended <strong class="offline-info-lastbroadcast"><?php 
echo isset($model->streamInfo['lastbroadcast']) ? Date::getElapsedTime(Date::getDateTime($model->streamInfo['lastbroadcast'])) : '';
?>
</strong><br />
              Was playing <strong class="offline-info-game"><?php 
echo isset($model->streamInfo['game']) ? Tpl::out($model->streamInfo['game']) : '';
?>
</strong><br />
            </div>
            <a href="/bigscreen" class="btn btn-lg btn-primary">Join the chat while you wait!</a>
            <small>&nbsp; Prefer the old layout? <a href="/screen">Try this</a></small>
          </div>
        </div>
      </div>
    </div>
  </section>
 /**
  * @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
 /**
  * Handles the IPN message
  *
  * @param PPIPNMessage $ipnMessage
  */
 protected function handleIPNTransaction($txnId, $txnType, array $data)
 {
     $log = Application::instance()->getLogger();
     $orderService = OrdersService::instance();
     $subService = SubscriptionsService::instance();
     $authService = AuthenticationService::instance();
     switch (strtolower($txnType)) {
         // Post back from checkout, make sure the payment lines up
         // This is sent when a express checkout has been performed by a user
         case 'express_checkout':
             $payment = $orderService->getPaymentByTransactionId($txnId);
             if (!empty($payment)) {
                 // Make sure the payment values are the same
                 if (number_format($payment['amount'], 2) != number_format($data['mc_gross'], 2)) {
                     throw new Exception('Amount for payment do not match');
                 }
                 // Update the payment status
                 $orderService->updatePaymentStatus($payment['paymentId'], $data['payment_status']);
                 $log->notice(sprintf('Updated payment status %s status %s', $data['txn_id'], $data['payment_status']));
                 // If the payment status WAS PENDING, and the IPN payment status is COMPLETED
                 // Then we need to activate the attached subscription and complete the order
                 // This is for the ECHECK payment method
                 if (strcasecmp($payment['paymentStatus'], PaymentStatus::PENDING) === 0 && strcasecmp($data['payment_status'], PaymentStatus::COMPLETED) === 0) {
                     $order = $orderService->getOrderByPaymentId($payment['paymentId']);
                     if (!empty($order)) {
                         $orderService->updateOrderState($order['orderId'], OrderStatus::COMPLETED);
                         $log->debug(sprintf('Updated order status %s status %s', $order['orderId'], OrderStatus::COMPLETED));
                         $subscription = $subService->getUserPendingSubscription($order['userId']);
                         if (!empty($subscription)) {
                             $subService->updateSubscriptionState($subscription['subscriptionId'], SubscriptionStatus::ACTIVE);
                             $log->notice(sprintf('Updated subscription status %s status %s', $order['orderId'], SubscriptionStatus::ACTIVE));
                             $authService->flagUserForUpdate($subscription['userId']);
                         }
                     }
                 }
             } else {
                 $log->info(sprintf('Express checkout IPN called, but no payment found [%s]', $txnId));
             }
             break;
             // Recurring payment, renew subscriptions, or set to pending depending on the type
             // This is sent from paypal when a recurring payment is billed
         // Recurring payment, renew subscriptions, or set to pending depending on the type
         // This is sent from paypal when a recurring payment is billed
         case 'recurring_payment':
             if (!isset($data['payment_status'])) {
                 throw new Exception('Invalid payment status');
             }
             if (!isset($data['next_payment_date'])) {
                 throw new Exception('Invalid next_payment_date');
             }
             $paymentProfile = $this->getPaymentProfile($data);
             // We dont care about what state the sub is in....
             $subscription = $subService->getSubscriptionByOrderId($paymentProfile['orderId']);
             if (empty($subscription)) {
                 $log->critical('Invalid recurring_payment', $data);
                 throw new Exception('Invalid subscription for recurring payment');
             }
             if ($subscription['userId'] != $paymentProfile['userId'] && $subscription['gifter'] != $paymentProfile['userId']) {
                 throw new Exception(sprintf('Invalid subscription for user %s', $subscription['userId']));
             }
             $nextPaymentDate = Date::getDateTime($data['next_payment_date']);
             $orderService->updatePaymentProfileNextPayment($paymentProfile['profileId'], $nextPaymentDate);
             // Update the subscription end date regardless if the payment was successful or not
             // We dont actually know if paypal moves the automatic payment forward if one fails and is then manually processed
             $end = Date::getDateTime($subscription['endDate']);
             $end->modify('+' . $paymentProfile['billingFrequency'] . ' ' . strtolower($paymentProfile['billingPeriod']));
             // Update subscription end-date
             $subService->updateSubscriptionDateEnd($subscription['subscriptionId'], $end);
             $log->debug(sprintf('Update Subscription end date %s [%s]', $subscription['subscriptionId'], $end->format(Date::FORMAT)));
             // Change the subscription state depending on the payment state
             if (strcasecmp($data['payment_status'], PaymentStatus::PENDING) === 0) {
                 $subService->updateSubscriptionState($subscription['subscriptionId'], SubscriptionStatus::PENDING);
                 $log->debug(sprintf('Updated subscription state %s status %s', $subscription['subscriptionId'], SubscriptionStatus::PENDING));
             } else {
                 if (strcasecmp($data['payment_status'], PaymentStatus::COMPLETED) === 0) {
                     $subService->updateSubscriptionState($subscription['subscriptionId'], SubscriptionStatus::ACTIVE);
                     $log->debug(sprintf('Updated subscription %s status %s', $subscription['subscriptionId'], SubscriptionStatus::ACTIVE));
                 } else {
                     $log->notice(sprintf('Subscription status %s not changed for payment profile %s', $subscription['subscriptionId'], $paymentProfile['profileId']));
                 }
             }
             // Add a payment to the order
             $payment = array();
             $payment['orderId'] = $paymentProfile['orderId'];
             $payment['payerId'] = $data['payer_id'];
             $payment['amount'] = $data['mc_gross'];
             $payment['currency'] = $data['mc_currency'];
             $payment['transactionId'] = $txnId;
             $payment['transactionType'] = $txnType;
             $payment['paymentType'] = $data['payment_type'];
             $payment['paymentStatus'] = $data['payment_status'];
             $payment['paymentDate'] = Date::getDateTime($data['payment_date'])->format('Y-m-d H:i:s');
             $orderService->addOrderPayment($payment);
             $log->notice(sprintf('Added order payment %s status %s', $data['recurring_payment_id'], $data['profile_status']));
             $authService->flagUserForUpdate($subscription['userId']);
             break;
             // Sent if user cancels subscription from Paypal's site.
         // Sent if user cancels subscription from Paypal's site.
         case 'recurring_payment_profile_cancel':
             $paymentProfile = $this->getPaymentProfile($data);
             $orderService->updatePaymentProfileState($paymentProfile['profileId'], $data['profile_status']);
             $log->debug(sprintf('Payment profile cancelled %s status %s', $data['recurring_payment_id'], $data['profile_status']));
             break;
             // sent on first postback when the user subscribes
         // sent on first postback when the user subscribes
         case 'recurring_payment_profile_created':
             $paymentProfile = $this->getPaymentProfile($data);
             if (strcasecmp($data['profile_status'], 'Active') === 0) {
                 $data['profile_status'] = 'ActiveProfile';
             }
             $orderService->updatePaymentProfileState($paymentProfile['profileId'], $data['profile_status']);
             $log->debug(sprintf('Updated payment profile %s status %s', $data['recurring_payment_id'], $data['profile_status']));
             break;
     }
 }
Example #29
0
 /**
  * @param array $address
  */
 public function updateAddress(array $address)
 {
     $conn = Application::instance()->getConnection();
     $address['modifiedDate'] = Date::getDateTime('NOW')->format('Y-m-d H:i:s');
     $conn->update('users_address', $address, array('id' => $address['id']));
 }
 /**
  * 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;
 }