_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q254300 | Google_Model.getMappedName | test | private function getMappedName($key)
{
if (isset($this->internal_gapi_mappings, $this->internal_gapi_mappings[$key])) {
$key = $this->internal_gapi_mappings[$key];
}
return $key;
} | php | {
"resource": ""
} |
q254301 | Google_Model.isAssociativeArray | test | protected function isAssociativeArray($array)
{
if (!is_array($array)) {
return false;
}
$keys = array_keys($array);
foreach ($keys as $key) {
if (is_string($key)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q254302 | Google_AuthHandler_AuthHandlerFactory.build | test | public static function build($cache = null, array $cacheConfig = [])
{
$version = ClientInterface::VERSION;
switch ($version[0]) {
case '5':
return new Google_AuthHandler_Guzzle5AuthHandler($cache, $cacheConfig);
case '6':
return new Google_AuthHandler_Guzzle6AuthHandler($cache, $cacheConfig);
default:
throw new Exception('Version not supported');
}
} | php | {
"resource": ""
} |
q254303 | Config.find_config | test | public function find_config() {
$config = $this->fix_win32_path($this->config);
if (!empty($config) && is_readable($config)) {
return $config;
}
if (!empty($config) && !is_readable($config)) {
throw new ConfigException("User defined config not found at '$config'");
}
// config.php in /user/
if (file_exists($this->root . '/user/config.php')) {
return $this->root . '/user/config.php';
}
// config.php in /includes/
if (file_exists($this->root . '/includes/config.php')) {
return $this->root . '/includes/config.php';
}
// config.php not found :(
throw new ConfigException('Cannot find config.php. Please read the readme.html to learn how to install YOURLS');
} | php | {
"resource": ""
} |
q254304 | Config.define_core_constants | test | public function define_core_constants() {
// Check minimal config job has been properly done
$must_haves = array('YOURLS_DB_USER', 'YOURLS_DB_PASS', 'YOURLS_DB_NAME', 'YOURLS_DB_HOST', 'YOURLS_DB_PREFIX', 'YOURLS_SITE');
foreach($must_haves as $must_have) {
if (!defined($must_have)) {
throw new ConfigException('Config is incomplete (missing at least '.$must_have.') Check config-sample.php and edit your config accordingly');
}
}
/**
* The following has an awful CRAP index and it would be much shorter reduced to something like
* defining an array of ('YOURLS_SOMETHING' => 'default value') and then a simple loop over the
* array, checking if $current is defined as a constant and otherwise define said constant with
* its default value. I did not wrote it that way because that would make it difficult for code
* parsers to identify which constants are defined and where. So, here it is, that long list of
* if (!defined) define(). Ho and by the way, such beautiful comment, much right aligned, wow !
*/
// physical path of YOURLS root
if (!defined( 'YOURLS_ABSPATH' ))
define('YOURLS_ABSPATH', $this->root);
// physical path of includes directory
if (!defined( 'YOURLS_INC' ))
define('YOURLS_INC', YOURLS_ABSPATH.'/includes');
// physical path of user directory
if (!defined( 'YOURLS_USERDIR' ))
define( 'YOURLS_USERDIR', YOURLS_ABSPATH.'/user' );
// URL of user directory
if (!defined( 'YOURLS_USERURL' ))
define( 'YOURLS_USERURL', YOURLS_SITE.'/user' );
// physical path of asset directory
if( !defined( 'YOURLS_ASSETDIR' ) )
define( 'YOURLS_ASSETDIR', YOURLS_ABSPATH.'/assets' );
// URL of asset directory
if( !defined( 'YOURLS_ASSETURL' ) )
define( 'YOURLS_ASSETURL', YOURLS_SITE.'/assets' );
// physical path of translations directory
if (!defined( 'YOURLS_LANG_DIR' ))
define( 'YOURLS_LANG_DIR', YOURLS_USERDIR.'/languages' );
// physical path of plugins directory
if (!defined( 'YOURLS_PLUGINDIR' ))
define( 'YOURLS_PLUGINDIR', YOURLS_USERDIR.'/plugins' );
// URL of plugins directory
if (!defined( 'YOURLS_PLUGINURL' ))
define( 'YOURLS_PLUGINURL', YOURLS_USERURL.'/plugins' );
// physical path of themes directory
if( !defined( 'YOURLS_THEMEDIR' ) )
define( 'YOURLS_THEMEDIR', YOURLS_USERDIR.'/themes' );
// URL of themes directory
if( !defined( 'YOURLS_THEMEURL' ) )
define( 'YOURLS_THEMEURL', YOURLS_USERURL.'/themes' );
// physical path of pages directory
if (!defined( 'YOURLS_PAGEDIR' ))
define('YOURLS_PAGEDIR', YOURLS_ABSPATH.'/pages' );
// table to store URLs
if (!defined( 'YOURLS_DB_TABLE_URL' ))
define( 'YOURLS_DB_TABLE_URL', YOURLS_DB_PREFIX.'url' );
// table to store options
if (!defined( 'YOURLS_DB_TABLE_OPTIONS' ))
define( 'YOURLS_DB_TABLE_OPTIONS', YOURLS_DB_PREFIX.'options' );
// table to store hits, for stats
if (!defined( 'YOURLS_DB_TABLE_LOG' ))
define( 'YOURLS_DB_TABLE_LOG', YOURLS_DB_PREFIX.'log' );
// minimum delay in sec before a same IP can add another URL. Note: logged in users are not throttled down.
if (!defined( 'YOURLS_FLOOD_DELAY_SECONDS' ))
define( 'YOURLS_FLOOD_DELAY_SECONDS', 15 );
// comma separated list of IPs that can bypass flood check.
if (!defined( 'YOURLS_FLOOD_IP_WHITELIST' ))
define( 'YOURLS_FLOOD_IP_WHITELIST', '' );
// life span of an auth cookie in seconds (60*60*24*7 = 7 days)
if (!defined( 'YOURLS_COOKIE_LIFE' ))
define( 'YOURLS_COOKIE_LIFE', 60*60*24*7 );
// life span of a nonce in seconds
if (!defined( 'YOURLS_NONCE_LIFE' ))
define( 'YOURLS_NONCE_LIFE', 43200 ); // 3600 * 12
// if set to true, disable stat logging (no use for it, too busy servers, ...)
if (!defined( 'YOURLS_NOSTATS' ))
define( 'YOURLS_NOSTATS', false );
// if set to true, force https:// in the admin area
if (!defined( 'YOURLS_ADMIN_SSL' ))
define( 'YOURLS_ADMIN_SSL', false );
// if set to true, verbose debug infos. Will break things. Don't enable.
if (!defined( 'YOURLS_DEBUG' ))
define( 'YOURLS_DEBUG', false );
// Error reporting
if (defined( 'YOURLS_DEBUG' ) && YOURLS_DEBUG == true ) {
error_reporting( -1 );
} else {
error_reporting( E_ERROR | E_PARSE );
}
} | php | {
"resource": ""
} |
q254305 | YDB.set_emulate_state | test | public function set_emulate_state() {
try {
$this->is_emulate_prepare = $this->getAttribute(PDO::ATTR_EMULATE_PREPARES);
} catch (\PDOException $e) {
$this->is_emulate_prepare = false;
}
} | php | {
"resource": ""
} |
q254306 | YDB.dead_or_error | test | public function dead_or_error(\Exception $exception) {
// Use any /user/db_error.php file
if( file_exists( YOURLS_USERDIR . '/db_error.php' ) ) {
include_once( YOURLS_USERDIR . '/db_error.php' );
die();
}
$message = yourls__( 'Incorrect DB config, or could not connect to DB' );
$message .= '<br/>' . get_class($exception) .': ' . $exception->getMessage();
yourls_die( yourls__( $message ), yourls__( 'Fatal error' ), 503 );
die();
} | php | {
"resource": ""
} |
q254307 | YDB.get_queries | test | public function get_queries() {
$queries = $this->getProfiler()->getProfiles();
if ($this->get_emulate_state()) {
// keep queries if $query['function'] != 'prepare'
$queries = array_filter($queries, function($query) {return $query['function'] !== 'prepare';});
}
return $queries;
} | php | {
"resource": ""
} |
q254308 | YOURLS_Locale_Formats.register_globals | test | function register_globals() {
$GLOBALS['weekday'] = $this->weekday;
$GLOBALS['weekday_initial'] = $this->weekday_initial;
$GLOBALS['weekday_abbrev'] = $this->weekday_abbrev;
$GLOBALS['month'] = $this->month;
$GLOBALS['month_abbrev'] = $this->month_abbrev;
} | php | {
"resource": ""
} |
q254309 | Options.get_all_options | test | public function get_all_options() {
// Get option values from DB
$table = YOURLS_DB_TABLE_OPTIONS;
$sql = "SELECT option_name, option_value FROM $table WHERE 1=1";
try {
$options = (array) $this->ydb->fetchPairs($sql);
} catch ( PDOException $e ) {
// We could not fetch value from the table. Let's check if the option table exists
try {
$check = $this->ydb->fetchAffected(sprintf("SHOW TABLES LIKE '%s'", $table));
// Table doesn't exist
if ($check ==0) {
return false;
}
// Error at this point means the database isn't readable
} catch ( PDOException $e ) {
$this->ydb->dead_or_error($e);
}
}
// Unlikely scenario, but who knows: table exists, but is empty
if (empty($options)) {
return false;
}
foreach ($options as $name => $value) {
$this->ydb->set_option($name, yourls_maybe_unserialize($value));
}
yourls_apply_filter('get_all_options', 'deprecated');
return true;
} | php | {
"resource": ""
} |
q254310 | Options.add | test | public function add($name, $value) {
$name = trim((string)$name);
if (empty($name)) {
return false;
}
// Use clone to break object refs -- see commit 09b989d375bac65e692277f61a84fede2fb04ae3
if (is_object($value)) {
$value = clone $value;
}
// Make sure the option doesn't already exist
if ($this->ydb->has_option($name)) {
return false;
}
// if (false !== yourls_get_option($name)) {
// return false;
// }
$table = YOURLS_DB_TABLE_OPTIONS;
$_value = yourls_maybe_serialize($value);
$sql = "INSERT INTO $table (option_name, option_value) VALUES (:name, :value)";
$bind = array('name' => $name, 'value' => $_value);
$do = $this->ydb->fetchAffected($sql, $bind);
if($do !== 1) {
// Something went wrong :(
return false;
}
// Cache option value to save a DB query if needed later
$this->ydb->set_option($name, $value);
yourls_do_action('add_option', $name, $_value);
return true;
} | php | {
"resource": ""
} |
q254311 | Options.delete | test | public function delete($name) {
$name = trim((string)$name);
if (empty($name)) {
return false;
}
$table = YOURLS_DB_TABLE_OPTIONS;
$sql = "DELETE FROM $table WHERE option_name = :name";
$bind = array('name' => $name);
$do = $this->ydb->fetchAffected($sql, $bind);
if($do !== 1) {
// Something went wrong :(
return false;
}
yourls_do_action('delete_option', $name);
$this->ydb->delete_option($name);
return true;
} | php | {
"resource": ""
} |
q254312 | RouteCollection.addPlaceholder | test | public function addPlaceholder($placeholder, string $pattern = null): RouteCollectionInterface
{
if (! is_array($placeholder))
{
$placeholder = [$placeholder => $pattern];
}
$this->placeholders = array_merge($this->placeholders, $placeholder);
return $this;
} | php | {
"resource": ""
} |
q254313 | RouteCollection.setDefaultNamespace | test | public function setDefaultNamespace(string $value): RouteCollectionInterface
{
$this->defaultNamespace = filter_var($value, FILTER_SANITIZE_STRING);
$this->defaultNamespace = rtrim($this->defaultNamespace, '\\') . '\\';
return $this;
} | php | {
"resource": ""
} |
q254314 | RouteCollection.setDefaultController | test | public function setDefaultController(string $value): RouteCollectionInterface
{
$this->defaultController = filter_var($value, FILTER_SANITIZE_STRING);
return $this;
} | php | {
"resource": ""
} |
q254315 | RouteCollection.setDefaultMethod | test | public function setDefaultMethod(string $value): RouteCollectionInterface
{
$this->defaultMethod = filter_var($value, FILTER_SANITIZE_STRING);
return $this;
} | php | {
"resource": ""
} |
q254316 | RouteCollection.discoverRoutes | test | protected function discoverRoutes()
{
if ($this->didDiscover)
{
return;
}
// We need this var in local scope
// so route files can access it.
$routes = $this;
if ($this->moduleConfig->shouldDiscover('routes'))
{
$files = $this->fileLocator->search('Config/Routes.php');
foreach ($files as $file)
{
// Don't include our main file again...
if ($file === APPPATH . 'Config/Routes.php')
{
continue;
}
include $file;
}
}
$this->didDiscover = true;
} | php | {
"resource": ""
} |
q254317 | RouteCollection.setDefaultConstraint | test | public function setDefaultConstraint(string $placeholder): RouteCollectionInterface
{
if (array_key_exists($placeholder, $this->placeholders))
{
$this->defaultPlaceholder = $placeholder;
}
return $this;
} | php | {
"resource": ""
} |
q254318 | RouteCollection.getRoutes | test | public function getRoutes($verb = null): array
{
if (empty($verb))
{
$verb = $this->getHTTPVerb();
}
// Since this is the entry point for the Router,
// take a moment to do any route discovery
// we might need to do.
$this->discoverRoutes();
$routes = [];
if (isset($this->routes[$verb]))
{
// Keep current verb's routes at the beginning so they're matched
// before any of the generic, "add" routes.
if (isset($this->routes['*']))
{
$extraRules = array_diff_key($this->routes['*'], $this->routes[$verb]);
$collection = array_merge($this->routes[$verb], $extraRules);
}
foreach ($collection as $r)
{
$key = key($r['route']);
$routes[$key] = $r['route'][$key];
}
}
return $routes;
} | php | {
"resource": ""
} |
q254319 | RouteCollection.getRoutesOptions | test | public function getRoutesOptions(string $from = null): array
{
return $from ? $this->routesOptions[$from] ?? [] : $this->routesOptions;
} | php | {
"resource": ""
} |
q254320 | RouteCollection.map | test | public function map(array $routes = [], array $options = null): RouteCollectionInterface
{
foreach ($routes as $from => $to)
{
$this->add($from, $to, $options);
}
return $this;
} | php | {
"resource": ""
} |
q254321 | RouteCollection.addRedirect | test | public function addRedirect(string $from, string $to, int $status = 302)
{
// Use the named route's pattern if this is a named route.
if (array_key_exists($to, $this->routes['*']))
{
$to = $this->routes['*'][$to]['route'];
}
$this->create('*', $from, $to, ['redirect' => $status]);
return $this;
} | php | {
"resource": ""
} |
q254322 | RouteCollection.isRedirect | test | public function isRedirect(string $from): bool
{
foreach ($this->routes['*'] as $name => $route)
{
// Named route?
if ($name === $from || key($route['route']) === $from)
{
return isset($route['redirect']) && is_numeric($route['redirect']);
}
}
return false;
} | php | {
"resource": ""
} |
q254323 | RouteCollection.getRedirectCode | test | public function getRedirectCode(string $from): int
{
foreach ($this->routes['*'] as $name => $route)
{
// Named route?
if ($name === $from || key($route['route']) === $from)
{
return $route['redirect'] ?? 0;
}
}
return 0;
} | php | {
"resource": ""
} |
q254324 | RouteCollection.match | test | public function match(array $verbs = [], string $from, $to, array $options = null): RouteCollectionInterface
{
foreach ($verbs as $verb)
{
$verb = strtolower($verb);
$this->{$verb}($from, $to, $options);
}
return $this;
} | php | {
"resource": ""
} |
q254325 | RouteCollection.options | test | public function options(string $from, $to, array $options = null): RouteCollectionInterface
{
$this->create('options', $from, $to, $options);
return $this;
} | php | {
"resource": ""
} |
q254326 | RouteCollection.environment | test | public function environment(string $env, \Closure $callback): RouteCollectionInterface
{
if (ENVIRONMENT === $env)
{
$callback($this);
}
return $this;
} | php | {
"resource": ""
} |
q254327 | RouteCollection.reverseRoute | test | public function reverseRoute(string $search, ...$params)
{
// Named routes get higher priority.
foreach ($this->routes as $verb => $collection)
{
if (array_key_exists($search, $collection))
{
return $this->fillRouteParams(key($collection[$search]['route']), $params);
}
}
// If it's not a named route, then loop over
// all routes to find a match.
foreach ($this->routes as $verb => $collection)
{
foreach ($collection as $route)
{
$from = key($route['route']);
$to = $route['route'][$from];
// Lose any namespace slash at beginning of strings
// to ensure more consistent match.
$to = ltrim($to, '\\');
$search = ltrim($search, '\\');
// If there's any chance of a match, then it will
// be with $search at the beginning of the $to string.
if (strpos($to, $search) !== 0)
{
continue;
}
// Ensure that the number of $params given here
// matches the number of back-references in the route
if (substr_count($to, '$') !== count($params))
{
continue;
}
return $this->fillRouteParams($from, $params);
}
}
// If we're still here, then we did not find a match.
return false;
} | php | {
"resource": ""
} |
q254328 | RouteCollection.determineCurrentSubdomain | test | private function determineCurrentSubdomain()
{
// We have to ensure that a scheme exists
// on the URL else parse_url will mis-interpret
// 'host' as the 'path'.
$url = $_SERVER['HTTP_HOST'];
if (strpos($url, 'http') !== 0)
{
$url = 'http://' . $url;
}
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['host']);
if ($host[0] === 'www')
{
unset($host[0]);
}
// Get rid of any domains, which will be the last
unset($host[count($host)]);
// Account for .co.uk, .co.nz, etc. domains
if (end($host) === 'co')
{
$host = array_slice($host, 0, -1);
}
// If we only have 1 part left, then we don't have a sub-domain.
if (count($host) === 1)
{
// Set it to false so we don't make it back here again.
return false;
}
return array_shift($host);
} | php | {
"resource": ""
} |
q254329 | RouteCollection.resetRoutes | test | public function resetRoutes()
{
$this->routes = ['*' => []];
foreach ($this->defaultHTTPMethods as $verb)
{
$this->routes[$verb] = [];
}
} | php | {
"resource": ""
} |
q254330 | Exceptions.errorHandler | test | public function errorHandler(int $severity, string $message, string $file = null, int $line = null, $context = null)
{
if (! (error_reporting() & $severity))
{
return;
}
// Convert it to an exception and pass it along.
throw new ErrorException($message, 0, $severity, $file, $line);
} | php | {
"resource": ""
} |
q254331 | Exceptions.shutdownHandler | test | public function shutdownHandler()
{
$error = error_get_last();
// If we've got an error that hasn't been displayed, then convert
// it to an Exception and use the Exception handler to display it
// to the user.
if (! is_null($error))
{
// Fatal Error?
if (in_array($error['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE]))
{
$this->exceptionHandler(new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']));
}
}
} | php | {
"resource": ""
} |
q254332 | Exceptions.determineView | test | protected function determineView(Throwable $exception, string $template_path): string
{
// Production environments should have a custom exception file.
$view = 'production.php';
$template_path = rtrim($template_path, '/ ') . '/';
if (str_ireplace(['off', 'none', 'no', 'false', 'null'], '', ini_get('display_errors')))
{
$view = 'error_exception.php';
}
// 404 Errors
if ($exception instanceof PageNotFoundException)
{
return 'error_404.php';
}
// Allow for custom views based upon the status code
else if (is_file($template_path . 'error_' . $exception->getCode() . '.php'))
{
return 'error_' . $exception->getCode() . '.php';
}
return $view;
} | php | {
"resource": ""
} |
q254333 | Exceptions.render | test | protected function render(Throwable $exception, int $statusCode)
{
// Determine directory with views
$path = $this->viewPath;
if (empty($path))
{
$paths = new Paths();
$path = $paths->viewDirectory . '/errors/';
}
$path = is_cli()
? $path . 'cli/'
: $path . 'html/';
// Determine the vew
$view = $this->determineView($exception, $path);
// Prepare the vars
$vars = $this->collectVars($exception, $statusCode);
extract($vars);
// Render it
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_clean();
}
ob_start();
include($path . $view);
$buffer = ob_get_contents();
ob_end_clean();
echo $buffer;
} | php | {
"resource": ""
} |
q254334 | Exceptions.collectVars | test | protected function collectVars(Throwable $exception, int $statusCode): array
{
return [
'title' => get_class($exception),
'type' => get_class($exception),
'code' => $statusCode,
'message' => $exception->getMessage() ?? '(null)',
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTrace(),
];
} | php | {
"resource": ""
} |
q254335 | Exceptions.determineCodes | test | protected function determineCodes(Throwable $exception): array
{
$statusCode = abs($exception->getCode());
if ($statusCode < 100 || $statusCode > 599)
{
$exitStatus = $statusCode + EXIT__AUTO_MIN; // 9 is EXIT__AUTO_MIN
if ($exitStatus > EXIT__AUTO_MAX) // 125 is EXIT__AUTO_MAX
{
$exitStatus = EXIT_ERROR; // EXIT_ERROR
}
$statusCode = 500;
}
else
{
$exitStatus = 1; // EXIT_ERROR
}
return [
$statusCode ?? 500,
$exitStatus,
];
} | php | {
"resource": ""
} |
q254336 | Exceptions.describeMemory | test | public static function describeMemory(int $bytes): string
{
if ($bytes < 1024)
{
return $bytes . 'B';
}
else if ($bytes < 1048576)
{
return round($bytes / 1024, 2) . 'KB';
}
return round($bytes / 1048576, 2) . 'MB';
} | php | {
"resource": ""
} |
q254337 | Exceptions.highlightFile | test | public static function highlightFile(string $file, int $lineNumber, int $lines = 15)
{
if (empty($file) || ! is_readable($file))
{
return false;
}
// Set our highlight colors:
if (function_exists('ini_set'))
{
ini_set('highlight.comment', '#767a7e; font-style: italic');
ini_set('highlight.default', '#c7c7c7');
ini_set('highlight.html', '#06B');
ini_set('highlight.keyword', '#f1ce61;');
ini_set('highlight.string', '#869d6a');
}
try
{
$source = file_get_contents($file);
}
catch (Throwable $e)
{
return false;
}
$source = str_replace(["\r\n", "\r"], "\n", $source);
$source = explode("\n", highlight_string($source, true));
$source = str_replace('<br />', "\n", $source[1]);
$source = explode("\n", str_replace("\r\n", "\n", $source));
// Get just the part to show
$start = $lineNumber - (int) round($lines / 2);
$start = $start < 0 ? 0 : $start;
// Get just the lines we need to display, while keeping line numbers...
$source = array_splice($source, $start, $lines, true);
// Used to format the line number in the source
$format = '% ' . strlen($start + $lines) . 'd';
$out = '';
// Because the highlighting may have an uneven number
// of open and close span tags on one line, we need
// to ensure we can close them all to get the lines
// showing correctly.
$spans = 1;
foreach ($source as $n => $row)
{
$spans += substr_count($row, '<span') - substr_count($row, '</span');
$row = str_replace(["\r", "\n"], ['', ''], $row);
if (($n + $start + 1) === $lineNumber)
{
preg_match_all('#<[^>]+>#', $row, $tags);
$out .= sprintf("<span class='line highlight'><span class='number'>{$format}</span> %s\n</span>%s", $n + $start + 1, strip_tags($row), implode('', $tags[0])
);
}
else
{
$out .= sprintf('<span class="line"><span class="number">' . $format . '</span> %s', $n + $start + 1, $row) . "\n";
}
}
if ($spans > 0)
{
$out .= str_repeat('</span>', $spans);
}
return '<pre><code>' . $out . '</code></pre>';
} | php | {
"resource": ""
} |
q254338 | FormatRules.alpha_space | test | public function alpha_space(string $value = null): bool
{
if ($value === null)
{
return true;
}
return (bool) preg_match('/^[A-Z ]+$/i', $value);
} | php | {
"resource": ""
} |
q254339 | FormatRules.regex_match | test | public function regex_match(string $str = null, string $pattern, array $data): bool
{
if (strpos($pattern, '/') !== 0)
{
$pattern = "/{$pattern}/";
}
return (bool) preg_match($pattern, $str);
} | php | {
"resource": ""
} |
q254340 | FormatRules.valid_email | test | public function valid_email(string $str = null): bool
{
if (function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46') && preg_match('#\A([^@]+)@(.+)\z#', $str, $matches))
{
$str = $matches[1] . '@' . idn_to_ascii($matches[2], 0, INTL_IDNA_VARIANT_UTS46);
}
return (bool) filter_var($str, FILTER_VALIDATE_EMAIL);
} | php | {
"resource": ""
} |
q254341 | FormatRules.valid_emails | test | public function valid_emails(string $str = null): bool
{
foreach (explode(',', $str) as $email)
{
$email = trim($email);
if ($email === '')
{
return false;
}
if ($this->valid_email($email) === false)
{
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q254342 | FormatRules.valid_url | test | public function valid_url(string $str = null): bool
{
if (empty($str))
{
return false;
}
elseif (preg_match('/^(?:([^:]*)\:)?\/\/(.+)$/', $str, $matches))
{
if (! in_array($matches[1], ['http', 'https'], true))
{
return false;
}
$str = $matches[2];
}
$str = 'http://' . $str;
return (filter_var($str, FILTER_VALIDATE_URL) !== false);
} | php | {
"resource": ""
} |
q254343 | FormatRules.valid_date | test | public function valid_date(string $str = null, string $format = null): bool
{
if (empty($format))
{
return (bool) strtotime($str);
}
$date = \DateTime::createFromFormat($format, $str);
return (bool) $date && \DateTime::getLastErrors()['warning_count'] === 0 && \DateTime::getLastErrors()['error_count'] === 0;
} | php | {
"resource": ""
} |
q254344 | HTTPException.forMoveFailed | test | public static function forMoveFailed(string $source, string $target, string $error)
{
return new static(lang('HTTP.moveFailed', [$source, $target, $error]));
} | php | {
"resource": ""
} |
q254345 | CreditCardRules.valid_cc_number | test | public function valid_cc_number(string $ccNumber = null, string $type, array $data): bool
{
$type = strtolower($type);
$info = null;
// Get our card info based on provided name.
foreach ($this->cards as $card)
{
if ($card['name'] === $type)
{
$info = $card;
break;
}
}
// If empty, it's not a card type we recognize, or invalid type.
if (empty($info))
{
return false;
}
// Make sure we have a valid length
if (strlen($ccNumber) === 0)
{
return false;
}
// Remove any spaces and dashes
$ccNumber = str_replace([' ', '-'], '', $ccNumber);
// Non-numeric values cannot be a number...duh
if (! is_numeric($ccNumber))
{
return false;
}
// Make sure it's a valid length for this card
$lengths = explode(',', $info['length']);
if (! in_array(strlen($ccNumber), $lengths))
{
return false;
}
// Make sure it has a valid prefix
$prefixes = explode(',', $info['prefixes']);
$validPrefix = false;
foreach ($prefixes as $prefix)
{
if (strpos($ccNumber, $prefix) === 0)
{
$validPrefix = true;
break;
}
}
if ($validPrefix === false)
{
return false;
}
// Still here? Then check the number against the Luhn algorithm, if required
// @see https://en.wikipedia.org/wiki/Luhn_algorithm
// @see https://gist.github.com/troelskn/1287893
if ($info['checkdigit'] === true)
{
return $this->isValidLuhn($ccNumber);
}
return true;
} | php | {
"resource": ""
} |
q254346 | CreditCardRules.isValidLuhn | test | protected function isValidLuhn(string $number = null): bool
{
settype($number, 'string');
$sumTable = [
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
],
[
0,
2,
4,
6,
8,
1,
3,
5,
7,
9,
],
];
$sum = 0;
$flip = 0;
for ($i = strlen($number) - 1; $i >= 0; $i --)
{
$sum += $sumTable[$flip ++ & 0x1][$number[$i]];
}
return $sum % 10 === 0;
} | php | {
"resource": ""
} |
q254347 | ComposerScripts.moveFile | test | protected static function moveFile(string $source, string $destination): bool
{
$source = realpath($source);
if (empty($source))
{
die('Cannot move file. Source path invalid.');
}
if (! is_file($source))
{
return false;
}
return copy($source, $destination);
} | php | {
"resource": ""
} |
q254348 | ComposerScripts.moveEscaper | test | public static function moveEscaper()
{
if (class_exists('\\Zend\\Escaper\\Escaper') && is_file(static::getClassFilePath('\\Zend\\Escaper\\Escaper')))
{
$base = basename(__DIR__) . '/' . static::$basePath . 'ZendEscaper';
foreach ([$base, $base . '/Exception'] as $path)
{
if (! is_dir($path))
{
mkdir($path, 0755);
}
}
$files = [
static::getClassFilePath('\\Zend\\Escaper\\Exception\\ExceptionInterface') => $base . '/Exception/ExceptionInterface.php',
static::getClassFilePath('\\Zend\\Escaper\\Exception\\InvalidArgumentException') => $base . '/Exception/InvalidArgumentException.php',
static::getClassFilePath('\\Zend\\Escaper\\Exception\\RuntimeException') => $base . '/Exception/RuntimeException.php',
static::getClassFilePath('\\Zend\\Escaper\\Escaper') => $base . '/Escaper.php',
];
foreach ($files as $source => $dest)
{
if (! static::moveFile($source, $dest))
{
die('Error moving: ' . $source);
}
}
}
} | php | {
"resource": ""
} |
q254349 | ComposerScripts.moveKint | test | public static function moveKint()
{
$filename = 'vendor/kint-php/kint/build/kint-aante-light.php';
if (is_file($filename))
{
$base = basename(__DIR__) . '/' . static::$basePath . 'Kint';
// Remove the contents of the previous Kint folder, if any.
if (is_dir($base))
{
static::removeDir($base);
}
// Create Kint if it doesn't exist already
if (! is_dir($base))
{
mkdir($base, 0755);
}
if (! static::moveFile($filename, $base . '/kint.php'))
{
die('Error moving: ' . $filename);
}
}
} | php | {
"resource": ""
} |
q254350 | Session.start | test | public function start()
{
if (is_cli() && ENVIRONMENT !== 'testing')
{
$this->logger->debug('Session: Initialization under CLI aborted.');
return;
}
elseif ((bool) ini_get('session.auto_start'))
{
$this->logger->error('Session: session.auto_start is enabled in php.ini. Aborting.');
return;
}
elseif (session_status() === PHP_SESSION_ACTIVE)
{
$this->logger->warning('Session: Sessions is enabled, and one exists.Please don\'t $session->start();');
return;
}
if (! $this->driver instanceof \SessionHandlerInterface)
{
$this->logger->error("Session: Handler '" . $this->driver .
"' doesn't implement SessionHandlerInterface. Aborting.");
}
$this->configure();
$this->setSaveHandler();
// Sanitize the cookie, because apparently PHP doesn't do that for userspace handlers
if (isset($_COOKIE[$this->sessionCookieName]) && (
! is_string($_COOKIE[$this->sessionCookieName]) || ! preg_match('#\A' . $this->sidRegexp . '\z#', $_COOKIE[$this->sessionCookieName])
)
)
{
unset($_COOKIE[$this->sessionCookieName]);
}
$this->startSession();
// Is session ID auto-regeneration configured? (ignoring ajax requests)
if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') && ($regenerate_time = $this->sessionTimeToUpdate) > 0
)
{
if (! isset($_SESSION['__ci_last_regenerate']))
{
$_SESSION['__ci_last_regenerate'] = time();
}
elseif ($_SESSION['__ci_last_regenerate'] < (time() - $regenerate_time))
{
$this->regenerate((bool) $this->sessionRegenerateDestroy);
}
}
// Another work-around ... PHP doesn't seem to send the session cookie
// unless it is being currently created or regenerated
elseif (isset($_COOKIE[$this->sessionCookieName]) && $_COOKIE[$this->sessionCookieName] === session_id())
{
$this->setCookie();
}
$this->initVars();
$this->logger->info("Session: Class initialized using '" . $this->sessionDriverName . "' driver.");
return $this;
} | php | {
"resource": ""
} |
q254351 | Session.configureSidLength | test | protected function configureSidLength()
{
$bits_per_character = (int) (ini_get('session.sid_bits_per_character') !== false
? ini_get('session.sid_bits_per_character')
: 4);
$sid_length = (int) (ini_get('session.sid_length') !== false
? ini_get('session.sid_length')
: 40);
if (($sid_length * $bits_per_character) < 160)
{
$bits = ($sid_length * $bits_per_character);
// Add as many more characters as necessary to reach at least 160 bits
$sid_length += (int) ceil((160 % $bits) / $bits_per_character);
ini_set('session.sid_length', $sid_length);
}
// Yes, 4,5,6 are the only known possible values as of 2016-10-27
switch ($bits_per_character)
{
case 4:
$this->sidRegexp = '[0-9a-f]';
break;
case 5:
$this->sidRegexp = '[0-9a-v]';
break;
case 6:
$this->sidRegexp = '[0-9a-zA-Z,-]';
break;
}
$this->sidRegexp .= '{' . $sid_length . '}';
} | php | {
"resource": ""
} |
q254352 | Session.initVars | test | protected function initVars()
{
if (empty($_SESSION['__ci_vars']))
{
return;
}
$current_time = time();
foreach ($_SESSION['__ci_vars'] as $key => &$value)
{
if ($value === 'new')
{
$_SESSION['__ci_vars'][$key] = 'old';
}
// Hacky, but 'old' will (implicitly) always be less than time() ;)
// DO NOT move this above the 'new' check!
elseif ($value < $current_time)
{
unset($_SESSION[$key], $_SESSION['__ci_vars'][$key]);
}
}
if (empty($_SESSION['__ci_vars']))
{
unset($_SESSION['__ci_vars']);
}
} | php | {
"resource": ""
} |
q254353 | Session.set | test | public function set($data, $value = null)
{
if (is_array($data))
{
foreach ($data as $key => &$value)
{
if (is_int($key))
{
$_SESSION[$value] = null;
}
else
{
$_SESSION[$key] = $value;
}
}
return;
}
$_SESSION[$data] = $value;
} | php | {
"resource": ""
} |
q254354 | Session.get | test | public function get(string $key = null)
{
if (! empty($key) && $value = dot_array_search($key, $_SESSION))
{
return $value;
}
elseif (empty($_SESSION))
{
return [];
}
if (! empty($key))
{
return null;
}
$userdata = [];
$_exclude = array_merge(
['__ci_vars'], $this->getFlashKeys(), $this->getTempKeys()
);
$keys = array_keys($_SESSION);
foreach ($keys as $key)
{
if (! in_array($key, $_exclude, true))
{
$userdata[$key] = $_SESSION[$key];
}
}
return $userdata;
} | php | {
"resource": ""
} |
q254355 | Session.push | test | public function push(string $key, array $data)
{
if ($this->has($key) && is_array($value = $this->get($key)))
{
$this->set($key, array_merge($value, $data));
}
} | php | {
"resource": ""
} |
q254356 | Session.remove | test | public function remove($key)
{
if (is_array($key))
{
foreach ($key as $k)
{
unset($_SESSION[$k]);
}
return;
}
unset($_SESSION[$key]);
} | php | {
"resource": ""
} |
q254357 | Session.setFlashdata | test | public function setFlashdata($data, $value = null)
{
$this->set($data, $value);
$this->markAsFlashdata(is_array($data) ? array_keys($data) : $data);
} | php | {
"resource": ""
} |
q254358 | Session.getFlashdata | test | public function getFlashdata(string $key = null)
{
if (isset($key))
{
return (isset($_SESSION['__ci_vars'], $_SESSION['__ci_vars'][$key], $_SESSION[$key]) &&
! is_int($_SESSION['__ci_vars'][$key])) ? $_SESSION[$key] : null;
}
$flashdata = [];
if (! empty($_SESSION['__ci_vars']))
{
foreach ($_SESSION['__ci_vars'] as $key => &$value)
{
is_int($value) || $flashdata[$key] = $_SESSION[$key];
}
}
return $flashdata;
} | php | {
"resource": ""
} |
q254359 | Session.markAsFlashdata | test | public function markAsFlashdata($key): bool
{
if (is_array($key))
{
for ($i = 0, $c = count($key); $i < $c; $i ++)
{
if (! isset($_SESSION[$key[$i]]))
{
return false;
}
}
$new = array_fill_keys($key, 'new');
$_SESSION['__ci_vars'] = isset($_SESSION['__ci_vars']) ? array_merge($_SESSION['__ci_vars'], $new) : $new;
return true;
}
if (! isset($_SESSION[$key]))
{
return false;
}
$_SESSION['__ci_vars'][$key] = 'new';
return true;
} | php | {
"resource": ""
} |
q254360 | Session.getFlashKeys | test | public function getFlashKeys(): array
{
if (! isset($_SESSION['__ci_vars']))
{
return [];
}
$keys = [];
foreach (array_keys($_SESSION['__ci_vars']) as $key)
{
is_int($_SESSION['__ci_vars'][$key]) || $keys[] = $key;
}
return $keys;
} | php | {
"resource": ""
} |
q254361 | Session.setTempdata | test | public function setTempdata($data, $value = null, int $ttl = 300)
{
$this->set($data, $value);
$this->markAsTempdata($data, $ttl);
} | php | {
"resource": ""
} |
q254362 | Session.getTempdata | test | public function getTempdata(string $key = null)
{
if (isset($key))
{
return (isset($_SESSION['__ci_vars'], $_SESSION['__ci_vars'][$key], $_SESSION[$key]) &&
is_int($_SESSION['__ci_vars'][$key])) ? $_SESSION[$key] : null;
}
$tempdata = [];
if (! empty($_SESSION['__ci_vars']))
{
foreach ($_SESSION['__ci_vars'] as $key => &$value)
{
is_int($value) && $tempdata[$key] = $_SESSION[$key];
}
}
return $tempdata;
} | php | {
"resource": ""
} |
q254363 | Session.markAsTempdata | test | public function markAsTempdata($key, int $ttl = 300): bool
{
$ttl += time();
if (is_array($key))
{
$temp = [];
foreach ($key as $k => $v)
{
// Do we have a key => ttl pair, or just a key?
if (is_int($k))
{
$k = $v;
$v = $ttl;
}
elseif (is_string($v))
{
$v = time() + $ttl;
}
else
{
$v += time();
}
if (! array_key_exists($k, $_SESSION))
{
return false;
}
$temp[$k] = $v;
}
$_SESSION['__ci_vars'] = isset($_SESSION['__ci_vars']) ? array_merge($_SESSION['__ci_vars'], $temp) : $temp;
return true;
}
if (! isset($_SESSION[$key]))
{
return false;
}
$_SESSION['__ci_vars'][$key] = $ttl;
return true;
} | php | {
"resource": ""
} |
q254364 | Session.unmarkTempdata | test | public function unmarkTempdata($key)
{
if (empty($_SESSION['__ci_vars']))
{
return;
}
is_array($key) || $key = [$key];
foreach ($key as $k)
{
if (isset($_SESSION['__ci_vars'][$k]) && is_int($_SESSION['__ci_vars'][$k]))
{
unset($_SESSION['__ci_vars'][$k]);
}
}
if (empty($_SESSION['__ci_vars']))
{
unset($_SESSION['__ci_vars']);
}
} | php | {
"resource": ""
} |
q254365 | Session.getTempKeys | test | public function getTempKeys(): array
{
if (! isset($_SESSION['__ci_vars']))
{
return [];
}
$keys = [];
foreach (array_keys($_SESSION['__ci_vars']) as $key)
{
is_int($_SESSION['__ci_vars'][$key]) && $keys[] = $key;
}
return $keys;
} | php | {
"resource": ""
} |
q254366 | Session.setCookie | test | protected function setCookie()
{
setcookie(
$this->sessionCookieName, session_id(), (empty($this->sessionExpiration) ? 0 : time() + $this->sessionExpiration), $this->cookiePath, $this->cookieDomain, $this->cookieSecure, true
);
} | php | {
"resource": ""
} |
q254367 | Throttler.check | test | public function check(string $key, int $capacity, int $seconds, int $cost = 1): bool
{
$tokenName = $this->prefix . $key;
// Check to see if the bucket has even been created yet.
if (($tokens = $this->cache->get($tokenName)) === false)
{
// If it hasn't been created, then we'll set it to the maximum
// capacity - 1, and save it to the cache.
$this->cache->save($tokenName, $capacity - $cost, $seconds);
$this->cache->save($tokenName . 'Time', time());
return true;
}
// If $tokens > 0, then we need to replenish the bucket
// based on how long it's been since the last update.
$throttleTime = $this->cache->get($tokenName . 'Time');
$elapsed = $this->time() - $throttleTime;
// Number of tokens to add back per second
$rate = $capacity / $seconds;
// We must have a minimum wait of 1 second for a new token
// Primarily stored to allow devs to report back to users.
$this->tokenTime = max(1, $rate);
// Add tokens based up on number per second that
// should be refilled, then checked against capacity
// to be sure the bucket didn't overflow.
$tokens += $rate * $elapsed;
$tokens = $tokens > $capacity ? $capacity : $tokens;
// If $tokens > 0, then we are save to perform the action, but
// we need to decrement the number of available tokens.
$response = false;
if ($tokens > 0)
{
$response = true;
$this->cache->save($tokenName, $tokens - $cost, $elapsed);
$this->cache->save($tokenName . 'Time', time());
}
return $response;
} | php | {
"resource": ""
} |
q254368 | Mimes.guessTypeFromExtension | test | public static function guessTypeFromExtension(string $extension)
{
$extension = trim(strtolower($extension), '. ');
if (! array_key_exists($extension, static::$mimes))
{
return null;
}
return is_array(static::$mimes[$extension]) ? static::$mimes[$extension][0] : static::$mimes[$extension];
} | php | {
"resource": ""
} |
q254369 | Mimes.guessExtensionFromType | test | public static function guessExtensionFromType(string $type, ?string $proposed_extension = null)
{
$type = trim(strtolower($type), '. ');
$proposed_extension = trim(strtolower($proposed_extension));
if (! is_null($proposed_extension) && array_key_exists($proposed_extension, static::$mimes) && in_array($type, is_string(static::$mimes[$proposed_extension]) ? [static::$mimes[$proposed_extension]] : static::$mimes[$proposed_extension]))
{
return $proposed_extension;
}
foreach (static::$mimes as $ext => $types)
{
if (is_string($types) && $types === $type)
{
return $ext;
}
else if (is_array($types) && in_array($type, $types))
{
return $ext;
}
}
return null;
} | php | {
"resource": ""
} |
q254370 | RedirectResponse.to | test | public function to(string $uri, int $code = null, string $method = 'auto')
{
// If it appears to be a relative URL, then convert to full URL
// for better security.
if (strpos($uri, 'http') !== 0)
{
$url = current_url(true)->resolveRelativeURI($uri);
$uri = (string)$url;
}
return $this->redirect($uri, $method, $code);
} | php | {
"resource": ""
} |
q254371 | RedirectResponse.route | test | public function route(string $route, array $params = [], int $code = 302, string $method = 'auto')
{
$routes = Services::routes(true);
$route = $routes->reverseRoute($route, ...$params);
if (! $route)
{
throw HTTPException::forInvalidRedirectRoute($route);
}
return $this->redirect(base_url($route), $method, $code);
} | php | {
"resource": ""
} |
q254372 | RedirectResponse.back | test | public function back(int $code = null, string $method = 'auto')
{
$this->ensureSession();
return $this->redirect(previous_url(), $method, $code);
} | php | {
"resource": ""
} |
q254373 | RedirectResponse.with | test | public function with(string $key, $message)
{
$session = $this->ensureSession();
$session->setFlashdata($key, $message);
return $this;
} | php | {
"resource": ""
} |
q254374 | Filters.run | test | public function run(string $uri, string $position = 'before')
{
$this->initialize(strtolower($uri));
foreach ($this->filters[$position] as $alias => $rules)
{
if (is_numeric($alias) && is_string($rules))
{
$alias = $rules;
}
if (! array_key_exists($alias, $this->config->aliases))
{
throw FilterException::forNoAlias($alias);
}
$class = new $this->config->aliases[$alias]();
if (! $class instanceof FilterInterface)
{
throw FilterException::forIncorrectInterface(get_class($class));
}
if ($position === 'before')
{
$result = $class->before($this->request, $this->arguments[$alias] ?? null);
if ($result instanceof RequestInterface)
{
$this->request = $result;
continue;
}
// If the response object was sent back,
// then send it and quit.
if ($result instanceof ResponseInterface)
{
// short circuit - bypass any other filters
return $result;
}
// Ignore an empty result
if (empty($result))
{
continue;
}
return $result;
}
elseif ($position === 'after')
{
$result = $class->after($this->request, $this->response);
if ($result instanceof ResponseInterface)
{
$this->response = $result;
continue;
}
}
}
return $position === 'before' ? $this->request : $this->response;
} | php | {
"resource": ""
} |
q254375 | Filters.initialize | test | public function initialize(string $uri = null)
{
if ($this->initialized === true)
{
return $this;
}
$this->processGlobals($uri);
$this->processMethods();
$this->processFilters($uri);
$this->initialized = true;
return $this;
} | php | {
"resource": ""
} |
q254376 | Filters.enableFilter | test | public function enableFilter(string $name, string $when = 'before')
{
// Get parameters and clean name
if (strpos($name, ':') !== false)
{
list($name, $params) = explode(':', $name);
$params = explode(',', $params);
array_walk($params, function (&$item) {
$item = trim($item);
});
$this->arguments[$name] = $params;
}
if (! array_key_exists($name, $this->config->aliases))
{
throw FilterException::forNoAlias($name);
}
if (! isset($this->filters[$when][$name]))
{
$this->filters[$when][] = $name;
}
return $this;
} | php | {
"resource": ""
} |
q254377 | Filters.getArguments | test | public function getArguments(string $key = null)
{
return is_null($key)
? $this->arguments
: $this->arguments[$key];
} | php | {
"resource": ""
} |
q254378 | ChromeLoggerHandler.format | test | protected function format($object)
{
if (! is_object($object))
{
return $object;
}
// @todo Modify formatting of objects once we can view them in browser.
$objectArray = (array) $object;
$objectArray['___class_name'] = get_class($object);
return $objectArray;
} | php | {
"resource": ""
} |
q254379 | ChromeLoggerHandler.sendLogs | test | public function sendLogs(ResponseInterface &$response = null)
{
if (is_null($response))
{
$response = Services::response(null, true);
}
$data = base64_encode(utf8_encode(json_encode($this->json)));
$response->setHeader($this->header, $data);
} | php | {
"resource": ""
} |
q254380 | IncomingRequest.detectLocale | test | public function detectLocale($config)
{
$this->locale = $this->defaultLocale = $config->defaultLocale;
if (! $config->negotiateLocale)
{
return;
}
$this->setLocale($this->negotiate('language', $config->supportedLocales));
} | php | {
"resource": ""
} |
q254381 | IncomingRequest.setLocale | test | public function setLocale(string $locale)
{
// If it's not a valid locale, set it
// to the default locale for the site.
if (! in_array($locale, $this->validLocales))
{
$locale = $this->defaultLocale;
}
$this->locale = $locale;
// If the intl extension is loaded, make sure
// that we set the locale for it... if not, though,
// don't worry about it.
// this should not block code coverage thru unit testing
// @codeCoverageIgnoreStart
try
{
if (class_exists('\Locale', false))
{
\Locale::setDefault($locale);
}
}
catch (\Exception $e)
{
}
// @codeCoverageIgnoreEnd
return $this;
} | php | {
"resource": ""
} |
q254382 | IncomingRequest.isSecure | test | public function isSecure(): bool
{
if (! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
{
return true;
}
elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
{
return true;
}
elseif (! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
{
return true;
}
return false;
} | php | {
"resource": ""
} |
q254383 | IncomingRequest.getJSON | test | public function getJSON(bool $assoc = false, int $depth = 512, int $options = 0)
{
return json_decode($this->body, $assoc, $depth, $options);
} | php | {
"resource": ""
} |
q254384 | IncomingRequest.getGet | test | public function getGet($index = null, $filter = null, $flags = null)
{
return $this->fetchGlobal('get', $index, $filter, $flags);
} | php | {
"resource": ""
} |
q254385 | IncomingRequest.getPost | test | public function getPost($index = null, $filter = null, $flags = null)
{
return $this->fetchGlobal('post', $index, $filter, $flags);
} | php | {
"resource": ""
} |
q254386 | IncomingRequest.getPostGet | test | public function getPostGet($index = null, $filter = null, $flags = null)
{
// Use $_POST directly here, since filter_has_var only
// checks the initial POST data, not anything that might
// have been added since.
return isset($_POST[$index]) ? $this->getPost($index, $filter, $flags) : $this->getGet($index, $filter, $flags);
} | php | {
"resource": ""
} |
q254387 | IncomingRequest.getGetPost | test | public function getGetPost($index = null, $filter = null, $flags = null)
{
// Use $_GET directly here, since filter_has_var only
// checks the initial GET data, not anything that might
// have been added since.
return isset($_GET[$index]) ? $this->getGet($index, $filter, $flags) : $this->getPost($index, $filter, $flags);
} | php | {
"resource": ""
} |
q254388 | IncomingRequest.getCookie | test | public function getCookie($index = null, $filter = null, $flags = null)
{
return $this->fetchGlobal('cookie', $index, $filter, $flags);
} | php | {
"resource": ""
} |
q254389 | IncomingRequest.getFiles | test | public function getFiles(): array
{
if (is_null($this->files))
{
$this->files = new FileCollection();
}
return $this->files->all(); // return all files
} | php | {
"resource": ""
} |
q254390 | IncomingRequest.getFile | test | public function getFile(string $fileID)
{
if (is_null($this->files))
{
$this->files = new FileCollection();
}
return $this->files->getFile($fileID);
} | php | {
"resource": ""
} |
q254391 | IncomingRequest.detectURI | test | protected function detectURI(string $protocol, string $baseURL)
{
$this->uri->setPath($this->detectPath($protocol));
// It's possible the user forgot a trailing slash on their
// baseURL, so let's help them out.
$baseURL = ! empty($baseURL) ? rtrim($baseURL, '/ ') . '/' : $baseURL;
// Based on our baseURL provided by the developer (if set)
// set our current domain name, scheme
if (! empty($baseURL))
{
// We cannot add the path here, otherwise it's possible
// that the routing will not work correctly if we are
// within a sub-folder scheme. So it's modified in
// the
$this->uri->setScheme(parse_url($baseURL, PHP_URL_SCHEME));
$this->uri->setHost(parse_url($baseURL, PHP_URL_HOST));
$this->uri->setPort(parse_url($baseURL, PHP_URL_PORT));
$this->uri->resolveRelativeURI(parse_url($baseURL, PHP_URL_PATH));
}
else
{
// @codeCoverageIgnoreStart
if (! is_cli())
{
die('You have an empty or invalid base URL. The baseURL value must be set in Config\App.php, or through the .env file.');
}
// @codeCoverageIgnoreEnd
}
} | php | {
"resource": ""
} |
q254392 | IncomingRequest.detectPath | test | public function detectPath(string $protocol = ''): string
{
if (empty($protocol))
{
$protocol = 'REQUEST_URI';
}
switch ($protocol)
{
case 'REQUEST_URI':
$path = $this->parseRequestURI();
break;
case 'QUERY_STRING':
$path = $this->parseQueryString();
break;
case 'PATH_INFO':
default:
$path = $this->fetchGlobal('server', $protocol) ?? $this->parseRequestURI();
break;
}
return $path;
} | php | {
"resource": ""
} |
q254393 | IncomingRequest.negotiate | test | public function negotiate(string $type, array $supported, bool $strictMatch = false): string
{
if (is_null($this->negotiator))
{
$this->negotiator = Services::negotiator($this, true);
}
switch (strtolower($type))
{
case 'media':
return $this->negotiator->media($supported, $strictMatch);
case 'charset':
return $this->negotiator->charset($supported);
case 'encoding':
return $this->negotiator->encoding($supported);
case 'language':
return $this->negotiator->language($supported);
}
throw HTTPException::forInvalidNegotiationType($type);
} | php | {
"resource": ""
} |
q254394 | IncomingRequest.parseRequestURI | test | protected function parseRequestURI(): string
{
if (! isset($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME']))
{
return '';
}
// parse_url() returns false if no host is present, but the path or query string
// contains a colon followed by a number
$parts = parse_url('http://dummy' . $_SERVER['REQUEST_URI']);
$query = $parts['query'] ?? '';
$uri = $parts['path'] ?? '';
if (isset($_SERVER['SCRIPT_NAME'][0]))
{
// strip the script name from the beginning of the URI
if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0)
{
$uri = (string) substr($uri, strlen($_SERVER['SCRIPT_NAME']));
}
// if the script is nested, strip the parent folder & script from the URI
elseif (strpos($uri, $_SERVER['SCRIPT_NAME']) > 0)
{
$uri = (string) substr($uri, strpos($uri, $_SERVER['SCRIPT_NAME']) + strlen($_SERVER['SCRIPT_NAME']));
}
// or if index.php is implied
elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0)
{
$uri = (string) substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME'])));
}
}
// This section ensures that even on servers that require the URI to contain the query string (Nginx) a correct
// URI is found, and also fixes the QUERY_STRING getServer var and $_GET array.
if (trim($uri, '/') === '' && strncmp($query, '/', 1) === 0)
{
$query = explode('?', $query, 2);
$uri = $query[0];
$_SERVER['QUERY_STRING'] = $query[1] ?? '';
}
else
{
$_SERVER['QUERY_STRING'] = $query;
}
parse_str($_SERVER['QUERY_STRING'], $_GET);
if ($uri === '/' || $uri === '')
{
return '/';
}
return $this->removeRelativeDirectory($uri);
} | php | {
"resource": ""
} |
q254395 | Connection.buildDSN | test | protected function buildDSN()
{
$this->DSN === '' || $this->DSN = '';
// If UNIX sockets are used, we shouldn't set a port
if (strpos($this->hostname, '/') !== false)
{
$this->port = '';
}
$this->hostname === '' || $this->DSN = "host={$this->hostname} ";
if (! empty($this->port) && ctype_digit($this->port))
{
$this->DSN .= "port={$this->port} ";
}
if ($this->username !== '')
{
$this->DSN .= "user={$this->username} ";
// An empty password is valid!
// password must be set to null to ignore it.
$this->password === null || $this->DSN .= "password='{$this->password}' ";
}
$this->database === '' || $this->DSN .= "dbname={$this->database} ";
// We don't have these options as elements in our standard configuration
// array, but they might be set by parse_url() if the configuration was
// provided via string> Example:
//
// postgre://username:password@localhost:5432/database?connect_timeout=5&sslmode=1
foreach (['connect_timeout', 'options', 'sslmode', 'service'] as $key)
{
if (isset($this->{$key}) && is_string($this->{$key}) && $this->{$key} !== '')
{
$this->DSN .= "{$key}='{$this->{$key}}' ";
}
}
$this->DSN = rtrim($this->DSN);
} | php | {
"resource": ""
} |
q254396 | Format.getFormatter | test | public function getFormatter(string $mime)
{
if (! array_key_exists($mime, $this->formatters))
{
throw new \InvalidArgumentException('No Formatter defined for mime type: ' . $mime);
}
$class = $this->formatters[$mime];
if (! class_exists($class))
{
throw new \BadMethodCallException($class . ' is not a valid Formatter.');
}
return new $class();
} | php | {
"resource": ""
} |
q254397 | Honeypot.before | test | public function before(RequestInterface $request)
{
$honeypot = Services::honeypot(new \Config\Honeypot());
if ($honeypot->hasContent($request))
{
throw HoneypotException::isBot();
}
} | php | {
"resource": ""
} |
q254398 | Honeypot.after | test | public function after(RequestInterface $request, ResponseInterface $response)
{
$honeypot = Services::honeypot(new \Config\Honeypot());
$honeypot->attachHoneypot($response);
} | php | {
"resource": ""
} |
q254399 | ImageMagickHandler._resize | test | public function _resize(bool $maintainRatio = false)
{
$source = ! empty($this->resource) ? $this->resource : $this->image->getPathname();
$destination = $this->getResourcePath();
$escape = '\\';
if (stripos(PHP_OS, 'WIN') === 0)
{
$escape = '';
}
$action = $maintainRatio === true ? ' -resize ' . $this->width . 'x' . $this->height . ' "' . $source . '" "' . $destination . '"' : ' -resize ' . $this->width . 'x' . $this->height . "{$escape}! \"" . $source . '" "' . $destination . '"';
$this->process($action);
return $this;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.