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 i...
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 ($err...
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('-----...
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']); ...
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');...
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]>)?)?</...
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'] = [];...
@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_B...
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 - $...
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)...
@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->getNbAd...
@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(), ...
@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_bloc...
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($...
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_...
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'))) { ...
@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; ...
{@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 //fi...
{@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->se...
{@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, ...
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::hasColum...
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(...
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, $co...
@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 @throw...
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::PA...
@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; } ...
@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': ...
@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($serv...
@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); ...
@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 ...
@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 (!empt...
@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 = arra...
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_n...
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('s...
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]); }...
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')...
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 { ret...
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; ...
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()) { $userApp...
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' => $u...
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 paren...
{@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()->getM...
@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']...
{@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 ...
{@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 (('user@example.com' === $oldEmail) && ('user@example.com' !== ...
{@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 ...
{@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_cod...
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)) { t...
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' => 'require...
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) { ...
{@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.'); } AppRoleM...
{@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($...
{@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.', 'ty...
{@inheritdoc}
entailment
public function handle() { $this->info('**********************************************************************************************************************'); $this->info('* Configuring DreamFactory... '); $this->info('**********************************************************************...
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(...
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 suppor...
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 . $rand...
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_VERS...
@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 } ...
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 ...
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, ...
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; bre...
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 s...
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'); ...
@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 { ...
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 // T...
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() : ServiceReque...
@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::AP...
@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_...
{@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_RO...
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])) { ...
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-...
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--) { ...
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