/** * @param string $key The data key * @param mixed $default The value to return if data key does not exist * @return mixed The data value, or the default value */ public function get($key, $default = null) { if ($value = parent::get($key, $default)) { return $value; } return $this->pimple[$key]; }
public function get() { $request = $this->getSlim()->request(); // Check authentication $this->getSlim()->auth->checkPermission('attachments'); $params = new Set($request->get()); if (!$params->has('sha2')) { throw new \Exception('Missing sha2 parameter!', Resource::STATUS_BAD_REQUEST); } $sha2 = $params->get('sha2'); $encoding = $params->get('encoding'); // Fetch attachment metadata and data $metadata = $this->attachmentService->fetchMetadataBySha2($sha2); $data = $this->attachmentService->fetchFileBySha2($sha2); if ($encoding !== 'binary') { $data = base64_encode($data); } $this->getSlim()->response->headers->set('Content-Type', $metadata->getContentType()); Resource::response(Resource::STATUS_OK, $data); }
public function renderGet() { $agent = new Set($this->agent); $object = ['objectType' => 'Person']; if ($agent->has('name')) { $object['name'] = [$agent->get('name')]; } if ($agent->has('mbox')) { $object['mbox'] = [$agent->get('mbox')]; } if ($agent->has('mbox_sha1sum')) { $object['mbox_sha1sum'] = [$agent->get('mbox_sha1sum')]; } if ($agent->has('openid')) { $object['openid'] = [$agent->get('openid')]; } if ($agent->has('account')) { $object['account'] = [$agent->get('account')]; } return $object; }
public function get() { $request = $this->getSlim()->request(); // Check authentication $this->getSlim()->auth->checkPermission('profile'); // TODO: Validation. $params = new Set($request->get()); $agent = $params->get('agent'); $agent = json_decode($agent, true); $view = new AgentView(['agent' => $agent]); $view = $view->renderGet(); Resource::jsonResponse(Resource::STATUS_OK, $view); }
/** * Fetches activity profiles according to the given parameters. * * @param array $request The incoming HTTP request * * @return array An array of activityProfile objects. */ public function activityGet($request) { $params = new Set($request->get()); $collection = $this->getDocumentManager()->getCollection('activities'); $cursor = $collection->find(); $cursor->where('id', $params->get('activityId')); if ($cursor->count() === 0) { throw new Exception('Activity does not exist.', Resource::STATUS_NOT_FOUND); } $this->cursor = $cursor; $this->single = true; return $this; }
/** * Fetch COOKIE data * * This method returns a key-value array of Cookie data sent in the HTTP request, or * the value of a array key if requested; if the array key does not exist, NULL is returned. * * @param string $key * @return array|string|null */ public function cookies($key = null) { if ($key) { return $this->cookies->get($key); } return $this->cookies; // if (!isset($this->env['slim.request.cookie_hash'])) { // $cookieHeader = isset($this->env['COOKIE']) ? $this->env['COOKIE'] : ''; // $this->env['slim.request.cookie_hash'] = Util::parseCookieHeader($cookieHeader); // } // if ($key) { // if (isset($this->env['slim.request.cookie_hash'][$key])) { // return $this->env['slim.request.cookie_hash'][$key]; // } else { // return null; // } // } else { // return $this->env['slim.request.cookie_hash']; // } }
/** * Logs the user in. * * @return \API\Document\User The user document */ public function loginPost($request) { $params = new Set($request->post()); // CSRF protection if (!$params->has('csrfToken') || !isset($_SESSION['csrfToken']) || $params->get('csrfToken') !== $_SESSION['csrfToken']) { throw new \Exception('Invalid CSRF token.', Resource::STATUS_BAD_REQUEST); } // This could be in JSON schema as well :) if (!$params->has('email') || !$params->has('password')) { throw new \Exception('Username or password missing!', Resource::STATUS_BAD_REQUEST); } $collection = $this->getDocumentManager()->getCollection('users'); $cursor = $collection->find(); $cursor->where('email', $params->get('email')); $cursor->where('passwordHash', sha1($params->get('password'))); $document = $cursor->current(); if (null === $document) { $errorMessage = 'Invalid login attempt. Try again!'; $this->errors[] = $errorMessage; throw new \Exception($errorMessage, Resource::STATUS_UNAUTHORIZED); } $this->single = true; $this->users = [$document]; // Set the session $_SESSION['userId'] = $document->getId(); $_SESSION['expiresAt'] = time() + 3600; //1 hour // Set the Remember me cookie $rememberMeStorage = new RemembermeMongoStorage($this->getDocumentManager()); $rememberMe = new Rememberme\Authenticator($rememberMeStorage); if ($params->has('rememberMe')) { $rememberMe->createCookie($document->getId()); } else { $rememberMe->clearCookie(); } return $document; }
public function __get($name) { return $this->container->get($name); }
/** * Tries to delete an access token. */ public function accessTokenDelete($request) { $params = new Set($request->get()); $this->deleteToken($params->get('key'), $params->get('secret')); return $this; }
/** * Fetches activity states according to the given parameters. * * @param array $request The incoming HTTP request * * @return self Nothing. */ public function activityProfileDelete($request) { $params = new Set($request->get()); $collection = $this->getDocumentManager()->getCollection('activityProfiles'); $cursor = $collection->find(); $cursor->where('profileId', $params->get('profileId')); $cursor->where('activityId', $params->get('activityId')); $result = $cursor->findOne(); if (!$result) { throw new \Exception('Profile does not exist!.', Resource::STATUS_NOT_FOUND); } // Check If-Match and If-None-Match here - these SHOULD* exist, but they do not have to // See https://github.com/adlnet/xAPI-Spec/blob/1.0.3/xAPI.md#lrs-requirements-7 // if (!$request->headers('If-Match') && !$request->headers('If-None-Match') && $result) { // throw new \Exception('There was a conflict. Check the current state of the resource and set the "If-Match" header with the current ETag to resolve the conflict.', Resource::STATUS_CONFLICT); // } // If-Match first if ($request->headers('If-Match') && $result && $this->trimHeader($request->headers('If-Match')) !== $result->getHash()) { throw new \Exception('If-Match header doesn\'t match the current ETag.', Resource::STATUS_PRECONDITION_FAILED); } // Then If-None-Match if ($request->headers('If-None-Match')) { if ($this->trimHeader($request->headers('If-None-Match')) === '*' && $result) { throw new \Exception('If-None-Match header is *, but a resource already exists.', Resource::STATUS_PRECONDITION_FAILED); } elseif ($result && $this->trimHeader($request->headers('If-None-Match')) === $result->getHash()) { throw new \Exception('If-None-Match header matches the current ETag.', Resource::STATUS_PRECONDITION_FAILED); } } // Add to log $this->getSlim()->requestLog->addRelation('activityProfiles', $result)->save(); $result->delete(); return $this; }
$app->container->singleton('mongo', function () use($app) { $client = new Client($app->config('database')['host_uri']); $client->map([$app->config('database')['db_name'] => '\\API\\Collection']); $client->useDatabase($app->config('database')['db_name']); return $client; }); }); // CORS compatibility layer (Internet Explorer) $app->hook('slim.before.router', function () use($app) { if ($app->request->isPost() && $app->request->get('method')) { $method = $app->request->get('method'); $app->environment()['REQUEST_METHOD'] = strtoupper($method); mb_parse_str($app->request->getBody(), $postData); $parameters = new Set($postData); if ($parameters->has('content')) { $content = $parameters->get('content'); $app->environment()['slim.input'] = $content; $parameters->remove('content'); } else { // Content is the only valid body parameter...everything else are either headers or query parameters $app->environment()['slim.input'] = ''; } $app->request->headers->replace($parameters->all()); $app->environment()['slim.request.query_hash'] = $parameters->all(); } }); // Parse version $app->hook('slim.before.dispatch', function () use($app) { // Version $app->container->singleton('version', function () use($app) { if ($app->request->isOptions() || $app->request->getPathInfo() === '/about' || strpos(strtolower($app->request->getPathInfo()), '/oauth') === 0) {
/** * @param string $key * @param null $default * * @return Tag */ public function get($key, $default = null) { return parent::get($key, $default); }
/** * Tries to PUT a statement with a specified statementId. * * @return */ public function statementPut($request) { // Check for multipart request if ($request->isMultipart()) { $jsonRequest = $request->parts()->get(0); } else { $jsonRequest = $request; } // Validation has been completed already - everyhing is assumed to be valid (from an external view!) // TODO: Move header validation in json-schema as well if ($jsonRequest->getMediaType() !== 'application/json') { throw new \Exception('Media type specified in Content-Type header must be \'application/json\'!', Resource::STATUS_BAD_REQUEST); } // Validation has been completed already - everyhing is assumed to be valid $body = $jsonRequest->getBody(); $body = json_decode($body, true); // Some clients escape the JSON - handle them if (is_string($body)) { $body = json_decode($body, true); } // Save attachments - this could be in a queue perhaps... if ($request->isMultipart()) { $fsAdapter = \API\Util\Filesystem::generateAdapter($this->getSlim()->config('filesystem')); $attachmentCollection = $this->getDocumentManager()->getCollection('attachments'); $partCount = $request->parts()->count(); for ($i = 1; $i < $partCount; $i++) { $part = $request->parts()->get($i); $attachmentBody = $part->getBody(); $detectedEncoding = mb_detect_encoding($attachmentBody); $contentEncoding = $part->headers('Content-Transfer-Encoding'); if ($detectedEncoding === 'UTF-8' && ($contentEncoding === null || $contentEncoding === 'binary')) { try { $attachmentBody = iconv('UTF-8', 'ISO-8859-1//IGNORE', $attachmentBody); } catch (\Exception $e) { //Use raw file on failed conversion (do nothing!) } } $hash = $part->headers('X-Experience-API-Hash'); $contentType = $part->headers('Content-Type'); $attachmentDocument = $attachmentCollection->createDocument(); $attachmentDocument->setSha2($hash); $attachmentDocument->setContentType($contentType); $attachmentDocument->setTimestamp(new MongoDate()); $attachmentDocument->save(); $fsAdapter->put($hash, $attachmentBody); } } $attachmentBase = $this->getSlim()->url->getBaseUrl() . $this->getSlim()->config('filesystem')['exposed_url']; // Single $params = new Set($request->get()); $activityCollection = $this->getDocumentManager()->getCollection('activities'); $collection = $this->getDocumentManager()->getCollection('statements'); $cursor = $collection->find(); // Single statement $cursor->where('statement.id', $params->get('statementId')); $result = $cursor->findOne(); // ID exists, check if different or conflict if ($result) { // Same - return 204 No content if ($body === $result) { $this->match = true; } else { // Mismatch - return 409 Conflict throw new Exception('An existing statement already exists with the same ID and is different from the one provided.', Resource::STATUS_CONFLICT); } } else { // Store new statement $statementDocument = $collection->createDocument(); // Overwrite authority - unless it's a super token and manual authority is set if (!($this->getAccessToken()->isSuperToken() && isset($statement['authority'])) || !isset($statement['authority'])) { $statement['authority'] = $this->getAccessToken()->generateAuthority(); } // Check statementId if (isset($body['id'])) { //Check for match if ($body['id'] !== $params->get('statementId')) { throw new \Exception('Statement ID query parameter doesn\'t match the given statement property', Resource::STATUS_BAD_REQUEST); } } else { $body['id'] = $params->get('statementId'); } // Set the statement $statementDocument->setStatement($body); // Dates $currentDate = new \DateTime(); $statementDocument->setStored(Util\Date::dateTimeToISO8601($currentDate)); $statementDocument->setMongoTimestamp(Util\Date::dateTimeToMongoDate($currentDate)); $statementDocument->setDefaultTimestamp(); $statementDocument->fixAttachmentLinks($attachmentBase); if ($statementDocument->isReferencing()) { // Copy values of referenced statement chain inside current statement for faster query-ing // (space-time tradeoff) $referencedStatement = $statementDocument->getReferencedStatement(); $existingReferences = []; if (null !== $referencedStatement->getReferences()) { $existingReferences = $referencedStatement->getReferences(); } $statementDocument->setReferences(array_push($existingReferences, $referencedStatement->getStatement())); } if ($statementDocument->isVoiding()) { $referencedStatement = $statementDocument->getReferencedStatement(); $referencedStatement->setVoided(true); $referencedStatement->save(); } if ($this->getAccessToken()->hasPermission('define')) { $activities = $statementDocument->extractActivities(); if (count($activities) > 0) { $activityCollection->insertMultiple($activities); } } $statementDocument->save(); // Add to log $this->getSlim()->requestLog->addRelation('statements', $statementDocument)->save(); $this->single = true; $this->statements = [$statementDocument]; } return $this; }
public function init(Set $container) { $this->add(new FakeMiddleware($container->get('logger'))); }
/** * @param Set $container */ public function init(Set $container) { $this->add($container->get('slim.middleware.request_logging')); $this->add($container->get('slim.middleware.store_events')); }
/** * Return view data value with key * @param string $key * @return mixed */ public function get($key) { return $this->data->get($key); }
/** * @param [type] $request [description] * * @return [type] [description] */ public function accessTokenPost($request) { $params = new Set($request->post()); $requiredParams = ['grant_type', 'client_id', 'client_secret', 'redirect_uri', 'code']; //TODO: Use json-schema validator foreach ($requiredParams as $requiredParam) { if (!$params->has($requiredParam)) { throw new \Exception('Parameter ' . $requiredParam . ' is missing!', Resource::STATUS_BAD_REQUEST); } } if ($params->get('grant_type') !== 'authorization_code') { throw new \Exception('Invalid grant_type specified.', Resource::STATUS_BAD_REQUEST); } $collection = $this->getDocumentManager()->getCollection('oAuthTokens'); $cursor = $collection->find(); $cursor->where('code', $params->get('code')); $tokenDocument = $cursor->current(); if (null === $tokenDocument) { throw new \Exception('Invalid code specified!', Resource::STATUS_BAD_REQUEST); } $clientDocument = $tokenDocument->client; if ($clientDocument->getClientId() !== $params->get('client_id') || $clientDocument->getSecret() !== $params->get('client_secret')) { throw new \Exception('Invalid client_id/client_secret combination!', Resource::STATUS_BAD_REQUEST); } if ($params->get('redirect_uri') !== $clientDocument->getRedirectUri()) { throw new \Exception('Redirect_uri mismatch!', Resource::STATUS_BAD_REQUEST); } //Remove one-time code $tokenDocument->setCode(false); $tokenDocument->save(); $this->accessTokens = [$tokenDocument]; $this->single = true; return $tokenDocument; }
/** * Fetches activity states according to the given parameters. * * @param array $request The incoming HTTP request * * @return array An array of statement objects. */ public function activityStateDelete($request) { $params = new Set($request->get()); $collection = $this->getDocumentManager()->getCollection('activityStates'); $expression = $collection->expression(); if ($params->has('stateId')) { $expression->where('stateId', $params->get('stateId')); } $expression->where('activityId', $params->get('activityId')); $agent = $params->get('agent'); $agent = json_decode($agent, true); //Fetch the identifier - otherwise we'd have to order the JSON if (isset($agent['mbox'])) { $uniqueIdentifier = 'mbox'; } elseif (isset($agent['mbox_sha1sum'])) { $uniqueIdentifier = 'mbox_sha1sum'; } elseif (isset($agent['openid'])) { $uniqueIdentifier = 'openid'; } elseif (isset($agent['account'])) { $uniqueIdentifier = 'account'; } else { throw new Exception('Invalid request!', Resource::STATUS_BAD_REQUEST); } $expression->where('agent.' . $uniqueIdentifier, $agent[$uniqueIdentifier]); if ($params->has('registration')) { $expression->where('registration', $params->get('registration')); } $collection->deleteDocuments($expression); return $this; }