_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q249500 | OAuth.getResourceAttribute | validation | protected function getResourceAttribute($name, $resourceOwner)
{
// Call resource owner getter first
$method = "get" . $name;
if (is_callable(array($resourceOwner, $method))) {
$res = $resourceOwner->$method();
return $res;
} else {
$resourceArray = $resourceOwner->toArray();
$res = $this->getValueByKey($resourceArray, $name);
return $res;
}
} | php | {
"resource": ""
} |
q249501 | OAuth.saveLoginInfo | validation | protected function saveLoginInfo($resourceOwner)
{
// Initialize the user
$u = new User();
$u->setAuthenticated(true);
$u->setAuthenticator($this->getName());
// Get user id from the Resource Owner
$attrMap = $this->providerConfig['attributeMap'];
$userIdAttr = $attrMap['userId'];
$userId = $this->getResourceAttribute($userIdAttr, $resourceOwner);
$u->setId($userId);
unset($attrMap['userId']);
// Get display name from the Resource Owner (if configured)
if (isset($attrMap['displayName'])) {
$name = $this->getResourceAttribute($attrMap['displayName'], $resourceOwner);
$u->setDisplayName($name);
unset($attrMap['displayName']);
}
// Retrieve all other custom attributes from the attributeMap
foreach ($attrMap as $mapKey => $mapValue) {
$value = $this->getResourceAttribute($mapValue, $resourceOwner);
$u->setAttribute($mapKey, $value);
}
// Set default droups and default attributes
$u->setGroups($this->providerConfig['default']['groups']);
foreach ($this->providerConfig['default']['attributes'] as $key => $value) {
if (null === $u->getAttribute($key)) {
$u->setAttribute($key, $value);
}
}
$this->picoAuth->setUser($u);
$this->picoAuth->afterLogin();
} | php | {
"resource": ""
} |
q249502 | OAuth.saveAfterLogin | validation | protected function saveAfterLogin(Request $httpRequest)
{
$referer = $httpRequest->headers->get("referer", null, true);
$afterLogin = Utils::getRefererQueryParam($referer, "afterLogin");
if ($afterLogin && Utils::isValidPageId($afterLogin)) {
$this->session->set("afterLogin", $afterLogin);
}
} | php | {
"resource": ""
} |
q249503 | OAuth.isValidCallback | validation | protected function isValidCallback(Request $httpRequest)
{
return $this->session->has("provider")
&& $httpRequest->query->has("state")
&& $this->session->has("oauth2state")
&& is_string($this->session->get("oauth2state"))
&& (strlen($this->session->get("oauth2state")) > 0);
} | php | {
"resource": ""
} |
q249504 | OAuth.onStateMismatch | validation | protected function onStateMismatch()
{
$this->logger->warning(
"OAuth2 response state mismatch: provider: {provider} from {addr}",
array(
"provider" => get_class($this->provider),
"addr" => $_SERVER['REMOTE_ADDR']
)
);
$this->session->remove("oauth2state");
$this->session->addFlash("error", "Invalid OAuth response.");
$this->picoAuth->redirectToLogin();
} | php | {
"resource": ""
} |
q249505 | OAuth.onOAuthError | validation | protected function onOAuthError($errorCode)
{
$errorCode = strlen($errorCode > 100) ? substr($errorCode, 0, 100) : $errorCode;
$this->logger->notice(
"OAuth2 error response: code {code}, provider {provider}",
array(
"code" => $errorCode,
"provider" => get_class($this->provider),
)
);
$this->session->addFlash("error", "The provider returned an error ($errorCode)");
$this->picoAuth->redirectToLogin();
} | php | {
"resource": ""
} |
q249506 | OAuth.onOauthResourceError | validation | protected function onOauthResourceError(IdentityProviderException $e)
{
$this->logger->critical(
"OAuth2 IdentityProviderException: {e}, provider {provider}",
array(
"e" => $e->getMessage(),
"provider" => get_class($this->provider),
)
);
$this->session->addFlash("error", "Failed to get an access token or user details.");
$this->picoAuth->redirectToLogin();
} | php | {
"resource": ""
} |
q249507 | File.lock | validation | public function lock($lockType)
{
if (!$this->isOpened()) {
return false;
}
if ($this->options["blocking"]) {
return flock($this->handle, $lockType);
} else {
$tries = 0;
do {
if (flock($this->handle, $lockType | LOCK_NB)) {
return true;
} else {
++$tries;
usleep(self::LOCK_RETRY_WAIT);
}
} while ($tries < self::LOCK_MAX_TRIES);
return false;
}
} | php | {
"resource": ""
} |
q249508 | File.close | validation | public function close()
{
if (!$this->isOpened()) {
return;
}
$this->unlock();
if ($this->handle && !fclose($this->handle)) {
throw new \RuntimeException("Could not close file " . $this->filePath);
}
} | php | {
"resource": ""
} |
q249509 | FileReader.open | validation | public function open()
{
if ($this->isOpened()) {
return;
}
if (!file_exists($this->filePath)) {
throw new \RuntimeException($this->filePath . " does not exist");
}
$this->handle = @fopen($this->filePath, self::OPEN_MODE);
if ($this->handle === false) {
throw new \RuntimeException("Could not open file for reading: " . $this->filePath);
}
if (!$this->lock(LOCK_SH)) {
$this->close();
throw new \RuntimeException("Could not aquire a shared lock for " . $this->filePath);
}
} | php | {
"resource": ""
} |
q249510 | FileReader.read | validation | public function read()
{
$this->open();
// Better performance than fread() from the existing handle
// but it doesn't respect flock
$data = file_get_contents($this->filePath);
if ($data === false) {
throw new \RuntimeException("Could not read from file " . $this->filePath);
}
return $data;
} | php | {
"resource": ""
} |
q249511 | PageLock.isUnlocked | validation | protected function isUnlocked($lockId)
{
$unlocked = $this->session->get("unlocked");
if ($unlocked && in_array($lockId, $unlocked)) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q249512 | PageLock.getKeyEncoder | validation | protected function getKeyEncoder($lockData)
{
if (isset($lockData['encoder']) && is_string($lockData['encoder'])) {
$name = $lockData['encoder'];
} else {
$name = $this->config["encoder"];
}
try {
$instance = $this->picoAuth->getContainer()->get($name);
} catch (\Exception $e) {
throw new \RuntimeException("Specified PageLock encoder not resolvable.");
}
return $instance;
} | php | {
"resource": ""
} |
q249513 | LocalAuthConfigurator.validateUsersSection | validation | public function validateUsersSection(&$config)
{
if (!isset($config["users"])) {
// No users are specified in the configuration file
return;
}
$this->assertArray($config, "users");
foreach ($config["users"] as $username => $userData) {
$this->assertUsername($username, $config);
try {
$this->validateUserData($userData);
} catch (ConfigurationException $e) {
$e->addBeforeMessage("Invalid userdata for $username:");
throw $e;
}
// Assure case insensitivity of username indexing
$lowercaseName = strtolower($username);
if ($username !== $lowercaseName) {
if (!isset($config["users"][$lowercaseName])) {
$config["users"][$lowercaseName] = $userData;
unset($config["users"][$username]);
} else {
throw new ConfigurationException("User $username is defined multiple times.");
}
}
}
} | php | {
"resource": ""
} |
q249514 | LocalAuthConfigurator.validateUserData | validation | public function validateUserData($userData)
{
$this->assertRequired($userData, "pwhash");
$this->assertString($userData, "pwhash");
// All remaining options are optional
$this->assertString($userData, "email");
$this->assertArray($userData, "attributes");
$this->assertString($userData, "encoder");
$this->assertBool($userData, "pwreset");
$this->assertArrayOfStrings($userData, "groups");
$this->assertString($userData, "displayName");
} | php | {
"resource": ""
} |
q249515 | LocalAuthConfigurator.assertUsername | validation | public function assertUsername($username, $config)
{
if (!is_string($username)) {
throw new ConfigurationException("Username $username must be a string.");
}
$len = strlen($username);
$minLen=$config["registration"]["nameLenMin"];
$maxLen=$config["registration"]["nameLenMax"];
if ($len < $minLen || $len > $maxLen) {
throw new ConfigurationException(
sprintf("Length of a username $username must be between %d-%d characters.", $minLen, $maxLen)
);
}
if (!$this->checkValidNameFormat($username)) {
throw new ConfigurationException("Username $username contains invalid character/s.");
}
} | php | {
"resource": ""
} |
q249516 | PicoAuthPlugin.handleEvent | validation | public function handleEvent($eventName, array $params)
{
if (method_exists($this, $eventName)) {
call_user_func_array(array($this, $eventName), $params);
}
} | php | {
"resource": ""
} |
q249517 | PicoAuthPlugin.triggerEvent | validation | public function triggerEvent($eventName, array $params = array())
{
foreach ($this->modules as $module) {
$module->handleEvent($eventName, $params);
}
} | php | {
"resource": ""
} |
q249518 | PicoAuthPlugin.onConfigLoaded | validation | public function onConfigLoaded(array &$config)
{
$config[self::PLUGIN_NAME] = $this->loadDefaultConfig($config);
$this->config = $config[self::PLUGIN_NAME];
$this->createContainer();
$this->initLogger();
} | php | {
"resource": ""
} |
q249519 | PicoAuthPlugin.onRequestUrl | validation | public function onRequestUrl(&$url)
{
$this->requestUrl = $url;
try {
// Plugin initialization
$this->init();
// Check submissions in all modules and apply their routers
$this->triggerEvent('onPicoRequest', [$url, $this->request]);
} catch (\Exception $e) {
$this->errorHandler($e, $url);
}
if (!$this->errorOccurred) {
$this->authRoutes();
}
} | php | {
"resource": ""
} |
q249520 | PicoAuthPlugin.onRequestFile | validation | public function onRequestFile(&$file)
{
// A special case for an error state of the plugin
if ($this->errorOccurred) {
$file = $this->requestFile;
return;
}
try {
// Resolve a normalized version of the url
$realUrl = ($this->requestFile) ? $this->requestUrl : $this->resolveRealUrl($file);
// Authorization
if (!in_array($realUrl, $this->alwaysAllowed, true)) {
$this->triggerEvent('denyAccessIfRestricted', [$realUrl]);
}
} catch (\Exception $e) {
$realUrl = (isset($realUrl)) ? $realUrl : "";
$this->errorHandler($e, $realUrl);
}
if ($this->requestFile) {
$file = $this->requestFile;
} else {
switch ($this->requestUrl) {
case 'login':
$file = $this->pluginDir . '/content/login.md';
break;
case 'logout':
$file = $this->pluginDir . '/content/logout.md';
break;
}
}
} | php | {
"resource": ""
} |
q249521 | PicoAuthPlugin.onPagesLoaded | validation | public function onPagesLoaded(array &$pages)
{
unset($pages["403"]);
if (!$this->config["alterPageArray"]) {
return;
}
// Erase all pages if an error occurred
if ($this->errorOccurred) {
$pages = array();
return;
}
foreach ($pages as $id => $page) {
try {
$allowed = $this->checkAccess($id);
} catch (\Exception $e) {
$this->errorHandler($e, $this->requestUrl);
$pages = array();
return;
}
if (!$allowed) {
unset($pages[$id]);
}
}
} | php | {
"resource": ""
} |
q249522 | PicoAuthPlugin.onTwigRegistered | validation | public function onTwigRegistered(&$twig)
{
// If a theme is not found, it will be searched for in PicoAuth/theme
$twig->getLoader()->addPath($this->pluginDir . '/theme');
$this_instance = $this;
$twig->addFunction(
new \Twig_SimpleFunction(
'csrf_token',
function ($action = null) use (&$this_instance) {
return $this_instance->csrf->getToken($action);
},
array('is_safe' => array('html'))
)
);
$twig->addFunction(
new \Twig_SimpleFunction(
'csrf_field',
function ($action = null) use (&$this_instance) {
return '<input type="hidden" name="csrf_token" value="'
. $this_instance->csrf->getToken($action)
. '">';
},
array('is_safe' => array('html'))
)
);
} | php | {
"resource": ""
} |
q249523 | PicoAuthPlugin.onPageRendering | validation | public function onPageRendering(&$templateName, array &$twigVariables)
{
$twigVariables['auth']['plugin'] = $this;
$twigVariables['auth']['vars'] = $this->output;
// Variables useful only in successful execution
if (!$this->errorOccurred) {
$twigVariables['auth']['user'] = $this->user;
// Previous form submission
$old = $this->session->getFlash('old');
if (count($old) && isset($old[0])) {
$twigVariables['auth']['old'] = $old[0];
}
}
} | php | {
"resource": ""
} |
q249524 | PicoAuthPlugin.resolveRealUrl | validation | protected function resolveRealUrl($fileName)
{
$fileNameClean = str_replace("\0", '', $fileName);
$realPath = realpath($fileNameClean);
if ($realPath === false) {
// the page doesn't exist or realpath failed
return $this->requestUrl;
}
// Get Pico content path and file extension
$contentPath = realpath($this->pico->getConfig('content_dir'));
$contentExt = $this->pico->getConfig('content_ext');
if (strpos($realPath, $contentPath) !== 0) {
// The file is not inside the content path (symbolic link)
throw new \RuntimeException("The plugin cannot be used with "
. "symbolic links inside the content directory.");
}
// Get a relative path of $realPath from inside the $contentPath and remove an extension
// len+1 to remove trailing path delimeter, which $contentPath doesn't have
$name = substr($realPath, strlen($contentPath)+1, -strlen($contentExt));
// Always use forward slashes
if (DIRECTORY_SEPARATOR !== '/') {
$name = str_replace(DIRECTORY_SEPARATOR, '/', $name);
}
// If the name ends with "/index", remove it, for the main page returns ""
if (strlen($name) >= 5 && 0 === substr_compare($name, "index", -5)) {
$name= rtrim(substr($name, 0, -5), '/');
}
return $name;
} | php | {
"resource": ""
} |
q249525 | PicoAuthPlugin.init | validation | protected function init()
{
$this->loadModules();
$this->session = $this->container->get('session');
$this->csrf = new CSRF($this->session);
$this->user = $this->getUserFromSession();
$this->request = Request::createFromGlobals();
// Auto regenerate_id on specified intervals
$this->sessionTimeoutCheck("sessionInterval", "_migT", false);
// Enforce absolute maximum duration of a session
$this->sessionTimeoutCheck("sessionTimeout", "_start", true);
// Invalidate session if it is idle for too long
$this->sessionTimeoutCheck("sessionIdle", "_idle", true, true);
} | php | {
"resource": ""
} |
q249526 | PicoAuthPlugin.sessionTimeoutCheck | validation | protected function sessionTimeoutCheck($configKey, $sessKey, $clear, $alwaysUpdate = false)
{
if ($this->config[$configKey] !== false) {
$t = time();
if ($this->session->has($sessKey)) {
if ($this->session->get($sessKey) < $t - $this->config[$configKey]) {
if ($clear) {
$this->session->invalidate();
} else {
$this->session->migrate(true);
}
$this->session->set($sessKey, $t);
} elseif ($alwaysUpdate) {
$this->session->set($sessKey, $t);
}
} else {
$this->session->set($sessKey, $t);
}
}
} | php | {
"resource": ""
} |
q249527 | PicoAuthPlugin.loadDefaultConfig | validation | protected function loadDefaultConfig(array $config)
{
$configurator = new PluginConfigurator;
$validConfig = $configurator->validate(
isset($config[self::PLUGIN_NAME]) ? $config[self::PLUGIN_NAME] : null
);
return $validConfig;
} | php | {
"resource": ""
} |
q249528 | PicoAuthPlugin.createContainer | validation | protected function createContainer()
{
$configDir = $this->pico->getConfigDir();
$userContainer = $configDir . "PicoAuth/container.php";
// If a user provided own container definiton, it is used
if (is_file($userContainer) && is_readable($userContainer)) {
$this->container = include $userContainer;
if ($this->container === false || !($this->container instanceof \League\Container\Container)) {
throw new \RuntimeException("The container.php does not return container instance.");
}
} else {
$this->container = include $this->pluginDir . '/src/container.php';
}
// Additional container entries
$this->container->share('configDir', new \League\Container\Argument\RawArgument($configDir));
$this->container->share('PicoAuth', $this);
if (!$this->config["rateLimit"]) {
$this->container->share('RateLimit', \PicoAuth\Security\RateLimiting\NullRateLimit::class);
}
} | php | {
"resource": ""
} |
q249529 | PicoAuthPlugin.loadModules | validation | protected function loadModules()
{
foreach ($this->config["authModules"] as $name) {
try {
$instance = $this->container->get($name);
} catch (\League\Container\Exception\NotFoundException $e) {
if (!class_exists($name)) {
throw new \RuntimeException("PicoAuth module not found: " . $name);
}
$instance = new $name;
}
if (!is_subclass_of($instance, Module\AbstractAuthModule::class, false)) {
throw new \RuntimeException("PicoAuth module class must inherit from AbstractAuthModule.");
}
$name = $instance->getName();
$this->modules[$name] = $instance;
}
} | php | {
"resource": ""
} |
q249530 | PicoAuthPlugin.authRoutes | validation | protected function authRoutes()
{
switch ($this->requestUrl) {
case 'login':
// Redirect already authenticated user visiting login page
if ($this->user->getAuthenticated()) {
$this->redirectToPage($this->config["afterLogin"]);
}
break;
case 'logout':
// Redirect non authenticated user to login
if (!$this->user->getAuthenticated()) {
$this->redirectToLogin();
}
$this->checkLogoutSubmission();
break;
}
} | php | {
"resource": ""
} |
q249531 | PicoAuthPlugin.checkLogoutSubmission | validation | protected function checkLogoutSubmission()
{
$post = $this->request->request;
if ($post->has("logout")) {
if (!$this->isValidCSRF($post->get("csrf_token"), self::LOGOUT_CSRF_ACTION)) {
$this->redirectToPage("logout");
}
$this->logout();
}
} | php | {
"resource": ""
} |
q249532 | PicoAuthPlugin.logout | validation | protected function logout()
{
$oldUser = $this->user;
$this->user = new User();
// Removes all session data (and invalidates all CSRF tokens)
$this->session->invalidate();
$this->triggerEvent("afterLogout", [$oldUser]);
// After logout redirect to main page
// If user was on restricted page, 403 would appear right after logout
$this->redirectToPage($this->config["afterLogout"]);
} | php | {
"resource": ""
} |
q249533 | PicoAuthPlugin.checkAccess | validation | protected function checkAccess($url)
{
foreach ($this->modules as $module) {
if (false === $module->handleEvent('checkAccess', [$url])) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q249534 | PicoAuthPlugin.errorHandler | validation | protected function errorHandler(\Exception $e, $url = "")
{
$this->errorOccurred = true;
$this->requestFile = $this->pluginDir . '/content/error.md';
if ($this->config["debug"] === true) {
$this->addOutput("_exception", (string)$e);
}
$this->logger->critical(
"Exception on url '{url}': {e}",
array(
"url" => $url,
"e" => $e
)
);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
// Change url to prevent other plugins that use url-based routing from
// changing the request file.
$this->requestUrl="500";
} | php | {
"resource": ""
} |
q249535 | RateLimitFileStorage.openTransactionFile | validation | private function openTransactionFile($id)
{
if (!isset($this->tFiles[$id])) {
self::preparePath($this->dir, self::DATA_DIR);
$fileName = $this->dir . static::DATA_DIR . $id;
$handle = @fopen($fileName, 'c+');
if ($handle === false) {
throw new \RuntimeException("Could not open file: " . $fileName);
}
$this->tFiles[$id] = new \PicoAuth\Storage\File\FileReader(
$fileName,
["handle"=>$handle]
);
}
} | php | {
"resource": ""
} |
q249536 | FileWriter.open | validation | public function open()
{
if ($this->isOpened()) {
return;
}
$this->handle = @fopen($this->filePath, self::OPEN_MODE);
if ($this->handle === false) {
throw new \RuntimeException("Could not open file for writing: " . $this->filePath);
}
if (!$this->lock(LOCK_EX)) {
$this->close();
throw new \RuntimeException("Could not aquire an exclusive lock for " . $this->filePath);
}
if ($this->options["backup"]) {
$this->createBkFile();
}
$this->writeErrors = false;
} | php | {
"resource": ""
} |
q249537 | FileWriter.write | validation | public function write($data)
{
if (!is_string($data)) {
throw new \InvalidArgumentException("The data is not a string.");
}
$this->open();
if (!ftruncate($this->handle, 0)) {
$this->writeErrors = true;
throw new \RuntimeException("Could not truncate file " . $this->filePath);
}
fseek($this->handle, 0);
$res = fwrite($this->handle, $data);
if (strlen($data) !== $res) {
$this->writeErrors = true;
throw new \RuntimeException("Could not write to file " . $this->filePath);
}
} | php | {
"resource": ""
} |
q249538 | FileWriter.createBkFile | validation | protected function createBkFile()
{
if (!is_writable(dirname($this->filePath))) {
return;
}
$this->bkFilePath = $this->filePath . '.' . date("y-m-d-H-i-s") . '.bak';
$bkHandle = @fopen($this->bkFilePath, 'x+');
if ($bkHandle === false) {
$this->close();
throw new \RuntimeException("Could not create a temporary file " . $this->bkFilePath);
}
$stat = fstat($this->handle);
if (stream_copy_to_stream($this->handle, $bkHandle) !== $stat['size']) {
$this->close();
throw new \RuntimeException("Could not create a copy of " . $this->filePath);
}
if (!fclose($bkHandle)) {
throw new \RuntimeException("Could not close a backup file " . $this->bkFilePath);
}
fseek($this->handle, 0);
} | php | {
"resource": ""
} |
q249539 | FileWriter.removeBkFile | validation | protected function removeBkFile()
{
if (!$this->options["backup"]) {
return;
}
// Remove backup file if the write was successful
if (!$this->writeErrors && $this->bkFilePath) {
unlink($this->bkFilePath);
}
} | php | {
"resource": ""
} |
q249540 | PageACL.addRule | validation | public function addRule($url, $rule)
{
if (!is_string($url) || !is_array($rule)) {
throw new \InvalidArgumentException("addRule() expects a string and an array.");
}
$this->runtimeRules[$url] = $rule;
} | php | {
"resource": ""
} |
q249541 | PicoAuth.handleEvent | validation | public function handleEvent($eventName, array $params)
{
parent::handleEvent($eventName, $params);
if ($this->isEnabled()) {
$this->picoAuthPlugin->handleEvent($eventName, $params);
}
} | php | {
"resource": ""
} |
q249542 | EditAccount.handleAccountPage | validation | public function handleAccountPage(Request $httpRequest)
{
// Check if the functionality is enabled by the configuration
if (!$this->config["enabled"]) {
return;
}
$user = $this->picoAuth->getUser();
$this->picoAuth->addAllowed("account");
$this->picoAuth->setRequestFile($this->picoAuth->getPluginPath() . '/content/account.md');
//check form submission
$post = $httpRequest->request;
if ($post->has("new_password")
&& $post->has("new_password_repeat")
&& $post->has("old_password")
) {
$newPassword = new Password($post->get("new_password"));
$newPasswordRepeat = new Password($post->get("new_password_repeat"));
$oldPassword = new Password($post->get("old_password"));
$username = $user->getId();
// CSRF validation
if (!$this->picoAuth->isValidCSRF($post->get("csrf_token"))) {
$this->picoAuth->redirectToPage("account");
}
if ($newPassword->get() !== $newPasswordRepeat->get()) {
$this->session->addFlash("error", "The passwords do not match.");
$this->picoAuth->redirectToPage("account");
}
// The current password check
$localAuth = $this->picoAuth->getContainer()->get('LocalAuth');
if (!$localAuth->loginAttempt($username, $oldPassword)) {
$this->session->addFlash("error", "The current password is incorrect");
$this->picoAuth->redirectToPage("account");
}
// Check password policy
if (!$localAuth->checkPasswordPolicy($newPassword)) {
$this->picoAuth->redirectToPage("account");
}
// Save user data
$userData = $this->storage->getUserByName($username);
$localAuth->userDataEncodePassword($userData, $newPassword);
$this->storage->saveUser($username, $userData);
$this->session->addFlash("success", "Password changed successfully.");
$this->picoAuth->redirectToPage("account");
}
} | php | {
"resource": ""
} |
q249543 | AbstractConfigurator.assertArray | validation | public function assertArray($config, $key)
{
if (array_key_exists($key, $config) && !is_array($config[$key])) {
throw new ConfigurationException($key." section must be an array.");
}
return $this;
} | php | {
"resource": ""
} |
q249544 | AbstractConfigurator.assertBool | validation | public function assertBool($config, $key)
{
if (array_key_exists($key, $config) && !is_bool($config[$key])) {
throw new ConfigurationException($key." must be a boolean value.");
}
return $this;
} | php | {
"resource": ""
} |
q249545 | AbstractConfigurator.assertInteger | validation | public function assertInteger($config, $key, $lowest = null, $highest = null)
{
if (array_key_exists($key, $config)) {
if (!is_int($config[$key])) {
throw new ConfigurationException($key." must be an integer.");
}
if ($lowest !== null && $config[$key] < $lowest) {
throw new ConfigurationException($key." cannot be lower than ".$lowest);
}
if ($highest !== null && $config[$key] > $highest) {
throw new ConfigurationException($key." cannot be higher than ".$highest);
}
}
return $this;
} | php | {
"resource": ""
} |
q249546 | AbstractConfigurator.assertGreaterThan | validation | public function assertGreaterThan($config, $keyGreater, $keyLower)
{
if (!isset($config[$keyLower])
|| !isset($config[$keyGreater])
|| $config[$keyLower] >= $config[$keyGreater]) {
throw new ConfigurationException($keyGreater." must be greater than ".$keyLower);
}
return $this;
} | php | {
"resource": ""
} |
q249547 | AbstractConfigurator.assertString | validation | public function assertString($config, $key)
{
if (array_key_exists($key, $config) && !is_string($config[$key])) {
throw new ConfigurationException($key." must be a string.");
}
return $this;
} | php | {
"resource": ""
} |
q249548 | AbstractConfigurator.assertStringContaining | validation | public function assertStringContaining($config, $key, $searchedPart)
{
$this->assertString($config, $key);
if (array_key_exists($key, $config) && strpos($config[$key], $searchedPart) === false) {
throw new ConfigurationException($key." must contain ".$searchedPart);
}
return $this;
} | php | {
"resource": ""
} |
q249549 | AbstractConfigurator.assertArrayOfStrings | validation | public function assertArrayOfStrings($config, $key)
{
if (!array_key_exists($key, $config)) {
return $this;
}
if (!is_array($config[$key])) {
throw new ConfigurationException($key." section must be an array.");
}
foreach ($config[$key] as $value) {
if (!is_string($value)) {
throw new ConfigurationException("Values in the `{$key}` must be strings"
. gettype($value) . " found.");
} elseif ($value==="") {
throw new ConfigurationException("Empty string not allowed in `{$key}` array.");
}
}
return $this;
} | php | {
"resource": ""
} |
q249550 | AbstractConfigurator.assertIntOrFalse | validation | public function assertIntOrFalse($config, $key, $lowest = null, $highest = null)
{
try {
$this->assertInteger($config, $key, $lowest, $highest);
} catch (ConfigurationException $e) {
if ($config[$key]!==false) {
throw new ConfigurationException(
"Key `{$key}` can be either false or a non-negative integer."
);
}
}
return $this;
} | php | {
"resource": ""
} |
q249551 | AbstractConfigurator.standardizeUrlFormat | validation | public function standardizeUrlFormat(&$rules, $pageUrl)
{
if (!is_string($pageUrl) || $pageUrl==="" || !is_array($rules) ||
!array_key_exists($pageUrl, $rules) ) {
return;
}
$oldIndex=$pageUrl;
if ($pageUrl[0] !== '/') {
$pageUrl='/'.$pageUrl;
}
$len=strlen($pageUrl);
if ($len>1 && $pageUrl[$len-1]==='/') {
$pageUrl= rtrim($pageUrl, '/');
}
if ($oldIndex!==$pageUrl) {
$rules[$pageUrl]=$rules[$oldIndex];
unset($rules[$oldIndex]);
}
} | php | {
"resource": ""
} |
q249552 | AbstractConfigurator.applyDefaults | validation | public function applyDefaults($config, array $defaults, $depth = 1)
{
if (!is_int($depth) || $depth < 0) {
throw new \InvalidArgumentException("Depth must be non-negative integer.");
}
if (!is_array($config)) {
return $defaults;
}
if ($depth === 0) {
$config += $defaults;
return $config;
}
foreach ($defaults as $key => $defaultValue) {
// Use the default value, if user's array is missing this key
if (!isset($config[$key])) {
$config[$key] = $defaultValue;
continue;
}
if (is_array($defaultValue)) {
if (is_array($config[$key])) {
$config[$key] = $this->applyDefaults($config[$key], $defaultValue, $depth-1);
} else {
throw new ConfigurationException("Configuration key "
.$key." expects an array, a scalar value found.");
}
} else {
if (is_array($config[$key])) {
throw new ConfigurationException("Configuration key "
.$key." expects scalar, an array found.");
}
}
}
return $config;
} | php | {
"resource": ""
} |
q249553 | PasswordReset.handlePasswordReset | validation | public function handlePasswordReset(Request $httpRequest)
{
$this->httpRequest = $httpRequest;
// Check if a valid reset link is present
$this->checkResetLink();
// Check if the user already has a password reset session
$resetData = $this->session->get("pwreset");
if ($resetData === null) {
$this->beginPasswordReset();
} else {
$this->finishPasswordReset($resetData);
}
} | php | {
"resource": ""
} |
q249554 | PasswordReset.beginPasswordReset | validation | protected function beginPasswordReset()
{
// Check if password reset is enabled
if (!$this->config["enabled"]) {
return;
}
$this->picoAuth->addAllowed("password_reset");
$this->picoAuth->setRequestFile($this->picoAuth->getPluginPath() . '/content/pwbeginreset.md');
if (count($this->session->getFlash('_pwresetsent'))) {
$this->picoAuth->addOutput("resetSent", true);
return;
}
$post = $this->httpRequest->request;
if ($post->has("reset_email")) {
// CSRF validation
if (!$this->picoAuth->isValidCSRF($post->get("csrf_token"))) {
$this->picoAuth->redirectToPage("password_reset");
}
$email = trim($post->get("reset_email"));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->session->addFlash("error", "Email address does not have a valid format.");
$this->picoAuth->redirectToPage("password_reset");
}
// Check if the action is not rate limited
if (!$this->limit->action("passwordReset", true, array("email" => $email))) {
$this->session->addFlash("error", $this->limit->getError());
$this->picoAuth->redirectToPage("password_reset");
}
if ($userData = $this->storage->getUserByEmail($email)) {
$this->sendResetMail($userData);
}
// Always display a message with success
$this->session->addFlash("_pwresetsent", true);
$this->session->addFlash("success", "Reset link sent via email.");
$this->picoAuth->redirectToPage("password_reset");
}
} | php | {
"resource": ""
} |
q249555 | PasswordReset.finishPasswordReset | validation | protected function finishPasswordReset(array $resetData)
{
if (time() > $resetData['validity']) {
$this->session->remove("pwreset");
$this->session->addFlash("error", "Page validity expired, please try again.");
$this->picoAuth->redirectToLogin();
}
$this->picoAuth->addOutput("isReset", true);
$this->picoAuth->setRequestFile($this->picoAuth->getPluginPath() . '/content/pwreset.md');
// Check the form submission
$post = $this->httpRequest->request;
if ($post->has("new_password")
&& $post->has("new_password_repeat")
) {
$newPassword = new Password($post->get("new_password"));
$newPasswordRepeat = new Password($post->get("new_password_repeat"));
$username = $resetData['user'];
// CSRF validation
if (!$this->picoAuth->isValidCSRF($post->get("csrf_token"))) {
$this->picoAuth->redirectToPage("password_reset");
}
if ($newPassword->get() !== $newPasswordRepeat->get()) {
$this->session->addFlash("error", "The passwords do not match.");
$this->picoAuth->redirectToPage("password_reset");
}
// Check password policy
$localAuth = $this->picoAuth->getContainer()->get('LocalAuth');
if (!$localAuth->checkPasswordPolicy($newPassword)) {
$this->picoAuth->redirectToPage("password_reset");
}
// Remove pwreset record on successful submission
$this->session->remove("pwreset");
// Save the new userdata
$userData = $this->storage->getUserByName($username);
$localAuth->userDataEncodePassword($userData, $newPassword);
$this->storage->saveUser($username, $userData);
$this->logPasswordReset($username);
$localAuth->login($username, $userData);
$this->picoAuth->afterLogin();
}
} | php | {
"resource": ""
} |
q249556 | PasswordReset.checkResetLink | validation | protected function checkResetLink()
{
// Check if the reset links are enabled, if token is present,
// if it has a valid format and length
if (!$this->config["enabled"]
|| !($token = $this->httpRequest->query->get("confirm", false))
|| !preg_match("/^[a-f0-9]+$/", $token)
|| strlen($token) !== 2*($this->config["tokenIdLen"]+$this->config["tokenLen"])) {
return;
}
// Delete the active password reset session, if set
$this->session->remove("pwreset");
// Split token parts
$tokenId = substr($token, 0, 2 * $this->config["tokenIdLen"]);
$verifier = substr($token, 2 * $this->config["tokenIdLen"]);
// Validate token timeout
$tokenData = $this->storage->getResetToken($tokenId);
// Token not found or expired
if (!$tokenData || time() > $tokenData['valid']) {
$this->session->addFlash("error", "Reset link has expired.");
$this->getLogger()->warning("Bad reset token {t} from {addr}", [$token, $_SERVER['REMOTE_ADDR']]);
$this->picoAuth->redirectToPage("password_reset");
}
if (hash_equals($tokenData['token'], hash('sha256', $verifier))) {
$this->session->addFlash("success", "Please set a new password.");
$this->startPasswordResetSession($tokenData['user']);
$this->logResetLinkVisit($tokenData);
$this->picoAuth->redirectToPage("password_reset");
}
} | php | {
"resource": ""
} |
q249557 | PasswordReset.startPasswordResetSession | validation | public function startPasswordResetSession($user)
{
$this->session->migrate(true);
$this->session->set("pwreset", array(
'user' => $user,
'validity' => time() + $this->config["resetTimeout"]
));
} | php | {
"resource": ""
} |
q249558 | PasswordReset.sendResetMail | validation | protected function sendResetMail($userData)
{
if (!$this->mailer) {
$this->getLogger()->critical("Sending mail but no mailer is set!");
return;
}
$url = $this->createResetToken($userData['name']);
// Replaces Pico-specific placeholders (like %site_title%)
$message = $this->picoAuth->getPico()->substituteFileContent($this->config["emailMessage"]);
$subject = $this->picoAuth->getPico()->substituteFileContent($this->config["emailSubject"]);
// Replaces placeholders in the configured email message template
$message = str_replace("%url%", $url, $message);
$message = str_replace("%username%", $userData['name'], $message);
$this->mailer->setup();
$this->mailer->setTo($userData['email']);
$this->mailer->setSubject($subject);
$this->mailer->setBody($message);
if (!$this->mailer->send()) {
$this->getLogger()->critical("Mailer error: {e}", ["e" => $this->mailer->getError()]);
} else {
$this->getLogger()->info("PwReset email sent to {email}", ["email" => $userData['email']]);
}
} | php | {
"resource": ""
} |
q249559 | PasswordPolicy.minLength | validation | public function minLength($n)
{
$this->constraints[] = (function (Password $str) use ($n) {
if (mb_strlen($str) < $n) {
return sprintf("Minimum password length is %d characters.", $n);
} else {
return true;
}
});
return $this;
} | php | {
"resource": ""
} |
q249560 | PasswordPolicy.matches | validation | public function matches($regexp, $message)
{
if (!is_string($regexp) || !is_string($message)) {
throw new \InvalidArgumentException("Both arguments must be string.");
}
$this->constraints[] = (function (Password $str) use ($regexp, $message) {
if (!preg_match($regexp, $str)) {
return $message;
} else {
return true;
}
});
return $this;
} | php | {
"resource": ""
} |
q249561 | Client.getCaptchaResultBulk | validation | public function getCaptchaResultBulk(array $captchaIds)
{
$response = $this->getHttpClient()->request('GET', '/res.php?' . http_build_query([
'key' => $this->apiKey,
'action' => 'get',
'ids' => join(',', $captchaIds)
]));
$captchaTexts = $response->getBody()->__toString();
$this->getLogger()->info("Got bulk response: `{$captchaTexts}`.");
$captchaTexts = explode("|", $captchaTexts);
$result = [];
foreach ($captchaTexts as $index => $captchaText) {
$captchaText = html_entity_decode(trim($captchaText));
$result[$captchaIds[$index]] =
($captchaText == self::STATUS_CAPTCHA_NOT_READY) ? false : $captchaText;
}
return $result;
} | php | {
"resource": ""
} |
q249562 | Client.badCaptcha | validation | public function badCaptcha($captchaId)
{
$response = $this
->getHttpClient()
->request('GET', "/res.php?key={$this->apiKey}&action=reportbad&id={$captchaId}");
$responseText = $response->getBody()->__toString();
if ($responseText === self::STATUS_OK_REPORT_RECORDED) {
return true;
}
throw new ErrorResponseException(
$this->getErrorMessage($responseText) ?: $responseText,
$this->getErrorCode($responseText) ?: 0
);
} | php | {
"resource": ""
} |
q249563 | Client.getLoad | validation | public function getLoad($paramsList = ['waiting', 'load', 'minbid', 'averageRecognitionTime'])
{
$parser = $this->getLoadXml();
if (is_string($paramsList)) {
return $parser->$paramsList->__toString();
}
$statusData = [];
foreach ($paramsList as $item) {
$statusData[$item] = $parser->$item->__toString();
}
return $statusData;
} | php | {
"resource": ""
} |
q249564 | Client.addPingback | validation | public function addPingback($url)
{
$response = $this
->getHttpClient()
->request('GET', "/res.php?key={$this->apiKey}&action=add_pingback&addr={$url}");
$responseText = $response->getBody()->__toString();
if ($responseText === self::STATUS_OK) {
return true;
}
throw new ErrorResponseException(
$this->getErrorMessage($responseText) ?: $responseText,
$this->getErrorCode($responseText) ?: 0
);
} | php | {
"resource": ""
} |
q249565 | Client.getPingbacks | validation | public function getPingbacks()
{
$response = $this
->getHttpClient()
->request('GET', "/res.php?key={$this->apiKey}&action=get_pingback");
$responseText = $response->getBody()->__toString();
if (strpos($responseText, 'OK|') !== false) {
$data = explode('|', $responseText);
unset($data[0]);
return empty($data[1]) ? [] : array_values($data);
}
throw new ErrorResponseException(
$this->getErrorMessage($responseText) ?: $responseText,
$this->getErrorCode($responseText) ?: 0
);
} | php | {
"resource": ""
} |
q249566 | Client.deletePingback | validation | public function deletePingback($uri)
{
$response = $this
->getHttpClient()
->request('GET', "/res.php?key={$this->apiKey}&action=del_pingback&addr={$uri}");
$responseText = $response->getBody()->__toString();
if ($responseText === self::STATUS_OK) {
return true;
}
throw new ErrorResponseException(
$this->getErrorMessage($responseText) ?: $responseText,
$this->getErrorCode($responseText) ?: 0
);
} | php | {
"resource": ""
} |
q249567 | Client.sendRecaptchaV2 | validation | public function sendRecaptchaV2($googleKey, $pageUrl, $extra = [])
{
$this->getLogger()->info("Try send google key (recaptcha) on {$this->serverBaseUri}/in.php");
if ($this->softId && !isset($extra[Extra::SOFT_ID])) {
$extra[Extra::SOFT_ID] = $this->softId;
}
$response = $this->getHttpClient()->request('POST', "/in.php", [
RequestOptions::QUERY => array_merge($extra, [
'method' => 'userrecaptcha',
'key' => $this->apiKey,
'googlekey' => $googleKey,
'pageurl' => $pageUrl
])
]);
$responseText = $response->getBody()->__toString();
if (strpos($responseText, 'OK|') !== false) {
$this->lastCaptchaId = explode("|", $responseText)[1];
$this->getLogger()->info("Sending success. Got captcha id `{$this->lastCaptchaId}`.");
return $this->lastCaptchaId;
}
throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`.");
} | php | {
"resource": ""
} |
q249568 | Client.recognizeRecaptchaV2 | validation | public function recognizeRecaptchaV2($googleKey, $pageUrl, $extra = [])
{
$captchaId = $this->sendRecaptchaV2($googleKey, $pageUrl, $extra);
$startTime = time();
while (true) {
$this->getLogger()->info("Waiting {$this->rTimeout} sec.");
sleep($this->recaptchaRTimeout);
if (time() - $startTime >= $this->mTimeout) {
throw new RuntimeException("Captcha waiting timeout.");
}
$result = $this->getCaptchaResult($captchaId);
if ($result === false) {
continue;
}
$this->getLogger()->info("Elapsed " . (time()-$startTime) . " second(s).");
return $result;
}
throw new RuntimeException('Unknown recognition logic error.');
} | php | {
"resource": ""
} |
q249569 | Client.getCaptchaResult | validation | public function getCaptchaResult($captchaId)
{
$response = $this
->getHttpClient()
->request('GET', "/res.php?key={$this->apiKey}&action=get&id={$captchaId}&json=1");
$responseData = json_decode($response->getBody()->__toString(), true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new InvalidArgumentException(
'json_decode error: ' . json_last_error_msg()
);
}
if ($responseData['status'] === self::STATUS_CODE_CAPCHA_NOT_READY) {
return false;
}
if ($responseData['status'] === self::STATUS_CODE_OK) {
$this->getLogger()->info("Got OK response: `{$responseData['request']}`.");
return $responseData['request'];
}
throw new ErrorResponseException(
$this->getErrorMessage(
$responseData['request']
) ?: $responseData['request'],
$responseData['status']
);
} | php | {
"resource": ""
} |
q249570 | Builder.whereExists | validation | public function whereExists(Closure $callback, $boolean = 'and', $not = false)
{
$type = $not ? 'NotExists' : 'Exists';
$this->wheres[] = compact('type', 'callback', 'boolean');
return $this;
} | php | {
"resource": ""
} |
q249571 | Driver.connect | validation | public function connect(array $params, $username = null, $password = null, array $driverOptions = [])
{
if (PlatformHelper::isWindows()) {
return $this->connectWindows($params, $username, $password, $driverOptions);
}
return $this->connectUnix($params, $username, $password, $driverOptions);
} | php | {
"resource": ""
} |
q249572 | Driver.constructPdoDsn | validation | public function constructPdoDsn(array $params)
{
if (PlatformHelper::isWindows()) {
return $this->constructPdoDsnWindows($params);
}
return $this->constructPdoDsnUnix($params);
} | php | {
"resource": ""
} |
q249573 | DblibSchemaManager.listSequences | validation | public function listSequences($database = null)
{
$query = "SELECT name FROM sysobjects WHERE xtype = 'U'";
$tableNames = $this->_conn->fetchAll($query);
return array_map([$this->_conn->formatter, 'fixSequenceName'], $tableNames);
} | php | {
"resource": ""
} |
q249574 | PdoSessionHandler.getSelectSql | validation | private function getSelectSql()
{
if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
$this->beginTransaction();
switch ($this->driver) {
case 'mysql':
case 'oci':
case 'pgsql':
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
case 'sqlsrv':
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
case 'sqlite':
// we already locked when starting transaction
break;
default:
throw new \DomainException(sprintf('Transactional locks are currently not implemented for PDO driver "%s".', $this->driver));
}
}
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id";
} | php | {
"resource": ""
} |
q249575 | Scope.addScope | validation | public function addScope($scope)
{
if($this->isValidScope($scope)){
$this->scope[$scope] = $scope;
}
return $this;
} | php | {
"resource": ""
} |
q249576 | Scope.removeScope | validation | public function removeScope($scope)
{
if($this->isValidScope($scope) && $this->hasScope($scope)){
unset($this->scope[$scope]);
}
return $this;
} | php | {
"resource": ""
} |
q249577 | InNestedArray.setValueMutator | validation | public function setValueMutator(callable $callback) : self
{
$this->valueMutator = $callback;
$this->value = ($this->valueMutator)($this->value);
return $this;
} | php | {
"resource": ""
} |
q249578 | Insert.values | validation | public function values($values)
{
if (is_array($values) === true) {
if (is_numeric(key($values)) === true) {
$this->values = array(
null,
implode(', ', $values)
);
} else {
$this->values = array('', '');
foreach ($values as $key => $value) {
if (stripos($key, '.') !== false) {
$key = substr($key, stripos($key, '.') + 1);
}
$this->values[0] .= $key . ', ';
$this->values[1] .= $value . ', ';
}
$this->values[0] = substr($this->values[0], 0, -2);
$this->values[1] = substr($this->values[1], 0, -2);
}
} else {
$this->values = array(
null,
$values
);
}
return $this;
} | php | {
"resource": ""
} |
q249579 | Insert.returning | validation | public function returning($returning)
{
if (is_array($returning) === true) {
$this->returning = implode(', ', $returning);
} else {
$this->returning = $returning;
}
return $this;
} | php | {
"resource": ""
} |
q249580 | Config.get | validation | public static function get(string $fileName) : array
{
if (isset(self::$files[$fileName]) === false) {
if (($content = file_get_contents($fileName)) === false) {
throw new FileNotReadable('file "' . $fileName . '" can\'t be read');
}
$content = (string) $content; // re: https://github.com/phpstan/phpstan/issues/647
try {
$content = Yaml::parse($content);
} catch (ParseException $e) {
throw new FileNotParsable('file "' . $fileName . '" can\'t be parsed');
}
self::$files[$fileName] = $content;
}
return self::$files[$fileName];
} | php | {
"resource": ""
} |
q249581 | Config.set | validation | public static function set(string $fileName, array $content)
{
try {
$json = Yaml::dump($content, 2);
if (file_put_contents($fileName, $json) === false) {
throw new FileNotWritable('can\'t write to "' . $fileName . '"');
}
} catch (DumpException $e) {
throw new BadUse('Config::set() content parameter can\'t be dump to YAML');
}
self::$files[$fileName] = $content;
} | php | {
"resource": ""
} |
q249582 | ErrorPage.init | validation | public static function init()
{
if (self::$isInit === false) {
self::$prettyPageHandler = new PrettyPageHandler();
self::$prettyPageHandler->setPageTitle('I just broke a string... - strayFw');
$whoops = new Run();
$whoops->pushHandler(new JsonResponseHandler());
$whoops->pushHandler(self::$prettyPageHandler);
$whoops->register();
self::$isInit = true;
}
} | php | {
"resource": ""
} |
q249583 | ErrorPage.addData | validation | public static function addData(string $title, array $data)
{
if (self::$isInit === true) {
self::$prettyPageHandler->AddDataTable($title, $data);
}
} | php | {
"resource": ""
} |
q249584 | Http.init | validation | public static function init()
{
if (self::$isInit === false) {
self::$rawRequest = null;
self::$routes = array();
self::$isInit = true;
if (defined('STRAY_IS_HTTP') === true && constant('STRAY_IS_HTTP') === true) {
self::$rawRequest = new RawRequest();
Session::init();
Locale::init(self::$rawRequest);
}
}
} | php | {
"resource": ""
} |
q249585 | Http.run | validation | public static function run()
{
if (self::$isInit === true) {
if ((self::$rawRequest instanceof RawRequest) === false) {
throw new RuntimeException('Raw request was not specified!');
}
self::$request = new Request(self::$rawRequest, self::$routes);
self::$controllers = array();
self::$response = new Response();
try {
ob_start();
$before = self::$request->getBefore();
foreach ($before as $b) {
$controller = Controllers::get($b['class']);
$action = $b['action'];
$controller->$action(self::$request, self::$response);
if (self::$request->hasEnded() === true) {
break;
}
}
if (self::$request->hasEnded() === false) {
$controller = Controllers::get(self::$request->getClass());
$action = self::$request->getAction();
$controller->$action(self::$request, self::$response);
if (self::$request->hasEnded() === false) {
$after = self::$request->getAfter();
foreach ($after as $a) {
$controller = Controllers::get($a['class']);
$action = $a['action'];
$controller->$action(self::$request, self::$response);
}
}
}
$render = self::$response->getRender();
if (!($render instanceof RenderInterface)) {
throw new NotARender('response->render is a non RenderInterface implementing object');
}
echo $render->render(self::$response->data);
ob_end_flush();
} catch (\Exception $e) {
ob_end_clean();
throw $e;
}
}
} | php | {
"resource": ""
} |
q249586 | Http.prefix | validation | public static function prefix(string $namespace, $subdomain = null, string $uri = null)
{
self::$namespace = $namespace;
self::$subdomain = is_array($subdomain) ? $subdomain : [ $subdomain ];
self::$uri = $uri;
} | php | {
"resource": ""
} |
q249587 | Http.route | validation | public static function route($method, $path, $action)
{
if (self::$isInit === true) {
self::$routes[] = array(
'type' => 'route',
'method' => $method,
'path' => $path,
'action' => $action,
'namespace' => self::$namespace,
'subdomain' => self::$subdomain,
'uri' => self::$uri
);
}
} | php | {
"resource": ""
} |
q249588 | PostVoter.canEdit | validation | public function canEdit(GroupableInterface $post, TokenInterface $token): bool
{
$user = $token->getUser();
if ($post->getAuthor() == $user->getUsername()) {
return true;
}
foreach ($post->getGroups() as $group) {
if ($this->decision_manager->decide($token, ['GROUP_ROLE_ADMIN'], $group)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q249589 | Enum.setValue | validation | public function setValue(string $v) : string
{
if (static::isValid($v) === false) {
throw new BadUse('"' . $v . '" is not recognized as a possible value');
}
$this->value = $v;
} | php | {
"resource": ""
} |
q249590 | Enum.toArray | validation | public static function toArray() : array
{
if (static::$array == null) {
$ref = new \ReflectionClass(static::class);
$consts = $ref->getConstants();
static::$array = array();
foreach ($consts as $key => $value) {
if (stripos($key, 'VALUE_') === 0) {
static::$array[$key] = $value;
}
}
}
return static::$array;
} | php | {
"resource": ""
} |
q249591 | EmailJob.perform | validation | public function perform(array $args = []): int
{
// Create a transport
$transport = new Swift_SmtpTransport(
$args['smtp']['host'],
$args['smtp']['port']
);
$transport->setUsername($args['smtp']['username']);
$transport->setPassword($args['smtp']['password']);
// Create a message
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message($args['subject']))
->setFrom([$args['from']['email'] => $args['from']['email']])
->setTo([$args['to']['email'] => $args['to']['name']])
->setBody($args['message']);
// Send the message
$result = $mailer->send($message);
// The email was successfully sent if $mail->send returns 1, indicating 1 email was sent
return $result === 1;
} | php | {
"resource": ""
} |
q249592 | Condition.toSqlLevel | validation | protected function toSqlLevel(array $tree) : string
{
if (count($tree) == 0) {
return '';
}
$sql = '(';
reset($tree);
if (is_numeric(key($tree)) === true) {
foreach ($tree as $elem) {
$sql .= $elem . ' AND ';
}
$sql = substr($sql, 0, -5);
} elseif (key($tree) === 'OR') {
foreach ($tree as $value) {
if (is_array($value) === true) {
$sql .= $this->toSqlLevel($value);
} else {
$sql .= $value;
}
$sql .= ' OR ';
}
$sql = substr($sql, 0, -4);
} elseif (key($tree) === 'AND') {
foreach ($tree as $value) {
if (is_array($value) === true) {
$sql .= $this->toSqlLevel($value);
} else {
$sql .= $value;
}
$sql .= ' AND ';
}
$sql = substr($sql, 0, -5);
} else {
foreach ($tree as $key => $value) {
$sql .= $key . ' = ' . $value . ' AND ';
}
$sql = substr($sql, 0, -5);
}
$sql .= ')';
return $sql;
} | php | {
"resource": ""
} |
q249593 | SignalHandler.handle | validation | public function handle(int $signal)
{
// If this signal is already being handled, return a Failure Promise and don't do anything
if (isset($this->handlers[$signal]) && $this->handlers[$signal] === true) {
return new Failure(new Exception('Signal is already being processed.'));
}
// Indicate that we're handling this signal to block repeat signals
$this->handlers[$signal] = true;
// Disable processing of new jobs while we handle the signal
$this->dispatcher->setIsRunning(false);
// Call the signal handler from the signal mapping
$fn = $this->signals[$signal];
$result = $this->$fn();
// $result is either going to be `null` or a boolean value
// If it's `true`, then skip the shutdown sequence
if ($result === true) {
unset($this->handlers[$signal]);
return new Success($result);
}
// Wait until all processes have ended before resolving the promise
$deferred = new Deferred;
Loop::repeat(1000, function ($watcherId, $callback) use ($deferred, $signal, $result) {
if (count($this->dispatcher->getProcesses()) === 0) {
Loop::cancel($watcherId);
unset($this->handlers[$signal]);
return $deferred->resolve($result);
}
});
return $deferred->promise();
} | php | {
"resource": ""
} |
q249594 | SignalHandler.shutdown | validation | private function shutdown($signal = 9)
{
// Iterate through all the existing processes, and send the appropriate signal to the process
foreach ($this->dispatcher->getProcesses() as $pid => $process) {
$this->logger->debug('Sending signal to process', [
'signal' => $signal,
'pid' => $pid,
'jobId' => $process['id'],
'queue' => $this->queue->getName()
]);
/**
* $process['process']->signal($signal)
* Amp\Process\Process::signal doesn't actually send signals correctly, and is not cross platform
* Use posix_kill to actually send the signal to the process for handling
*/
\posix_kill($pid, $signal);
// If a signal other than SIGKILL was sent to the process, create a deadline timeout and force kill the process if it's still alive after the deadline
if ($signal !== 9) {
if ($this->config['deadline_timeout'] !== null) {
Loop::delay(((int)$this->config['deadline_timeout'] * 1000), function ($watcherId, $callback) use ($process, $pid) {
if ($process['process']->isRunning()) {
$this->logger->info('Process has exceeded deadline timeout. Killing', [
'pid' => $pid,
'jobId' => $process['id'],
'queue' => $this->queue->getName()
]);
// Send SIGKILL to the process
\posix_kill($pid, SIGKILL);
}
});
}
}
}
} | php | {
"resource": ""
} |
q249595 | Schema.buildEnum | validation | private function buildEnum(string $enumName, array $enumDefinition)
{
$mapping = Mapping::get($this->mapping);
$definition = $this->getDefinition();
$database = GlobalDatabase::get($mapping['config']['database']);
$enumRealName = null;
if (isset($enumDefinition['name']) === true) {
$enumRealName = $enumDefinition['name'];
} else {
$enumRealName = Helper::codifyName($this->mapping) . '_' . Helper::codifyName($enumName);
}
if (isset($enumDefinition['values']) === false) {
throw new InvalidSchemaDefinition('enum "' . $enumName . '" has no value');
}
$values = array();
foreach ($enumDefinition['values'] as $valueName => $valueAlias) {
$valueRealName = null;
if (is_string($valueName) === true) {
$valueRealName = $valueName;
} else {
$valueRealName = Helper::codifyName($enumName) . '_' . Helper::codifyName($valueAlias);
}
$values[] = $valueRealName;
}
$statement = Mutation\AddEnum::statement($database, $enumRealName, $values);
if ($statement->execute() == false) {
throw new DatabaseError('db/build : ' . print_r($statement->errorInfo(), true));
}
echo $enumName . ' - Done' . PHP_EOL;
} | php | {
"resource": ""
} |
q249596 | Schema.buildModel | validation | private function buildModel(string $modelName, array $modelDefinition)
{
$mapping = Mapping::get($this->mapping);
$definition = $this->getDefinition();
$database = GlobalDatabase::get($mapping['config']['database']);
$tableName = null;
if (isset($modelDefinition['name']) === true) {
$tableName = $modelDefinition['name'];
} else {
$tableName = Helper::codifyName($this->mapping) . '_' . Helper::codifyName($modelName);
}
if (isset($modelDefinition['fields']) === false) {
throw new InvalidSchemaDefinition('model "' . $modelName . '" has no field');
}
$statement = Mutation\AddTable::statement($database, $this->getDefinition(), $this->mapping, $tableName, $modelName);
if ($statement->execute() == false) {
throw new DatabaseError('db/build : ' . print_r($statement->errorInfo(), true));
}
if (isset($modelDefinition['indexes']) === true) {
foreach ($modelDefinition['indexes'] as $indexName => $indexDefinition) {
$statement = Mutation\AddIndex::statement($database, $modelName, $tableName, $modelDefinition, $indexName);
if ($statement->execute() == false) {
throw new DatabaseError('db/build : ' . print_r($statement->errorInfo(), true));
}
}
}
if (isset($modelDefinition['uniques']) === true) {
foreach ($modelDefinition['uniques'] as $uniqueName => $uniqueDefinition) {
$statement = Mutation\AddUnique::statement($database, $modelName, $tableName, $modelDefinition, $uniqueName);
if ($statement->execute() == false) {
throw new DatabaseError('db/build : ' . print_r($statement->errorInfo(), true));
}
}
}
echo $modelName . ' - Done' . PHP_EOL;
} | php | {
"resource": ""
} |
q249597 | Schema.generateModels | validation | public function generateModels()
{
$definition = $this->getDefinition();
foreach ($definition as $modelName => $modelDefinition) {
$type = 'model';
if (isset($modelDefinition['type']) === true && in_array($modelDefinition['type'], [ 'enum', 'model' ]) === true) {
$type = $modelDefinition['type'];
}
if ($type == 'enum') {
$this->generateEnum($modelName, $modelDefinition);
} else {
$this->generateModel($modelName, $modelDefinition);
}
}
} | php | {
"resource": ""
} |
q249598 | Helper.extractDomain | validation | public static function extractDomain(RawRequest $rawRequest)
{
$domain = null;
if (preg_match("/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i", $rawRequest->getHost(), $matches)) {
$domain = $matches['domain'];
}
return $domain;
} | php | {
"resource": ""
} |
q249599 | Helper.niceUrl | validation | public static function niceUrl(string $url)
{
$nice = null;
if (($pos = stripos($url, '.')) !== false) {
list($subDomain, $url) = explode('.', $url);
$request = Http::getRequest();
$nice = $request->getRawRequest()->getScheme() . '://';
if ($subDomain != null) {
$nice .= $subDomain . '.';
}
$nice .= self::extractDomain($request->getRawRequest());
}
return $nice . '/' . ltrim((string) preg_replace('/\/+/', '/', $url), '/');
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.