Example #1
0
 public function __construct()
 {
     $this->redis = new Redis();
     if (!$this->redis->connect(AppConfig::getValue('redis_socket'))) {
         AppController::fatalError('unable to connect to Redis server');
     }
 }
Example #2
0
 public function __get($property)
 {
     $property = toSnakeCase($property);
     // we couldn't find it, maybe it needs to be snake_case?
     if (property_exists($this, $property)) {
         return $this->{$property};
     } else {
         if (strcasecmp($property, 'id') === 0 && property_exists($this, $this->idField)) {
             // Allow the ID field to be referenced by either the proper name or a pseudo name...
             return $this->{$this->idField};
         } else {
             AppController::fatalError("access to undefined property ({$property}) on " . get_called_class());
         }
     }
 }
Example #3
0
 public function urlForAction($action, $args = null)
 {
     foreach ($this->route_list as $route) {
         if ($route->matchesAction($action)) {
             // Non-Default Port?
             $port = $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443 ? ':' . $_SERVER['SERVER_PORT'] : '';
             if ($args) {
                 return $this->request->protocol() . "://" . HOSTNAME . $port . $route->injectArgs($args);
             } else {
                 return $this->request->protocol() . "://" . HOSTNAME . $port . $route->url();
             }
         }
     }
     AppController::fatalError("URL not found for given Action: {$action}");
     // not found
 }
Example #4
0
 public static function stripHTML(&$input)
 {
     if (is_array($input)) {
         foreach ($input as $key => $value) {
             self::stripHTML($input[$key]);
         }
     } else {
         if (is_string($input)) {
             // Avoid JSON
             if (!json_decode($input, true)) {
                 $input = htmlspecialchars($input, ENT_QUOTES);
             }
         } else {
             if (is_object($input) && get_class($input) !== 'Alert') {
                 // allow alerts to pass through
                 AppController::fatalError('unsafe data (' . gettype($input) . ') passed to the HTMLView, use get_object_vars() for passing objects to convert them to arrays');
             }
         }
     }
 }
Example #5
0
 private function __construct()
 {
     if (($this->config_params = parse_ini_file(CONFIG_FILE)) === false) {
         AppController::fatalError('Failed to read/load APP_CONFIG_FILE (' . CONFIG_FILE . ') in ' . __METHOD__);
     }
 }
Example #6
0
/**
 * This function should be called at the beginning of all dynamically created classes where route URL or GET query arguments are required, it checks to see that all required arguments have been passed to the class.
 * This function should ONLY be used for testing routing/GET arguments as null values are considered missing and this may break other functionality!
 * The purpose of this function is to determine if a routing argument or GET parameter has been set, if either type of argument is missing it won't exist in the array,
 * if the argument is empty like the GET variable 'name' in "?name=&age" then the variable will be present and set with an empty string, this will evaluate to true with isset().
 * As this function will only be used on routing/GET arguments, no value will (should) ever be null, hence if somehow it is then we want the test to fail.
 */
function checkArgsExist($passed_args, $required_args)
{
    if (count($required_args) > 0) {
        if (!isset($passed_args)) {
            AppController::fatalError("All arguments were omitted, failed validation in validateArguments(), empty argument list.");
        }
        foreach ($required_args as $required_arg) {
            if (!isset($passed_args[$required_arg])) {
                AppController::fatalError("Arguments were omitted, failed validation in validateArguments().");
            }
        }
    }
}
Example #7
0
 /**
  * This function creates a session and inserts it into the database...
  * The attempt parameter is for use only from within this function for tracking recursion, don't use outside this function.
  * Volatile sessions are sessions which end when the user closes their browser, we can't always tell when the user closes their browser, so we have to limit how long we should assume they are active.
  * Users will opt out of persistent sessions but leave their browser open, if they still don't want to be remembered or they forgot to close it, then we should pretend to have forgot them...
  * We also want to make sure that they are the real user if we haven't heard from them in a while!
  */
 public function create($user_id, $persistent = false, $attempt = 1)
 {
     $now = Carbon::now();
     // set here, avoid multiple function calls
     $expires = $persistent ? Carbon::now()->addDays(self::PERSISTENT_SESSION_DAYS_TO_REMEMBER) : Carbon::now()->addHours(self::VOLATILE_SESSION_ALLOW_HOURS_INACTIVE);
     $id = hash("sha256", microtime());
     // nothing special required, just be unique
     // Create Data Array
     $data = array(':id' => $id, ':user_id' => $user_id, ':update_timestamp' => $now, ':expiry_timestamp' => $expires, ':persistent' => $persistent);
     $db = Database::getConnection();
     $query = $db->query("INSERT INTO " . self::TABLE_NAME . " " . Database::buildSQLInsertQuery($data), $data, ['23505']);
     // Check the Query Result (hopefully no duplicates)
     if ($query && $query->rowCount()) {
         $this->id = $id;
         // update with new ID
         /**
          * Warning: The current cookie variables (if set) contain the old session identifiers and any new SessionModel objects will pick up the old session, not the new one!
          * So, in order for any new SessionModel instantiations to detect our newly created session, we need to update the current session identifiers...
          * By setting the cookie internally to the new session ID, 
          * it means that any functions that look at the current session will see the cookie we're sending out with this request, not the one that came in.
          */
         $_COOKIE[self::COOKIE_NAME] = $id;
         // new ID
         // Set the Cookie
         setcookie(self::COOKIE_NAME, $id, $persistent ? $expires->timestamp : 0, '/', COOKIE_DOMAIN, RequestModel::currentRequest()->isHTTPS(), true);
         return true;
     } else {
         if ($query && $query->errorCode() == "23505") {
             // 23505 = duplicate key (hash)
             // Attempt to generate a key 3 times only!
             if ($attempt < 3) {
                 // Attempt Again...
                 $this->create($user_id, $persistent, ++$attempt);
             } else {
                 // We've used up all the recursion attempts, shouldn't have -- would be a pretty rare occurance! (another error somewhere?)
                 // The collision probability is miniscule, but requests of the same microtime() will yield a collision, let's just plan for it...
                 AppController::fatalError('All recursive attempts at generating a session ID have failed due to duplicate keys!');
             }
         }
     }
 }
