/** * Display output as html using a header and footer. * * @param array $parameters Output parameters to display * @param $VIEWER_page $page Page's file name * @param $VIEWER_title Page's title */ public function view($parameters) { $num_args = func_num_args(); if ($num_args > 1) { $VIEWER_page = func_get_arg(1); } if ($num_args > 2) { $VIEWER_title = func_get_arg(2); } if (!isset($VIEWER_page) || !$VIEWER_page) { //In case page parameter is not set $VIEWER_page = 'error'; } //copy title if not set as funtion argument and set in parameters if ((!isset($VIEWER_title) || !$VIEWER_title) && isset($parameters['title'])) { $VIEWER_title = $parameters['title']; } elseif (!isset($VIEWER_title)) { $VIEWER_title = ''; } $parameters['base'] = \Phramework\Phramework::getSetting('base'); $parameters['VIEWER_title'] = $VIEWER_title; $parameters['VIEWER_page'] = $VIEWER_page; extract($parameters); include __DIR__ . '/header.php'; //Include the page file include __DIR__ . '/pages/' . $VIEWER_page . '.php'; include __DIR__ . '/footer.php'; }
/** * Database \Exception * * @todo Notify administrators * @param string $message \Exception message * @param string $error Internal error message */ public function __construct($message, $error = null) { if (\Phramework\Phramework::getSetting('debug') && $error) { parent::__construct($error, 500); } else { parent::__construct($message, 500); } }
/** * Get url of the API resource. * * This method uses `api_base` setting to create the url. * @param string $endpoint [Optional] * @param string $suffix [Optional] Will append to the end of url * @return string Returns the created url */ public static function url($endpoint = null, $suffix = '') { $base = Phramework::getSetting('base'); if ($endpoint) { $suffix = $endpoint . '/' . $suffix; $suffix = str_replace('//', '/', $suffix); } return $base . $suffix; }
/** * Protected constructor to prevent creating a new instance of the * *Singleton* via the `new` operator from outside of this class. */ protected function __construct() { try { if (!self::$instance && class_exists('Memcached')) { self::$instance = new \Memcached(); self::$instance->addServer('localhost', 11211); if ($prefix = \Phramework\Phramework::getSetting('cache_prefix')) { self::$prefix = $prefix; } } } catch (\Exception $e) { self::$instance = null; } }
/** * Send an e-mail * * @param string $address * @param string $subject * @param string $body * @param string $account *[Optional]*, Account name * @throws \Exception When email setting is not set */ public static function send($address, $subject, $body, $account = 'default') { $HTML = true; $accounts = \Phramework\Phramework::getSetting('email'); if (!$accounts || !isset($accounts['default'])) { throw new \Exception('email setting is required'); } if (!isset($accounts[$account])) { $account = 'default'; } $headers = []; $headers[] = "MIME-Version: 1.0" . "\r\n"; if (!$HTML) { $headers[] = 'Content-Type: text/plain;charset=utf-8' . "\r\n"; } else { $headers[] = 'Content-Type: text/html;charset=utf-8' . "\r\n"; } $headers[] = 'From: ' . $accounts[$account]['name'] . ' <' . $accounts[$account]['mail'] . '>' . "\r\n"; $headers[] = 'Reply-To: ' . $accounts[$account]['name'] . ' <' . $accounts[$account]['mail'] . "\r\n"; mail($address, $subject, $body, implode('', $headers), '-f' . $accounts[$account]['mail']); }
public static function prepare() { if (static::$adapter !== null) { return; } $dbSettings = \Phramework\Phramework::getSetting('query-log', 'database'); if (!$dbSettings) { throw new \Phramework\Exceptions\ServerException('query-log.database is not configured'); } if (is_array($dbSettings)) { $dbSettings = (object) $dbSettings; } $adapterNamespace = $dbSettings->adapter; $adapter = new $adapterNamespace((array) $dbSettings); if (!$adapter instanceof \Phramework\Database\IAdapter) { throw new \Exception(sprintf('Class "%s" is not implementing Phramework\\Database\\IAdapter', $adapterNamespace)); } if (isset($dbSettings->schema)) { static::$schema = $dbSettings->schema; } static::$table = isset($dbSettings->table) ? $dbSettings->table : 'query_log'; static::setAdapter($adapter); }
/** * Authenticate a user using JWT authentication method * @param array $params Request parameters * @param string $method Request method * @param array $headers Request headers * @return false|array Returns false on failure */ public function authenticate($params, $method, $headers) { //Require email and password set in params $validationModel = new \Phramework\Validate\ObjectValidator(['email' => new \Phramework\Validate\EmailValidator(3, 100), 'password' => new \Phramework\Validate\StringValidator(3, 128, null, true)], ['email', 'password']); $parsed = $validationModel->parse($params); $email = $parsed->email; $password = $parsed->password; //Get user object $user = call_user_func(Manager::getUserGetByEmailMethod(), $email); if (!$user) { return false; } // Verify user's password (password is stored as hash) if (!password_verify($password, $user['password'])) { return false; } $secret = Phramework::getSetting('jwt', 'secret'); $algorithm = Phramework::getSetting('jwt', 'algorithm'); $serverName = Phramework::getSetting('jwt', 'server'); $tokenId = base64_encode(\mcrypt_create_iv(32)); $issuedAt = time(); $notBefore = $issuedAt + Phramework::getSetting('jwt', 'nbf', 0); $expire = $notBefore + Phramework::getSetting('jwt', 'exp', 3600); /* * Create the token as an array */ $data = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'nbf' => $notBefore, 'exp' => $expire, 'data' => ['id' => $user['id']]]; //copy user attributes to jwt's data foreach (Manager::getAttributes() as $attribute) { if (!isset($user[$attribute])) { throw new \Phramework\Exceptions\ServerException(sprintf('Attribute "%s" is not set in user object', $attribute)); } $data['data'][$attribute] = $user[$attribute]; } $jwt = \Firebase\JWT\JWT::encode($data, $secret, $algorithm); //Call onAuthenticate callback if set if (($callback = Manager::getOnAuthenticateCallback()) !== null) { call_user_func($callback, (object) $data['data'], $jwt); } return [(object) $data['data'], $jwt]; }
/** * Type cast entry's attributes based on the provided model * * If any TYPE_UNIX_TIMESTAMP are present an additional attribute will * be included with the suffix _formatted, the format of the string can be * changed from timestamp_format setting. * @param array $entry * @param array $model * @return array Returns the typecasted entry * @deprecated since 1.1.0 */ public static function castEntry($entry, $model) { if (!$entry) { return $entry; } $timestamp_format = \Phramework\Phramework::getSetting('timestamp_format', null, 'Y-m-d\\TH:i:s\\Z'); //Repeat for each model's attribute of the entry. //$k holds the key of the attribute and $v the type foreach ($model as $k => $v) { if (!isset($entry[$k])) { continue; } //Typecast Filter::typecast($entry[$k], $v); //if type is a Validate::TYPE_UNIX_TIMESTAMP //then inject a string version of the timestamp to this entry if ($v === Validate::TYPE_UNIX_TIMESTAMP) { //offset included! $converted = gmdate($timestamp_format, $entry[$k]); //inject the string version of the timestamp $entry[$k . '_formatted'] = $converted; } } return $entry; }
/** * Invoke URIStrategy * @param object $requestParameters Request parameters * @param string $requestMethod HTTP request method * @param array $requestHeaders Request headers * @param object|false $requestUser Use object if successful * authenticated otherwise false * @throws Phramework\Exceptions\NotFoundException * @throws Phramework\Exceptions\UnauthorizedException * @throws Phramework\Exceptions\ServerException * @return string[2] This method should return `[$class, $method]` on success */ public function invoke(&$requestParameters, $requestMethod, $requestHeaders, $requestUser) { //Get controller from the request (URL parameter) if (!isset($requestParameters['controller']) || empty($requestParameters['controller'])) { if ($defaultController = Phramework::getSetting('default_controller')) { $requestParameters['controller'] = $defaultController; } else { throw new \Phramework\Exceptions\ServerException('Default controller has not been configured'); } } $controller = $requestParameters['controller']; unset($requestParameters['controller']); //Check if requested controller and method are allowed if (!in_array($controller, $this->controllerWhitelist)) { throw new NotFoundException('Method not found'); } elseif (!in_array($requestMethod, Phramework::$methodWhitelist)) { throw new \Phramework\Exceptions\MethodNotAllowedException('Method not found'); } //If not authenticated allow only certain controllers to access if (!$requestUser && !in_array($controller, $this->controllerUnauthenticatedWhitelist) && !in_array($controller, $this->controllerPublicWhitelist)) { throw new \Phramework\Exceptions\UnauthorizedException(); } // Append suffix $controller = $controller . ($this->suffix ? $this->suffix : ''); /** * Check if the requested controller and model is callable * In order to be callable : * 1) The controllers class must be defined as : myname_$suffix * 2) the methods must be defined as : public static function GET($requestParameters) * where $requestParameters are the passed parameters */ if (!is_callable($this->namespace . "{$controller}::{$requestMethod}")) { //Retry using capitalized first letter of the class $controller = ucfirst($controller); if (!is_callable($this->namespace . "{$controller}::{$requestMethod}")) { throw new NotFoundException('Method not found'); } } //Call handler method call_user_func([$this->namespace . $controller, $requestMethod], $requestParameters, $requestMethod, $requestHeaders); return [$controller, $requestMethod]; }