sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function createLogString(RepositoryInterface $repository, $limit, $skip) { return implode( str_repeat(PHP_EOL, 3), array_map( function(array $log) { return sprintf('r%d | %s | %s:'.PHP_EOL.'%s', $log[0], $log[2], $log[1], $log[3]); ...
Creates the log string to be fed into the string buffer @param RepositoryInterface $repository The repository @param integer|null $limit The maximum number of log entries returned @param integer|null $skip Number of log entries that are skipped from the beginning @return str...
entailment
public function setCommitMsg($commitMsg) { if ($commitMsg === null) { $this->commitMsg = null; } else { $this->commitMsg = (string)$commitMsg; } return $this; }
Sets the commit message that will be used when committing the transaction @param string|null $commitMsg The commit message @return Transaction
entailment
public function setAuthor($author) { if ($author === null) { $this->author = null; } else { $this->author = (string)$author; } return $this; }
Sets the author that will be used when committing the transaction @param string|null $author The author @return Transaction
entailment
public function hasCommandHandler($command) { $class = get_class($command); if (isset($this->handlers[$class])) { return true; } $callback = $this->mapper; if (!$callback || method_exists($command, 'handle')) { return false; } $this...
Determine if the given command has a handler. @param mixed $command @return bool
entailment
public static function simpleMapping($command, string $commandNamespace, string $handlerNamespace) { $command = str_replace($commandNamespace, '', get_class($command)); return $handlerNamespace.'\\'.trim($command, '\\').'Handler'; }
Map the command to a handler within a given root namespace. @param object $command @param string $commandNamespace @param string $handlerNamespace @return string
entailment
public function register() { $this->app->singleton('semantic-form', function ($app) { $builder = new SemanticForm(); $builder->setErrorStore(new IlluminateErrorStore($app['session.store'])); $builder->setOldInputProvider(new IlluminateOldInputProvider($app['session.store...
Register the service provider. @return void
entailment
public function canAccessController(string $controllerName): bool { if (!isset($this->controllerDefaults[$controllerName])) { return false; } $requiredRoles = $this->controllerDefaults[$controllerName]; if (!$requiredRoles) { return true; } if...
Check the guard configuration to see if the current user (or guest) can access a specific controller. Critical distinction: this method does not invoke action rules, only roles. @param $controllerName @return bool
entailment
public function canAccessAction(string $controllerName, string $action): bool { if (isset($this->actions[$controllerName][$action])) { if (!$this->actions[$controllerName][$action]) { return true; } foreach ($this->actions[$controllerName][$action] as $ro...
Similar to controller access, see if the config array grants the current user (or guest) access to a specific action on a given controller. @param $controllerName @param $action @return bool
entailment
public function requiresAuthentication(string $controllerName, string $action): bool { if (isset($this->actions[$controllerName][$action])) { if (!$this->actions[$controllerName][$action]) { return false; } return true; } if (isset($this-...
Cursory check to see if authentication is required for a controller/action pair. Assumes that a guard exists, for the controller/action being queried. Note that this method qualifies the route, and not the user & route relationship. @param string $controllerName @param string $action @return bool @throws GuardExpec...
entailment
public function hasRoleWithName(string $role): bool { $this->compileUserRoles(); return in_array($role, $this->userRoles); }
Check if the current user has a given role. @param $role @return bool True if the role fits, false if there is no user or the role is not accessible in the hierarchy of existing user roles.
entailment
public function addRoleByName(string $roleName) { if (!$this->user) { throw new UserRequiredException(); } $this->compileUserRoles(); if ($this->hasRoleWithName($roleName)) { return; } $role = $this->roleProvider->getRoleWithName($roleName);...
Add a role for the current User @param $roleName @throws InvalidRoleException @throws UserRequiredException @internal param $roleId
entailment
private function compileUserRoles() { if ($this->userRoles !== null) { return; } if (!$this->user) { $this->userRoles = []; return; } $roleList = []; $roleExpansion = []; /** @var Role $role */ foreach ($this->ro...
Flattens roles using the roleProvider, for quick lookup.
entailment
public function getGroupPermissions($resource): array { if ($resource instanceof ResourceInterface) { return $this->groupPermissions->getResourcePermissions($resource); } if (\is_string($resource)) { return $this->groupPermissions->getPermissions($resource); ...
Permissions are an ability to do 'something' with either a 'string' or ResourceInterface as the subject. Some permissions are attributed to roles, as defined by your role provider. This method checks to see if the set of roles associated to your user, grants access to a specific verb-actions on a resource. @param Re...
entailment
public function getUserPermission($resource) { if (!$this->user) { throw new UserRequiredException(); } if ($resource instanceof ResourceInterface) { return $this->userPermissions->getResourceUserPermission($resource, $this->user); } if (\is_string($...
Permissions can also be defined at a user level. Similar to group rules (e.g., all admins can 'shutdown' 'servers'), you can give users individual privileges on verbs and resources. You can create circumstances such as "all admins can 'shutdown' 'servers', and user 45 can do it too!" This method expects that a user h...
entailment
public function isAllowed($resource, string $action): bool { $groupPermissions = $this->getGroupPermissions($resource); // check roles first foreach ($groupPermissions as $groupPermission) { if ($groupPermission->can($action) && $this->hasRole($groupPermission->getRole())) { ...
This is the crux of all resource and verb checks. Two important concepts: - Resources can be simple strings, or can be objects that implement ResourceInterface - Actions are an action string It was a design condition to favor consistent method invocation, and let this library handle string or resource distinction, r...
entailment
public function isAllowedUser($resource, string $action): bool { $permission = $this->getUserPermission($resource); return $permission && $permission->can($action); }
Similar to isAllowed, this method checks user-rules specifically. If there is no user in session, and this method is called directly, a UserRequiredException will be thrown. isAllowed, will pass the buck to this method if no group rules satisfy the action. @param ResourceInterface|string $resource @param string ...
entailment
public function listAllowedByClass($resourceClass, string $action = ''): array { $permissions = $this->groupPermissions->getResourcePermissionsByClass($resourceClass); $permitted = []; foreach ($permissions as $permission) { if (!$action || $permission->can($action)) { ...
List allowed resource IDs by class @param $resourceClass @param $action @return array Array of IDs whose class was $resourceClass
entailment
public function grantRoleAccess(RoleInterface $role, ResourceInterface $resource, string $action) { $resourcePermissions = $this->getGroupPermissions($resource); $matchedPermission = null; // // 1. Check to see if the role, or its parents already have access. Don't pollute the data...
Give a role, access to a specific resource @param RoleInterface $role @param ResourceInterface $resource @param string $action @throws ExistingAccessException @throws UnknownResourceTypeException
entailment
public function grantUserAccess($resource, string $action) { $permission = $this->getUserPermission($resource); // already have permission? get out if ($this->isAllowed($resource, $action)) { return; } // make sure we can work with this if ($permission &...
Grant a user, string (simple) or ResourceInterface permissions. The action whose permission is being granted, must be specified. Example: $this->grantAccess('car','start'); The user must have been loaded in using setUser (done automatically by the factory when a user is authenticated) prior to this call. @param Re...
entailment
public function revokeUserAccess($resource, string $action) { $resourceRule = $this->getUserPermission($resource); if (!$resourceRule) { return; } // make sure we can work with this if ($resourceRule && !($resourceRule instanceof UserPermissionInterface)) { ...
Revoke access to a resource @param ResourceInterface|string $resource @param string $action @throws PermissionExpectedException @throws UnknownResourceTypeException @throws UserRequiredException
entailment
public function authenticate(string $username, string $password): User { $auth = $this->authenticationProvider->findByUsername($username); $user = null; if (!$auth && filter_var($username, FILTER_VALIDATE_EMAIL)) { if ($user = $this->userProvider->findByEmail($username)) { ...
Passed in by a successful form submission, should set proper auth cookies if the identity verifies. The login should work with both username, and email address. @param $username @param $password @return User @throws BadPasswordException Thrown when the password doesn't work @throws NoSuchUserException Thrown when th...
entailment
public function changeUsername(User $user, string $newUsername): AuthenticationRecordInterface { /** @var AuthenticationRecordInterface $auth */ $auth = $this->authenticationProvider->findByUserId($user->getId()); if (!$auth) { throw new NoSuchUserException(); } ...
Change an auth record username given a user id and a new username. Note - in this case username is email. @param User $user @param $newUsername @return AuthenticationRecordInterface @throws NoSuchUserException Thrown when the user's authentication records couldn't be found @throws UsernameTakenException
entailment
private function setSessionCookies(AuthenticationRecordInterface $authentication) { $systemKey = new EncryptionKey($this->systemEncryptionKey); $sessionKey = new HiddenString($authentication->getSessionKey()); $userKey = new EncryptionKey($sessionKey); $hashCookieName = hash_hmac('sh...
Set the auth session cookies that can be used to regenerate the session on subsequent visits @param AuthenticationRecordInterface $authentication
entailment
private function setCookie(string $name, $value) { $expiry = $this->transient ? 0 : (time() + 2629743); $sessionParameters = session_get_cookie_params(); setcookie( $name, $value, $expiry, '/', $sessionParameters['domain'], ...
Set a cookie with values defined by configuration @param $name @param $value
entailment
public function getIdentity() { if ($this->identity) { return $this->identity; } if (!isset($_COOKIE[self::COOKIE_VERIFY_A], $_COOKIE[self::COOKIE_VERIFY_B], $_COOKIE[self::COOKIE_USER])) { return null; } $systemKey = new EncryptionKey($this->systemE...
Rifle through 4 cookies, ensuring that all details line up. If they do, we accept that the cookies authenticate a specific user. Some notes: - COOKIE_VERIFY_A is a do-not-decrypt check of COOKIE_USER - COOKIE_VERIFY_B is a do-not-decrypt check of the random-named-cookie specified by COOKIE_USER - COOKIE_USER has its...
entailment
private function purgeHashCookies(string $skipCookie = null) { $sp = session_get_cookie_params(); foreach ($_COOKIE as $cookieName => $value) { if ($cookieName !== $skipCookie && strpos($cookieName, self::COOKIE_HASH_PREFIX) !== false) { setcookie($cookieName, null, null,...
Remove all hash cookies, potentially saving one @param string|null $skipCookie
entailment
private function enforcePasswordStrength(string $password) { if ($this->passwordChecker && !$this->passwordChecker->isStrongPassword($password)) { throw new WeakPasswordException(); } }
@param string $password @throws WeakPasswordException
entailment
public function resetPassword(User $user, string $newPassword) { $this->enforcePasswordStrength($newPassword); $auth = $this->authenticationProvider->findByUserId($user->getId()); if (!$auth) { throw new NoSuchUserException(); } $hash = password_hash($newPasswor...
Reset this user's password @param User $user The user to whom this password gets assigned @param string $newPassword Cleartext password that's being hashed @throws NoSuchUserException @throws WeakPasswordException
entailment
public function verifyPassword(User $user, string $password): bool { $this->enforcePasswordStrength($password); $auth = $this->authenticationProvider->findByUserId($user->getId()); if (!$auth) { throw new NoSuchUserException(); } return password_verify($password...
Validate user password @param User $user The user to validate password for @param string $password Cleartext password that'w will be verified @return bool @throws NoSuchUserException @throws WeakPasswordException
entailment
public function create(User $user, string $username, string $password): AuthenticationRecordInterface { $this->enforcePasswordStrength($password); $auth = $this->registerAuthenticationRecord($user, $username, $password); $this->setSessionCookies($auth); $this->setIdentity($user); ...
Register a new user into the auth tables, and, log them in. Essentially calls registerAuthenticationRecord and then stores the necessary cookies and identity into the service. @param User $user @param string $username @param string $password @return AuthenticationRecordInterface @throws PersistedUserRequiredExcepti...
entailment
public function registerAuthenticationRecord(User $user, string $username, string $password): AuthenticationRecordInterface { if (!$user->getId()) { throw new PersistedUserRequiredException("Your user must have an ID before you can create auth records with it"); } if ($this->aut...
Very similar to create, except that it won't log the user in. This was created to satisfy circumstances where you are creating users from an admin panel for example. This function is also used by create. @param User $user @param string $username @param string $password @return AuthenticationRecordInterface @throw...
entailment
private function resetAuthenticationKey(AuthenticationRecordInterface $auth): AuthenticationRecordInterface { $key = KeyFactory::generateEncryptionKey(); $auth->setSessionKey($key->getRawKeyMaterial()); $this->authenticationProvider->update($auth); return $auth; }
Resalt a user's authentication table salt @param AuthenticationRecordInterface $auth @return AuthenticationRecordInterface
entailment
public function clearIdentity() { if ($user = $this->getIdentity()) { $auth = $this->authenticationProvider->findByUserId($user->getId()); $this->resetAuthenticationKey($auth); } $sp = session_get_cookie_params(); foreach ([self::COOKIE_USER, self::COOKIE_VER...
Logout. Reset the user authentication key, and delete all cookies.
entailment
public function createRecoveryToken(User $user): UserResetToken { if (!$this->resetTokenProvider) { throw new PasswordResetProhibitedException('The configuration currently prohibits the resetting of passwords!'); } $auth = $this->authenticationProvider->findByUserId($user->getId...
Forgot-password mechanisms are a potential back door; but they're needed. This only takes care of hash generation. @param User $user @return UserResetToken @throws NoSuchUserException @throws PasswordResetProhibitedException @throws TooManyRecoveryAttemptsException
entailment
public function changePasswordWithRecoveryToken(User $user, int $tokenId, string $token, string $newPassword) { if (!$this->resetTokenProvider) { throw new PasswordResetProhibitedException('The configuration currently prohibits the resetting of passwords!'); } $auth = $this->aut...
@param User $user @param int $tokenId @param string $token @param string $newPassword @throws InvalidResetTokenException @throws NoSuchUserException @throws PasswordResetProhibitedException @throws \CirclicalUser\Exception\WeakPasswordException
entailment
public function create($userId, $username, $hash, $rawKey): AuthenticationRecordInterface { return new Authentication($userId, $username, $hash, $rawKey); }
@param $userId @param $username @param $hash @param $rawKey @return AuthenticationRecordInterface
entailment
public function throwException( $message, $code, $connectionErrorNumber = null, $httpStatusCode = null, $previousException = null ) { throw new PhpCapException( $message, $code, $connectionErrorNumber, $httpStatusCode, ...
{@inheritdoc} @see <a href="http://php.net/manual/en/function.debug-backtrace.php">debug_backtrace()</a> for information on how to get a stack trace within this method.
entailment
private function getExceptionData($exception) { $data = []; $data['enviroment'] = env('APP_ENV'); $data['host'] = Request::server('SERVER_NAME'); $data['method'] = Request::method(); $data['fullUrl'] = Request::fullUrl(); $data['exception'] = $exception->getMessage()...
@param $exception @return array
entailment
public function checkEnvironments() { /* * If we did not fill in any environment, log every environment. */ if(!count($this->config['environments'])){ return true; } /* * If we did fill in environments, check the array. */ if (...
checkEnvironments function. @return bool
entailment
private function getLineInfo($lines, $line, $i) { $currentLine = $line + $i; $index = $currentLine - 1; if (!array_key_exists($index, $lines)) { return; } return [ 'line' => '<span class="exception-currentline">' . $currentLine . '.</span> ' . Syntax...
Gets information from the line @param $lines @param $line @param $i @return array|void
entailment
private function logError($exception, array $additionalData = []) { $logger = (new Logger($exception)); if(count($additionalData)){ $logger->addAdditionalData($additionalData); } $logger->send(); }
@param array $exception @param array $additionalData
entailment
private function addExceptionToSleep(array $data) { $exceptionString = $this->createExceptionString($data); return Cache::put($exceptionString, $exceptionString, $this->config['sleep']); }
addExceptionToSleep function. @param array $data @return bool
entailment
public function url($return = null, $altRealm = null) { $useHttps = !empty($_SERVER['HTTPS']) || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'); if (!is_null($return)) { if (!$this->validateUrl($return)) { throw new Exception...
Build the Steam login URL @param string $return A custom return to URL @return string
entailment
public function validate($timeout = 30) { $response = null; try { $params = array( 'openid.assoc_handle' => $_GET['openid_assoc_handle'], 'openid.signed' => $_GET['openid_signed'], 'openid.sig' => $_GET['openid_sig'], ...
Validates a Steam login request and returns the users Steam Community ID @return string
entailment
public function getRequestCount(AuthenticationRecordInterface $authenticationRecord): int { $fiveMinutesAgo = new \DateTime('now', new \DateTimeZone('UTC')); $fiveMinutesAgo->modify('-5 minutes'); $query = $this->getRepository()->createQueryBuilder('r') ->select('COUNT(r.id) AS ...
Get the count of requests in the last 5 minutes @param AuthenticationRecordInterface $authenticationRecord @return int @throws \Doctrine\ORM\NoResultException @throws \Doctrine\ORM\NonUniqueResultException
entailment
public function invalidateUnusedTokens(AuthenticationRecordInterface $authenticationRecord) { $query = $this->getRepository()->createQueryBuilder('r') ->update() ->set('r.status', UserResetTokenInterface::STATUS_INVALID) ->where('r.authentication = :authentication') ...
Modify previously created tokens that are not used, so that their status is invalid. There should only be one valid token at any time. @param AuthenticationRecordInterface $authenticationRecord @return mixed
entailment
public function getFunctions() { // dump is safe if var_dump is overridden by xdebug $isDumpOutputHtmlSafe = extension_loaded('xdebug') // false means that it was not set (and the default is on) or it explicitly enabled && (false === ini_get('xdebug.overload_var_dump') || ini_ge...
Get Functions @return array
entailment
public function dump(\Twig_Environment $env, $context, ...$vars) { if (!$env->isDebug()) { return null; } if (!$vars) { $vars = []; foreach ($context as $key => $value) { if (!$value instanceof \Twig_Template) { $vars[$...
Override dump version of Symfony's VarDumper component @param \Twig_Environment $env @param array $context @param mixed ...$vars @return string|null
entailment
private function replaceId($matches) { $match = $matches[0]; $id = "##r" . uniqid() . "##"; // String or Comment? if (substr($match, 0, 2) == '//' || substr($match, 0, 2) == '/*' || substr($match, 0, 2) == '##' || substr($match, 0, 7) == '&lt;!--') { $this->tokens[$id] =...
/* Regexp-Callback to replace every comment or string with a uniqid and save the matched text in an array This way, strings and comments will be stripped out and wont be processed by the other expressions searching for keywords etc.
entailment
public function compress($input) { if (!($input = trim((string) $input))) { return $input; // Nothing to do. } if (mb_stripos($input, '</html>') === false) { return $input; // Not an HTML doc. } if ($this->isCurrentUrlUriExcluded()) { retur...
Handles compression. The heart of this class. Full instructions and all `$options` are listed in the [README.md](http://github.com/WebSharks/HTML-Compressor) file. See: <http://github.com/WebSharks/HTML-Compressor> @since 140417 Initial release. @api This method is available for public use. @param string $input The...
entailment
protected function isValidUtf8($html) { preg_match('/./u', $html); $last_error = preg_last_error(); return !in_array($last_error, [PREG_BAD_UTF8_ERROR, PREG_BAD_UTF8_OFFSET_ERROR], true); }
/* Validation-Related Methods
entailment
protected function tokenizeGlobalExclusions($html) { $html = (string) $html; $_this = $this; $global_exclusions = [ '/\<noscript(?:\s[^>]*)?\>.*?\<\/noscript\>/uis', ]; $html = preg_replace_callback( $global_exclusions, ...
Global exclusion tokenizer. @since 150821 Adding global exclusion tokenizer. @param string $html Input HTML code. @return string HTML code, after tokenizing exclusions.
entailment
protected function restoreGlobalExclusions($html) { $html = (string) $html; if (!$this->current_global_exclusion_tokens) { return $html; // Nothing to restore. } if (mb_strpos($html, '<htmlc-gxt-') === false) { return $html; // Nothing to restore. } ...
Restore global exclusions. @since 150821 Adding global exclusion tokenizer. @param string $html Input HTML code. @return string HTML code, after restoring exclusions.
entailment
protected function isDocAmpd($html) { $html = (string) $html; if (preg_match('/\/amp\/(?:$|[?&#])/ui', $this->currentUrlUri())) { return true; } elseif ($html && preg_match('/\<html(?:\s[^>]+?\s|\s)(?:⚡|amp)[\s=\>]/ui', $html)) { return true; } return...
Document is AMPd? @since 161207 AMP exclusions. @param string $html HTML markup. @return bool Returns `TRUE` if AMPd.
entailment
protected function maybeCompressCombineHeadBodyCss($html) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $html = (string) $html; // Force string value. if (isset($this->options['compress...
Handles possible compression of head/body CSS. @since 140417 Initial release. @param string $html Input HTML code. @return string HTML code, after possible CSS compression.
entailment
protected function compileCssTagFragsIntoParts(array $css_tag_frags, $for) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $for = (string) $for; // Force string. $css_parts ...
Compiles CSS tag fragments into CSS parts with compression. @since 140417 Initial release. @param array $css_tag_frags CSS tag fragments. @param string $for Where will these parts go? One of `head`, `body`, `foot`. @throws \Exception If unable to cache CSS parts. @return array Array of CSS parts, else an...
entailment
protected function getCssTagFrags(array $html_frag) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $css_tag_frags = []; // Initialize. if (!$html_frag) { goto finale; // Noth...
Parses and returns an array of CSS tag fragments. @since 140417 Initial release. @param array $html_frag An HTML tag fragment array. @return array An array of CSS tag fragments (ready to be converted into CSS parts). Else an empty array (i.e. no CSS tag fragments in the HTML fragment array). @see http://css-tricks....
entailment
protected function isLinkTagFragCss(array $tag_frag) { if (empty($tag_frag['link_self_closing_tag'])) { return false; // Nope; missing tag. } $type = $rel = ''; // Initialize. if (mb_stripos($tag_frag['link_self_closing_tag'], 'type') !== 0) { if (preg_match(...
Test a tag fragment to see if it's CSS. @since 140922 Improving tag tests. @param array $tag_frag A tag fragment. @return bool TRUE if it contains CSS.
entailment
protected function isStyleTagFragCss(array $tag_frag) { if (empty($tag_frag['style_open_tag']) || empty($tag_frag['style_closing_tag'])) { return false; // Nope; missing open|closing tag. } $type = ''; // Initialize. if (mb_stripos($tag_frag['style_open_tag'], 'type') !=...
Test a tag fragment to see if it's CSS. @since 140922 Improving tag tests. @param array $tag_frag A tag fragment. @return bool TRUE if it contains CSS.
entailment
protected function getLinkCssHref(array $tag_frag, $test_for_css = true) { if ($test_for_css && !$this->isLinkTagFragCss($tag_frag)) { return ''; // This tag does not contain CSS. } if (preg_match('/\shref\s*\=\s*(["\'])(?P<value>.+?)\\1/ui', $tag_frag['link_self_closing_tag'], $...
Get a CSS link href value from a tag fragment. @since 140417 Initial release. @param array $tag_frag A CSS tag fragment. @param bool $test_for_css Defaults to a TRUE value. If TRUE, we will test tag fragment to make sure it's CSS. @return string The link href value if possible; else an empty string.
entailment
protected function getLinkCssMedia(array $tag_frag, $test_for_css = true) { if ($test_for_css && !$this->isLinkTagFragCss($tag_frag)) { return ''; // This tag does not contain CSS. } if (preg_match('/\smedia\s*\=\s*(["\'])(?P<value>.+?)\\1/ui', $tag_frag['link_self_closing_tag'],...
Get a CSS link media rule from a tag fragment. @since 140417 Initial release. @param array $tag_frag A CSS tag fragment. @param bool $test_for_css Defaults to a TRUE value. If TRUE, we will test tag fragment to make sure it's CSS. @return string The link media value if possible; else an empty string.
entailment
protected function getStyleCssMedia(array $tag_frag, $test_for_css = true) { if ($test_for_css && !$this->isStyleTagFragCss($tag_frag)) { return ''; // This tag does not contain CSS. } if (preg_match('/\smedia\s*\=\s*(["\'])(?P<value>.+?)\\1/ui', $tag_frag['style_open_tag'], $_m)...
Get a CSS style media rule from a tag fragment. @since 140417 Initial release. @param array $tag_frag A CSS tag fragment. @param bool $test_for_css Defaults to a TRUE value. If TRUE, we will test tag fragment to make sure it's CSS. @return string The style media value if possible; else an empty string.
entailment
protected function getStyleCss(array $tag_frag, $test_for_css = true) { if (empty($tag_frag['style_css'])) { return ''; // Not possible; no CSS code. } if ($test_for_css && !$this->isStyleTagFragCss($tag_frag)) { return ''; // This tag does not contain CSS. } ...
Get style CSS from a CSS tag fragment. @since 140417 Initial release. @param array $tag_frag A CSS tag fragment. @param bool $test_for_css Defaults to a TRUE value. If TRUE, we will test tag fragment to make sure it's CSS. @return string The style CSS code (if possible); else an empty string.
entailment
protected function stripExistingCssCharsets($css) { if (!($css = (string) $css)) { return $css; // Nothing to do. } $css = preg_replace('/@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?charset(?:\s+[^;]*?)?;/ui', '', $css); return $css = $css ? trim($css) : $css...
Strip existing charset rules from CSS code. @since 140417 Initial release. @param string $css CSS code. @return string CSS after having stripped away existing charset rules.
entailment
protected function stripPrependCssCharsetUtf8($css) { if (!($css = (string) $css)) { return $css; // Nothing to do. } $css = $this->stripExistingCssCharsets($css); return $css = $css ? '@charset "UTF-8";'."\n".$css : $css; }
Strip existing charsets and add a UTF-8 `@charset` rule. @since 140417 Initial release. @param string $css CSS code. @return string CSS code (possibly with a prepended UTF-8 charset rule).
entailment
protected function moveSpecialCssAtRulesToTop($css, $___recursion = 0) { if (!($css = (string) $css)) { return $css; // Nothing to do. } $max_recursions = 2; // `preg_match_all()` calls. if ($___recursion >= $max_recursions) { return $css; // All done. ...
Moves special CSS `@rules` to the top. @since 140417 Initial release. @param string $css CSS code. @param int $___recursion Internal use only. @return string CSS code after having moved special `@rules` to the top. @see <https://developer.mozilla.org/en-US/docs/Web/CSS/@charset> @see <http://stackoverfl...
entailment
protected function resolveResolvedCssImports($css, $media, $___recursion = false) { if (!($css = (string) $css)) { return $css; // Nothing to do. } $media = $this->current_css_media = (string) $media; if (!$media) { $media = $this->current_css_media = 'all'; ...
Resolves `@import` rules in CSS code recursively. @since 140417 Initial release. @param string $css CSS code. @param string $media Current media specification. @param bool $___recursion Internal use only. @return string CSS code after all `@import` rules have been resolved recursively.
entailment
protected function resolveResolvedCssImportsCb(array $m) { if (empty($m['url'])) { return ''; // Nothing to resolve. } if (!empty($m['media']) && $m['media'] !== $this->current_css_media) { return $m[0]; // Not possible; different media. } if (($css = ...
Callback handler for resolving @ import rules. @since 140417 Initial release. @param array $m An array of regex matches. @return string CSS after import resolution, else an empty string.
entailment
protected function resolveCssRelatives($css, $base = '') { if (!($css = (string) $css)) { return $css; // Nothing to do. } $this->current_base = $base; // Make this available to callback handlers (possible empty string here). $import_without_url_regex = '/(?P<import>@(?:...
Resolve relative URLs in CSS code. @since 140417 Initial release. @param string $css CSS code. @param string $base Optional. Base URL to calculate from. Defaults to the current HTTP location for the browser. @return string CSS code after having all URLs resolved.
entailment
protected function resolveCssRelativesImportCb(array $m) { return $m['import'].$m['open_encap'].$this->resolveRelativeUrl($m['url'], $this->current_base).$m['close_encap']; }
Callback handler for CSS relative URL resolutions. @since 140417 Initial release. @param array $m An array of regex matches. @return string CSS `@import` rule with relative URL resolved.
entailment
protected function resolveCssRelativesUrlCb(array $m) { if (mb_stripos($m['url'], 'data:') === 0) { return $m[0]; // Don't resolve `data:` URIs. } return $m['url_'].$m['open_bracket'].$m['open_encap'].$this->resolveRelativeUrl($m['url'], $this->current_base).$m['close_encap'].$m[...
Callback handler for CSS relative URL resolutions. @since 140417 Initial release. @param array $m An array of regex matches. @return string CSS `url()` resource with relative URL resolved.
entailment
protected function forceAbsRelativePathsInCss($css) { if (!($css = (string) $css)) { return $css; // Nothing to do. } $regex = '/(?:[a-z0-9]+\:)?\/\/'.$this->pregQuote($this->currentUrlHost()).'\//ui'; return preg_replace($regex, '/', $css); // Absolute relative paths. ...
Force absolute relative paths in CSS. @since 150511 Improving CSS handling. @param string $css Raw CSS code. @return string CSS code (possibly altered here).
entailment
protected function maybeFilterCssUrls($css) { if (!($css = (string) $css)) { return $css; // Nothing to do. } if (!$this->hook_api->hasFilter('css_url()')) { return $css; // No reason to do this. } $import_without_url_regex = '/(?P<import>@(?:\-(?:'.$t...
Maybe filter URLs in CSS code. @since 150821 Adding URL filter support. @param string $css CSS code. @return string CSS code after having filtered all URLs.
entailment
protected function filterCssUrlCb(array $m) { if (mb_stripos($m['url'], 'data:') === 0) { return $m[0]; // Don't filter `data:` URIs. } return $m['url_'].$m['open_bracket'].$m['open_encap'].$this->hook_api->applyFilters('css_url()', $m['url']).$m['close_encap'].$m['close_bracket'...
Callback handler for CSS URL filters. @since 150821 Adding URL filter support. @param array $m An array of regex matches. @return string CSS `url()` resource with with filtered URL.
entailment
protected function maybeCompressCombineHeadJs($html) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $html = (string) $html; // Force string value. if (isset($this->options['compress_comb...
Handles possible compression of head JS. @since 140417 Initial release. @param string $html Input HTML code. @return string HTML code, after possible JS compression.
entailment
protected function maybeCompressCombineFooterJs($html) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $html = (string) $html; // Force string value. if (isset($this->options['compress_co...
Handles possible compression of footer JS. @since 140417 Initial release. @param string $html Input HTML code. @return string HTML code, after possible JS compression.
entailment
protected function compileJsTagFragsIntoParts(array $js_tag_frags, $for) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $for = (string) $for; // Force string. $js_parts ...
Compiles JS tag fragments into JS parts with compression. @since 140417 Initial release. @param array $js_tag_frags JS tag fragments. @param string $for Where will these parts go? One of `head`, `body`, `foot`. @throws \Exception If unable to cache JS parts. @return array Array of JS parts, else an empty ...
entailment
protected function getJsTagFrags(array $html_frag) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $js_tag_frags = []; // Initialize. if (!$html_frag) { goto finale; // Nothin...
Parses and return an array of JS tag fragments. @since 140417 Initial release. @param array $html_frag An HTML tag fragment array. @return array An array of JS tag fragments (ready to be converted into JS parts). Else an empty array (i.e. no JS tag fragments in the HTML fragment array). @see http://css-tricks.com/h...
entailment
protected function isScriptTagFragJson(array $tag_frag) { if (empty($tag_frag['script_open_tag']) || empty($tag_frag['script_closing_tag'])) { return false; // Nope; missing open|closing tag. } $type = $language = ''; // Initialize. if (mb_stripos($tag_frag['script_open_...
Test a script tag fragment to see if it's JSON. @since 150424 Adding support for JSON compression. @param array $tag_frag A JS tag fragment. @return bool TRUE if it contains JSON.
entailment
protected function getScriptJsSrc(array $tag_frag, $test_for_js = true) { if ($test_for_js && !$this->isScriptTagFragJs($tag_frag)) { return ''; // This script tag does not contain JavaScript. } if (preg_match('/\ssrc\s*\=\s*(["\'])(?P<value>.+?)\\1/ui', $tag_frag['script_open_ta...
Get script JS src value from a JS tag fragment. @since 140417 Initial release. @param array $tag_frag A JS tag fragment. @param bool $test_for_js Defaults to a TRUE value. If TRUE, we will test tag fragment to make sure it's JavaScript. @return string The script JS src value (if possible); else an empty string.
entailment
protected function getScriptJsAsync(array $tag_frag, $test_for_js = true) { if ($test_for_js && !$this->isScriptTagFragJs($tag_frag)) { return ''; // This script tag does not contain JavaScript. } if (preg_match('/\s(?:async|defer)(?:\>|\s+[^=]|\s*\=\s*(["\'])(?:1|on|yes|true|asy...
Get script JS async|defer value from a JS tag fragment. @since 140417 Initial release. @param array $tag_frag A JS tag fragment. @param bool $test_for_js Defaults to a TRUE value. If TRUE, we will test tag fragment to make sure it's JavaScript. @return string The script JS async|defer value (if possible); else a...
entailment
protected function getScriptJs(array $tag_frag, $test_for_js = true) { if (empty($tag_frag['script_js'])) { return ''; // Not possible; no JavaScript code. } if ($test_for_js && !$this->isScriptTagFragJs($tag_frag)) { return ''; // This script tag does not contain Jav...
Get script JS from a JS tag fragment. @since 140417 Initial release. @param array $tag_frag A JS tag fragment. @param bool $test_for_js Defaults to a TRUE value. If TRUE, we will test tag fragment to make sure it's JavaScript. @return string The script JS code (if possible); else an empty string.
entailment
protected function getScriptJson(array $tag_frag, $test_for_json = true) { if (empty($tag_frag['script_json'])) { return ''; // Not possible; no JSON code. } if ($test_for_json && !$this->isScriptTagFragJson($tag_frag)) { return ''; // This script tag does not contain...
Get script JSON from a JS tag fragment. @since 150424 Adding support for JSON compression. @param array $tag_frag A JS tag fragment. @param bool $test_for_js Defaults to a TRUE value. If TRUE, we will test tag fragment to make sure it's JSON. @param mixed $test_for_json @return string The script JSON code (i...
entailment
protected function getHtmlFrag($html) { if (!($html = (string) $html)) { return []; // Nothing to do. } if (preg_match('/(?P<all>(?P<open_tag>\<html(?:\s+[^>]*?)?\>)(?P<contents>.*?)(?P<closing_tag>\<\/html\>))/uis', $html, $html_frag)) { return $this->removeNumericKe...
Build an HTML fragment from HTML source code. @since 140417 Initial release. @param string $html Raw HTML code. @return array An HTML fragment (if possible); else an empty array.
entailment
protected function getHeadFrag($html) { if (!($html = (string) $html)) { return []; // Nothing to do. } if (preg_match('/(?P<all>(?P<open_tag>\<head(?:\s+[^>]*?)?\>)(?P<contents>.*?)(?P<closing_tag>\<\/head\>))/uis', $html, $head_frag)) { return $this->removeNumericKe...
Build a head fragment from HTML source code. @since 140417 Initial release. @param string $html Raw HTML code. @return array A head fragment (if possible); else an empty array.
entailment
protected function getFooterScriptsFrag($html) { if (!($html = (string) $html)) { return []; // Nothing to do. } if (preg_match('/(?P<all>(?P<open_tag>\<\!\-\-\s*footer[\s_\-]+scripts\s*\-\-\>)(?P<contents>.*?)(?P<closing_tag>(?P=open_tag)))/uis', $html, $head_frag)) { ...
Build a footer scripts fragment from HTML source code. @since 140417 Initial release. @param string $html Raw HTML code. @return array A footer scripts fragment (if possible); else an empty array.
entailment
protected function getTagFragsChecksum(array $tag_frags) { foreach ($tag_frags as &$_frag) { $_frag = $_frag['exclude'] ? ['exclude' => true] : $_frag; } // unset($_frag); // A little housekeeping. return md5(serialize($tag_frags)); }
Construct a checksum for an array of tag fragments. @since 140417 Initial release. @note This routine purposely excludes any "exclusions" from the checksum. All that's important here is an exclusion's position in the array, not its fragmentation; it's excluded anyway. @param array $tag_frags Array of tag fragments. ...
entailment
protected function maybeCompressHtmlCode($html) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $html = (string) $html; // Force string value. if (isset($this->options['compress_html_code...
Maybe compress HTML code. @since 140417 Initial release. @param string $html Raw HTML code. @return string Possibly compressed HTML code.
entailment
protected function compressHtml($html) { if (!($html = (string) $html)) { return $html; // Nothing to do. } $static = &static::$static[__FUNCTION__]; if (!isset($static['preservations'], $static['compressions'], $static['compress_with'])) { $static['preservat...
Compresses HTML markup (as quickly as possible). @since 140417 Initial release. @param string $html Any HTML markup (no empty strings please). @return string Compressed HTML markup. With all comments and extra whitespace removed as quickly as possible. This preserves portions of HTML that depend on whitespace. Like ...
entailment
protected function maybeCompressCssCode($css) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $css = (string) $css; // Force string value. if (isset($this->options['compress_css_code'])) ...
Maybe compress CSS code. @since 140417 Initial release. @param string $css Raw CSS code. @return string CSS code (possibly compressed).
entailment
protected function maybeCompressJsCode($js) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $js = (string) $js; // Force string value. if (isset($this->options['compress_js_code'])) { ...
Maybe compress JS code. @since 140417 Initial release. @param string $js Raw JS code. @return string JS code (possibly compressed).
entailment
protected function maybeCompressInlineJsCode($html) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $html = (string) $html; // Force string value. if (isset($this->options['compress_js_co...
Maybe compress inline JS code within the HTML source. @since 140417 Initial release. @param string $html Raw HTML code. @return string HTML source code, with possible inline JS compression.
entailment
protected function compressInlineJsCode($js) { if (!($js = (string) $js)) { return $js; // Nothing to do. } if (($compressed_js = \WebSharks\JsMinifier\Core::compress($js))) { return '/*<![CDATA[*/'.$compressed_js.'/*]]>*/'; } return $js; }
Helper function; compress inline JS code. @since 140417 Initial release. @param string $js Raw JS code. @return string JS code (possibly minified).
entailment
protected function maybeCompressInlineJsonCode($html) { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $html = (string) $html; // Force string value. if (isset($this->options['compress_js_...
Maybe compress inline JSON code within the HTML source. @since 150424 Adding support for JSON compression. @param string $html Raw HTML code. @return string HTML source code, with possible inline JSON compression.
entailment
protected function compressInlineJsonCode($json) { if (!($json = (string) $json)) { return $json; // Nothing to do. } if (($compressed_json = \WebSharks\JsMinifier\Core::compress($json))) { return '/*<![CDATA[*/'.$compressed_json.'/*]]>*/'; } return $j...
Helper function; compress inline JSON code. @since 150424 Adding support for JSON compression. @param string $js Raw JSON code. @param mixed $json @return string JSON code (possibly minified).
entailment
protected function compileKeyElementsDeep(array $array, $keys, $preserve_keys = false, $search_dimensions = -1, $___current_dimension = 1) { if ($___current_dimension === 1) { $keys = (array) $keys; $search_dimensions = (int) $search_dimensions; } $key_el...
Compiles a new array of all `$key` elements (deeply). @since 140417 Initial release. @note This is a recursive scan running deeply into multiple dimensions of arrays. @param array $array An input array to search in. @param string|int|array $keys An array of `key` elements to...
entailment
protected function removeNumericKeysDeep(array $array, $___recursion = false) { foreach ($array as $_key => &$_value) { if (is_numeric($_key)) { unset($array[$_key]); } elseif (is_array($_value)) { $_value = $this->removeNumericKeysDeep($_value, true);...
Removes all numeric array keys (deeply). @since 140417 Initial release. @note This is a recursive scan running deeply into multiple dimensions of arrays. @param array $array An input array. @param bool $___recursion Internal use only. @return array Output array with only non-numeric keys (deeply).
entailment
protected function pregQuote($value, $delimiter = '/') { if (is_array($value) || is_object($value)) { foreach ($value as &$_value) { $_value = $this->pregQuote($_value, $delimiter); } // unset($_value); // Housekeeping. return $value; } ret...
Escapes regex special chars deeply. @since 140417 Initial release. @param mixed $value Input value. @param string $delimiter Delimiter. @return string|array|object Escaped string, array, object.
entailment
protected function substrReplace($value, $replace, $start, $length = null) { if (is_array($value) || is_object($value)) { foreach ($value as $_key => &$_value) { $_value = $this->substrReplace($_value, $replace, $start, $length); } // unset($_key, $_value); ...
Multibyte `substr_replace()`. @since 161207 Enhancing multibyte. @param mixed $value Input value. @param string $replace Replacement string. @param int $start Substring start position. @param int|null $length Substring length. @return string|array|object Output value. @link http://php.net/manual/en/f...
entailment
protected function replaceOnce($needle, $replace, $value, $caSe_insensitive = false) { if (is_array($value) || is_object($value)) { foreach ($value as $_key => &$_value) { $_value = $this->replaceOnce($needle, $replace, $_value, $caSe_insensitive); } // unset($_key, $...
String replace (ONE time) deeply. @since 140417 Initial release. @param string|array $needle String, or an array of strings, to search for. @param string|array $replace String, or an array of strings, to use as replacements. @param mixed $value Any input value will do just fine he...
entailment