Example #8
0
 public static function validateDirection($direction)
 {
     if (strtoupper($direction) != 'ASC' && strtoupper($direction) != 'DESC') {
         AppController::fatalError("direction {$direction} is invalid");
     }
     return $direction;
     // ok
 }
 public function payment()
 {
     $user = $this->session->user();
     if ($this->request->isPOST()) {
         $post = $this->request->postData();
         if (!empty($post['token'])) {
             try {
                 \Stripe\Stripe::setApiKey(AppConfig::getValue('stripe_secret_api_key'));
                 // New Customer?
                 if (!$user->isStripeCustomer()) {
                     $newCustomer = true;
                     // Create Customer
                     $customer = \Stripe\Customer::create(['email' => $user->email]);
                     $user->setStripeData(['customer_id' => $customer->id]);
                     $user->save();
                     // save now!
                 } else {
                     $newCustomer = false;
                     // Fetch Customer
                     $customer = $this->getCustomer($user);
                 }
                 // Add/Create Card
                 $customer->sources->create(['card' => $post['token']]);
                 // Done, Redirect...
                 AppController::redirect(addQueryParams(RouteController::fqURL($newCustomer ? 'subscription.plan' : 'subscription.payment'), ['status' => 'card-added']));
             } catch (\Stripe\Error\Card $exception) {
                 $this->logStripeException($exception, $user->email);
             } catch (\Stripe\Error\InvalidRequest $exception) {
                 $this->logStripeException($exception, $user->email);
             } catch (\Stripe\Error\Authentication $exception) {
                 $this->logStripeException($exception, $user->email);
             } catch (\Stripe\Error\ApiConnection $exception) {
                 $this->logStripeException($exception, $user->email);
             } catch (\Stripe\Error\Base $exception) {
                 $this->logStripeException($exception, $user->email);
             }
         } else {
             AppController::fatalError('token (required) was missing from the request');
         }
     } else {
         if ($this->request->isQueryArgSet('card') && $this->request->queryArgValue('action') === 'remove-card') {
             try {
                 \Stripe\Stripe::setApiKey(AppConfig::getValue('stripe_secret_api_key'));
                 // Fetch Customer and Cards
                 $customer = $this->getCustomer($user);
                 $cards = $this->getCardsOnFile($customer);
                 // Enough Cards? (backup)
                 if ($cards && count($cards['data']) > 1) {
                     // Remove Card
                     $customer->sources->retrieve($this->request->queryArgValue('card'))->delete();
                     // Done, Redirect...
                     AppController::redirect(addQueryParams(RouteController::fqURL('subscription.payment'), ['status' => 'card-removed']));
                 } else {
                     // Need to Add a Card First (or cancel subscription)
                     AppController::redirect(addQueryParams(RouteController::fqURL('subscription.payment'), ['status' => 'no-backup']));
                 }
             } catch (\Stripe\Error\Card $exception) {
                 $this->logStripeException($exception, $user->email);
             } catch (\Stripe\Error\InvalidRequest $exception) {
                 $this->logStripeException($exception, $user->email);
             } catch (\Stripe\Error\Authentication $exception) {
                 $this->logStripeException($exception, $user->email);
             } catch (\Stripe\Error\ApiConnection $exception) {
                 $this->logStripeException($exception, $user->email);
             } catch (\Stripe\Error\Base $exception) {
                 $this->logStripeException($exception, $user->email);
             }
         }
     }
     try {
         if (!isset($customer) && $user->isStripeCustomer()) {
             \Stripe\Stripe::setApiKey(AppConfig::getValue('stripe_secret_api_key'));
             $customer = $this->getCustomer($user);
             $cards = $this->getCardsOnFile($customer);
             foreach ($cards['data'] as $card) {
                 $cardList[] = ['id' => $card->id, 'last4' => $card->last4, 'brand' => $card->brand, 'expiry_month' => $card->exp_month, 'expiry_year' => $card->exp_year];
             }
         }
     } catch (\Stripe\Error\Card $exception) {
         $this->logStripeException($exception, $user->email);
     } catch (\Stripe\Error\InvalidRequest $exception) {
         $this->logStripeException($exception, $user->email);
     } catch (\Stripe\Error\Authentication $exception) {
         $this->logStripeException($exception, $user->email);
     } catch (\Stripe\Error\ApiConnection $exception) {
         $this->logStripeException($exception, $user->email);
     } catch (\Stripe\Error\Base $exception) {
         $this->logStripeException($exception, $user->email);
     }
     $this->view = new HTMLView();
     $this->view->includeTemplate('subscription.payment', ['app_name' => AppConfig::getValue('app_name'), 'cards' => isset($cardList) ? $cardList : null]);
     $this->view->render(true);
 }