/** * Load settings from a file. * * @param string $location The location of the settings file. * @throws Settings\Exception */ private function loadFromLocation($location) { Logger::get()->debug('Loading settings...'); // Add the trailing slash to the folder if it is missing. if (substr($location, -1) != DIRECTORY_SEPARATOR) { $location .= DIRECTORY_SEPARATOR; } $settingsLocation = $location . 'settings.json'; if (!is_readable($settingsLocation)) { Logger::get()->error('Settings file %s cannot be read.', $settingsLocation); throw new Settings\Exception("Settings file {$settingsLocation} is unavailable."); } // Load the settings. $settings = json_decode(file_get_contents($settingsLocation), true); if (empty($settings)) { throw new Settings\Exception('Settings file cannot be parsed.'); } // Load settings customised for the current environment. $environmentSettings = null; $environment = self::getEnvironment(); if ($environment) { $environmentSettingsLocation = sprintf('%ssettings-%s.json', $location, strtolower($environment)); if (is_readable($environmentSettingsLocation)) { $environmentSettings = json_decode(file_get_contents($environmentSettingsLocation), true); if (!empty($environmentSettings)) { $settings = self::mergeSettings($settings, $environmentSettings); } } } $this->settings = self::objectify($settings); }
public function issue() { if ($this->nextUrl) { Logger::get()->debug("Redirecting to {$this->nextUrl}..."); $this->addHeader('Location', $this->nextUrl); } else { throw new \InvalidArgumentException('No redirection URL has been set.'); } parent::issue(); }
public function render() { $this->prepare(); if ($this->document) { // Output the page. echo $this->document; Logger::get()->debug(get_class($this) . ': medium has finished rendering.'); } else { throw new Exception('There is no document.'); } }
/** * Creates a new Dom document. * * @param type $source A file location or an XML string. * @param type $encoding the encoding of the resulting document. * @throws Dom\Exception */ public function __construct($source = null, $encoding = "UTF-8") { // Creation of the DOM document. try { $this->logger = Logger::get(); $this->domDocument = new \DOMDocument("1.0", $encoding); // If there is any source, get it into the document. if ($source) { if (is_array($source)) { throw new Dom\Exception("dom-cannot-use-array"); // It is not clear where arrayToXML is defined. Maybe it can be removed. // $this->document = $this->arrayToXML($source, $rootElement); } elseif (is_string($source)) { // If $source is a string, it can be a file or // an XML representation of a document. // If the source starts with a < character, // we can be pretty sure we are in front // of an XML string. If not, there is little // the library can do to parse it, so a filename // is assumed. if (strpos(trim($source), "<") === false) { if (is_readable($source)) { // If $source is a file location, try to load it. $this->fileName = $source; try { if ($this->domDocument->load($this->fileName)) { $this->logger->debug('Loaded XML document at ' . $this->fileName); } else { throw new Dom\Exception("dom-cannot-load-document-bad-file", array($this->fileName, "code" => 404)); } } catch (DOMException $exception) { $this->logger->error($exception->getMessage()); throw new Dom\Exception("dom-cannot-load-document", 404); } } else { $this->logger->warning('File cannot be read: ' . $source, LOG_WARNING); throw new Dom\Exception(sprintf('Cannot load document at %s (Current path: %s)', $source, realpath('.'))); } } else { if ($this->domDocument->loadHTML($source)) { $this->logger->debug('Loaded HTML document at ' . realpath($source)); $this->domDocument->normalize(); } else { throw new Dom\Exception('Cannot create DOM document from this source.'); } } } } } catch (\DOMException $exception) { $this->logger->error($exception->getMessage()); throw new Dom\Exception("dom-cannot-create-document"); } }
/** * Returns a responder that supports HTTP requests. * * @param HttpRequest $request the request to satisfy. */ private static function getHttpResponder(HttpRequest $request) { $responder = null; $responderClassName = $request->getResponderClassName(); if (class_exists($responderClassName)) { $responder = new $responderClassName($request); Logger::get()->debug("Responder '{$responderClassName}' is ready."); } else { throw new \Eix\Services\Net\Http\NotFoundException("'{$responderClassName}' responder not found."); } return $responder; }
/** * Makes sure the user is authenticated. If not, an exception is thrown. * @throws NotAuthenticatedException */ public function authenticate() { Logger::get()->debug('Authenticating OpenID user...'); if (!$this->isAuthenticated) { if (!static::getConsumer()->validate()) { Logger::get()->debug(' Failed!'); throw new NotAuthenticatedException('OpenID authentication failed.'); } else { $this->isAuthenticated = true; } } Logger::get()->debug(' OK!'); }
public function __construct($request = null) { if (!$request instanceof ErrorRequest) { throw new \InvalidArgumentException(sprintf("An error request is required for error responders: %s", get_class($request))); } parent::__construct($request); if ($request) { $throwable = @$request->getThrowable(); if ($throwable) { $this->setThrowable($throwable); Logger::get()->debug(sprintf('Error controller called because %s [%d].%s%s', lcfirst($throwable->getMessage()), $throwable->getCode(), PHP_EOL, $throwable->getTraceAsString())); } else { throw new Exception('The request does not carry an error or an exception.'); } } }
/** * Extracts the responder, action and parameter from an HTTP request. */ private function parsePath() { $components = array(); $uri = $this->getUri(); if ($uri !== false) { Logger::get()->debug('Parsing URI: ' . $uri); // Add the URL parameters. $components = $this->getHttpParameters(); $matched = false; foreach (self::getRoutes() as $route) { if (preg_match("#^{$route['uri']}\$#", $uri, $matches)) { Logger::get()->debug('Found a matching route: ' . $route['uri']); foreach ($route as $name => $value) { switch ($name) { case 'uri': // Ignore. break; default: if (is_numeric($value)) { // If the value is a number, it refers to a // regex block in the route. if (isset($matches[$value])) { $components[$name] = $matches[$value]; } } else { // Otherwise it's the parameter's value. $components[$name] = $value; } break; } } $matched = true; break; } } // If no matching routes have been found, the request is not // considered valid. if (!$matched) { throw new Exception("No routes match URI '{$uri}'.", 404); } } return $components; }
public function send() { if (is_array($this->messages)) { try { // Start communication. $this->connect(); $this->handshake(); $this->authenticate(); foreach ($this->messages as $message) { // Perform message-level checks. $sender = $message->getSender(); if ($sender) { $this->sendSender($sender); } else { throw new NoSenderException(); } $subject = $message->subject; if (trim($subject)) { $this->setHeader("Subject", $subject); } else { throw new NoSubjectException(); } $recipients = $message->getRecipients(); if (count($recipients) > 0) { $this->sendRecipients($recipients); } else { throw new NoRecipientsException(); } $this->sendData($message); Logger::get()->debug('A message has been sent to ' . implode(", ", array_keys($recipients))); } // End communication. $this->quit(); } catch (Exception $exception) { // Ensure communication is cut whatever the circumstances. $this->reset(); $this->quit(); throw $exception; } } else { throw new NoMessagesException(); } }
/** * Performs OpenID verification with the OP. * @return Bool Whether the verification was successful. * @throws \ErrorException */ public function validate() { # If the request was using immediate mode, a failure may be reported # by presenting user_setup_url (for 1.1) or reporting # mode 'setup_needed' (for 2.0). Also catching all modes other than # id_res, in order to avoid throwing errors. if (isset($this->data['openid_user_setup_url'])) { $this->setup_url = $this->data['openid_user_setup_url']; return false; } if ($this->mode != 'id_res') { Logger::get()->debug('OpenID validation failed: no id_res found.'); return false; } $this->claimed_id = isset($this->data['openid_claimed_id']) ? $this->data['openid_claimed_id'] : $this->data['openid_identity']; $params = array('openid.assoc_handle' => $this->data['openid_assoc_handle'], 'openid.signed' => $this->data['openid_signed'], 'openid.sig' => $this->data['openid_sig']); if (isset($this->data['openid_ns'])) { # We're dealing with an OpenID 2.0 server, so let's set an ns # Even though we should know location of the endpoint, # we still need to verify it by discovery, so $server is not set here $params['openid.ns'] = 'http://specs.openid.net/auth/2.0'; } elseif (isset($this->data['openid_claimed_id']) && $this->data['openid_claimed_id'] != $this->data['openid_identity']) { # If it's an OpenID 1 provider, and we've got claimed_id, # we have to append it to the returnUrl, like authUrl_v1 does. $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id; } if ($this->data['openid_return_to'] != $this->returnUrl) { # The return_to url must match the url of current request. # I'm assuing that noone will set the returnUrl to something that doesn't make sense. Logger::get()->debug(sprintf('OpenID validation failed: return URL (%s) does not match the current document\'s (%s).', $this->data['openid_return_to'], $this->returnUrl)); return false; } $server = $this->discover($this->claimed_id); foreach (explode(',', $this->data['openid_signed']) as $item) { # Checking whether magic_quotes_gpc is turned on, because # the function may fail if it is. For example, when fetching # AX namePerson, it might containg an apostrophe, which will be escaped. # In such case, validation would fail, since we'd send different data than OP # wants to verify. stripslashes() should solve that problem, but we can't # use it when magic_quotes is off. $value = $this->data['openid_' . str_replace('.', '_', $item)]; $params['openid.' . $item] = function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() ? stripslashes($value) : $value; } $params['openid.mode'] = 'check_authentication'; Logger::get()->debug('OpenID validation: checking authentication...'); $response = $this->request($server, 'POST', $params); $isValid = preg_match('/is_valid\\s*:\\s*true/i', $response); Logger::get()->debug(sprintf('OpenID validation: ' . ($isValid ? 'valid' : 'not valid'), $this->claimed_id)); return $isValid; }
/** * Stores the object in the persistence layer. */ public function store() { // Check whether the object has ever been stored. if ($this->isNew) { Logger::get()->debug('Storing new entity ' . get_class($this) . '...'); // Create the record. Get an ID back. $this->id = $this->getDataSource()->create($this->getFieldsData()); // Store this object in the appropriate factory for further use. $this->getFactory()->registerEntity($this); } else { Logger::get()->debug('Updating entity ' . get_class($this) . ":{$this->id}..."); $this->getDataSource()->update($this->id, $this->getFieldsData()); } // Once stored, the entity is no longer new. $this->isNew = false; }
/** * Returns a function name that represents the method and response's * expected content type. * * e.g. httpGetForHtml represents a GET request expecting HTML back. * e.g. httpPostForJson represents a POST request expecting JSON back. * e.g. httpPutForAll represents a PUT request expecting whatever back. */ private function getFunctionName($httpMethod) { if ($this->getRequest()) { $functionName = null; // Prefix starts with 'http'. $functionPrefix = 'http'; // The HTTP method is then appended. $functionPrefix .= ucfirst(strtolower($httpMethod)); // If an action has been captured in the URI, append it too. $action = $this->getRequest()->getParameter('action'); if ($action) { $functionPrefix .= ucfirst($action); // If there is an action, check whether the function is likely // to exist. if (!$this->isBaseFunctionAvailable($functionPrefix)) { throw new \Eix\Services\Net\Http\NotFoundException("This responder does not have any methods starting with {$functionPrefix}."); } } $found = false; $acceptedContentTypes = $this->getRequest()->getAcceptedContentTypes(); // Append a token to the function name, based on the requested content foreach ($acceptedContentTypes as $contentType => $quality) { try { $contentTypeToken = \Eix\Core\Requests\Http::getContentTypeToken($contentType); // Append the token for the response's expected content type. $functionName = $functionPrefix . 'For' . $contentTypeToken; Logger::get()->debug("Trying {$functionName} for {$contentType}..."); // Check whether a method with that name exists. if (method_exists($this, $functionName)) { return $functionName; } } catch (\InvalidArgumentException $exception) { // This content type is invalid, keep on checking. } } // Although a base method exists, it does not for this content type, // so that's a 406. throw new \Eix\Services\Net\Http\NotAcceptableException("This responder cannot serve content type {$contentType}."); } else { // If there is no request, return the generic responder method. return 'httpGetForAll'; } }
/** * Flag the user as no longer in existence, so that it does not * automatically get saved in the session. */ public function destroy() { parent::destroy(); Logger::get()->debug('Destroying user ' . $this->id); // If this user is the one stored in the session, destroy that too. if (!empty($_SESSION) && $_SESSION['current_user'] == $this) { unset($_SESSION['current_user']); } }
public function destroy($id) { self::normaliseId($id); $result = $this->collection->remove(array('_id' => $id)); Logger::get()->debug("Deleted record {$id}."); return true; }
/** * Drops the selected entity from memory. */ public function unregisterEntity(Entity $entity) { Logger::get()->debug('Dropping entity ' . get_class($entity) . ":{$entity->id}..."); unset(self::$entities[get_called_class()][$entity->id]); Logger::get()->debug('Dropped.'); }
public function __construct(HttpRequest $request = null) { Logger::get()->debug('Using HTTP response ' . get_class($this)); $this->request = $request; }
public function destroy($id) { Logger::get()->debug("Deleting image {$id}..."); unlink($this->getAssetLocation($id)); Logger::get()->debug('Deleted.'); return true; }
public function read() { $data = ""; // Checks if there is something in the buffer, so a call // to read with an empty buffer does not block. $bufferLength = @socket_recvfrom($this->socket, $buffer, $this->bufferSize, 2, $this->host, $this->port); // If there is, retrieve it. if ($bufferLength > 0) { socket_recv($this->socket, $data, $bufferLength, 0); if ($data === false) { Logger::get()->error(socket_strerror(socket_last_error())); throw new Exception('Socket read error: ' . socket_strerror(socket_last_error())); } } Logger::get()->debug("[From socket] {$data}"); return $data; }
/** * Use the specified identity provider to establish an authenticated * user. */ public static function getFromIdentityProvider(Provider $identityProvider) { // Have the identity provider authenticate the current identity. $identityProvider->authenticate(); // The identity is valid according to the provider, so authentication is // passed. $userId = $identityProvider->getUserId(); // Check for authorisation. try { Logger::get()->debug(sprintf('Checking OpenID user %s...', $userId)); $user = Users::getInstance()->findEntity($userId); // The user is valid according to our records. Keep it in the session. $user->authenticate($identityProvider); } catch (NotFoundException $exception) { Logger::get()->warning(sprintf('OpenID user %s is not known.', $userId)); throw new NotAuthorisedException('OpenID user is not authorised.'); } return $user; }
/** * Prepares the document by merging * the template and the data. */ protected function prepare() { // Set data into dataDocument structure; if (is_array($this->data)) { foreach ($this->data as $key => $value) { $this->addData($key, $value); } } Logger::get()->debug("Response data:\n" . $this->dataDocument->toString(false)); // Merge data with template. $this->document = $this->dataDocument->transform($this->getTemplate()); }
/** * Keeps the currently requested URL, to be able to retrieve it at a later * point. */ private function keepCurrentLocator(Request $request) { // Ensure a location is not already set, to avoid overwriting it. if (!@$_COOKIE[self::LOCATOR_COOKIE_NAME]) { $currentUrl = $request->getCurrentUrl(); // Do not keep identity URLs. if (!preg_match('#/identity.+#', $currentUrl)) { setcookie(self::LOCATOR_COOKIE_NAME, $currentUrl, time() + 300); Logger::get()->debug('Current locator stored: ' . $currentUrl); } } }