sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function pretty_json($json) { $result = null; $pos = 0; $length = strlen($json); $indentString = ' '; $newLine = PHP_EOL; $lastChar = null; $outOfQuotes = true; for ($i = 0; $i < $length; $i++) { // Grab the next character in the string. $char = $json[$i]; // Put spaces around colons if ($outOfQuotes && ':' == $char && ' ' != $lastChar) { $result .= ' '; } if ($outOfQuotes && ' ' != $char && ':' == $lastChar) { $result .= ' '; } // Are we inside a quoted string? if ('"' == $char && '\\' != $lastChar) { $outOfQuotes = !$outOfQuotes; // If this character is the end of an element, // output a new line and indent the next line. } else { if (($char == '}' || $char == ']') && $outOfQuotes) { $result .= $newLine; $pos--; for ($j = 0; $j < $pos; $j++) { $result .= $indentString; } } } // Add the character to the result string. $result .= $char; // If the last character was the beginning of an element output a new line and indent the next line. if ((',' == $char || '{' == $char || '[' == $char) && $outOfQuotes) { $result .= $newLine; if ('{' == $char || '[' == $char) { $pos++; } for ($j = 0; $j < $pos; $j++) { $result .= $indentString; } } $lastChar = $char; } return $result; }
Indents a flat JSON string to make it more human-readable. Stolen from http://recursive-design.com/blog/2008/03/11/format-json-with-php/ and adapted to put spaces around : characters, then cleaned up. @param string $json The original JSON string to process. @return string Indented version of the original JSON string.
entailment
public static function validationErrorsToString($messages) { if ($messages instanceof MessageBag) { $messages = $messages->getMessages(); } $errorString = ''; if (is_array($messages)) { foreach ($messages as $field => $errors) { foreach ($errors as $error) { $errorString .= ' ' . $error; } } } return $errorString; }
Converts validation errors to plain string. @param $messages @return string
entailment
public function handle() { if (file_exists('vendor/bin/homestead')) { $memory = 4096; $cpus = 2; $version = "3.1.0"; $script = ($this->option('dev'))? 'server/config/homestead/after-dev.sh' : 'server/config/homestead/after.sh'; $this->info('----------------------------------------------------------------------------'); $this->info('Configuring Homestead with following settings: '); $this->info('IP: 192.168.10.10'); $this->info('Memory: ' . $memory); $this->info('CPUs: ' . $cpus); $this->info('Box Version: ' . $version); $this->info('Script: ' . $script); $this->info('----------------------------------------------------------------------------'); $this->warn('Edit Homestead.yaml file if you like to change any of the above settings.'); exec("php vendor/bin/homestead make", $out); $output = implode('\n', $out); $this->info($output); $this->info('You can now run "vagrant up" to provision your homestead vagrant box.'); $this->info('----------------------------------------------------------------------------'); if (file_exists('Homestead.yaml')) { file_put_contents('Homestead.yaml', str_replace("memory: 2048", "memory: $memory", file_get_contents('Homestead.yaml'))); file_put_contents('Homestead.yaml', str_replace("cpus: 1", "cpus: $cpus", file_get_contents('Homestead.yaml'))); if (strpos(file_get_contents('Homestead.yaml'), 'version:') === false) { file_put_contents('Homestead.yaml', str_replace("provider: virtualbox", "provider: virtualbox\nversion: $version", file_get_contents('Homestead.yaml')) ); } if (strpos(file_get_contents('Homestead.yaml'), 'script:') === false) { file_put_contents('Homestead.yaml', str_replace("provider: virtualbox", "provider: virtualbox\nscript: $script", file_get_contents('Homestead.yaml')) ); } // if(strpos(file_get_contents('Homestead.yaml'), 'type: "nfs"') === false){ // file_put_contents('Homestead.yaml', // str_replace("to: /home/vagrant/code\n", "to: /home/vagrant/code\n type: \"nfs\"\n", // file_get_contents('Homestead.yaml')) // ); // } if(strpos(file_get_contents('Homestead.yaml'), 'php: "7.1"') === false){ file_put_contents('Homestead.yaml', str_replace("to: /home/vagrant/code/public\n", "to: /home/vagrant/code/public\n php: \"7.1\"\n", file_get_contents('Homestead.yaml')) ); } } // Remove after.sh and aliases files create by Homestead configurator // as we supply our own in server/config/homestead/ diretory. @unlink('after.sh'); @unlink('aliases'); } }
Execute the console command. @return mixed
entailment
public static function getExternalIP() { $ip = \Cache::rememberForever('external-ip-address', function () { $response = Curl::get('http://ipinfo.io/ip'); $ip = trim($response, "\t\r\n"); try { $validator = Validator::make(['ip' => $ip], ['ip' => 'ip']); $validator->validate(); } catch (ValidationException $e) { $ip = null; } return $ip; }); return $ip; }
Returns instance's external IP address. @return mixed
entailment
public static function getURI() { $s = $_SERVER; $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on'); $sp = strtolower(array_get($s, 'SERVER_PROTOCOL', 'http://')); $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : ''); $port = array_get($s, 'SERVER_PORT', '80'); $port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':' . $port; $host = (isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : array_get($s, 'SERVER_NAME', 'localhost')); $host = (strpos($host, ':') !== false) ? $host : $host . $port; return $protocol . '://' . $host; }
Returns instance's URI @return string
entailment
public static function getPhpInfo() { $html = null; $info = []; $pattern = '#(?:<h2>(?:<a name=".*?">)?(.*?)(?:</a>)?</h2>)|(?:<tr(?: class=".*?")?><t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>)?)?</tr>)#s'; \ob_start(); @\phpinfo(); $html = \ob_get_contents(); \ob_end_clean(); if (preg_match_all($pattern, $html, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $keys = array_keys($info); $lastKey = end($keys); if (strlen($match[1])) { $info[$match[1]] = []; } elseif (isset($match[3])) { $info[$lastKey][$match[2]] = isset($match[4]) ? [$match[3], $match[4]] : $match[3]; } else { $info[$lastKey][] = $match[2]; } unset($keys, $match); } } return static::cleanPhpInfo($info); }
Parses the data coming back from phpinfo() call and returns in an array @return array
entailment
public static function cleanPhpInfo($info, $recursive = false) { static $excludeKeys = ['directive', 'variable',]; $clean = []; // Remove images and move nested args to root if (!$recursive && isset($info[0], $info[0][0]) && is_array($info[0])) { $info['general'] = []; foreach ($info[0] as $key => $value) { if (is_numeric($key) || in_array(strtolower($key), $excludeKeys)) { continue; } $info['general'][$key] = $value; unset($info[0][$key]); } unset($info[0]); } foreach ($info as $key => $value) { if (in_array(strtolower($key), $excludeKeys)) { continue; } $key = strtolower(str_replace(' ', '_', $key)); if (is_array($value) && 2 == count($value) && isset($value[0], $value[1])) { $v1 = array_get($value, 0); if ($v1 == '<i>no value</i>') { $v1 = null; } if (in_array(strtolower($v1), ['on', 'off', '0', '1'])) { $v1 = array_get_bool($value, 0); } $value = $v1; } if (is_array($value)) { $value = static::cleanPhpInfo($value, true); } $clean[$key] = $value; } return $clean; }
@param array $info @param bool $recursive @return array
entailment
public function getMask(): IP { if ($this->mask === null) { if ($this->prefix == 0) { $this->mask = new static::$ip_class(0); } else { $max_int = gmp_init(static::$ip_class::MAX_INT); $mask = gmp_shiftl($max_int, static::$ip_class::NB_BITS - $this->prefix); $mask = gmp_and($mask, $max_int); // truncate to 128 bits only $this->mask = new static::$ip_class($mask); } } return $this->mask; }
Return netmask. @return IP
entailment
public function getDelta(): IP { if ($this->delta === null) { if ($this->prefix == 0) { $this->delta = new static::$ip_class(static::$ip_class::MAX_INT); } else { $this->delta = new static::$ip_class(gmp_sub(gmp_shiftl(1, static::$ip_class::NB_BITS - $this->prefix), 1)); } } return $this->delta; }
Return delta to last IP address. @return IP
entailment
public static function create($ip, $prefix = ''): IPBlock { try { return new IPv4Block($ip, $prefix); } catch (\InvalidArgumentException $e) { // do nothing } try { return new IPv6Block($ip, $prefix); } catch (\InvalidArgumentException $e) { // do nothing } throw new \InvalidArgumentException("$ip does not appear to be an IPv4 or IPv6 block"); }
@param mixed $ip @param mixed $prefix @return IPv4Block|IPv6Block
entailment
public function minus(int $value): IPBlock { if ($value < 0) { return $this->plus(-1 * $value); } if ($value == 0) { return clone $this; } // check boundaries try { $first_ip = $this->first_ip->minus(gmp_mul($value, $this->getNbAddresses())); return new static( $first_ip, $this->prefix ); } catch (\InvalidArgumentException $e) { throw new \OutOfBoundsException($e->getMessage()); } }
@param int $value @return IPBlock
entailment
protected function checkPrefix($prefix) { if ($prefix === '' || $prefix === null || $prefix === false || $prefix < 0 || $prefix > $this->getMaxPrefix()) { throw new \InvalidArgumentException(sprintf( "Invalid IPv%s block prefix '%s'", $this->getVersion(), $prefix )); } }
@internal Check if the prefix is valid @param mixed $prefix @throws \InvalidArgumentException
entailment
public function getSubBlocks($prefix): IPBlockIterator { $prefix = ltrim($prefix, '/'); $this->checkPrefix($prefix); if ($prefix <= $this->prefix) { throw new \InvalidArgumentException("Prefix must be smaller than {$this->prefix} ($prefix given)"); } $first_block = new static($this->first_ip, $prefix); $number_of_blocks = gmp_pow(2, $prefix - $this->prefix); return new IPBlockIterator($first_block, $number_of_blocks); }
Split the block into smaller blocks. Returns an iterator, use foreach to loop it and count to get number of subnets. @param mixed $prefix @return IPBlockIterator
entailment
public function getSuperBlock($prefix): IPBlock { $prefix = ltrim($prefix, '/'); $this->checkPrefix($prefix); if ($prefix >= $this->prefix) { throw new \InvalidArgumentException("Prefix must be bigger than {$this->prefix} ($prefix given)"); } return new static($this->first_ip, $prefix); }
Return the super block containing the current block. @param mixed $prefix @return IPBlock
entailment
public function contains($ip_or_block): bool { if ((is_string($ip_or_block) && strpos($ip_or_block, '/') !== false) || $ip_or_block instanceof IPBlock) { return $this->containsBlock($ip_or_block); } else { return $this->containsIP($ip_or_block); } }
Determine if the current block contains an IP address or block. @param mixed $ip_or_block @return bool
entailment
public function containsIP($ip): bool { if (!$ip instanceof IP) { $ip = IP::create($ip); } return ($ip->numeric() >= $this->getFirstIp()->numeric()) && ($ip->numeric() <= $this->getLastIp()->numeric()); }
Determine if the current block contains an IP address. @param mixed $ip @return bool
entailment
public function containsBlock($block): bool { if (!$block instanceof IPBlock) { $block = new static($block); } return $block->getFirstIp()->numeric() >= $this->first_ip->numeric() && $block->getLastIp()->numeric() <= $this->last_ip->numeric(); }
Determine if the current block contains another block. True in this situation: $this: first_ip[ ]last_ip $block: first_ip[ ]last_ip @param mixed $block @return bool
entailment
public function isIn($block): bool { if (!$block instanceof IPBlock) { $block = new static($block); } return $block->containsBlock($this); }
Determine if the current block is contained in another block. @param mixed $block @return bool
entailment
public function getNbAddresses(): string { if ($this->nb_addresses === null) { $this->nb_addresses = gmp_strval(gmp_pow(2, $this->getMaxPrefix() - $this->prefix)); } return $this->nb_addresses; }
Return the number of IP addresses in the block. @return string numeric string (can be huge)
entailment
public function count(): int { $network_size = gmp_init($this->getNbAddresses()); if (gmp_cmp($network_size, PHP_INT_MAX) > 0) { throw new \RuntimeException('The number of addresses is bigger than PHP_INT_MAX, use getNbAddresses() instead'); } return gmp_intval($network_size); }
Count the number of addresses contained with the address block. May exceed PHP's internal maximum integer. @return int @throws \RuntimeException thrown if the number of addresses exceeds PHP_INT_MAX
entailment
public function offsetGet($offset): IP { if (!$this->offsetExists($offset)) { throw new \OutOfBoundsException("Offset $offset does not exists"); } return $this->first_ip->plus($offset); }
{@inheritdoc}
entailment
public function handle($request, Closure $next) { if (!in_array($route = $request->getPathInfo(), ['/setup', '/setup_db'])) { try { if (!User::adminExists()) { return redirect()->to('/setup'); } elseif (!empty(config('df.package_path'))) { if (false === \Cache::get('package_imported', false)) { \Artisan::call('df:import-pkg'); \Cache::forever('package_imported', true); } } } catch (QueryException $e) { try { //base table or view not found. \Cache::put('setup_db', true, config('df.default_cache_ttl')); return redirect()->to('/setup_db'); } catch (\Exception $ex) { throw $ex; } } } return $next($request); }
@param Request $request @param \Closure $next @return \Illuminate\Http\RedirectResponse @throws \Exception
entailment
public static function getConfig($id, $local_config = null, $protect = true) { $out = []; /** @var BaseServiceConfigModel $model */ /** @noinspection PhpUndefinedMethodInspection */ if ($model = static::whereServiceId($id)->first()) { $model->protectedView = $protect; $out = $model->toArray(); } if ($local_config) { $out = array_merge((array)$out, $local_config); } return $out; }
{@inheritdoc}
entailment
public static function setConfig($id, $config, $local_config = null) { if ($id) { //Making sure service_id is the first item in the config. //This way service_id will be set first and is available //for use right away. This helps setting an auto-generated //field that may depend on parent data. See OAuthConfig->setAttribute. $config = array_reverse($config, true); $config[static::getServiceIdField()] = $id; $config = array_reverse($config, true); /** @noinspection PhpUndefinedMethodInspection */ $model = (static::$alwaysNewOnSet ? new static() : static::firstOrNew([static::getServiceIdField() => $id])); } else { $model = new static(); } /** @var BaseServiceConfigModel $model */ $config = array_only($config, $model->getFillable()); $model->fill((array)$config); $model->validate($model->attributes); if ($id) { // only save if the service has been created $model->save(); } return $local_config; // by default, just return what the service passed us }
{@inheritdoc}
entailment
public static function storeConfig($id, $config) { //Making sure service_id is the first item in the config. //This way service_id will be set first and is available //for use right away. This helps setting an auto-generated //field that may depend on parent data. See OAuthConfig->setAttribute. $config = array_reverse($config, true); $config[static::getServiceIdField()] = $id; $config = array_reverse($config, true); /** @noinspection PhpUndefinedMethodInspection */ /** @var BaseServiceConfigModel $model */ $model = (static::$alwaysNewOnSet ? new static() : static::firstOrNew([static::getServiceIdField() => $id])); $config = array_only($config, $model->getFillable()); $model->fill((array)$config); $model->save(); }
{@inheritdoc}
entailment
public static function request($method, $url, $payload = [], $curlOptions = []) { return static::_httpRequest($method, $url, $payload, $curlOptions); }
@param string $method @param string $url @param array|\stdClass $payload @param array $curlOptions @return string|\stdClass
entailment
public static function getInfo($key = null, $defaultValue = null) { return null === $key ? static::$_info : array_get(static::$_info, $key, $defaultValue); }
@param string $key Leaving this null will return the entire structure, otherwise just the value for the supplied key @param mixed $defaultValue The default value to return if the $key was not found @return array
entailment
public static function currentUrl($includeQuery = true, $includePath = true) { // Are we SSL? Check for load balancer protocol as well... $_port = intval(array_get($_SERVER, 'HTTP_X_FORWARDED_PORT', array_get($_SERVER, 'SERVER_PORT', 80))); $_protocol = array_get($_SERVER, 'HTTP_X_FORWARDED_PROTO', 'http' . (array_get_bool($_SERVER, 'HTTPS') ? 's' : null)) . '://'; $_host = array_get($_SERVER, 'HTTP_X_FORWARDED_HOST', array_get($_SERVER, 'HTTP_HOST', gethostname())); $_parts = parse_url($_protocol . $_host . array_get($_SERVER, 'REQUEST_URI')); if ((empty($_port) || !is_numeric($_port)) && null !== ($_parsePort = array_get($_parts, 'port'))) { $_port = @intval($_parsePort); } if (null !== ($_query = array_get($_parts, 'query'))) { $_query = static::urlSeparator($_query) . http_build_query(explode('&', $_query)); } if (false !== strpos($_host, ':') || ($_protocol == 'https://' && $_port == 443) || ($_protocol == 'http://' && $_port == 80) ) { $_port = null; } else { $_port = ':' . $_port; } if (false !== strpos($_host, ':')) { $_port = null; } $_currentUrl = $_protocol . $_host . $_port . (true === $includePath ? array_get($_parts, 'path') : null) . (true === $includeQuery ? $_query : null); return $_currentUrl; }
Returns the validated URL that has been called to get here @param bool $includeQuery If true, query string is included @param bool $includePath If true, the uri path is included @return string
entailment
public function up() { // Laravel 5.4 changed the table layout for jobs and failed_jobs if (Schema::hasColumn('jobs', 'reserved')) { Schema::table('jobs', function (Blueprint $table) { $table->dropColumn('reserved'); }); } if (!Schema::hasColumn('failed_jobs', 'exception')) { Schema::table('failed_jobs', function (Blueprint $table) { $table->longText('exception'); }); } }
Run the migrations. @return void
entailment
public function down() { if (!Schema::hasColumn('jobs', 'reserved')) { Schema::table('jobs', function (Blueprint $table) { $table->tinyInteger('reserved')->unsigned(); }); } if (Schema::hasColumn('failed_jobs', 'reserved')) { Schema::table('failed_jobs', function (Blueprint $table) { $table->dropColumn('exception'); }); } }
Reverse the migrations. @return void
entailment
public function handle(UserViewingThread $event) { if ($this->auth->check()) { $primaryKey = $this->auth->user()->getKeyName(); $event->thread->markAsRead($this->auth->user()->{$primaryKey}); } }
Handle the event. @param UserViewingThread $event @return void
entailment
public static function checkServicePermission( $action, $service, $component = null, $requestor = ServiceRequestorTypes::API, $exception = true ) { $verb = VerbsMask::toNumeric(static::cleanAction($action)); $mask = static::getServicePermissions($service, $component, $requestor); if (!($verb & $mask)) { if (ServiceManager::isAccessException($service, $component, $action)) { return true; } if (false === $exception) { return false; } $msg = ucfirst($action) . " access to "; if (!empty($component)) { $msg .= "component '$component' of "; } $msg .= "service '$service' is not allowed by this user's role."; throw new ForbiddenException($msg); } return true; }
@param string $action - REST API action name @param string $service - API name of the service @param string $component - API component/resource name @param int $requestor - Entity type requesting the service @param bool $exception - Set false to return false @returns boolean @throws ForbiddenException @throws \DreamFactory\Core\Exceptions\NotFoundException @throws \DreamFactory\Core\Exceptions\NotImplementedException
entailment
public static function getServicePermissions($service, $component = null, $requestor = ServiceRequestorTypes::API) { if (static::isSysAdmin()) { return VerbsMask::GET_MASK | VerbsMask::POST_MASK | VerbsMask::PUT_MASK | VerbsMask::PATCH_MASK | VerbsMask::DELETE_MASK; } $roleId = Session::getRoleId(); if ($roleId && !Role::getCachedInfo($roleId, 'is_active')) { return false; } $services = (array)static::get('role.services'); $service = strval($service); $component = ltrim(strval($component), '/'); if ((false !== $parenStart = strpos($component, '(')) && (false !== $parenEnd = strpos($component, ')'))) { $component = substr_replace($component, '', $parenStart, $parenEnd - $parenStart + 1); } // If exact match found take it, otherwise follow up the chain as necessary // All - Service - Component - Sub-component $allAllowed = VerbsMask::NONE_MASK; $allFound = false; $serviceAllowed = VerbsMask::NONE_MASK; $serviceFound = false; $componentAllowed = VerbsMask::NONE_MASK; $componentFound = false; $exactAllowed = VerbsMask::NONE_MASK; $exactFound = false; foreach ($services as $svcInfo) { $tempRequestors = array_get($svcInfo, 'requestor_mask', ServiceRequestorTypes::API); if (!($requestor & $tempRequestors)) { // Requestor type not found in allowed requestors, skip access setting continue; } $tempService = strval(array_get($svcInfo, 'service')); $tempComponent = strval(array_get($svcInfo, 'component')); $tempVerbs = array_get($svcInfo, 'verb_mask'); if (0 == strcasecmp($service, $tempService)) { if (!empty($component)) { if (0 == strcasecmp($component, $tempComponent)) { // exact match $exactAllowed |= $tempVerbs; $exactFound = true; } elseif ((false !== $tempCompStarPos = strpos($tempComponent, '*')) && (0 == strcasecmp(substr($component . '/', 0, $tempCompStarPos) . '*', $tempComponent)) ) { $componentAllowed |= $tempVerbs; $componentFound = true; } elseif ('*' == $tempComponent) { $serviceAllowed |= $tempVerbs; $serviceFound = true; } elseif ((false !== $wildcardStart = strpos($component, '{')) && (false !== $wildcardEnd = strpos($component, '}'))) { $compReg = '^' . substr_replace($component, '[a-zA-Z0-9_]{1,}$', $wildcardStart, $wildcardEnd - $wildcardStart + 1); $compReg = str_replace('/', '\/', $compReg); if ((false !== preg_match("/$compReg/", $tempComponent, $matches)) && !empty($matches)) { $componentAllowed |= $tempVerbs; $componentFound = true; } } } else { if (empty($tempComponent)) { // exact match $exactAllowed |= $tempVerbs; $exactFound = true; } elseif ('*' == $tempComponent) { $serviceAllowed |= $tempVerbs; $serviceFound = true; } } } else { if (empty($tempService) && (('*' == $tempComponent) || (empty($tempComponent) && empty($component)))) { $allAllowed |= $tempVerbs; $allFound = true; } } } if ($exactFound) { return $exactAllowed; } elseif ($componentFound) { return $componentAllowed; } elseif ($serviceFound) { return $serviceAllowed; } elseif ($allFound) { return $allAllowed; } return VerbsMask::NONE_MASK; }
@param string $service - API name of the service @param string $component - API component/resource name @param int $requestor - Entity type requesting the service @returns int|boolean
entailment
public static function allowsServiceAccess($service, $requestor = ServiceRequestorTypes::API) { if (static::isSysAdmin()) { return true; } $roleId = Session::getRoleId(); if ($roleId && !Role::getCachedInfo($roleId, 'is_active')) { return false; } $services = (array)static::get('role.services'); $service = strval($service); // If exact match found take it, otherwise follow up the chain as necessary // All - Service - Component - Sub-component $allAllowed = VerbsMask::NONE_MASK; $allFound = false; $serviceAllowed = VerbsMask::NONE_MASK; $serviceFound = false; foreach ($services as $svcInfo) { $tempRequestors = array_get($svcInfo, 'requestor_mask', ServiceRequestorTypes::API); if (!($requestor & $tempRequestors)) { // Requestor type not found in allowed requestors, skip access setting continue; } $tempService = strval(array_get($svcInfo, 'service')); $tempVerbs = array_get($svcInfo, 'verb_mask'); if (0 == strcasecmp($service, $tempService)) { $serviceAllowed |= $tempVerbs; $serviceFound = true; } elseif (empty($tempService)) { $allAllowed |= $tempVerbs; $allFound = true; } } if ($serviceFound) { return (VerbsMask::NONE_MASK !== $serviceAllowed); } elseif ($allFound) { return (VerbsMask::NONE_MASK !== $allAllowed); } return false; }
@param string $service - API name of the service @param int $requestor - Entity type requesting the service @returns boolean
entailment
protected static function cleanAction($action) { // check for non-conformists $action = strtoupper($action); switch ($action) { case 'READ': return Verbs::GET; case 'CREATE': return Verbs::POST; case 'UPDATE': return Verbs::PUT; } return $action; }
@param string $action - requested REST action @return string
entailment
public static function getServiceFilters( $action, $service, $component = null, $requestor = ServiceRequestorTypes::API ) { if (static::isSysAdmin()) { return null; } $services = (array)static::get('role.services'); $service = strval($service); $component = strval($component); if ((false !== $parenStart = strpos($component, '(')) && (false !== $parenEnd = strpos($component, ')'))) { $component = substr_replace($component, '', $parenStart, $parenEnd - $parenStart + 1); } $action = VerbsMask::toNumeric(static::cleanAction($action)); $serviceAllowed = null; $serviceFound = false; $componentAllowed = null; $componentFound = false; $exactAllowed = null; $exactFound = false; foreach ($services as $svcInfo) { $tempRequestors = array_get($svcInfo, 'requestor_mask', ServiceRequestorTypes::API); if (!($requestor & $tempRequestors)) { // Requestor type not found in allowed requestors, skip access setting continue; } $tempVerbs = array_get($svcInfo, 'verb_mask'); if (!($tempVerbs & $action)) { continue; } $tempService = strval(array_get($svcInfo, 'service')); if (0 !== strcasecmp($service, $tempService)) { continue; // filters only available starting at the service } $tempComponent = strval(array_get($svcInfo, 'component')); if (!empty($component)) { if (0 == strcasecmp($component, $tempComponent)) { // exact match $exactAllowed = $svcInfo; $exactFound = true; } elseif ((false !== $tempCompStarPos = strpos($tempComponent, '*')) && (0 == strcasecmp(substr($component . '/', 0, $tempCompStarPos) . '*', $tempComponent)) ) { $componentAllowed = $svcInfo; $componentFound = true; } elseif ('*' == $tempComponent) { $serviceAllowed = $svcInfo; $serviceFound = true; } elseif ((false !== $wildcardStart = strpos($component, '{')) && (false !== $wildcardEnd = strpos($component, '}'))) { $compReg = '^' . substr_replace($component, '[a-zA-Z0-9_]{1,}$', $wildcardStart, $wildcardEnd - $wildcardStart + 1); $compReg = str_replace('/', '\/', $compReg); if ((false !== preg_match("/$compReg/", $tempComponent, $matches)) && !empty($matches)) { $componentAllowed = $svcInfo; $componentFound = true; } } } else { if (empty($tempComponent)) { // exact match $exactAllowed = $svcInfo; $exactFound = true; } elseif ('*' == $tempComponent) { $serviceAllowed = $svcInfo; $serviceFound = true; } } } $info = null; if ($exactFound) { $info = $exactAllowed; } elseif ($componentFound) { $info = $componentAllowed; } elseif ($serviceFound) { $info = $serviceAllowed; } if ($info) { if (empty($filters = array_get($info, 'filters'))) { return null; } return ['filters' => $filters, 'filter_op' => array_get($info, 'filter_op', 'AND')]; } return null; }
@param string $action @param string $service @param string $component @param int $requestor - Entity type requesting the service @returns array @throws \DreamFactory\Core\Exceptions\NotImplementedException
entailment
public static function getLookupValue($lookup, &$value, $use_private = false) { if (empty($lookup)) { return false; } $_parts = explode('.', $lookup); if (count($_parts) > 1) { $_section = array_shift($_parts); $_lookup = implode('.', $_parts); if (!empty($_section)) { switch ($_section) { case 'session': switch ($_lookup) { case 'id': case 'token': $value = static::getSessionToken(); return true; // case 'ticket': // $value = static::_generateTicket(); // // return true; } break; case 'user': case 'role': // get fields here if (!empty($_lookup)) { $info = static::get($_section); if (isset($info, $info[$_lookup])) { $value = $info[$_lookup]; return true; } } break; case 'app': switch ($_lookup) { case 'id': $value = static::get('app.id');; return true; case 'api_key': $value = static::getApiKey(); return true; } break; case 'df': switch ($_lookup) { case 'host_url': $value = Curl::currentUrl(false, false); return true; case 'name': $value = \Config::get('app.name'); return true; case 'version': $value = \Config::get('app.version'); return true; case 'api_version': $value = \Config::get('df.api_version'); return true; case 'confirm_invite_url': $value = url(\Config::get('df.confirm_invite_url')); return true; case 'confirm_register_url': $value = url(\Config::get('df.confirm_register_url')); return true; case 'confirm_reset_url': $value = url(\Config::get('df.confirm_reset_url')); return true; } break; } } } if ($use_private) { $lookups = static::get('lookup_secret'); if (array_key_exists($lookup, (array)$lookups)) { $value = $lookups[$lookup]; return true; } } // non-private $lookups = static::get('lookup'); if (array_key_exists($lookup, (array)$lookups)) { $value = $lookups[$lookup]; return true; } return false; }
@param string $lookup @param string $value @param bool $use_private @returns bool
entailment
public static function authenticate(array $credentials, $remember = false, $login = true, $appId = null) { if (\Auth::attempt($credentials)) { $user = \Auth::getLastAttempted(); /** @noinspection PhpUndefinedFieldInspection */ static::checkRole($user->id); if ($login) { /** @noinspection PhpUndefinedFieldInspection */ $user->last_login_date = Carbon::now()->toDateTimeString(); /** @noinspection PhpUndefinedFieldInspection */ $user->confirm_code = 'y'; /** @noinspection PhpUndefinedMethodInspection */ $user->save(); /** @noinspection PhpParamsInspection */ Session::setUserInfoWithJWT($user, $remember, $appId); } return true; } else { return false; } }
@param array $credentials @param bool $remember @param bool $login @param integer $appId @return bool @throws \Exception
entailment
protected static function checkRole($userId) { $appId = static::get('app.id', null); if (!empty($appId) && !empty($userId)) { $roleId = UserAppRole::getRoleIdByAppIdAndUserId($appId, $userId); $roleInfo = ($roleId) ? Role::getCachedInfo($roleId) : null; if (!empty($roleInfo) && !array_get($roleInfo, 'is_active', false)) { throw new ForbiddenException('Role is not active.'); } } }
@param $userId @throws \DreamFactory\Core\Exceptions\ForbiddenException
entailment
public static function setUserInfoWithJWT($user, $forever = false, $appId = null) { $userInfo = null; if ($user instanceof User) { $userInfo = $user->toArray(); $userInfo['is_sys_admin'] = $user->is_sys_admin; } if (!empty($userInfo)) { $id = array_get($userInfo, 'id'); $email = array_get($userInfo, 'email'); $token = JWTUtilities::makeJWTByUser($id, $email, $forever); static::setSessionToken($token); if (!empty($appId) && !$user->is_sys_admin) { static::setSessionData($appId, $id); return true; } else { return static::setUserInfo($userInfo); } } return false; }
Sets basic info of the user in session with JWT when authenticated. @param array|User $user @param bool $forever @param integer $appId @return bool
entailment
public static function setUserInfo($user) { if (!empty($user)) { \Session::put('user.id', array_get($user, 'id')); \Session::put('user.name', array_get($user, 'name')); \Session::put('user.username', array_get($user, 'username')); \Session::put('user.display_name', array_get($user, 'name')); \Session::put('user.first_name', array_get($user, 'first_name')); \Session::put('user.last_name', array_get($user, 'last_name')); \Session::put('user.email', array_get($user, 'email')); \Session::put('user.is_sys_admin', array_get($user, 'is_sys_admin')); \Session::put('user.last_login_date', array_get($user, 'last_login_date')); \Session::put('user.ldap_username', array_get($user, 'ldap_username')); return true; } return false; }
Sets basic info of the user in session when authenticated. @param array $user @return bool
entailment
public static function getPublicInfo() { if (empty(session('user'))) { throw new UnauthorizedException('There is no valid session for the current request.'); } $sessionData = [ 'session_token' => session('session_token'), 'session_id' => session('session_token'), // temp for compatibility with 1.x 'id' => session('user.id'), 'name' => session('user.display_name'), 'first_name' => session('user.first_name'), 'last_name' => session('user.last_name'), 'email' => session('user.email'), 'is_sys_admin' => session('user.is_sys_admin'), 'last_login_date' => session('user.last_login_date'), 'host' => gethostname() ]; $role = static::get('role'); if (!session('user.is_sys_admin') && !empty($role)) { $sessionData['role'] = array_get($role, 'name'); $sessionData['role_id'] = array_get($role, 'id'); } return $sessionData; }
Fetches user session data based on the authenticated user. @return array @throws UnauthorizedException
entailment
public static function removeEmptyStrings($array) { foreach ($array as $key => $value) { if (is_array($value)) { $array[$key] = self::removeEmptyStrings($value); if (empty($array[$key])) { unset($array[$key]); } } elseif ($value === '') { unset($array[$key]); } } return $array; }
Recursively removes all the keys containing an empty string as value. Also removes empty arrays in the process. @param $array The array to filter @return the filtered array
entailment
public static function verify($url, $caDir) { static $hostsByDir = []; if (!isset($hostsByDir[$caDir])) { $hostsByDir[$caDir] = []; } $extensions = ['crt', 'pem', 'cer', 'der']; // Must be https if (substr($url, 0, 5) != 'https') { return false; } // Default $defaultCA = $caDir . 'curl-ca-bundle.crt'; // Look for a host specific CA file $host = strtolower(parse_url($url, PHP_URL_HOST)); if (!$host) { return $defaultCA; } if (array_key_exists($host, $hostsByDir[$caDir])) { return $hostsByDir[$caDir][$host]; } $filename = $host; do { // Look for the possible extensions foreach ($extensions as $ext) { if (file_exists($verify = $caDir . $filename . '.' . $ext)) { $hostsByDir[$caDir][$host] = $verify; return $verify; } } // Remove a subdomain each time $filename = substr($filename, strpos($filename, '.') + 1); } while (substr_count($filename, '.') > 0); // No specific match $hostsByDir[$caDir][$host] = $defaultCA; return $defaultCA; }
Looks for a Certificate Authority file in the CA folder that matches the host and return the values for the verify option to its full path. If no specific file regarding a host is found, uses curl-ca-bundle.crt by default.
entailment
public static function getRoleIdByAppIdAndUserId($app_id, $user_id) { $cacheKey = static::makeRoleIdCacheKey($app_id, $user_id); $result = \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'), function () use ($app_id, $user_id) { try { return static::whereAppId($app_id)->whereUserId($user_id)->value('role_id'); } catch (ModelNotFoundException $ex) { return null; } }); return $result; }
Use this primarily in middle-ware or where no session is established yet. Once session is established, the role id is accessible via Session. @param int $app_id @param int $user_id @return null|int The role id or null for admin
entailment
public function isConfirmationExpired() { $ttl = \Config::get('df.confirm_code_ttl', 1440); $lastModTime = strtotime($this->last_modified_date); $code = $this->confirm_code; if ('y' !== $code && !is_null($code) && ((time() - $lastModTime) > ($ttl * 60))) { return true; } else { return false; } }
Checks to se if confirmation period is expired. @return bool
entailment
public static function applyDefaultUserAppRole($user, $defaultRole) { $apps = App::all(); if (count($apps) === 0) { return false; } foreach ($apps as $app) { if (!UserAppRole::whereUserId($user->id)->whereAppId($app->id)->exists()) { $userAppRoleData = [ 'user_id' => $user->id, 'app_id' => $app->id, 'role_id' => $defaultRole ]; UserAppRole::create($userAppRoleData); } } return true; }
Assigns a role to a user for all apps in the system. @param $user @param $defaultRole @return bool @throws \Exception
entailment
public static function applyAppRoleMapByService($user, $serviceId) { $maps = AppRoleMap::whereServiceId($serviceId)->get(); foreach ($maps as $map) { UserAppRole::whereUserId($user->id)->whereAppId($map->app_id)->delete(); $userAppRoleData = [ 'user_id' => $user->id, 'app_id' => $map->app_id, 'role_id' => $map->role_id ]; UserAppRole::create($userAppRoleData); } }
Applies App to Role mapping to a user. @param User $user @param integer $serviceId
entailment
public function validate($data, $throwException = true) { $loginAttribute = strtolower(config('df.login_attribute', 'email')); if ($loginAttribute === 'username') { $this->rules['username'] = str_replace('|nullable', '|required', $this->rules['username']); } return parent::validate($data, $throwException); }
{@inheritdoc}
entailment
public static function validatePassword($password) { $data = [ 'password' => $password ]; $rule = [ 'password' => 'min:6' ]; $validator = Validator::make($data, $rule); if ($validator->fails()) { $msg = $validator->errors()->getMessages(); $errorString = DataFormatter::validationErrorsToString($msg); throw new BadRequestException('Invalid data supplied.' . $errorString, null, null, $msg); } }
@param $password @throws \DreamFactory\Core\Exceptions\BadRequestException
entailment
protected static function createInternal($record, $params = []) { try { if (!isset($record['name'])) { // potentially combine first and last $first = (isset($record['first_name']) ? $record['first_name'] : null); $last = (isset($record['last_name']) ? $record['last_name'] : null); $name = (!empty($first)) ? $first : ''; $name .= (!empty($name) && !empty($last)) ? ' ' : ''; $name .= (!empty($last)) ? $last : ''; if (empty($name)) { // use the first part of their email or the username $email = (isset($record['email']) ? $record['email'] : null); $name = (!empty($email) && strpos($email, '@')) ? strstr($email, '@', true) : ''; } $record['name'] = $name; } $password = array_get($record, 'password'); if (!empty($password)) { static::validatePassword($password); } $model = static::create($record); if (array_get_bool($params, 'admin') && array_get_bool($record, 'is_sys_admin')) { $model->is_sys_admin = 1; } $model->password = $password; $model->save(); } catch (\Exception $ex) { if (!$ex instanceof ForbiddenException && !$ex instanceof BadRequestException) { throw new InternalServerErrorException('Failed to create resource: ' . $ex->getMessage()); } else { throw $ex; } } return static::buildResult($model, $params); }
{@inheritdoc}
entailment
public static function updateInternal($id, $record, $params = []) { if (empty($record)) { throw new BadRequestException('There are no fields in the record to create . '); } if (empty($id)) { //Todo:perform logging below //Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) ); throw new BadRequestException('Identifying field "id" can not be empty for update request . '); } /** @type User $model */ $model = static::find($id); if (!$model instanceof Model) { throw new NotFoundException("Record with identifier '$id' not found."); } $pk = $model->primaryKey; // Remove the PK from the record since this is an update unset($record[$pk]); try { if ($model->is_sys_admin && !array_get_bool($params, 'admin')) { throw new ForbiddenException('Not allowed to change an admin user.'); } elseif (array_get_bool($params, 'admin') && !$model->is_sys_admin) { throw new BadRequestException('Cannot update a non-admin user.'); } $password = array_get($record, 'password'); if (!empty($password)) { $model->password = $password; static::validatePassword($password); } $model->update($record); return static::buildResult($model, $params); } catch (\Exception $ex) { if (!$ex instanceof ForbiddenException && !$ex instanceof BadRequestException) { throw new InternalServerErrorException('Failed to update resource: ' . $ex->getMessage()); } else { throw $ex; } } }
{@inheritdoc}
entailment
public function update(array $attributes = [], array $options = []) { $oldEmail = $this->email; $updated = parent::update($attributes); if ($updated && $this->is_sys_admin) { $newEmail = $this->email; if (('[email protected]' === $oldEmail) && ('[email protected]' !== $newEmail)) { // Register user RegisterContact::registerUser($this); } } return $updated; }
{@inheritdoc}
entailment
public static function deleteInternal($id, $record, $params = []) { if (empty($record)) { throw new BadRequestException('There are no fields in the record to create . '); } if (empty($id)) { //Todo:perform logging below //Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) ); throw new BadRequestException('Identifying field "id" can not be empty for update request . '); } /** @type User $model */ $model = static::find($id); if (!$model instanceof Model) { throw new NotFoundException("Record with identifier '$id' not found."); } try { if ($model->is_sys_admin && !array_get_bool($params, 'admin')) { throw new ForbiddenException('Not allowed to delete an admin user.'); } elseif (array_get_bool($params, 'admin') && !$model->is_sys_admin) { throw new BadRequestException('Cannot delete a non-admin user.'); } elseif (Session::getCurrentUserId() === $model->id) { throw new ForbiddenException('Cannot delete your account.'); } $result = static::buildResult($model, $params); if ('sqlsrv' === $model->getConnection()->getDriverName()) { // cleanup references not happening automatically due to schema setup $references = $model->getReferences(); /** @type RelationSchema $reference */ foreach ($references as $reference) { if ((RelationSchema::HAS_ONE === $reference->type) && (('created_by_id' === $reference->refField[0]) || ('last_modified_by_id' === $reference->refField[0])) ) { $stmt = 'update [' . $reference->refTable . '] set [' . $reference->refField[0] . '] = null where [' . $reference->refField[0] . '] = ' . $id; if (0 !== $rows = \DB::update($stmt)) { \Log::debug('found rows: ' . $rows); } } elseif ((RelationSchema::HAS_MANY === $reference->type) && (('created_by_id' === $reference->refField[0]) || ('last_modified_by_id' === $reference->refField[0])) ) { $stmt = 'update [' . $reference->refTable . '] set [' . $reference->refField[0] . '] = null where [' . $reference->refField[0] . '] = ' . $id; if (0 !== $rows = \DB::update($stmt)) { \Log::debug('found rows: ' . $rows); } } elseif ((RelationSchema::BELONGS_TO === $reference->type) && (('created_by_id' === $reference->field[0]) || ('last_modified_by_id' === $reference->field[0])) ) { $stmt = 'update [' . $reference->refTable . '] set [' . $reference->field[0] . '] = null where [' . $reference->field[0] . '] = ' . $id . ' and [' . $reference->refField[0] . '] != ' . $id; if (0 !== $rows = \DB::update($stmt)) { \Log::debug('found rows: ' . $rows); } } } } $model->delete(); return $result; } catch (\Exception $ex) { if (!$ex instanceof ForbiddenException && !$ex instanceof BadRequestException) { throw new InternalServerErrorException('Failed to delete resource: ' . $ex->getMessage()); } else { throw $ex; } } }
{@inheritdoc}
entailment
public function setPasswordAttribute($password) { if (!empty($password)) { $password = bcrypt($password); JWTUtilities::invalidateTokenByUserId($this->id); // When password is set user account must be confirmed. Confirming user // account here with confirm_code = null. // confirm_code = 'y' indicates cases where account is confirmed by user // using confirmation email. if (isset($this->attributes['confirm_code']) && $this->attributes['confirm_code'] !== 'y') { $this->attributes['confirm_code'] = null; } } $this->attributes['password'] = $password; }
Encrypts password. @param $password
entailment
public static function getCachedInfo($id, $key = null, $default = null) { $cacheKey = 'user:' . $id; $result = \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'), function () use ($id){ $user = static::whereId($id)->first(); if (empty($user)) { throw new NotFoundException("User not found."); } if (!$user->is_active) { throw new ForbiddenException("User is not active."); } $userInfo = $user->toArray(); $userInfo['is_sys_admin'] = $user->is_sys_admin; return $userInfo; }); if (is_null($result)) { return $default; } if (is_null($key)) { return $result; } return (isset($result[$key]) ? $result[$key] : $default); }
Returns user info cached, or reads from db if not present. Pass in a key to return a portion/index of the cached data. @param int $id @param null|string $key @param null $default @return mixed|null
entailment
public static function createFirstAdmin(array &$data) { if (empty($data['username'])) { $data['username'] = $data['email']; } $validationRules = [ 'name' => 'required|max:255', 'first_name' => 'required|max:255', 'last_name' => 'required|max:255', 'email' => 'required|email|max:255|unique:user', 'password' => 'required|confirmed|min:6', 'username' => 'min:6|unique:user,username|regex:/^\S*$/u|required' ]; $validator = Validator::make($data, $validationRules); if ($validator->fails()) { $errors = $validator->getMessageBag()->all(); $data = array_merge($data, ['errors' => $errors, 'version' => \Config::get('app.version')]); return false; } else { /** @type User $user */ $attributes = array_only($data, ['name', 'first_name', 'last_name', 'email', 'username']); $attributes['is_active'] = 1; $user = static::create($attributes); $user->password = array_get($data, 'password'); $user->is_sys_admin = 1; $user->save(); // Register user RegisterContact::registerUser($user); // Reset admin_exists flag in cache. \Cache::forever('admin_exists', true); return $user; } }
Creates first admin user. @param array $data @return User|boolean
entailment
public static function getConfig($id, $local_config = null, $protect = true) { $config = parent::getConfig($id, $local_config, $protect); $appRoleMaps = AppRoleMap::whereServiceId($id)->get(); $maps = []; /** @var AppRoleMap $map */ foreach ($appRoleMaps as $map) { $map->protectedView = $protect; $maps[] = $map->toArray(); } $config['app_role_map'] = $maps; return $config; }
{@inheritdoc}
entailment
public static function setConfig($id, $config, $local_config = null) { if (isset($config['app_role_map'])) { $maps = $config['app_role_map']; if (!is_array($maps)) { throw new BadRequestException('App to Role map must be an array.'); } AppRoleMap::whereServiceId($id)->delete(); if (!empty($maps)) { foreach ($maps as $map) { AppRoleMap::setConfig($id, $map, $local_config); } } } return parent::setConfig($id, $config, $local_config); }
{@inheritdoc}
entailment
public static function storeConfig($id, $config) { if (isset($config['app_role_map'])) { $maps = $config['app_role_map']; if (!is_array($maps)) { throw new BadRequestException('App to Role map must be an array.'); } AppRoleMap::whereServiceId($id)->delete(); if (!empty($maps)) { foreach ($maps as $map) { AppRoleMap::storeConfig($id, $map); } } } parent::storeConfig($id, $config); }
{@inheritdoc}
entailment
public static function getConfigSchema() { $schema = parent::getConfigSchema(); $schema[] = [ 'name' => 'app_role_map', 'label' => 'Role per App', 'description' => 'Select a desired Role per App for users logging in via this service.', 'type' => 'array', 'required' => false, 'allow_null' => true, 'items' => AppRoleMap::getConfigSchema(), ]; return $schema; }
{@inheritdoc}
entailment
public function handle() { $this->info('**********************************************************************************************************************'); $this->info('* Configuring DreamFactory... '); $this->info('**********************************************************************************************************************'); if (!file_exists('.env')) { copy('.env-dist', '.env'); $this->info('Created .env file with default configuration.'); } if (!file_exists('phpunit.xml')) { copy('phpunit.xml-dist', 'phpunit.xml'); $this->info('Created phpunit.xml with default configuration.'); } if ($this->doInteractive()) { $db = $this->choice('Which database would you like to use for system tables?', ['sqlite', 'mysql', 'pgsql', 'sqlsrv'], 0); if ('sqlite' === $db) { $database = $this->ask('Enter your database name'); $config = [ 'DB_CONNECTION' => $db, 'DB_DATABASE' => $database, 'DF_INSTALL' => $this->option('df_install') ]; } else { $driver = $db; $host = $this->ask('Enter your ' . $db . ' Host'); $port = $this->ask('Enter your Database Port', config('database.connections.' . $db . '.port')); $database = $this->ask('Enter your database name'); $username = $this->ask('Enter your database username'); $password = ''; $passwordMatch = false; while (!$passwordMatch) { $password = $this->secret('Enter your database password'); $password2 = $this->secret('Re-enter your database password'); if ($password === $password2) { $passwordMatch = true; } else { $this->error('Passwords did not match. Please try again.'); } } $config = [ 'DB_CONNECTION' => $driver, 'DB_HOST' => $host, 'DB_DATABASE' => $database, 'DB_USERNAME' => $username, 'DB_PASSWORD' => $password, 'DB_PORT' => $port, 'DF_INSTALL' => $this->option('df_install') ]; } } else { $driver = $this->option('db_connection'); if (!in_array($driver, ['sqlite', 'mysql', 'pgsql', 'sqlsrv'])) { $this->warn('DB DRIVER ' . $driver . ' is not supported. Using default driver sqlite.'); $driver = 'sqlite'; } $config = []; if ('sqlite' === $driver) { static::setIfValid($config, 'DB_CONNECTION', $this->option('db_connection')); static::setIfValid($config, 'DB_DATABASE', $this->option('db_database')); } else { static::setIfValid($config, 'DF_INSTALL', $this->option('df_install')); static::setIfValid($config, 'DB_HOST', $this->option('db_host')); static::setIfValid($config, 'DB_CONNECTION', $this->option('db_connection')); static::setIfValid($config, 'DB_DATABASE', $this->option('db_database')); static::setIfValid($config, 'DB_USERNAME', $this->option('db_username')); static::setIfValid($config, 'DB_PASSWORD', $this->option('db_password')); static::setIfValid($config, 'DB_PORT', $this->option('db_port')); } } $cacheDriver = $this->option('cache_driver'); if (!in_array($cacheDriver, ['file', 'redis', 'memcached'])) { $this->warn('CACHE DRIVER ' . $cacheDriver . ' is not supported. Using default driver file.'); $cacheDriver = 'file'; } static::setIfValid($config, 'CACHE_DRIVER', $cacheDriver); if ('redis' === strtolower($cacheDriver)) { static::setIfValid($config, 'REDIS_HOST', $this->option('redis_host')); static::setIfValid($config, 'REDIS_PORT', $this->option('redis_port')); static::setIfValid($config, 'REDIS_DATABASE', $this->option('redis_database')); static::setIfValid($config, 'REDIS_PASSWORD', $this->option('redis_password')); } elseif ('memcached' === strtolower($cacheDriver)) { static::setIfValid($config, 'MEMCACHED_HOST', $this->option('memcached_host')); static::setIfValid($config, 'MEMCACHED_PORT', $this->option('memcached_port')); static::setIfValid($config, 'MEMCACHED_WEIGHT', $this->option('memcached_weight')); } FileUtilities::updateEnvSetting($config); $this->info('Configuration complete!'); $this->warn('*************************************************** WARNING! *********************************************************'); $this->warn('*'); $this->warn('* Please take a moment to review the .env file. You can make any changes as necessary there. '); $this->warn('*'); $this->warn('* Please run "php artisan df:setup" to complete the setup process.'); $this->warn('*'); $this->warn('**********************************************************************************************************************'); }
Execute the console command.
entailment
protected function doInteractive() { $interactive = true; $options = $this->option(); foreach ($options as $key => $value) { if (substr($key, 0, 3) === 'db_' && !empty($value)) { $interactive = false; } } return $interactive; }
Used to determine interactive mode on/off @return bool
entailment
public function handle($request, Closure $next) { $request->enableHttpMethodParameterOverride(); // enables _method URL parameter $method = $request->getMethod(); if (('POST' === $method) && (!empty($dfOverride = $request->header('X-HTTP-Method', $request->header('X-Method-Override', $request->query('method'))))) ) { $request->setMethod($method = strtoupper($dfOverride)); } // support old MERGE as PATCH if ('MERGE' === strtoupper($method)) { $request->setMethod('PATCH'); } return $next($request); }
Check for verb tunneling by the various method override headers or query params Tunnelling verb overrides: X-Http-Method (Microsoft) X-Http-Method-Override (Google/GData) X-Method-Override (IBM) Symfony natively supports X-HTTP-METHOD-OVERRIDE header and "_method" URL parameter we just need to add our historical support for other options, including "method" URL parameter @param Request $request @param Closure $next @return array|mixed|string
entailment
public function up() { if (Schema::hasTable('email_template') && !Schema::hasColumn('email_template', 'attachment')) { Schema::table('email_template', function (Blueprint $t){ $t->text('attachment')->nullable()->after('subject'); }); } }
Run the migrations. @return void
entailment
public function down() { if (Schema::hasTable('email_template') && Schema::hasColumn('email_template', 'attachment')) { Schema::table('email_template', function (Blueprint $t){ $t->dropColumn('attachment'); }); } }
Reverse the migrations. @return void
entailment
protected static function createRecordId($table) { $randomTime = abs(time()); if ($randomTime == 0) { $randomTime = 1; } $random1 = rand(1, $randomTime); $random2 = rand(1, 2000000000); $generateId = strtolower(md5($random1 . $table . $randomTime . $random2)); $randSmall = rand(10, 99); return $generateId . $randSmall; }
General method for creating a pseudo-random identifier @param string $table Name of the table where the item will be stored @return string
entailment
public static function removeFromCache($key) { $fullKey = static::makeCacheKey($key); if (!Cache::forget($fullKey)) { return false; } static::removeKeys($key); return true; }
@param string $key @return boolean
entailment
public static function getConfig($id, $local_config = null, $protect = true) { $model = new static((array)$local_config); $model->protectedView = $protect; return $model->toArray(); }
{@inheritdoc}
entailment
public static function setConfig($id, $config, $local_config = null) { $model = new static((array)$local_config); $model->fill($config); if ($model->validate($model->attributes)) { $config = $model->attributes; } return $config; }
{@inheritdoc}
entailment
private static function fromInt(int $ip): \GMP { $ip = gmp_init(sprintf('%u', $ip), 10); if (!self::isValid($ip)) { throw new \InvalidArgumentException(sprintf('The integer "%s" is not a valid IPv%d address.', gmp_strval($ip), static::IP_VERSION)); } return $ip; }
@param $ip @return \GMP
entailment
private static function fromFloat(float $ip): \GMP { $ip = gmp_init(sprintf('%s', $ip), 10); if (!self::isValid($ip)) { throw new \InvalidArgumentException(sprintf('The double "%s" is not a valid IPv%d address.', gmp_strval($ip), static::IP_VERSION)); } return $ip; }
@param float $ip @return \GMP
entailment
private static function fromString(string $ip): \GMP { // binary, packed string if (@inet_ntop($ip) !== false) { if (static::NB_BYTES != strlen($ip)) { throw new \InvalidArgumentException(sprintf('The binary string "%s" is not a valid IPv%d address.', $ip, static::IP_VERSION)); } $hex = unpack('H*', $ip); return gmp_init($hex[1], 16); } // valid IP string $filterFlag = constant('FILTER_FLAG_IPV'.static::IP_VERSION); if (filter_var($ip, FILTER_VALIDATE_IP, $filterFlag)) { $ip = inet_pton($ip); $hex = unpack('H*', $ip); return gmp_init($hex[1], 16); } // numeric string (decimal) if (ctype_digit($ip)) { $ip = gmp_init($ip, 10); if (!self::isValid($ip)) { throw new \InvalidArgumentException(sprintf('"%s" is not a valid decimal IPv%d address.', gmp_strval($ip), static::IP_VERSION)); } return $ip; } throw new \InvalidArgumentException(sprintf('The string "%s" is not a valid IPv%d address.', $ip, static::IP_VERSION)); }
@param string $ip @return \GMP
entailment
private static function fromGMP(\GMP $ip): \GMP { if (!static::isValid($ip)) { throw new \InvalidArgumentException(sprintf('"%s" is not a valid decimal IPv%d address.', gmp_strval($ip), static::IP_VERSION)); } return $ip; }
@param \GMP $ip @return \GMP
entailment
public static function create($ip): IP { try { return new IPv4($ip); } catch (\InvalidArgumentException $e) { // do nothing } try { return new IPv6($ip); } catch (\InvalidArgumentException $e) { // do nothing } throw new \InvalidArgumentException("$ip does not appear to be an IPv4 or IPv6 address"); }
Take an IP string/int and return an object of the correct type. Either IPv4 or IPv6 may be supplied, but integers less than 2^32 will be considered to be IPv4 by default. @param mixed $ip Anything that can be converted into an IP (string, int, bin, etc.) @return IPv4|IPv6
entailment
public function numeric(int $base = 10): string { if ($base < 2 || $base > 36) { throw new \InvalidArgumentException('Base must be between 2 and 36 (included)'); } $value = gmp_strval($this->ip, $base); // fix for newer versions of GMP (> 5.0) in PHP 5.4+ that removes // the leading 0 in base 2 if ($base == 2) { $value = str_pad($value, static::NB_BITS, '0', STR_PAD_LEFT); } return $value; }
Return numeric representation of the IP in base $base. The return value is a PHP string. It can base used for comparison. @param $base int from 2 to 36 @return string
entailment
public function binary(): string { $hex = str_pad($this->numeric(16), static::NB_BITS / 4, '0', STR_PAD_LEFT); return pack('H*', $hex); }
Return binary string representation. @return string Binary string
entailment
public function bit_and($value): IP { if (!$value instanceof self) { $value = new static($value); } return new static(gmp_and($this->ip, $value->ip)); }
Bitwise AND. @param $value mixed anything that can be converted into an IP object @return IP
entailment
public function bit_or($value): IP { if (!$value instanceof self) { $value = new static($value); } return new static(gmp_or($this->ip, $value->ip)); }
Bitwise OR. @param $value mixed anything that can be converted into an IP object @return IP
entailment
public function plus($value): IP { if ($value < 0) { return $this->minus(-1 * $value); } if ($value == 0) { return clone $this; } if (!$value instanceof self) { $value = new static($value); } $result = gmp_add($this->ip, $value->ip); if (!self::isValid($result)) { throw new \OutOfBoundsException(sprintf( 'The sum of "%s" and "%s" is not a valid IPv%d address.', $this->humanReadable(), $value->humanReadable(), static::IP_VERSION )); } return new static($result); }
Plus (+). @throws \OutOfBoundsException @param $value mixed anything that can be converted into an IP object @return IP
entailment
public function isIn($block): bool { if (!$block instanceof IPBlock) { $block = IPBlock::create($block); } return $block->contains($this); }
Check if the IP is contained in given block. @param $block mixed Anything that can be converted into an IPBlock @return bool
entailment
public function isPrivate(): bool { if ($this->is_private !== null) { return $this->is_private; } $this->is_private = false; foreach (static::$private_ranges as $range) { if ($this->isIn($range)) { $this->is_private = true; break; } } return $this->is_private; }
Return true if the address is reserved per IANA IPv4/6 Special Registry. @return bool
entailment
public function isLinkLocal(): bool { if ($this->is_link_local === null) { $this->is_link_local = $this->isIn(static::$link_local_block); } return $this->is_link_local; }
Determine if the address is a Link-Local address. @return bool
entailment
public function isLoopback(): bool { if ($this->is_loopback === null) { $this->is_loopback = $this->isIn(static::$loopback_range); } return $this->is_loopback; }
Return true if the address is within the loopback range. @return bool
entailment
public function connect(array $config) { $options = $this->getOptions($config); // SQLite supports "in-memory" databases that only last as long as the owning // connection does. These are useful for tests or for short lifetime store // querying. In-memory databases may only have a single open connection. if ($config['database'] == ':memory:') { return $this->createConnection('sqlite::memory:', $config, $options); } // PDO driver will automatically create the file if permissions are granted. $file = $config['database']; if (false === strpos($file, DIRECTORY_SEPARATOR)) { // no directories involved, store it where we want to store it if (!empty($storage = config('df.db.sqlite_storage'))) { $file = rtrim($storage, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file; } } if (false === $path = realpath($file)) { $storage = dirname($file); if (false === $path = realpath($storage)) { // Attempt @mkdir($storage); } if (false === $path = realpath($storage)) { logger('Failed to access storage path ' . $storage); throw new \InvalidArgumentException('Failed to create storage location for SQLite database.'); } $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . basename($file); } return $this->createConnection("sqlite:{$path}", $config, $options); }
Establish a database connection. @param array $config @return \PDO
entailment
public static function makeJWTByUser($userId, $email, $forever = false) { if (\Config::get('df.allow_forever_sessions') === false) { $forever = false; } $customClaims = ['user_id' => $userId, 'forever' => $forever]; $customClaimFields = config('jwt.custom_claims'); if (!empty($customClaimFields)) { /** @var User $user */ $user = User::find($userId); if (!empty($user)) { $user = $user->toArray(); foreach ($customClaimFields as $ccf) { $value = array_get($user, $ccf); if (!empty($value)) { $customClaims[$ccf] = $value; } } } } /** @type Payload $payload */ /** @noinspection PhpUndefinedMethodInspection */ $payload = JWTFactory::sub(md5($email))->customClaims($customClaims)->make(); /** @type Token $token */ $token = JWTAuth::manager()->encode($payload); $tokenValue = $token->get(); static::setTokenMap($payload, $tokenValue); return $tokenValue; }
@param $userId @param $email @param bool $forever @return string
entailment
public static function verifyUser($payload) { $userId = $payload->get('user_id'); $userKey = $payload->get('sub'); $userInfo = ($userId) ? User::getCachedInfo($userId) : null; if (!empty($userInfo) && $userKey === md5($userInfo['email'])) { return true; } else { throw new TokenInvalidException('User verification failed.'); } }
Verifies JWT user. @param Payload $payload @return bool @throws TokenInvalidException
entailment
public static function refreshToken() { $token = Session::getSessionToken(); //----------------------------------------------------------------- // This will avoid TokenExpiredException error as long as we are // still in the refresh TTL window. Will still allow throwing // TokenExpiredException after refresh TTL has passed. // // NOTE: No tokens (including forever tokens) can ever be // refreshed after refresh TTL has passed. JWTAuth::manager()->setRefreshFlow(); //----------------------------------------------------------------- try { JWTAuth::setToken($token); // Checks for token validity - Expired TTL, Expired Refresh TTL, Blacklisted. JWTAuth::checkOrFail(); // Retrieve the 'forever' flag (remember_me flag set to true during login.) $payloadArray = JWTAuth::manager()->getJWTProvider()->decode($token); $forever = boolval(array_get($payloadArray, 'forever')); // Retrieve the user associated with the token $userId = array_get($payloadArray, 'user_id'); /** @var User $user */ $user = User::find($userId); // If token is marked forever then re-issue a new token (not refresh) // in order to bump up the refresh TTL for the new token. if ($forever) { // Clear any existing claims. We will be re-issuing a new token with new claims // based on the same user of the original token. JWTFactory::claims([]); // Re-issue new token. Session::setUserInfoWithJWT($user, $forever); } else { $newToken = JWTAuth::refresh(true); JWTAuth::setToken($newToken); $payload = JWTAuth::getPayload(); // Add new token to our token mapping static::setTokenMap($payload, $newToken); Session::setSessionToken($newToken); $userInfo = $user->toArray(); $userInfo['is_sys_admin'] = $user->is_sys_admin; Session::setUserInfo($userInfo); } // Invalidate and remove from our token mapping static::invalidate($token); } catch (JWTException $e) { throw new UnauthorizedException('Token refresh failed. ' . $e->getMessage()); } return Session::getSessionToken(); }
Refreshes a JWT token. Re-issues new JWT token if the original token is marked as 'forever' NOTE: No tokens (including forever tokens) can ever be refreshed after refresh TTL has passed. @return string @throws \DreamFactory\Core\Exceptions\UnauthorizedException
entailment
protected static function removeTokenMap($userId, $exp) { return DB::table('token_map')->where('user_id', $userId)->where('exp', $exp)->delete(); }
@param $userId @param $exp @return int
entailment
protected static function setTokenMap($payload, $token) { $map = [ 'user_id' => $payload->get('user_id'), 'iat' => $payload->get('iat'), 'exp' => $payload->get('exp'), 'token' => $token ]; return DB::table('token_map')->insert($map); }
@param Payload $payload @param string $token @return bool
entailment
public function checkPermission($operation, $resource = null) { $path = $this->getFullPathName(); if (!empty($resource)) { $path = (!empty($path)) ? $path . '/' . $resource : $resource; } $requestType = ($this->request) ? $this->request->getRequestorType() : ServiceRequestorTypes::API; Session::checkServicePermission($operation, $this->getServiceName(), $path, $requestType); return true; }
@param string $operation @param string $resource @return bool @throws \DreamFactory\Core\Exceptions\ForbiddenException
entailment
public function getPermissions($resource = null) { $path = $this->getFullPathName(); if (!empty($resource)) { $path = (!empty($path)) ? $path . '/' . $resource : $resource; } $requestType = ($this->request) ? $this->request->getRequestorType() : ServiceRequestorTypes::API; return Session::getServicePermissions($this->getServiceName(), $path, $requestType); }
@param string $resource @return int
entailment
public function configure(TcTable $table) { $this->table = $table; $table ->on(TcTable::EV_BODY_ADD, [$this, 'initialize']) ->on(TcTable::EV_ROW_ADD, [$this, 'checkAvailableHeight']) ->on(TcTable::EV_ROW_ADDED, [$this, 'checkFooter']) ->on(TcTable::EV_ROW_SKIPPED, [$this, 'onRowSkipped']) ->on(TcTable::EV_ROW_HEIGHT_GET, [$this, 'onRowHeightGet']) ->on(TcTable::EV_BODY_ADDED, [$this, 'purge']); }
{@inheritDocs}
entailment
public function unconfigure(TcTable $table) { $this->table = $table; $table ->un(TcTable::EV_BODY_ADD, [$this, 'initialize']) ->un(TcTable::EV_ROW_ADD, [$this, 'checkAvailableHeight']) ->un(TcTable::EV_ROW_ADDED, [$this, 'checkFooter']) ->un(TcTable::EV_ROW_SKIPPED, [$this, 'onRowSkipped']) ->un(TcTable::EV_ROW_HEIGHT_GET, [$this, 'onRowHeightGet']) ->un(TcTable::EV_BODY_ADDED, [$this, 'purge']); }
Unconfigure the plugin @param TcTable $table @return void
entailment
public function initialize(TcTable $table, $rows, callable $fn = null) { $this->_widowsCalculatedHeight = []; $this->height = $this->getCalculatedWidowsHeight($table, $rows, $fn); $this->count = count($rows); $this->rows = $rows; $this->resetPageBreakTrigger(); }
Called before body is added. Configure everything about widows @param TcTable $table @param array|Traversable $rows @param callable $fn @return void
entailment
public function onRowHeightGet(TcTable $table, $row = null, $rowIndex = null) { // if current row index is one of the already-calculated widows height, // we take this value, instead of calculating it a second time. if ($rowIndex !== null && isset($this->_widowsCalculatedHeight[$rowIndex])) { return $this->_widowsCalculatedHeight[$rowIndex]; } }
Called when TcTable copy default column definition inside the current row definition. We set an action here, so we can use the widow's cache height, instead of calculating it a second time @param TcTable $table @param array|object $row @param int $rowIndex @return float
entailment
public function checkFooter(TcTable $table, $row, $rowIndex) { $pdf = $table->getPdf(); if ($rowIndex == $this->count - 1 && $pdf->GetY() + $this->height >= $this->pageBreakTrigger) { if ($table->trigger(TcTable::EV_PAGE_ADD, [$this->rows, $rowIndex, true]) !== false) { $pdf->AddPage(); $table->trigger(TcTable::EV_PAGE_ADDED, [$this->rows, $rowIndex, true]); } } }
Check if there's space for the footer, after the last row is added @param TcTable $table @param array|object $row @param int $rowIndex @return void
entailment
private function getCalculatedWidowsHeight(TcTable $table, $rows, callable $fn = null) { $count = count($rows); $limit = $count - $this->minWidowsOnPage; $h = 0; if ($this->minWidowsOnPage && $count && $limit >= 0) { for ($i = $count - 1; $i >= $limit; $i--) { // the userfunc has returned false everytime, so in the end, the // data array is empty. Return current height. if (!isset($rows[$i])) { return $h; } $data = $fn ? $fn($table, $rows[$i], $i, true) : $rows[$i]; // check row only if it's an array. It gives the possibility to // skip some rows with the user func if (is_array($data) || is_object($data)) { $this->_widowsCalculatedHeight[$i] = $table->getCurrentRowHeight($data); $h += $this->_widowsCalculatedHeight[$i]; } else { // adapt limit so the widow management behave the best it // can $limit--; } } } return $h; }
Get real height that widows will take. Used to force a page break if the remaining height isn't enough to draw all the widows on the current page. @param TcTable $table @param array|Traversable $rows the complete set of data @param callable $fn addBody function for data layout @return float
entailment
public function getFromCache($key, $default = null) { $fullKey = $this->makeCacheKey($key); return Cache::get($fullKey, $default); }
@param string $key @param mixed $default @return mixed The value of cache associated with the given type, id and key
entailment
public function flush() { $keys = $this->getCacheKeys(); foreach ($keys as $key) { Cache::forget($this->makeCacheKey($key)); } $this->removeKeys($keys); }
Forget all keys that we know
entailment