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; }
/** * @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]; }
/** * @param string $key * @param Tag $tag * * @throws InvalidTagException if the passed $value is not a Tag */ public function set($key, $tag) { if ($tag instanceof Tag) { throw InvalidTagException::build([], ['invalidTag' => $tag]); } parent::set($key, $tag); }
/** * Set cookie * * The second argument may be a single scalar value, in which case * it will be merged with the default settings and considered the `value` * of the merged result. * * The second argument may also be an array containing any or all of * the keys shown in the default settings above. This array will be * merged with the defaults shown above. * * @param string $key Cookie name * @param mixed $value Cookie settings */ public function set($key, $value) { if (is_array($value)) { $cookieSettings = array_replace($this->defaults, $value); } else { $cookieSettings = array_replace($this->defaults, array('value' => $value)); } parent::set($key, $cookieSettings); }
/** * Configure inversion of control/dependency injection container. * * @param \Slim\Helper\Set $container IOC container */ protected function configureIoc(\Slim\Helper\Set $container) { $container->singleton('i18nCache', function ($c) { return new JsonCache($c->settings['i18n.path'], $c->log); }); $container->singleton('i18nContext', function ($c) { return new I18nContext($c->i18nCache, $c->settings['i18n.default'], $c->log); }); $container->singleton('mailer', function ($c) { return new Mailer(array('Host' => $c->settings['smtp.host']), $c->log); }); $container->singleton('parsoid', function ($c) { return new ParsoidClient($c->settings['parsoid.url'], $c->settings['parsoid.cache'], $c->log); }); $container->singleton('quips', function ($c) { $settings = array('url' => $c->settings['es.url'], 'log' => true); if ($c->settings['es.user'] !== '') { $creds = base64_encode($c->settings['es.user'] . ':' . $c->settings['es.password']); $settings['headers'] = array('Authorization' => "Basic {$creds}"); } $client = new \Elastica\Client($settings); $client->setLogger($c->log); return new Quips($client, $c->log); }); $container->singleton('oauthConfig', function ($c) { $conf = new \MediaWiki\OAuthClient\ClientConfig($c->settings['oauth.endpoint']); $conf->setRedirURL($c->settings['oauth.redir']); $conf->setConsumer(new \MediaWiki\OAuthClient\Consumer($c->settings['oauth.consumer_token'], $c->settings['oauth.secret_token'])); return $conf; }); $container->singleton('oauthClient', function ($c) { $client = new \MediaWiki\OAuthClient\Client($c->oauthConfig, $c->log); $client->setCallback($c->settings['oauth.callback']); return $client; }); $container->singleton('userManager', function ($c) { return new OAuthUserManager($c->oauthClient, $c->log); }); $container->singleton('authManager', function ($c) { return new AuthManager($c->userManager); }); // TODO: figure out where to send logs }
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); }
/** * Render a template file * * NOTE: This method should be overridden by custom view subclasses * * @var string $template The template pathname, relative to the template base directory * @return string The rendered template * @throws \RuntimeException If resolved template pathname is not a valid file */ protected function render($template) { $templatePathname = $this->getTemplatePathname($template); if (!is_file($templatePathname)) { throw new \RuntimeException("View cannot render `{$template}` because the template does not exist"); } extract($this->data->all()); ob_start(); require $templatePathname; return ob_get_clean(); }
/** * Render a template file * * NOTE: This method should be overridden by custom view subclasses * * @param string $template The template pathname, relative to the template base directory * @param array $data Any additonal data to be passed to the template. * @return string The rendered template * @throws \RuntimeException If resolved template pathname is not a valid file */ protected function render($template, $data = null) { #echo $this->getTemplatePathname($template);die; $templatePathname = $this->getTemplatePathname($template); if (!is_file($templatePathname)) { throw new \RuntimeException("View cannot render `{$template}` because the template does not exist"); } $data = array_merge($this->data->all(), (array) $data); extract($data); ob_start(); require $templatePathname; return ob_get_clean(); }
/** * 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; }
/** * 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']; // } }
/** * Configure inversion of control/dependency injection container. * * @param \Slim\Helper\Set $container IOC container */ protected function configureIoc(\Slim\Helper\Set $container) { $container->singleton('i18nCache', function ($c) { return new JsonCache($c->settings['i18n.path'], $c->log); }); $container->singleton('i18nContext', function ($c) { return new I18nContext($c->i18nCache, $c->settings['i18n.default'], $c->log); }); $container->singleton('mailer', function ($c) { return new Mailer(['Host' => $c->settings['smtp.host']], $c->log); }); $container->singleton('parsoid', function ($c) { return new ParsoidClient($c->settings['parsoid.url'], $c->settings['parsoid.cache'], $c->log); }); $container->singleton('logs', function ($c) { return new Logs(new \Elastica\Client(['url' => $c->settings['es.url']]), $c->log); }); // TODO: figure out where to send logs }
/** * Construct. */ public function __construct($items = []) { parent::__construct($items); $this->setSlim(Slim::getInstance()); }
public function testConsumeSlimContainer() { $anoterContainer = new Set(); $anoterContainer->foo = []; $anoterContainer->bar = new \stdClass(); $anoterContainer->baz = function ($c) { return 'Hello'; }; $anoterContainer->singleton('foobar', function ($c) { return 'Hello'; }); $anoterContainer->barfoo = [$this, 'fakeMethod']; $this->container->consumeSlimContainer($anoterContainer); $this->assertTrue($this->sm->has('foo')); $this->assertTrue($this->container->has('foo')); $this->assertTrue($this->sm->has('bar')); $this->assertTrue($this->container->has('bar')); $this->assertTrue($this->sm->has('baz')); $this->assertTrue($this->container->has('baz')); $this->assertTrue($this->sm->has('foobar')); $this->assertTrue($this->container->has('foobar')); $this->assertTrue($this->sm->has('barfoo')); $this->assertTrue($this->container->has('barfoo')); }
/** * 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; }
function __construct($items = array()) { parent::__construct($items); $this->converted = false; }
// Database layer setup $app->hook('slim.before', function () use($app) { $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
/** * @param Set $container */ public function init(Set $container) { $this->add($container->get('slim.middleware.request_logging')); $this->add($container->get('slim.middleware.store_events')); }
public function init(Set $container) { $this->add(new FakeMiddleware($container->get('logger'))); }
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 __construct($items = array()) { @session_start(); $this->data =& $_SESSION; parent::__construct($items); }
/** * 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 __unset($name) { $this->container->remove($name); }
/** * @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 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; }
public function render($name, $data = array()) { $php = LightnCandy::compile($this->getTemplate($name), array('flags' => LightnCandy::FLAG_ERROR_EXCEPTION | LightnCandy::FLAG_ERROR_LOG | LightnCandy::FLAG_INSTANCE | LightnCandy::FLAG_MUSTACHE | LightnCandy::FLAG_HANDLEBARS, 'basedir' => $this->directories, 'fileext' => $this->extensions, 'helpers' => $this->helpers->all(), 'hbhelpers' => $this->block_helpers->all())); $renderer = LightnCandy::prepare($php); return $renderer(array_merge($data ?: array(), $this->all()), LCRun3::DEBUG_ERROR_LOG); }
/** * Constructor * @param array $userSettings Associative array of application settings */ public function __construct(array $userSettings = array()) { // Setup IoC container $this->container = new \Slim\Helper\Set(); $this->container['settings'] = array_merge(static::getDefaultSettings(), $userSettings); // Default environment $this->container->singleton('environment', function ($c) { return \Slim\Environment::getInstance(); }); // Default request $this->container->singleton('request', function ($c) { return new \Slim\Http\Request($c['environment']); }); // Default response $this->container->singleton('response', function ($c) { return new \Slim\Http\Response(); }); // Default router $this->container->singleton('router', function ($c) { return new \Slim\Router(); }); // Default view $this->container->singleton('view', function ($c) { $viewClass = $c['settings']['view']; return $viewClass instanceof \Slim\View ? $viewClass : new $viewClass(); }); // Default log writer $this->container->singleton('logWriter', function ($c) { $logWriter = $c['settings']['log.writer']; return is_object($logWriter) ? $logWriter : new \Slim\LogWriter($c['environment']['slim.errors']); }); // Default log $this->container->singleton('log', function ($c) { $log = new \Slim\Log($c['logWriter']); $log->setEnabled($c['settings']['log.enabled']); $log->setLevel($c['settings']['log.level']); $env = $c['environment']; $env['slim.log'] = $log; return $log; }); // Default mode $this->container['mode'] = function ($c) { $mode = $c['settings']['mode']; if (isset($_ENV['SLIM_MODE'])) { $mode = $_ENV['SLIM_MODE']; } else { $envMode = getenv('SLIM_MODE'); if ($envMode !== false) { $mode = $envMode; } } return $mode; }; // Define default middleware stack $this->middleware = array($this); $this->add(new \Slim\Middleware\Flash()); $this->add(new \Slim\Middleware\MethodOverride()); // Make default if first instance if (is_null(static::getInstance())) { $this->setName('default'); } }
function __construct(MvcContext $context) { parent::__construct($_SESSION); $this->context = $context; }
public function __construct(ServiceManager $sm = null) { parent::__construct(); $this->initServiceManager($sm); }
/** * 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; }