_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q249400
User.getIsStatus
validation
public function getIsStatus() { switch ($this->status) { case User::STATUS_PENDING: return '<div class="text-center"><span class="text-primary">Pending</span></div>'; case User::STATUS_ACTIVE: return '<div class="text-center"><span class="text-success">Active</span></div>'; case User::STATUS_BLOCKED: return '<div class="text-center"><span class="text-danger">Blocked</span></div>'; } return NULL; }
php
{ "resource": "" }
q249401
User.confirm
validation
public function confirm() { $this->status = User::STATUS_ACTIVE; if ($this->save(FALSE)) return TRUE; return FALSE; }
php
{ "resource": "" }
q249402
User.block
validation
public function block() { $this->status = User::STATUS_BLOCKED; if ($this->save(FALSE)) return TRUE; return FALSE; }
php
{ "resource": "" }
q249403
User.unblock
validation
public function unblock() { $this->status = User::STATUS_ACTIVE; if ($this->save(FALSE)) return TRUE; return FALSE; }
php
{ "resource": "" }
q249404
Plugin.register
validation
static public function register() { // only register once if (static::$registered === true) { return true; } $kirby = kirby(); if (!class_exists('Kirby\Component\Template')) { throw new Exception('The Kirby Twig plugin requires Kirby 2.3 or higher. Current version: ' . $kirby->version()); } if (!class_exists('Twig_Environment')) { require_once __DIR__.'/../lib/Twig/lib/Twig/Autoloader.php'; \Twig_Autoloader::register(); } $kirby->set('component', 'template', 'Kirby\Twig\TwigComponent'); if (is_executable('twig') === false) { require_once __DIR__ . '/helpers.php'; } return static::$registered = true; }
php
{ "resource": "" }
q249405
Plugin.render
validation
static public function render($template, $userData) { if (!is_string($template)) return ''; $path = strlen($template) <= 256 ? trim($template) : ''; $data = array_merge(Tpl::$data, is_array($userData) ? $userData : []); $twig = TwigEnv::instance(); // treat template as a path only if it *looks like* a Twig template path if (Str::startsWith($path, '@') || Str::endsWith(strtolower($path), '.twig')) { return $twig->renderPath($path, $data); } return $twig->renderString($template, $data); }
php
{ "resource": "" }
q249406
Twig_Compiler.compile
validation
public function compile(Twig_NodeInterface $node, $indentation = 0) { $this->lastLine = null; $this->source = ''; $this->debugInfo = array(); $this->sourceOffset = 0; // source code starts at 1 (as we then increment it when we encounter new lines) $this->sourceLine = 1; $this->indentation = $indentation; $this->varNameSalt = 0; if ($node instanceof Twig_Node_Module) { // to be removed in 2.0 $this->filename = $node->getTemplateName(); } $node->compile($this); return $this; }
php
{ "resource": "" }
q249407
Twig_Compiler.write
validation
public function write() { $strings = func_get_args(); foreach ($strings as $string) { $this->source .= str_repeat(' ', $this->indentation * 4).$string; } return $this; }
php
{ "resource": "" }
q249408
Twig_Compiler.addIndentation
validation
public function addIndentation() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use write(\'\') instead.', E_USER_DEPRECATED); $this->source .= str_repeat(' ', $this->indentation * 4); return $this; }
php
{ "resource": "" }
q249409
Twig_Compiler.outdent
validation
public function outdent($step = 1) { // can't outdent by more steps than the current indentation level if ($this->indentation < $step) { throw new LogicException('Unable to call outdent() as the indentation would become negative.'); } $this->indentation -= $step; return $this; }
php
{ "resource": "" }
q249410
Twig_Autoloader.register
validation
public static function register($prepend = false) { @trigger_error('Using Twig_Autoloader is deprecated since version 1.21. Use Composer instead.', E_USER_DEPRECATED); if (PHP_VERSION_ID < 50300) { spl_autoload_register(array(__CLASS__, 'autoload')); } else { spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend); } }
php
{ "resource": "" }
q249411
AccountRecoverPasswordForm.recoverPassword
validation
public function recoverPassword() { $user = User::findOne(['email' => $this->email]); if ($user != NULL) { $user->password_reset_token = Yii::$app->getSecurity()->generateRandomString() . '_' . time(); $user->save(FALSE); } // Sends recovery mail Mailer::sendRecoveryMessage($user); Yii::$app->session->setFlash('info', 'You will receive an email with instructions on how to reset your password in a few minutes.'); }
php
{ "resource": "" }
q249412
TwigEnv.renderString
validation
public function renderString($tplString='', $tplData=[]) { try { return $this->twig->createTemplate($tplString)->render($tplData); } catch (Twig_Error $err) { return $this->error($err, false, $tplString); } }
php
{ "resource": "" }
q249413
TwigEnv.getSourceExcerpt
validation
private function getSourceExcerpt($source='', $line=1, $plus=1, $format=false) { $excerpt = []; $twig = Escape::html($source); $lines = preg_split("/(\r\n|\n|\r)/", $twig); $start = max(1, $line - $plus); $limit = min(count($lines), $line + $plus); for ($i = $start - 1; $i < $limit; $i++) { if ($format) { $attr = 'data-line="'.($i+1).'"'; if ($i === $line - 1) $excerpt[] = "<mark $attr>$lines[$i]</mark>"; else $excerpt[] = "<span $attr>$lines[$i]</span>"; } else { $excerpt[] = $lines[$i]; } } return implode("\n", $excerpt); }
php
{ "resource": "" }
q249414
TwigEnv.addCallable
validation
private function addCallable($type='function', $name, $func) { if (!is_string($name) || !is_callable($func)) { return; } $twname = trim($name, '*'); $params = []; if (strpos($name, '*') === 0) { $params['is_safe'] = ['html']; } if ($type === 'function') { $this->twig->addFunction(new Twig_SimpleFunction($twname, $func, $params)); } if ($type === 'filter') { $this->twig->addFilter(new Twig_SimpleFilter($twname, $func, $params)); } }
php
{ "resource": "" }
q249415
Twig_TokenParser_For.checkLoopUsageCondition
validation
protected function checkLoopUsageCondition(Twig_TokenStream $stream, Twig_NodeInterface $node) { if ($node instanceof Twig_Node_Expression_GetAttr && $node->getNode('node') instanceof Twig_Node_Expression_Name && 'loop' == $node->getNode('node')->getAttribute('name')) { throw new Twig_Error_Syntax('The "loop" variable cannot be used in a looping condition.', $node->getTemplateLine(), $stream->getSourceContext()); } foreach ($node as $n) { if (!$n) { continue; } $this->checkLoopUsageCondition($stream, $n); } }
php
{ "resource": "" }
q249416
Twig_NodeVisitor_Optimizer.optimizePrintNode
validation
protected function optimizePrintNode(Twig_NodeInterface $node, Twig_Environment $env) { if (!$node instanceof Twig_Node_Print) { return $node; } $exprNode = $node->getNode('expr'); if ( $exprNode instanceof Twig_Node_Expression_BlockReference || $exprNode instanceof Twig_Node_Expression_Parent ) { $exprNode->setAttribute('output', true); return $exprNode; } return $node; }
php
{ "resource": "" }
q249417
RecoveryController.actionRecoverPassword
validation
public function actionRecoverPassword() { $model = new AccountRecoverPasswordForm(); if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { $model->recoverPassword(); } } return $this->render('recoverPassword', ['model' => $model]); }
php
{ "resource": "" }
q249418
Mailer.sendWelcomeMessage
validation
public static function sendWelcomeMessage(User $user) { return Mailer::sendMail($user->email, 'Welcome to ' . Yii::$app->name, 'welcome', ['user' => $user]); }
php
{ "resource": "" }
q249419
Mailer.sendMail
validation
protected function sendMail($to, $subject, $view, $params = []) { $mailer = Yii::$app->mailer; $mailer->viewPath = '@abhimanyu/user/views/mail'; return $mailer->compose(['html' => $view, 'text' => 'text/' . $view], $params) ->setTo($to) ->setFrom(Yii::$app->config->get('mail.username'), '[email protected]') ->setSubject($subject) ->send(); }
php
{ "resource": "" }
q249420
AccountLoginForm.login
validation
public function login() { return $this->validate() ? Yii::$app->user->login($this->getUser(), $this->rememberMe ? UserModule::$rememberMeDuration : 0) : FALSE; }
php
{ "resource": "" }
q249421
Twig_Extension_Escaper.setDefaultStrategy
validation
public function setDefaultStrategy($defaultStrategy) { // for BC if (true === $defaultStrategy) { @trigger_error('Using "true" as the default strategy is deprecated since version 1.21. Use "html" instead.', E_USER_DEPRECATED); $defaultStrategy = 'html'; } if ('filename' === $defaultStrategy) { @trigger_error('Using "filename" as the default strategy is deprecated since version 1.27. Use "name" instead.', E_USER_DEPRECATED); $defaultStrategy = 'name'; } if ('name' === $defaultStrategy) { $defaultStrategy = array('Twig_FileExtensionEscapingStrategy', 'guess'); } $this->defaultStrategy = $defaultStrategy; }
php
{ "resource": "" }
q249422
Twig_Extension_Escaper.getDefaultStrategy
validation
public function getDefaultStrategy($name) { // disable string callables to avoid calling a function named html or js, // or any other upcoming escaping strategy if (!is_string($this->defaultStrategy) && false !== $this->defaultStrategy) { return call_user_func($this->defaultStrategy, $name); } return $this->defaultStrategy; }
php
{ "resource": "" }
q249423
Twig_Profiler_Profile.getDuration
validation
public function getDuration() { if ($this->isRoot() && $this->profiles) { // for the root node with children, duration is the sum of all child durations $duration = 0; foreach ($this->profiles as $profile) { $duration += $profile->getDuration(); } return $duration; } return isset($this->ends['wt']) && isset($this->starts['wt']) ? $this->ends['wt'] - $this->starts['wt'] : 0; }
php
{ "resource": "" }
q249424
Twig_Profiler_Profile.getMemoryUsage
validation
public function getMemoryUsage() { return isset($this->ends['mu']) && isset($this->starts['mu']) ? $this->ends['mu'] - $this->starts['mu'] : 0; }
php
{ "resource": "" }
q249425
Twig_Profiler_Profile.getPeakMemoryUsage
validation
public function getPeakMemoryUsage() { return isset($this->ends['pmu']) && isset($this->starts['pmu']) ? $this->ends['pmu'] - $this->starts['pmu'] : 0; }
php
{ "resource": "" }
q249426
Twig_Template.getParent
validation
public function getParent(array $context) { if (null !== $this->parent) { return $this->parent; } try { $parent = $this->doGetParent($context); if (false === $parent) { return false; } if ($parent instanceof self) { return $this->parents[$parent->getTemplateName()] = $parent; } if (!isset($this->parents[$parent])) { $this->parents[$parent] = $this->loadTemplate($parent); } } catch (Twig_Error_Loader $e) { $e->setSourceContext(null); $e->guess(); throw $e; } return $this->parents[$parent]; }
php
{ "resource": "" }
q249427
Twig_Template.displayBlock
validation
public function displayBlock($name, array $context, array $blocks = array(), $useBlocks = true) { $name = (string) $name; if ($useBlocks && isset($blocks[$name])) { $template = $blocks[$name][0]; $block = $blocks[$name][1]; } elseif (isset($this->blocks[$name])) { $template = $this->blocks[$name][0]; $block = $this->blocks[$name][1]; } else { $template = null; $block = null; } // avoid RCEs when sandbox is enabled if (null !== $template && !$template instanceof self) { throw new LogicException('A block must be a method on a Twig_Template instance.'); } if (null !== $template) { try { $template->$block($context, $blocks); } catch (Twig_Error $e) { if (!$e->getSourceContext()) { $e->setSourceContext($template->getSourceContext()); } // this is mostly useful for Twig_Error_Loader exceptions // see Twig_Error_Loader if (false === $e->getTemplateLine()) { $e->setTemplateLine(-1); $e->guess(); } throw $e; } catch (Exception $e) { throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $template->getSourceContext(), $e); } } elseif (false !== $parent = $this->getParent($context)) { $parent->displayBlock($name, $context, array_merge($this->blocks, $blocks), false); } else { @trigger_error(sprintf('Silent display of undefined block "%s" in template "%s" is deprecated since version 1.29 and will throw an exception in 2.0. Use the "block(\'%s\') is defined" expression to test for block existence.', $name, $this->getTemplateName(), $name), E_USER_DEPRECATED); } }
php
{ "resource": "" }
q249428
Twig_Template.hasBlock
validation
public function hasBlock($name, array $context = null, array $blocks = array()) { if (null === $context) { @trigger_error('The '.__METHOD__.' method is internal and should never be called; calling it directly is deprecated since version 1.28 and won\'t be possible anymore in 2.0.', E_USER_DEPRECATED); return isset($this->blocks[(string) $name]); } if (isset($blocks[$name])) { return $blocks[$name][0] instanceof self; } if (isset($this->blocks[$name])) { return true; } if (false !== $parent = $this->getParent($context)) { return $parent->hasBlock($name, $context); } return false; }
php
{ "resource": "" }
q249429
Twig_Template.getBlockNames
validation
public function getBlockNames(array $context = null, array $blocks = array()) { if (null === $context) { @trigger_error('The '.__METHOD__.' method is internal and should never be called; calling it directly is deprecated since version 1.28 and won\'t be possible anymore in 2.0.', E_USER_DEPRECATED); return array_keys($this->blocks); } $names = array_merge(array_keys($blocks), array_keys($this->blocks)); if (false !== $parent = $this->getParent($context)) { $names = array_merge($names, $parent->getBlockNames($context)); } return array_unique($names); }
php
{ "resource": "" }
q249430
Twig_Template.getContext
validation
final protected function getContext($context, $item, $ignoreStrictCheck = false) { if (!array_key_exists($item, $context)) { if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { return; } throw new Twig_Error_Runtime(sprintf('Variable "%s" does not exist.', $item), -1, $this->getSourceContext()); } return $context[$item]; }
php
{ "resource": "" }
q249431
RegistrationController.actionRegister
validation
public function actionRegister() { $model = new User(); $model->scenario = 'register'; if ($model->load(Yii::$app->request->post()) && $model->register(FALSE, User::STATUS_PENDING)) { // Send Welcome Message to activate the account Mailer::sendWelcomeMessage($model); Yii::$app->session->setFlash( 'success', Yii::t('user', 'You\'ve successfully been registered. Check your mail to activate your account')); return $this->redirect(Yii::$app->urlManager->createUrl('//user/auth/login')); } return $this->render('register', ['model' => $model]); }
php
{ "resource": "" }
q249432
RegistrationController.actionConfirm
validation
public function actionConfirm($id, $code) { $user = UserIdentity::findByActivationToken($id, $code); if ($user == NULL) throw new NotFoundHttpException; if (!empty($user)) { $user->activation_token = NULL; $user->status = User::STATUS_ACTIVE; $user->save(FALSE); Yii::$app->session->setFlash('success', Yii::t('user', 'Account ' . $user->email . ' has successfully been activated')); } else Yii::$app->session->setFlash('error', Yii::t('user', 'Account ' . $user->email . ' could not been activated. Please contact the Administrator')); return $this->render('confirm', ['user' => $user]); }
php
{ "resource": "" }
q249433
Twig_FileExtensionEscapingStrategy.guess
validation
public static function guess($name) { if (in_array(substr($name, -1), array('/', '\\'))) { return 'html'; // return html for directories } if ('.twig' === substr($name, -5)) { $name = substr($name, 0, -5); } $extension = pathinfo($name, PATHINFO_EXTENSION); switch ($extension) { case 'js': return 'js'; case 'css': return 'css'; case 'txt': return false; default: return 'html'; } }
php
{ "resource": "" }
q249434
TwigComponent.file
validation
public function file($name) { $usephp = c::get('twig.usephp', true); $base = str_replace('\\', '/', $this->kirby->roots()->templates().'/'.$name); $twig = $base . '.twig'; $php = $base . '.php'; // only check existing files if PHP template support is active if ($usephp and !is_file($twig) and is_file($php)) { return $php; } else { return $twig; } }
php
{ "resource": "" }
q249435
TwigComponent.render
validation
public function render($template, $data = [], $return = true) { if ($template instanceof Page) { $page = $template; $file = $page->templateFile(); $data = $this->data($page, $data); } else { $file = $template; $data = $this->data(null, $data); } // check for an existing template if (!file_exists($file)) { throw new Exception('The template could not be found'); } // merge and register the template data globally $startData = Tpl::$data; Tpl::$data = array_merge(Tpl::$data, $data); // load the template if (pathinfo($file, PATHINFO_EXTENSION) === 'twig') { $twig = TwigEnv::instance(); $result = $twig->renderPath($file, Tpl::$data, $return, true); } else { $result = Tpl::load($file, [], $return); } // reset the template data Tpl::$data = $startData; return $result; }
php
{ "resource": "" }
q249436
Twig_ExpressionParser.checkConstantExpression
validation
protected function checkConstantExpression(Twig_NodeInterface $node) { if (!($node instanceof Twig_Node_Expression_Constant || $node instanceof Twig_Node_Expression_Array || $node instanceof Twig_Node_Expression_Unary_Neg || $node instanceof Twig_Node_Expression_Unary_Pos )) { return false; } foreach ($node as $n) { if (!$this->checkConstantExpression($n)) { return false; } } return true; }
php
{ "resource": "" }
q249437
Twig_Util_DeprecationCollector.collectDir
validation
public function collectDir($dir, $ext = '.twig') { $iterator = new RegexIterator( new RecursiveIteratorIterator( new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY ), '{'.preg_quote($ext).'$}' ); return $this->collect(new Twig_Util_TemplateDirIterator($iterator)); }
php
{ "resource": "" }
q249438
Twig_Util_DeprecationCollector.collect
validation
public function collect(Traversable $iterator) { $this->deprecations = array(); set_error_handler(array($this, 'errorHandler')); foreach ($iterator as $name => $contents) { try { $this->twig->parse($this->twig->tokenize(new Twig_Source($contents, $name))); } catch (Twig_Error_Syntax $e) { // ignore templates containing syntax errors } } restore_error_handler(); $deprecations = $this->deprecations; $this->deprecations = array(); return $deprecations; }
php
{ "resource": "" }
q249439
Twig_TokenStream.next
validation
public function next() { if (!isset($this->tokens[++$this->current])) { throw new Twig_Error_Syntax('Unexpected end of template.', $this->tokens[$this->current - 1]->getLine(), $this->source); } return $this->tokens[$this->current - 1]; }
php
{ "resource": "" }
q249440
Twig_TokenStream.expect
validation
public function expect($type, $value = null, $message = null) { $token = $this->tokens[$this->current]; if (!$token->test($type, $value)) { $line = $token->getLine(); throw new Twig_Error_Syntax(sprintf('%sUnexpected token "%s" of value "%s" ("%s" expected%s).', $message ? $message.'. ' : '', Twig_Token::typeToEnglish($token->getType()), $token->getValue(), Twig_Token::typeToEnglish($type), $value ? sprintf(' with value "%s"', $value) : ''), $line, $this->source ); } $this->next(); return $token; }
php
{ "resource": "" }
q249441
Twig_TokenStream.look
validation
public function look($number = 1) { if (!isset($this->tokens[$this->current + $number])) { throw new Twig_Error_Syntax('Unexpected end of template.', $this->tokens[$this->current + $number - 1]->getLine(), $this->source); } return $this->tokens[$this->current + $number]; }
php
{ "resource": "" }
q249442
ExportCommand.exportJob
validation
protected function exportJob($job) { $stats = $this->getJobStats($job); $contents = $this->renderForExport($job, $stats); $filename = trim($this->path, '/').'/'.$this->buildJobFileName($job, $stats); if (file_exists($filename)) { throw new \RuntimeException('File already exists.'); } if (! file_put_contents($filename, $contents)) { throw new \RuntimeException('Error saving the file.'); } }
php
{ "resource": "" }
q249443
ArtisanBeansServiceProvider.registerCommand
validation
protected function registerCommand($command) { $abstract = "command.artisan.beans.$command"; $commandClass = "\\Pvm\\ArtisanBeans\\Console\\{$command}Command"; $this->app->singleton($abstract, function ($app) use ($commandClass) { return new $commandClass(); }); $this->commands($abstract); }
php
{ "resource": "" }
q249444
BaseCommand.peekJob
validation
protected function peekJob($tube, $state) { $peekMethod = 'peek'.ucfirst($state); try { return $this->getPheanstalk()->$peekMethod($tube); } catch (ServerException $e) { if ($this->isNotFoundException($e)) { return; } throw $e; } }
php
{ "resource": "" }
q249445
BaseCommand.reserveJob
validation
protected function reserveJob($tube) { try { return $this->getPheanstalk()->reserveFromTube($tube, 0); } catch (ServerException $e) { if ($this->isNotFoundException($e)) { return; } throw $e; } }
php
{ "resource": "" }
q249446
BaseCommand.getJobStats
validation
protected function getJobStats($job) { try { return (array) $this->getPheanstalk()->statsJob($job); } catch (ServerException $e) { if ($this->isNotFoundException($e)) { return; } throw $e; } }
php
{ "resource": "" }
q249447
BaseCommand.buryJob
validation
protected function buryJob($job, $priority = null) { if (is_null($priority)) { $priority = Pheanstalk::DEFAULT_PRIORITY; } $this->getPheanstalk()->bury($job, $priority); }
php
{ "resource": "" }
q249448
BaseCommand.putJob
validation
protected function putJob($tube, $body, $priority, $delay, $ttr) { $id = $this->getPheanstalk() ->putInTube($tube, $body, $priority, $delay, $ttr); return $id; }
php
{ "resource": "" }
q249449
BaseCommand.getPheanstalk
validation
public function getPheanstalk() { if (! $this->pheanstalk) { $this->pheanstalk = new Pheanstalk($this->host, $this->port); } return $this->pheanstalk; }
php
{ "resource": "" }
q249450
BaseCommand.parseArguments
validation
protected function parseArguments() { $this->parseConnection($this->option('connection')); if ($this->option('host')) { $this->host = $this->option('host'); } if ($this->option('port')) { $this->port = (int) $this->option('port'); } $this->parseCommandArguments(); }
php
{ "resource": "" }
q249451
BaseCommand.parseConnection
validation
protected function parseConnection($connectionName) { $connection = null; // If user provided the connection name read it directly if ($connectionName) { if (! $connection = config("queue.connections.$connectionName")) { throw new \InvalidArgumentException("Connection '$connectionName' doesn't exist."); } } // Try default connection if (! $connection) { $defaultConnection = config('queue.default'); if ('beanstalkd' == config("queue.connections.$defaultConnection.driver")) { $connection = config("queue.connections.$defaultConnection"); } } // Try first connection that has beanstalkd driver if (! $connection) { foreach (config('queue.connections') as $connection) { if ('beanstalkd' == $connection['driver']) { break; } } } if (! empty($connection['host'])) { $parsedConfigHost = explode(':', $connection['host']); $this->host = $parsedConfigHost[0]; if (isset($parsedConfigHost[1])) { $this->port = $parsedConfigHost[1]; } } if (! empty($connection['queue'])) { $this->defaultTube = $connection['queue']; } }
php
{ "resource": "" }
q249452
BaseCommand.buildCommandSignature
validation
protected function buildCommandSignature() { $this->signature = $this->namespace.':'.$this->commandName.' '. $this->commandArguments. $this->commandOptions. $this->commonOptions; }
php
{ "resource": "" }
q249453
BaseCommand.validateFile
validation
protected function validateFile($filePath, $message = 'File', $allowEmpty = true) { if (! file_exists($filePath) || ! is_readable($filePath)) { throw new \RuntimeException("$message '{$filePath}' doesn't exist or is not readable."); } if (! $allowEmpty && 0 === filesize($filePath)) { throw new \RuntimeException("$message '{$filePath}' is empty."); } return realpath($filePath); }
php
{ "resource": "" }
q249454
BaseCommand.renderJob
validation
protected function renderJob($job) { $stats = $this->getJobStats($job); $format = '<info>id</info>: %u, <info>length</info>: %u, <info>priority</info>: %u, <info>delay</info>: %u, <info>age</info>: %u, <info>ttr</info>: %u'; $line = sprintf($format, $job->getId(), strlen($job->getData()), $stats['pri'], $stats['delay'], $stats['age'], $stats['ttr']); $this->output->writeln($line); $format = '<comment>reserves</comment>: %u, <comment>releases</comment>: %u, <comment>buries</comment>: %u, <comment>kicks</comment>: %u, <comment>timeouts</comment>: %u'; $line = sprintf($format, $stats['reserves'], $stats['releases'], $stats['buries'], $stats['kicks'], $stats['timeouts']); $this->output->writeln($line); $this->output->writeln('<comment>body:</comment>'); $data = $job->getData(); $this->output->writeln("\"$data\""); }
php
{ "resource": "" }
q249455
BaseCommand.getTubeStats
validation
protected function getTubeStats($tube) { try { $stats = $this->getPheanstalk()->statsTube($tube); } catch (ServerException $e) { if ($this->isNotFoundException($e)) { throw new \RuntimeException("Tube '$tube' doesn't exist."); } throw $e; } return $stats; }
php
{ "resource": "" }
q249456
BaseCommand.getServerStats
validation
protected function getServerStats($pattern = '') { $stats = (array) $this->getPheanstalk()->stats(); if (! empty($pattern)) { $stats = array_filter($stats, function ($key) use ($pattern) { return 1 === preg_match("/$pattern/i", $key); }, ARRAY_FILTER_USE_KEY); } ksort($stats); return $stats; }
php
{ "resource": "" }
q249457
MoveCommand.getNextJob
validation
private function getNextJob($tube, $state) { if ('ready' == $this->state) { return $this->reserveJob($tube); } return $this->peekJob($tube, $state); }
php
{ "resource": "" }
q249458
Utils.getRefererQueryParam
validation
public static function getRefererQueryParam($url, $key) { if (!$url) { return null; } $query = []; parse_str(parse_url($url, PHP_URL_QUERY), $query); if (isset($query[$key])) { return $query[$key]; } return null; }
php
{ "resource": "" }
q249459
RateLimit.isAllowed
validation
protected function isAllowed($limit, $config) { if ($limit["cnt"] >= $config["count"]) { if (time() > $limit["ts"] + $config["blockDuration"]) { return true; } else { return false; } } else { return true; } }
php
{ "resource": "" }
q249460
RateLimit.getIp
validation
protected function getIp($config) { $remoteAddr = $_SERVER['REMOTE_ADDR']; if (filter_var($remoteAddr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { $netmask = (isset($config["netmask_IPv4"])) ? $config["netmask_IPv4"] : self::DEFAULT_NETMASK_IPV4; } else { $netmask = (isset($config["netmask_IPv6"])) ? $config["netmask_IPv6"] : self::DEFAULT_NETMASK_IPV6; } $ipSubnet = $this->getSubnet($remoteAddr, $netmask); return $ipSubnet; }
php
{ "resource": "" }
q249461
RateLimit.getSubnet
validation
protected function getSubnet($ip, $netmask) { $binString = @inet_pton($ip); if ($binString === false) { throw new \InvalidArgumentException("Not a valid IP address."); } // Length of the IP in bytes (4 or 16) $byteLen = mb_strlen($binString, "8bit"); if (!is_int($netmask) || $netmask < 0 || $netmask > $byteLen * 8) { throw new \InvalidArgumentException("Not a valid netmask."); } for ($byte = $byteLen - 1; ($byte + 1) * 8 > $netmask; --$byte) { // Bitlength of a mask for the current byte $maskLen = min(8, ($byte + 1) * 8 - $netmask); // Create the byte mask of maskLen bits $mask = (~((1 << $maskLen) - 1)) & 0xff; // Export byte as 'unsigned char' and apply the mask $maskedByte = $mask & unpack('C', $binString[$byte])[1]; $binString[$byte] = pack('C', $maskedByte); } return inet_ntop($binString) . '/' . $netmask; }
php
{ "resource": "" }
q249462
RateLimit.getEntityId
validation
protected function getEntityId($blockType, $config, $params = array()) { $entityId = null; if ($blockType === "account" && isset($params["name"])) { $entityId = md5($params["name"]); } elseif ($blockType === "email" && isset($params["email"])) { $entityId = md5($params["email"]); } elseif ($blockType === "ip") { $entityId = $this->getIp($config); } return $entityId; }
php
{ "resource": "" }
q249463
RateLimit.getLimitFor
validation
protected function getLimitFor($actionName, $blockType, $entityId) { $limit = $this->storage->getLimitFor($actionName, $blockType, $entityId); if ($limit === null) { $limit = array("ts" => 0, "cnt" => 0); } return $limit; }
php
{ "resource": "" }
q249464
RateLimit.incrementCounter
validation
protected function incrementCounter($actionName, $blockType, $entityId, $config) { // Begin an exclusive transaction $this->storage->transaction($actionName, $blockType, RateLimitStorageInterface::TRANSACTION_BEGIN); $limit = $this->getLimitFor($actionName, $blockType, $entityId); $time = time(); $resetCounter = // Counter reset after specified timeout since the last action ($time > $limit["ts"] + $config["counterTimeout"]) || // Counter reset after blockout delay timeout ($limit["cnt"] >= $config["count"] && $time > $limit["ts"] + $config["blockDuration"]); if ($resetCounter) { $limit["cnt"] = 0; } $limitBeforeIncrement = $limit; // The limit will be reached with this increment if ($limit["cnt"] === $config["count"] - 1) { $this->logRateLimitReached($actionName, $blockType, $entityId, $config); } ++$limit["cnt"]; $limit["ts"] = $time; // Update the limit if the entity is not blocked if ($limit["cnt"] <= $config["count"]) { $this->storage->updateLimitFor($actionName, $blockType, $entityId, $limit); if (rand(0, 100) <= $this->config["cleanupProbability"]) { $this->storage->cleanup($actionName, $blockType, $config); } $this->storage->save($actionName, $blockType); } // Close the transaction $this->storage->transaction($actionName, $blockType, RateLimitStorageInterface::TRANSACTION_END); // Returns the limit array before the increment return $limitBeforeIncrement; }
php
{ "resource": "" }
q249465
RateLimit.logRateLimitReached
validation
protected function logRateLimitReached($actionName, $blockType, $entityId, $config) { $this->getLogger()->notice( "Rate limit of {cnt} reached: {action} for {entity} ({type}).", array('cnt' => $config["count"], 'action' => $actionName, 'entity' => $entityId, 'type' => $blockType) ); }
php
{ "resource": "" }
q249466
Registration.handleRegistration
validation
public function handleRegistration(Request $httpRequest) { // Abort if disabled if (!$this->config["enabled"]) { return; } $user = $this->picoAuth->getUser(); if ($user->getAuthenticated()) { $this->picoAuth->redirectToPage("index"); } $this->picoAuth->addAllowed("register"); $this->picoAuth->setRequestFile($this->picoAuth->getPluginPath() . '/content/register.md'); // Check the form submission $post = $httpRequest->request; if ($post->has("username") && $post->has("email") && $post->has("password") && $post->has("password_repeat") ) { // CSRF validation if (!$this->picoAuth->isValidCSRF($post->get("csrf_token"), self::REGISTER_CSRF_ACTION)) { $this->picoAuth->redirectToPage("register"); } // Abort if a limit for maximum users is exceeded $this->assertLimits(); // Registration fields $reg = array( "username" => strtolower(trim($post->get("username"))), "email" => trim($post->get("email")), "password" => new Password($post->get("password")), "passwordRepeat" => new Password($post->get("password_repeat")), ); $isValid = $this->validateRegistration($reg); if ($isValid) { // Check if the action is not rate limited if (!$this->limit->action("registration")) { $this->session->addFlash("error", $this->limit->getError()); $this->picoAuth->redirectToPage("register"); } $this->logSuccessfulRegistration($reg); $userData = array('email' => $reg["email"]); $localAuth = $this->picoAuth->getContainer()->get('LocalAuth'); $localAuth->userDataEncodePassword($userData, $reg["password"]); $this->storage->saveUser($reg["username"], $userData); $this->session->addFlash("success", "Registration completed successfully, you can now log in."); $this->picoAuth->redirectToLogin(); } else { // Prefill the old values to the form $this->session->addFlash("old", array( 'username' => $reg["username"], 'email' => $reg["email"] )); // Redirect back and display errors $this->picoAuth->redirectToPage("register"); } } }
php
{ "resource": "" }
q249467
Registration.validateRegistration
validation
protected function validateRegistration(array $reg) { $isValid = true; // Username format try { $this->storage->checkValidName($reg["username"]); } catch (\RuntimeException $e) { $isValid = false; $this->session->addFlash("error", $e->getMessage()); } // Username length $min = $this->config["nameLenMin"]; $max = $this->config["nameLenMax"]; if (strlen($reg["username"]) < $min || strlen($reg["username"]) > $max) { $isValid = false; $this->session->addFlash( "error", sprintf("Length of a username must be between %d-%d characters.", $min, $max) ); } // Email format if (!filter_var($reg["email"], FILTER_VALIDATE_EMAIL)) { $isValid = false; $this->session->addFlash("error", "Email address does not have a valid format."); } // Email unique if (null !== $this->storage->getUserByEmail($reg["email"])) { $isValid = false; $this->session->addFlash("error", "This email is already in use."); } // Password repeat matches if ($reg["password"]->get() !== $reg["passwordRepeat"]->get()) { $isValid = false; $this->session->addFlash("error", "The passwords do not match."); } // Check password policy $localAuth = $this->picoAuth->getContainer()->get('LocalAuth'); if (!$localAuth->checkPasswordPolicy($reg["password"])) { $isValid = false; } // Username unique if ($this->storage->getUserByName($reg["username"]) !== null) { $isValid = false; $this->session->addFlash("error", "The username is already taken."); } return $isValid; }
php
{ "resource": "" }
q249468
Registration.logSuccessfulRegistration
validation
protected function logSuccessfulRegistration(array $reg) { $this->getLogger()->info( "New registration: {name} ({email}) from {addr}", array( "name" => $reg["username"], "email" => $reg["email"], "addr" => $_SERVER['REMOTE_ADDR'] ) ); // Log the amount of users on each 10% of the maximum capacity $max = $this->config["maxUsers"]; $count = $this->storage->getUsersCount()+1; if ($count % ceil($max/10) === 0) { $percent = intval($count/ceil($max/100)); $this->getLogger()->warning( "The amount of users has reached {percent} of the maximum capacity {max}.", array( "percent" => $percent, "max" => $max ) ); } }
php
{ "resource": "" }
q249469
Registration.assertLimits
validation
protected function assertLimits() { if ($this->storage->getUsersCount() >= $this->config["maxUsers"]) { $this->session->addFlash("error", "New registrations are currently disabled."); $this->picoAuth->redirectToPage("register"); } }
php
{ "resource": "" }
q249470
FileStorage.readFile
validation
public static function readFile($fileName, $options = []) { $reader = new File\FileReader($fileName, $options); $success = true; $contents = null; try { $reader->open(); $contents = $reader->read(); } catch (\RuntimeException $e) { self::$lastError = $e->getMessage(); $success = false; } try { $reader->close(); } catch (\RuntimeException $e) { self::$lastError = $e->getMessage(); $success = false; } return ($success) ? $contents : false; }
php
{ "resource": "" }
q249471
FileStorage.writeFile
validation
public static function writeFile($fileName, $data, $options = []) { $writer = new File\FileWriter($fileName, $options); $isSuccess = true; $written = 0; try { $writer->open(); $written = $writer->write($data); } catch (\RuntimeException $e) { self::$lastError = $e->getMessage(); $isSuccess = false; } try { $writer->close(); } catch (\RuntimeException $e) { self::$lastError = $e->getMessage(); $isSuccess = false; } return $isSuccess; }
php
{ "resource": "" }
q249472
FileStorage.getItemByUrl
validation
public static function getItemByUrl($items, $url) { if (!isset($items)) { return null; } // Check for the exact rule if (array_key_exists("/" . $url, $items)) { return $items["/" . $url]; } $urlParts = explode("/", trim($url, "/")); $urlPartsLen = count($urlParts); while ($urlPartsLen > 0) { unset($urlParts[--$urlPartsLen]); $subUrl = "/" . join("/", $urlParts); // Use the higher level rule, if it doesn't have deactivated recursive application if (array_key_exists($subUrl, $items) && (!isset($items[$subUrl]["recursive"]) || $items[$subUrl]["recursive"]===true)) { return $items[$subUrl]; } } return null; }
php
{ "resource": "" }
q249473
FileStorage.readConfiguration
validation
protected function readConfiguration() { // Return if already loaded if (is_array($this->config)) { return; } $fileName = $this->dir . static::CONFIG_FILE; // Abort if the file doesn't exist if (!file_exists($fileName)) { $this->config = $this->validateConfiguration(); return; } $modifyTime = filemtime($fileName); if (false === $modifyTime) { throw new \RuntimeException("Unable to get mtime of the configuration file."); } // Check if the configuration is in cache $cacheKey = md5($fileName); if ($this->cache->has($cacheKey)) { $this->config=$this->cache->get($cacheKey); // Cached file is up to date if ($this->config["_mtime"] === $modifyTime) { return; } } if (($yaml = self::readFile($fileName)) !== false) { $config = \Symfony\Component\Yaml\Yaml::parse($yaml); $this->config = $this->validateConfiguration($config); } else { throw new \RuntimeException("Unable to read configuration file."); } // Save to cache with updated modify-time $storedConfig = $this->config; $storedConfig["_mtime"]= $modifyTime; $this->cache->set($cacheKey, $storedConfig); }
php
{ "resource": "" }
q249474
CSRF.getToken
validation
public function getToken($action = null, $reuse = true) { $tokenStorage = $this->session->get(self::SESSION_KEY, []); $index = ($action) ? $action : self::DEFAULT_SELECTOR; if (!isset($tokenStorage[$index])) { $token = bin2hex(random_bytes(self::TOKEN_SIZE)); $tokenStorage[$index] = array( 'time' => time(), 'token' => $token ); } else { // Token already exists and is not expired $token = $tokenStorage[$index]['token']; // Update token time $tokenStorage[$index]['time'] = time(); } $tokenStorage[$index]['reuse'] = $reuse; $key = bin2hex(random_bytes(self::TOKEN_SIZE)); $tokenHMAC = $this->tokenHMAC($token, $key); $this->session->set(self::SESSION_KEY, $tokenStorage); return $key . self::TOKEN_DELIMTER . $tokenHMAC; }
php
{ "resource": "" }
q249475
CSRF.isExpired
validation
protected function isExpired(array $tokenData, $tokenValidity = null) { return time() > $tokenData['time'] + (($tokenValidity!==null) ? $tokenValidity : self::TOKEN_VALIDITY); }
php
{ "resource": "" }
q249476
CSRF.ivalidateToken
validation
protected function ivalidateToken($index, array &$tokenStorage) { unset($tokenStorage[$index]); $this->session->set(self::SESSION_KEY, $tokenStorage); }
php
{ "resource": "" }
q249477
Installer.checkServerConfiguration
validation
protected function checkServerConfiguration() { $pico = $this->picoAuth->getPico(); // Pico config.yml file $configDir = $pico->getBaseUrl() . basename($pico->getConfigDir()); $configFile = $configDir . "/config.yml"; // index.md file $contentDir = $pico->getBaseUrl() . basename($pico->getConfig('content_dir')); $indexFile = $contentDir . "/index" . $pico->getConfig('content_ext'); $urls = array( 'dir_listing' => $configDir, 'config_file' => $configFile, 'content_file' => $indexFile ); $this->httpsTest(); $this->webRootDirsTest(); $this->picoAuth->addOutput("installer_urltest", $urls); }
php
{ "resource": "" }
q249478
Installer.configGenerationAction
validation
protected function configGenerationAction(ParameterBag $post) { //CSRF validation if (!$this->picoAuth->isValidCSRF($post->get("csrf_token"))) { // On a token mismatch the submission gets ignored $this->picoAuth->addOutput("installer_step", 1); return; } $this->picoAuth->addOutput("installer_step", 2); $this->outputModulesConfiguration($post); }
php
{ "resource": "" }
q249479
Installer.outputModulesConfiguration
validation
protected function outputModulesConfiguration(ParameterBag $post) { $modulesClasses = array(); $modulesNames = array(); foreach ($this->modules as $key => $value) { if ($post->has($key)) { $modulesClasses[] = $value; $modulesNames[] = $key; } } $config = array( self::CONFIG_PLUGIN_KEY => array( self::CONFIG_MODULES_KEY => $modulesClasses ) ); $yaml = \Symfony\Component\Yaml\Yaml::dump($config, 2, 4); // Adds output to the template variables $this->picoAuth->addOutput("installer_modules_config", $yaml); $this->picoAuth->addOutput("installer_modules_names", $modulesNames); }
php
{ "resource": "" }
q249480
User.setAuthenticated
validation
public function setAuthenticated($v) { if (!$v) { $this->authenticator = null; } $this->authenticated = $v; return $this; }
php
{ "resource": "" }
q249481
LocalAuthFileStorage.saveResetTokens
validation
protected function saveResetTokens($tokens, FileWriter $writer = null) { // Before saving, remove all expired tokens $time = time(); foreach ($tokens as $id => $token) { if ($time > $token['valid']) { unset($tokens[$id]); } } $fileName = $this->dir . self::RESET_TOKENS; $yaml = \Symfony\Component\Yaml\Yaml::dump($tokens, 1, 2); if ($writer && $writer->isOpened()) { // An exclusive lock is already held, then use the given writer instance $writer->write($yaml); // Will throw on write error } else { self::preparePath($this->dir, dirname(self::RESET_TOKENS)); if ((self::writeFile($fileName, $yaml) === false)) { throw new \RuntimeException("Unable to save token file (".self::RESET_TOKENS.")."); } } }
php
{ "resource": "" }
q249482
LocalAuthFileStorage.getDirFiles
validation
protected function getDirFiles($searchDir) { // Error state is handled by the excpetion, warning disabled $files = @scandir($searchDir, SCANDIR_SORT_NONE); if ($files === false) { throw new \RuntimeException("Cannot list directory contents: {$searchDir}."); } return array_diff($files, array('..', '.')); }
php
{ "resource": "" }
q249483
LocalAuth.handleLogin
validation
protected function handleLogin(Request $httpRequest) { $post = $httpRequest->request; if (!$post->has("username") || !$post->has("password")) { return; } //CSRF validation if (!$this->picoAuth->isValidCSRF($post->get("csrf_token"), self::LOGIN_CSRF_ACTION)) { $this->picoAuth->redirectToLogin(null, $httpRequest); return; } $username = strtolower(trim($post->get("username"))); $password = new Password($post->get("password")); //Check if the login action is not rate limited if (!$this->limit->action("login", false, array("name" => $username))) { $this->session->addFlash("error", $this->limit->getError()); $this->picoAuth->redirectToLogin(null, $httpRequest); return; } if (!$this->loginAttempt($username, $password)) { $this->logInvalidLoginAttempt($username); $this->limit->action("login", true, array("name" => $username)); $this->session->addFlash("error", "Invalid username or password"); $this->picoAuth->redirectToLogin(null, $httpRequest); return; } else { $userData = $this->storage->getUserByName($username); if ($this->needsPasswordRehash($userData)) { $this->passwordRehash($username, $password); } $this->login($username, $userData); $this->picoAuth->afterLogin(); } }
php
{ "resource": "" }
q249484
LocalAuth.loginAttempt
validation
public function loginAttempt($username, Password $password) { $userData = $this->storage->getUserByName($username); $encoder = $this->getPasswordEncoder($userData); $dummy = bin2hex(\random_bytes(32)); $dummyHash = $encoder->encode($dummy); if (!$userData) { // The user doesn't exist, dummy call is performed to prevent time analysis $encoder->isValid($dummyHash, $password); return false; } return $encoder->isValid($userData['pwhash'], $password->get()); }
php
{ "resource": "" }
q249485
LocalAuth.login
validation
public function login($id, $userData) { $this->abortIfExpired($id, $userData); $u = new User(); $u->setAuthenticated(true); $u->setAuthenticator($this->getName()); $u->setId($id); if (isset($userData['groups'])) { $u->setGroups($userData['groups']); } if (isset($userData['displayName'])) { $u->setDisplayName($userData['displayName']); } if (isset($userData['attributes'])) { foreach ($userData['attributes'] as $key => $value) { $u->setAttribute($key, $value); } } $this->picoAuth->setUser($u); }
php
{ "resource": "" }
q249486
LocalAuth.abortIfExpired
validation
protected function abortIfExpired($id, $userData) { if (isset($userData['pwreset']) && $userData['pwreset']) { $this->session->addFlash("error", "Please set a new password."); $this->picoAuth->getContainer()->get('PasswordReset')->startPasswordResetSession($id); $this->picoAuth->redirectToPage("password_reset"); } }
php
{ "resource": "" }
q249487
LocalAuth.getPasswordEncoder
validation
protected function getPasswordEncoder($userData = null) { if (isset($userData['encoder']) && is_string($userData['encoder'])) { $name = $userData['encoder']; } else { $name = $this->config["encoder"]; } $container = $this->picoAuth->getContainer(); if (!$container->has($name)) { throw new \RuntimeException("Specified LocalAuth encoder is not resolvable."); } return $container->get($name); }
php
{ "resource": "" }
q249488
LocalAuth.userDataEncodePassword
validation
public function userDataEncodePassword(&$userData, Password $newPassword) { $encoderName = $this->config["encoder"]; $encoder = $this->picoAuth->getContainer()->get($encoderName); $userData['pwhash'] = $encoder->encode($newPassword->get()); $userData['encoder'] = $encoderName; if (isset($userData['pwreset'])) { unset($userData['pwreset']); } }
php
{ "resource": "" }
q249489
LocalAuth.checkPasswordPolicy
validation
public function checkPasswordPolicy(Password $password) { $result = true; $policy = $this->picoAuth->getContainer()->get("PasswordPolicy"); $maxAllowedLen = $this->getPasswordEncoder()->getMaxAllowedLen(); if (is_int($maxAllowedLen) && strlen($password)>$maxAllowedLen) { $this->session->addFlash("error", "Maximum length is {$maxAllowedLen}."); $result = false; } if (!$policy->check($password)) { $errors = $policy->getErrors(); foreach ($errors as $error) { $this->session->addFlash("error", $error); } return false; } return $result; }
php
{ "resource": "" }
q249490
LocalAuth.needsPasswordRehash
validation
protected function needsPasswordRehash(array $userData) { // Return if password rehashing is not enabled if ($this->config["login"]["passwordRehash"] !== true) { return false; } // Password hash is created using a different algorithm than default if (isset($userData['encoder']) && $userData['encoder'] !== $this->config["encoder"]) { return true; } $encoder = $this->getPasswordEncoder($userData); // If password hash algorithm options have changed return $encoder->needsRehash($userData['pwhash']); }
php
{ "resource": "" }
q249491
LocalAuth.passwordRehash
validation
protected function passwordRehash($username, Password $password) { $userData = $this->storage->getUserByName($username); try { $this->userDataEncodePassword($userData, $password); } catch (\PicoAuth\Security\Password\Encoder\EncoderException $e) { // The encoder was changed to one that is not able to store this password $this->session->addFlash("error", "Please set a new password."); $this->picoAuth->getContainer()->get('PasswordReset')->startPasswordResetSession($username); $this->picoAuth->redirectToPage("password_reset"); } $this->storage->saveUser($username, $userData); }
php
{ "resource": "" }
q249492
LocalAuth.isValidUsername
validation
protected function isValidUsername($name) { if (!is_string($name) || !$this->storage->checkValidName($name) || strlen($name) < $this->config["registration"]["nameLenMin"] || strlen($name) > $this->config["registration"]["nameLenMax"] ) { return false; } return true; }
php
{ "resource": "" }
q249493
LocalAuth.logInvalidLoginAttempt
validation
protected function logInvalidLoginAttempt($name) { // Trim logged name to the maximum allowed length $max = $this->config["registration"]["nameLenMax"]; if (strlen($name)>$max) { $max = substr($name, 0, $max) . " (trimmed)"; } $this->getLogger()->notice( "Invalid login attempt for {name} by {addr}", array( "name" => $name, "addr" => $_SERVER['REMOTE_ADDR'], ) ); }
php
{ "resource": "" }
q249494
LocalAuth.handleAccountPage
validation
protected function handleAccountPage(Request $httpRequest) { $user = $this->picoAuth->getUser(); if (!$user->getAuthenticated()) { $this->session->addFlash("error", "Login to access this page."); $this->picoAuth->redirectToLogin(); return; } // Page for password editing available only to local accounts if ($user->getAuthenticator() !== $this->getName()) { $this->picoAuth->redirectToPage("index"); return; } $editAccount = $this->picoAuth->getContainer()->get('EditAccount'); $editAccount->setConfig($this->config) ->handleAccountPage($httpRequest); }
php
{ "resource": "" }
q249495
LocalAuth.handleRegistration
validation
protected function handleRegistration(Request $httpRequest) { $registration = $this->picoAuth->getContainer()->get('Registration'); $registration->setConfig($this->config) ->handleRegistration($httpRequest); }
php
{ "resource": "" }
q249496
LocalAuth.handlePasswordReset
validation
protected function handlePasswordReset(Request $httpRequest) { $passwordReset = $this->picoAuth->getContainer()->get('PasswordReset'); $passwordReset->setConfig($this->config) ->handlePasswordReset($httpRequest); }
php
{ "resource": "" }
q249497
OAuth.initProvider
validation
protected function initProvider($providerConfig) { $providerClass = $providerConfig['provider']; $options = $providerConfig['options']; if (!isset($options['redirectUri'])) { // Set OAuth 2.0 callback page from the configuration $options['redirectUri'] = $this->picoAuth->getPico()->getPageUrl($this->config["callbackPage"]); } if (!class_exists($providerClass)) { throw new \RuntimeException("Provider class $providerClass does not exist."); } if (!is_subclass_of($providerClass, AbstractProvider::class, true)) { throw new \RuntimeException("Class $providerClass is not a League\OAuth2 provider."); } $this->provider = new $providerClass($options); $this->providerConfig = $providerConfig; }
php
{ "resource": "" }
q249498
OAuth.startAuthentication
validation
protected function startAuthentication() { $authorizationUrl = $this->provider->getAuthorizationUrl(); $this->session->migrate(true); $this->session->set("oauth2state", $this->provider->getState()); // The final redirect, halts the script $this->picoAuth->redirectToPage($authorizationUrl, null, false); }
php
{ "resource": "" }
q249499
OAuth.finishAuthentication
validation
protected function finishAuthentication(Request $httpRequest) { $sessionCode = $this->session->get("oauth2state"); $this->session->remove("oauth2state"); // Check that the state from OAuth response matches the one in the session if ($httpRequest->query->get("state") !== $sessionCode) { $this->onStateMismatch(); } // Returns one of https://tools.ietf.org/html/rfc6749#section-4.1.2.1 if ($httpRequest->query->has("error")) { $this->onOAuthError($httpRequest->query->get("error")); } // Error not set, but code not present (not an RFC complaint response) if (!$httpRequest->query->has("code")) { $this->onOAuthError("no_code"); } try { $accessToken = $this->provider->getAccessToken('authorization_code', [ 'code' => $httpRequest->query->get("code"), ]); $resourceOwner = $this->provider->getResourceOwner($accessToken); $this->saveLoginInfo($resourceOwner); } catch (IdentityProviderException $e) { $this->onOauthResourceError($e); } }
php
{ "resource": "" }