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]);
},
$repository->getLog($limit, $skip)
)
);
} | 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 string | 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->handlers[$class] = $callback($command);
return true;
} | 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']));
return $builder;
});
} | 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 (!$this->user) {
return false;
}
foreach ($requiredRoles as $role) {
if ($this->hasRoleWithName($role)) {
return true;
}
}
return false;
} | 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 $role) {
if ($this->hasRoleWithName($role)) {
return true;
}
}
return false;
}
return $this->canAccessController($controllerName);
} | 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->controllerDefaults[$controllerName])) {
if (!$this->controllerDefaults[$controllerName]) {
return false;
}
return true;
}
throw new GuardExpectedException($controllerName);
} | 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 GuardExpectedException | 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);
if (!$role) {
throw new InvalidRoleException($roleName);
}
$this->user->addRole($role);
$this->userRoles[] = $roleName;
$this->userProvider->update($this->user);
} | 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->roleProvider->getAllRoles() as $role) {
$roleList[$role->getId()] = $role;
}
/** @var Role $userRole */
$userRoles = $this->user->getRoles();
if ($userRoles) {
foreach ($userRoles as $userRole) {
$roleExpansion[] = $userRole->getName();
$parentRole = $userRole->getParent();
while ($parentRole) {
$roleExpansion[] = $parentRole->getName();
$parentRole = $parentRole->getParent();
}
}
}
$this->userRoles = array_unique($roleExpansion);
} | 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);
}
throw new UnknownResourceTypeException(\get_class($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 ResourceInterface|string $resource
@return GroupPermissionInterface[]
@throws UnknownResourceTypeException | 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($resource)) {
return $this->userPermissions->getUserPermission($resource, $this->user);
}
throw new UnknownResourceTypeException(\get_class($resource));
} | 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 has been set, e.g., by the Factory.
A single permission is returned, since the user can only have one permission set attributed to a given Resource
@param ResourceInterface|string $resource
@return UserPermissionInterface
@throws \Exception
@throws UnknownResourceTypeException
@throws UserRequiredException | 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())) {
return true;
}
}
if ($this->user) {
return $this->isAllowedUser($resource, $action);
}
return false;
} | 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, rather than force you to differentiate the cases in your code.
@param ResourceInterface|string $resource
@param string $action
@return bool
@throws \Exception
@throws UnknownResourceTypeException
@throws UserRequiredException | 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 $action
@return bool
@throws \Exception
@throws UnknownResourceTypeException
@throws UserRequiredException | entailment |
public function listAllowedByClass($resourceClass, string $action = ''): array
{
$permissions = $this->groupPermissions->getResourcePermissionsByClass($resourceClass);
$permitted = [];
foreach ($permissions as $permission) {
if (!$action || $permission->can($action)) {
$permitted[] = $permission->getResourceId();
}
}
return array_unique($permitted);
} | 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 database.
//
$examinedRole = $role;
while ($examinedRole) {
foreach ($resourcePermissions as $permission) {
if ($role === $permission->getRole()) {
$matchedPermission = $permission;
}
if ($permission->can($action)) {
throw new ExistingAccessException($role, $resource, $action, $permission->getRole()->getName());
}
}
$examinedRole = $examinedRole->getParent();
}
//
// 2. Give access
//
if (!$matchedPermission) {
$newPermission = $this->groupPermissions->create($role, $resource->getClass(), $resource->getId(), [$action]);
$this->groupPermissions->save($newPermission);
} else {
$matchedPermission->addAction($action);
$this->groupPermissions->update($matchedPermission);
}
} | 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 && !($permission instanceof UserPermissionInterface)) {
throw new PermissionExpectedException(UserPermissionInterface::class, \get_class($permission));
}
/** @var UserPermissionInterface $permission */
if ($permission) {
if ($permission->can($action)) {
return;
}
$permission->addAction($action);
$this->userPermissions->update($permission);
} else {
$isString = \is_string($resource);
$permission = $this->userPermissions->create(
$this->user,
$isString ? 'string' : $resource->getClass(),
$isString ? $resource : $resource->getId(),
[$action]
);
$this->userPermissions->save($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 ResourceInterface|string $resource
@param string $action
@throws PermissionExpectedException
@throws UnknownResourceTypeException
@throws UserRequiredException | 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)) {
throw new PermissionExpectedException(UserPermissionInterface::class, \get_class($resourceRule));
}
if ($resourceRule) {
if (!\in_array($action, $resourceRule->getActions(), true)) {
return;
}
$resourceRule->removeAction($action);
$this->userPermissions->update($resourceRule);
}
} | 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)) {
$auth = $this->authenticationProvider->findByUserId($user->getId());
}
}
if (!$auth) {
throw new NoSuchUserException();
}
if (password_verify($password, $auth->getHash())) {
if (!$user) {
$user = $this->userProvider->getUser($auth->getUserId());
}
if ($user) {
$this->resetAuthenticationKey($auth);
$this->setSessionCookies($auth);
$this->setIdentity($user);
if (password_needs_rehash($auth->getHash(), PASSWORD_DEFAULT)) {
$auth->setHash(password_hash($password, PASSWORD_DEFAULT));
$this->authenticationProvider->update($auth);
}
return $user;
} else {
throw new NoSuchUserException();
}
}
throw new BadPasswordException();
} | 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 the user can't be identified | entailment |
public function changeUsername(User $user, string $newUsername): AuthenticationRecordInterface
{
/** @var AuthenticationRecordInterface $auth */
$auth = $this->authenticationProvider->findByUserId($user->getId());
if (!$auth) {
throw new NoSuchUserException();
}
// check to see if already taken
if ($otherAuth = $this->authenticationProvider->findByUsername($newUsername)) {
if ($auth == $otherAuth) {
return $auth;
} else {
throw new UsernameTakenException();
}
}
$auth->setUsername($newUsername);
$this->authenticationProvider->update($auth);
return $auth;
} | 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('sha256', $sessionKey . $authentication->getUsername(), $systemKey);
$userTuple = base64_encode(Crypto::encrypt(new HiddenString($authentication->getUserId() . ':' . $hashCookieName), $systemKey));
$hashCookieContents = base64_encode(Crypto::encrypt(new HiddenString(time() . ':' . $authentication->getUserId() . ':' . $authentication->getUsername()), $userKey));
//
// 1 - Set the cookie that contains the user ID, and hash cookie name
//
$this->setCookie(
self::COOKIE_USER,
$userTuple
);
//
// 2 - Set the cookie with random name, that contains a verification hash, that's a function of the switching session key
//
$this->setCookie(
self::COOKIE_HASH_PREFIX . $hashCookieName,
$hashCookieContents
);
//
// 3 - Set the sign cookie, that acts as a safeguard against tampering
//
$this->setCookie(
self::COOKIE_VERIFY_A,
hash_hmac('sha256', $userTuple, $systemKey)
);
//
// 4 - Set a sign cookie for the hashCookie's values
//
$this->setCookie(
self::COOKIE_VERIFY_B,
hash_hmac('sha256', $hashCookieContents, $userKey)
);
} | 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'],
$this->secure,
true
);
} | 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->systemEncryptionKey);
$verificationCookie = $_COOKIE[self::COOKIE_VERIFY_A];
$hashPass = hash_equals(
hash_hmac('sha256', $_COOKIE[self::COOKIE_USER], $systemKey),
$verificationCookie
);
//
// 1. Is the verify cookie still equivalent to the user cookie, if so, do not decrypt
//
if (!$hashPass) {
return null;
}
//
// 2. If the user cookie was not tampered with, decrypt its contents with the system key
//
try {
$userTuple = Crypto::decrypt(base64_decode($_COOKIE[self::COOKIE_USER]), $systemKey);
if (strpos($userTuple, ':') === false) {
throw new \Exception();
}
// paranoid, make sure we have everything we need
@list($cookieUserId, $hashCookieSuffix) = @explode(":", $userTuple, 2);
if (!isset($cookieUserId, $hashCookieSuffix) || !is_numeric($cookieUserId) || !trim($hashCookieSuffix)) {
throw new \Exception();
}
/** @var AuthenticationRecordInterface $auth */
if (!($auth = $this->authenticationProvider->findByUserId($cookieUserId))) {
throw new \Exception();
}
$hashCookieName = self::COOKIE_HASH_PREFIX . $hashCookieSuffix;
//
// 2. Check the hashCookie for corroborating data
//
if (!isset($_COOKIE[$hashCookieName])) {
throw new \Exception();
}
$userKey = new EncryptionKey(new HiddenString($auth->getSessionKey()));
$hashPass = hash_equals(
hash_hmac('sha256', $_COOKIE[$hashCookieName], $userKey),
$_COOKIE[self::COOKIE_VERIFY_B]
);
if (!$hashPass) {
throw new \Exception();
}
//
// 3. Decrypt the hash cookie with the user key
//
$hashedCookieContents = Crypto::decrypt(base64_decode($_COOKIE[$hashCookieName]), $userKey);
if (!substr_count($hashedCookieContents, ':') === 2) {
throw new \Exception();
}
list(, $hashedUserId, $hashedUsername) = explode(':', $hashedCookieContents);
if ($hashedUserId !== $cookieUserId) {
throw new \Exception();
}
if ($hashedUsername !== $auth->getUsername()) {
throw new \Exception();
}
$this->purgeHashCookies($hashCookieName);
//
// 4. Cookies check out - it's up to the user provider now
//
$user = $this->userProvider->getUser($auth->getUserId());
if ($user) {
$this->setIdentity($user);
return $this->identity;
}
} catch (\Exception $x) {
$this->purgeHashCookies();
}
return null;
} | 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 contents encrypted by the system key
- the random-named-cookie has its contents encrypted by the user key
@see self::setSessionCookies
@return User|null | 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, '/', $sp['domain'], false, true);
}
}
} | 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($newPassword, PASSWORD_DEFAULT);
$auth->setHash($hash);
$this->resetAuthenticationKey($auth);
$this->authenticationProvider->update($auth);
} | 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, $auth->getHash());
} | 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);
return $auth;
} | 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 PersistedUserRequiredException | 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->authenticationProvider->findByUsername($username)) {
throw new UsernameTakenException();
}
if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
if ($user->getEmail() !== $username) {
throw new MismatchedEmailsException();
}
if ($emailUser = $this->userProvider->findByEmail($username)) {
if ($emailUser !== $user) {
throw new EmailUsernameTakenException();
}
}
}
$hash = password_hash($password, PASSWORD_DEFAULT);
$auth = $this->authenticationProvider->create(
$user->getId(),
$username,
$hash,
KeyFactory::generateEncryptionKey()->getRawKeyMaterial()
);
$this->authenticationProvider->save($auth);
return $auth;
} | 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
@throws EmailUsernameTakenException
@throws MismatchedEmailsException
@throws PersistedUserRequiredException
@throws UsernameTakenException | 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_VERIFY_A, self::COOKIE_VERIFY_B] as $cookieName) {
setcookie($cookieName, null, null, '/', $sp['domain'], false, true);
}
$this->identity = null;
} | 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());
if (!$auth) {
throw new NoSuchUserException();
}
if ($this->resetTokenProvider->getRequestCount($auth) > 5) {
throw new TooManyRecoveryAttemptsException();
}
$this->resetTokenProvider->invalidateUnusedTokens($auth);
$remote = new RemoteAddress();
$remote->setUseProxy(true);
$token = new UserResetToken($auth, $remote->getIpAddress());
$this->resetTokenProvider->save($token);
return $token;
} | 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->authenticationProvider->findByUserId($user->getId());
if (!$auth) {
throw new NoSuchUserException();
}
$remote = new RemoteAddress();
$remote->setUseProxy(true);
$resetToken = $this->resetTokenProvider->get($tokenId);
if (!$resetToken) {
throw new InvalidResetTokenException();
}
if (!$resetToken->isValid($auth, $token, $remote->getIpAddress(), $this->validateFingerprint, $this->validateIp)) {
throw new InvalidResetTokenException();
}
$this->resetPassword($user, $newPassword);
$resetToken->setStatus(UserResetTokenInterface::STATUS_USED);
$this->resetTokenProvider->update($resetToken);
} | @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,
$previousException
);
} | {@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();
$data['error'] = $exception->getTraceAsString();
$data['line'] = $exception->getLine();
$data['file'] = $exception->getFile();
$data['class'] = get_class($exception);
$data['storage'] = [
'SERVER' => Request::server(),
'GET' => Request::query(),
'POST' => $_POST,
'FILE' => Request::file(),
'OLD' => Request::hasSession() ? Request::old() : [],
'COOKIE' => Request::cookie(),
'SESSION' => Request::hasSession() ? Session::all() : [],
'HEADERS' => Request::header(),
];
$data['storage'] = array_filter($data['storage']);
$count = $this->config['count'];
$lines = file($data['file']);
$data['exegutor'] = [];
for ($i = -1 * abs($count); $i <= abs($count); $i++) {
$data['exegutor'][] = $this->getLineInfo($lines, $data['line'], $i);
}
$data['exegutor'] = array_filter($data['exegutor']);
// to make symfony exception more readable
if ($data['class'] == 'Symfony\Component\Debug\Exception\FatalErrorException') {
preg_match("~^(.+)' in ~", $data['exception'], $matches);
if (isset($matches[1])) {
$data['exception'] = $matches[1];
}
}
return $data;
} | @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 (in_array(env('APP_ENV'), $this->config['environments'])) {
return true;
}
return false;
} | 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> ' . SyntaxHighlight::process($lines[$index]),
'wrap_left' => $i ? '' : '<span class="exception-line">', // color: #F5F5F5; background-color: #5A3E3E; width: 100%; display: block;
'wrap_right' => $i ? '' : '</span>',
];
} | 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('The return URL must be a valid URL with a URI Scheme or http or https.');
}
}
else {
if($altRealm == null)
$return = ($useHttps ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
else
$return = $altRealm . $_SERVER['SCRIPT_NAME'];
}
$params = array(
'openid.ns' => 'http://specs.openid.net/auth/2.0',
'openid.mode' => 'checkid_setup',
'openid.return_to' => $return,
'openid.realm' => $altRealm != null ? $altRealm : (($useHttps ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']),
'openid.identity' => 'http://specs.openid.net/auth/2.0/identifier_select',
'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select',
);
return self::$openId . '?' . http_build_query($params);
} | 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'],
'openid.ns' => 'http://specs.openid.net/auth/2.0',
);
$signed = explode(',', $_GET['openid_signed']);
foreach ($signed as $item) {
$val = $_GET['openid_' . str_replace('.', '_', $item)];
$params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($val) : $val;
}
$params['openid.mode'] = 'check_authentication';
$data = http_build_query($params);
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' =>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($data) . "\r\n",
'content' => $data,
'timeout' => $timeout
),
));
$result = file_get_contents(self::$openId, false, $context);
preg_match("#^https://steamcommunity.com/openid/id/([0-9]{17,25})#", $_GET['openid_claimed_id'], $matches);
$steamID64 = is_numeric($matches[1]) ? $matches[1] : 0;
$response = preg_match("#is_valid\s*:\s*true#i", $result) == 1 ? $steamID64 : null;
} catch (Exception $e) {
$response = null;
}
if (is_null($response)) {
throw new Exception('The Steam login request timed out or was invalid');
}
return $response;
} | 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 total')
->where('r.authentication = :authentication')
->andWhere('r.request_time > :since')
->setParameter('authentication', $authenticationRecord)
->setParameter('since', $fiveMinutesAgo)
->getQuery();
return $query->getSingleScalarResult();
} | 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')
->andWhere('r.status = :status_unused')
->setParameters([
'authentication' => $authenticationRecord,
'status_unused' => UserResetTokenInterface::STATUS_UNUSED,
])
->getQuery();
$query->execute();
} | 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_get('xdebug.overload_var_dump'))
// false means that it was not set (and the default is on) or it explicitly enabled
// xdebug.overload_var_dump produces HTML only when html_errors is also enabled
&& (false === ini_get('html_errors') || ini_get('html_errors'))
|| 'cli' === PHP_SAPI;
return [
new Twig_SimpleFunction('d', [$this, 'd']),
new Twig_SimpleFunction('dd', [$this, 'dd']),
new Twig_Function('dump', [$this, 'dump'], [
'is_safe' => $isDumpOutputHtmlSafe ? ['html'] : [],
'needs_context' => true,
'needs_environment' => true,
]),
];
} | 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[$key] = $value;
}
}
}
ob_start();
VarDumper::dump($vars);
echo ob_get_clean();
} | 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) == '<!--') {
$this->tokens[$id] = '<span class="exception-comment">' . $match . '</span>'; // #7F9F7F
} else {
$this->tokens[$id] = '<span class="exception-string">' . $match . '</span>'; // #CC9385
}
return $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()) {
return $input; // Nothing to do.
}
if (($benchmark = !empty($this->options['benchmark']))) {
$time = microtime(true);
}
$html = &$input; // Raw HTML.
$is_valid_utf8 = $this->isValidUtf8($html);
if ($is_valid_utf8) { // Must have valid UTF-8.
if (!empty($this->options['amp_exclusions_enable']) && $this->isDocAmpd($html)) {
$this->options['compress_combine_head_body_css'] = false;
$this->options['compress_combine_head_js'] = false;
$this->options['compress_combine_footer_js'] = false;
$this->options['compress_combine_remote_css_js'] = false;
} // This auto-enables AMP compatibility.
$html = $this->tokenizeGlobalExclusions($html);
$html = $this->maybeCompressCombineHeadBodyCss($html);
$html = $this->maybeCompressCombineHeadJs($html);
$html = $this->maybeCompressCombineFooterJs($html);
$html = $this->maybeCompressInlineJsCode($html);
$html = $this->maybeCompressInlineJsonCode($html);
$html = $this->restoreGlobalExclusions($html);
$html = $this->maybeCompressHtmlCode($html);
}
if (!isset($this->options['cleanup_cache_dirs']) || $this->options['cleanup_cache_dirs']) {
mt_rand(1, 20) === 1 ? $this->cleanupCacheDirs() : null;
}
if ($benchmark && !empty($time)) {
$time = number_format(microtime(true) - $time, 5, '.', '');
if ($this->benchmark->times) {
$html .= "\n"; // Spacer.
}
foreach ($this->benchmark->times as $_benchmark_time) {
$html .= "\n".'<!-- '.sprintf(
'%1$s took %2$s seconds %3$s.',
htmlspecialchars($this->product_title, ENT_NOQUOTES, 'UTF-8'),
htmlspecialchars($_benchmark_time['time'], ENT_NOQUOTES, 'UTF-8'),
htmlspecialchars($_benchmark_time['task'], ENT_NOQUOTES, 'UTF-8')
).' -->';
} // unset($_benchmark_time); // Housekeeping.
if (!$is_valid_utf8) {
$html .= "\n\n".'<!-- '.sprintf(
'%1$s did not run; HTML contains invalid UTF-8.',
htmlspecialchars($this->product_title, ENT_NOQUOTES, 'UTF-8')
).' -->';
} else {
$html .= "\n\n".'<!-- '.sprintf(
'%1$s took %2$s seconds (overall).',
htmlspecialchars($this->product_title, ENT_NOQUOTES, 'UTF-8'),
htmlspecialchars($time, ENT_NOQUOTES, 'UTF-8')
).' -->';
}
}
return $html; // HTML markup.
} | 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 input passed into this routine.
@return string Compressed HTML code (if at all possible). Note that `$input` must be HTML code.
i.e. It must contain a closing `</html>` tag; otherwise no compression will occur. | 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,
function ($m) use ($_this) {
$_this->current_global_exclusion_tokens[] = $m[0]; // Tokenize.
return '<htmlc-gxt-'.(count($_this->current_global_exclusion_tokens) - 1).' />';
},
$html // Exclusions replaced by tokens.
);
return $html;
} | 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.
}
foreach (array_reverse($this->current_global_exclusion_tokens, true) as $_token => $_value) {
// Must go in reverse order so nested tokens unfold properly.
$html = str_replace('<htmlc-gxt-'.$_token.' />', $_value, $html);
} // unset($_token, $_value); // Housekeeping.
$this->current_global_exclusion_tokens = [];
return $html;
} | 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 false;
} | 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_combine_head_body_css'])) {
if (!$this->options['compress_combine_head_body_css']) {
$disabled = true; // Disabled flag.
}
}
if (!$html || !empty($disabled)) {
goto finale; // Nothing to do.
}
if (($html_frag = $this->getHtmlFrag($html)) && ($head_frag = $this->getHeadFrag($html))) {
if (($css_tag_frags = $this->getCssTagFrags($html_frag)) && ($css_parts = $this->compileCssTagFragsIntoParts($css_tag_frags, 'head'))) {
$css_tag_frags_all_compiled = $this->compileKeyElementsDeep($css_tag_frags, 'all');
$html = $this->replaceOnce($head_frag['all'], '%%htmlc-head%%', $html);
$html = $this->replaceOnce($css_tag_frags_all_compiled, '', $html);
$cleaned_head_contents = $this->replaceOnce($css_tag_frags_all_compiled, '', $head_frag['contents']);
$cleaned_head_contents = $this->cleanupSelfClosingHtmlTagLines($cleaned_head_contents);
$compressed_css_tags = []; // Initialize.
foreach ($css_parts as $_css_part) {
if (isset($_css_part['exclude_frag'], $css_tag_frags[$_css_part['exclude_frag']]['all'])) {
$compressed_css_tags[] = $css_tag_frags[$_css_part['exclude_frag']]['all'];
} else {
$compressed_css_tags[] = $_css_part['tag'];
}
} // unset($_css_part); // Housekeeping.
$compressed_css_tags = implode("\n", $compressed_css_tags);
$compressed_head_parts = [$head_frag['open_tag'], $cleaned_head_contents, $compressed_css_tags, $head_frag['closing_tag']];
$html = $this->replaceOnce('%%htmlc-head%%', implode("\n", $compressed_head_parts), $html);
if ($benchmark) {
$this->benchmark->addData(
__FUNCTION__,
compact(
'head_frag',
'css_tag_frags',
'css_parts',
'cleaned_head_contents',
'compressed_css_tags',
'compressed_head_parts'
)
);
}
}
}
finale: // Target point; finale/return value.
if ($html) {
$html = trim($html);
} // Trim it up now!
if ($benchmark && !empty($time) && $html && empty($disabled)) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compressing/combining head/body CSS in checksum: `%1$s`', md5($html))
);
}
return $html; // With possible compression having been applied here.
} | 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 = []; // Initialize.
$css_parts_checksum = ''; // Initialize.
if (!$css_tag_frags) {
goto finale; // Nothing to do.
}
$css_parts_checksum = $this->getTagFragsChecksum($css_tag_frags);
$public_cache_dir = $this->cacheDir($this::DIR_PUBLIC_TYPE, $css_parts_checksum);
$private_cache_dir = $this->cacheDir($this::DIR_PRIVATE_TYPE, $css_parts_checksum);
$public_cache_dir_url = $this->cacheDirUrl($this::DIR_PUBLIC_TYPE, $css_parts_checksum);
$cache_parts_file = $css_parts_checksum.'-compressor-parts.css-cache';
$cache_parts_file_path = $private_cache_dir.'/'.$cache_parts_file;
$cache_parts_file_path_tmp = $cache_parts_file_path.'.'.uniqid('', true).'.tmp';
// Cache file creation is atomic; i.e. tmp file w/ rename.
$cache_part_file = '%%code-checksum%%-compressor-part.css';
$cache_part_file_path = $public_cache_dir.'/'.$cache_part_file;
$cache_part_file_url = $public_cache_dir_url.'/'.$cache_part_file;
if (is_file($cache_parts_file_path) && filemtime($cache_parts_file_path) > strtotime('-'.$this->cache_expiration_time)) {
if (is_array($cached_parts = unserialize(file_get_contents($cache_parts_file_path)))) {
$css_parts = $cached_parts; // Use cached parts.
goto finale; // Using the cache; all done here.
}
}
$_css_part = 0; // Initialize part counter.
$_last_css_tag_frag_media = 'all'; // Initialize.
foreach ($css_tag_frags as $_css_tag_frag_pos => $_css_tag_frag) {
if ($_css_tag_frag['exclude']) {
if ($_css_tag_frag['link_href'] || $_css_tag_frag['style_css']) {
if ($css_parts) {
++$_css_part; // Starts new part.
}
$css_parts[$_css_part]['tag'] = '';
$css_parts[$_css_part]['exclude_frag'] = $_css_tag_frag_pos;
++$_css_part; // Always indicates a new part in the next iteration.
}
} elseif ($_css_tag_frag['link_href']) {
if (($_css_tag_frag['link_href'] = $this->resolveRelativeUrl($_css_tag_frag['link_href']))) {
if (($_css_code = $this->stripUtf8Bom($this->mustGetUrl($_css_tag_frag['link_href'])))) {
$_css_code = $this->resolveCssRelatives($_css_code, $_css_tag_frag['link_href']);
$_css_code = $this->resolveResolvedCssImports($_css_code, $_css_tag_frag['media']);
if ($_css_code) {
if ($_css_tag_frag['media'] !== $_last_css_tag_frag_media) {
++$_css_part; // Starts new part; different `@media` spec here.
} elseif (!empty($css_parts[$_css_part]['code']) && mb_stripos($css_parts[$_css_part]['code'], '@import') !== false) {
++$_css_part; // Starts new part; existing code contains an @import.
}
$css_parts[$_css_part]['media'] = $_css_tag_frag['media'];
if (!empty($css_parts[$_css_part]['code'])) {
$css_parts[$_css_part]['code'] .= "\n\n".$_css_code;
} else {
$css_parts[$_css_part]['code'] = $_css_code;
}
}
}
}
} elseif ($_css_tag_frag['style_css']) {
$_css_code = $_css_tag_frag['style_css'];
$_css_code = $this->stripUtf8Bom($_css_code);
$_css_code = $this->resolveCssRelatives($_css_code);
$_css_code = $this->resolveResolvedCssImports($_css_code, $_css_tag_frag['media']);
if ($_css_code) {
if ($_css_tag_frag['media'] !== $_last_css_tag_frag_media) {
++$_css_part; // Starts new part; different `@media` spec here.
} elseif (!empty($css_parts[$_css_part]['code']) && mb_stripos($css_parts[$_css_part]['code'], '@import') !== false) {
++$_css_part; // Starts new part; existing code contains an @import.
}
$css_parts[$_css_part]['media'] = $_css_tag_frag['media'];
if (!empty($css_parts[$_css_part]['code'])) {
$css_parts[$_css_part]['code'] .= "\n\n".$_css_code;
} else {
$css_parts[$_css_part]['code'] = $_css_code;
}
}
}
$_last_css_tag_frag_media = $_css_tag_frag['media'];
} // unset($_css_part, $_last_css_tag_frag_media, $_css_tag_frag_pos, $_css_tag_frag, $_css_code);
foreach (array_keys($css_parts = array_values($css_parts)) as $_css_part) {
if (!isset($css_parts[$_css_part]['exclude_frag']) && !empty($css_parts[$_css_part]['code'])) {
$_css_media = 'all'; // Default media value; i.e., `all` media queries.
if (!empty($css_parts[$_css_part]['media'])) {
$_css_media = $css_parts[$_css_part]['media'];
}
$_css_code = $css_parts[$_css_part]['code'];
$_css_code = $this->moveSpecialCssAtRulesToTop($_css_code);
$_css_code = $this->stripPrependCssCharsetUtf8($_css_code);
$_css_code = $this->forceAbsRelativePathsInCss($_css_code);
$_css_code = $this->maybeFilterCssUrls($_css_code);
$_css_code_cs = md5($_css_code); // Before compression.
$_css_code = $this->maybeCompressCssCode($_css_code);
$_css_code_path = str_replace('%%code-checksum%%', $_css_code_cs, $cache_part_file_path);
$_css_code_url = str_replace('%%code-checksum%%', $_css_code_cs, $cache_part_file_url);
$_css_code_url = $this->hook_api->applyFilters('part_url', $_css_code_url, $for);
$_css_code_path_tmp = $_css_code_path.'.'.uniqid('', true).'.tmp';
// Cache file creation is atomic; i.e. tmp file w/ rename.
if (!(file_put_contents($_css_code_path_tmp, $_css_code) && rename($_css_code_path_tmp, $_css_code_path))) {
throw new \Exception(sprintf('Unable to cache CSS code file: `%1$s`.', $_css_code_path));
}
$css_parts[$_css_part]['tag'] = '<link type="text/css" rel="stylesheet" href="'.htmlspecialchars($_css_code_url, ENT_QUOTES, 'UTF-8').'" media="'.htmlspecialchars($_css_media, ENT_QUOTES, 'UTF-8').'" />';
unset($css_parts[$_css_part]['code']); // Ditch this; no need to cache this code too.
}
} // unset($_css_part, $_css_media, $_css_code, $_css_code_cs, $_css_code_path, $_css_code_path_tmp, $_css_code_url);
if (!(file_put_contents($cache_parts_file_path_tmp, serialize($css_parts)) && rename($cache_parts_file_path_tmp, $cache_parts_file_path))) {
throw new \Exception(sprintf('Unable to cache CSS parts into: `%1$s`.', $cache_parts_file_path));
}
finale: // Target point; finale/return value.
if ($benchmark && !empty($time) && $css_parts_checksum) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('building parts based on CSS tag frags in checksum: `%1$s`', $css_parts_checksum)
);
}
return $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 empty array on failure. | 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; // Nothing to do.
}
$regex = '/(?P<all>'.// Entire match.
'(?P<if_open_tag>\<\![^[>]*?\[if\W[^\]]*?\][^>]*?\>\s*)?'.
'(?:(?P<link_self_closing_tag>\<link(?:\s+[^>]*?)?\>)'.// Or a <style></style> tag.
'|(?P<style_open_tag>\<style(?:\s+[^>]*?)?\>)(?P<style_css>.*?)(?P<style_closing_tag>\<\/style\>))'.
'(?P<if_closing_tag>\s*\<\![^[>]*?\[endif\][^>]*?\>)?'.
')/uis'; // Dot matches line breaks.
if (!empty($html_frag['contents']) && preg_match_all($regex, $html_frag['contents'], $_tag_frags, PREG_SET_ORDER)) {
foreach ($_tag_frags as $_tag_frag) {
$_link_href = $_style_css = $_media = ''; // Initialize.
if (($_link_href = $this->getLinkCssHref($_tag_frag, true))) {
$_media = $this->getLinkCssMedia($_tag_frag, false);
} elseif (($_style_css = $this->getStyleCss($_tag_frag, true))) {
$_media = $this->getStyleCssMedia($_tag_frag, false);
}
if ($_link_href || $_style_css) {
$css_tag_frags[] = [
'all' => $_tag_frag['all'],
'if_open_tag' => isset($_tag_frag['if_open_tag']) ? $_tag_frag['if_open_tag'] : '',
'if_closing_tag' => isset($_tag_frag['if_closing_tag']) ? $_tag_frag['if_closing_tag'] : '',
'link_self_closing_tag' => isset($_tag_frag['link_self_closing_tag']) ? $_tag_frag['link_self_closing_tag'] : '',
'link_href_external' => ($_link_href) ? $this->isUrlExternal($_link_href) : false,
'link_href' => $_link_href, // This could also be empty.
'style_open_tag' => isset($_tag_frag['style_open_tag']) ? $_tag_frag['style_open_tag'] : '',
'style_css' => $_style_css, // This could also be empty.
'style_closing_tag' => isset($_tag_frag['style_closing_tag']) ? $_tag_frag['style_closing_tag'] : '',
'media' => $_media ? $_media : 'all', // Default value.
'exclude' => false, // Default value.
];
$_tag_frag_r = &$css_tag_frags[count($css_tag_frags) - 1];
if ($_tag_frag_r['if_open_tag'] || $_tag_frag_r['if_closing_tag']) {
$_tag_frag_r['exclude'] = true;
} elseif ($_tag_frag_r['link_href'] && $_tag_frag_r['link_href_external'] && isset($this->options['compress_combine_remote_css_js']) && !$this->options['compress_combine_remote_css_js']) {
$_tag_frag_r['exclude'] = true;
} elseif ($this->regex_css_exclusions && preg_match($this->regex_css_exclusions, $_tag_frag_r['link_self_closing_tag'].' '.$_tag_frag_r['style_open_tag'].' '.$_tag_frag_r['style_css'])) {
$_tag_frag_r['exclude'] = true;
} elseif ($this->built_in_regex_css_exclusions && preg_match($this->built_in_regex_css_exclusions, $_tag_frag_r['link_self_closing_tag'].' '.$_tag_frag_r['style_open_tag'].' '.$_tag_frag_r['style_css'])) {
$_tag_frag_r['exclude'] = true;
}
}
}
} // unset($_tag_frags, $_tag_frag, $_tag_frag_r, $_link_href, $_style_css, $_media);
finale: // Target point; finale/return value.
if ($benchmark && !empty($time) && $html_frag) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compiling CSS tag frags in checksum: `%1$s`', md5(serialize($html_frag)))
);
}
return $css_tag_frags;
} | 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.com/how-to-create-an-ie-only-stylesheet/
@see http://stackoverflow.com/a/12102131 | 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('/\stype\s*\=\s*(["\'])(?P<value>.+?)\\1/ui', $tag_frag['link_self_closing_tag'], $_m)) {
$type = $_m['value'];
}
} // unset($_m); // Just a little housekeeping.
if (mb_stripos($tag_frag['link_self_closing_tag'], 'rel') !== 0) {
if (preg_match('/\srel\s*\=\s*(["\'])(?P<value>.+?)\\1/ui', $tag_frag['link_self_closing_tag'], $_m)) {
$rel = $_m['value'];
}
} // unset($_m); // Just a little housekeeping.
if ($type && mb_stripos($type, 'css') === false) {
return false; // Not CSS.
}
if ($rel && mb_stripos($rel, 'stylesheet') === false) {
return false; // Not CSS.
}
return true; // Yes, this is CSS.
} | 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') !== 0) {
if (preg_match('/\stype\s*\=\s*(["\'])(?P<value>.+?)\\1/ui', $tag_frag['style_open_tag'], $_m)) {
$type = $_m['value'];
}
} // unset($_m); // Just a little housekeeping.
if ($type && mb_stripos($type, 'css') === false) {
return false; // Not CSS.
}
return true; // Yes, this is CSS.
} | 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'], $_m)) {
return trim($this->nUrlAmps($_m['value']));
} // unset($_m); // Just a little housekeeping.
return ''; // Unable to find an `href` attribute value.
} | 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'], $_m)) {
return trim(mb_strtolower($_m['value']));
} // unset($_m); // Just a little housekeeping.
return ''; // Unable to find a `media` attribute value.
} | 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)) {
return trim(mb_strtolower($_m['value']));
} // unset($_m); // Just a little housekeeping.
return ''; // Unable to find a `media` attribute value.
} | 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.
}
return trim($tag_frag['style_css']); // CSS code.
} | 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.
}
if (mb_stripos($css, 'charset') === false && mb_stripos($css, 'import') === false) {
return $css; // Save some time. Nothing to do here.
}
if (preg_match_all('/(?P<rule>@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?charset(?:\s+[^;]*?)?;)/ui', $css, $rules, PREG_SET_ORDER)
|| preg_match_all('/(?P<rule>@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?import(?:\s+[^;]*?)?;)/ui', $css, $rules, PREG_SET_ORDER)
) { // Searched in a specific order. Recursion dictates a precise order.
$top_rules = []; // Initialize.
foreach ($rules as $_rule) {
$top_rules[] = $_rule['rule'];
} // unset($_rule); // Just a little housekeeping.
$css = $this->replaceOnce($top_rules, '', $css);
$css = $this->moveSpecialCssAtRulesToTop($css, $___recursion + 1);
$css = implode("\n\n", $top_rules)."\n\n".$css;
}
return $css; // With special `@rules` to the top.
} | 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://stackoverflow.com/questions/11746581/nesting-media-rules-in-css> | 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';
}
$import_media_without_url_regex = '/@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?import\s*(["\'])(?P<url>.+?)\\1(?P<media>[^;]*?);/ui';
$import_media_with_url_regex = '/@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?import\s+url\s*\(\s*(["\']?)(?P<url>.+?)\\1\s*\)(?P<media>[^;]*?);/ui';
$css = preg_replace_callback($import_media_without_url_regex, [$this, 'resolveResolvedCssImportsCb'], $css);
$css = preg_replace_callback($import_media_with_url_regex, [$this, 'resolveResolvedCssImportsCb'], $css);
if (preg_match_all($import_media_without_url_regex, $css, $_m)) {
foreach ($_m['media'] as $_media) {
if (!$_media || $_media === $this->current_css_media) {
return $this->resolveResolvedCssImports($css, $this->current_css_media, true);
}
} // unset($_media);
} // unset($_m); // Housekeeping.
if (preg_match_all($import_media_with_url_regex, $css, $_m)) {
foreach ($_m['media'] as $_media) {
if (!$_media || $_media === $this->current_css_media) {
return $this->resolveResolvedCssImports($css, $this->current_css_media, true);
}
} // unset($_media);
} // unset($_m); // Housekeeping.
return $css;
} | 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 = $this->stripUtf8Bom($this->mustGetUrl($m['url'])))) {
$css = $this->resolveCssRelatives($css, $m['url']);
}
return $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>@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?import\s*)(?P<open_encap>["\'])(?P<url>.+?)(?P<close_encap>\\2)/ui';
$any_url_regex = '/(?P<url_>url\s*)(?P<open_bracket>\(\s*)(?P<open_encap>["\']?)(?P<url>.+?)(?P<close_encap>\\3)(?P<close_bracket>\s*\))/ui';
$css = preg_replace_callback($import_without_url_regex, [$this, 'resolveCssRelativesImportCb'], $css);
$css = preg_replace_callback($any_url_regex, [$this, 'resolveCssRelativesUrlCb'], $css);
return $css;
} | 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['close_bracket'];
} | 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>@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?import\s*)(?P<open_encap>["\'])(?P<url>.+?)(?P<close_encap>\\2)/ui';
$any_url_regex = '/(?P<url_>url\s*)(?P<open_bracket>\(\s*)(?P<open_encap>["\']?)(?P<url>.+?)(?P<close_encap>\\3)(?P<close_bracket>\s*\))/ui';
$css = preg_replace_callback($import_without_url_regex, [$this, 'filterCssUrlImportCb'], $css);
$css = preg_replace_callback($any_url_regex, [$this, 'filterCssUrlCb'], $css);
return $css;
} | 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_combine_head_js'])) {
if (!$this->options['compress_combine_head_js']) {
$disabled = true; // Disabled flag.
}
}
if (!$html || !empty($disabled)) {
goto finale; // Nothing to do.
}
if (($head_frag = $this->getHeadFrag($html)) /* No need to get the HTML frag here; we're operating on the `<head>` only. */) {
if (($js_tag_frags = $this->getJsTagFrags($head_frag)) && ($js_parts = $this->compileJsTagFragsIntoParts($js_tag_frags, 'head'))) {
$js_tag_frags_all_compiled = $this->compileKeyElementsDeep($js_tag_frags, 'all');
$html = $this->replaceOnce($head_frag['all'], '%%htmlc-head%%', $html);
$cleaned_head_contents = $this->replaceOnce($js_tag_frags_all_compiled, '', $head_frag['contents']);
$cleaned_head_contents = $this->cleanupSelfClosingHtmlTagLines($cleaned_head_contents);
$compressed_js_tags = []; // Initialize.
foreach ($js_parts as $_js_part) {
if (isset($_js_part['exclude_frag'], $js_tag_frags[$_js_part['exclude_frag']]['all'])) {
$compressed_js_tags[] = $js_tag_frags[$_js_part['exclude_frag']]['all'];
} else {
$compressed_js_tags[] = $_js_part['tag'];
}
} // unset($_js_part); // Housekeeping.
$compressed_js_tags = implode("\n", $compressed_js_tags);
$compressed_head_parts = [$head_frag['open_tag'], $cleaned_head_contents, $compressed_js_tags, $head_frag['closing_tag']];
$html = $this->replaceOnce('%%htmlc-head%%', implode("\n", $compressed_head_parts), $html);
if ($benchmark) {
$this->benchmark->addData(
__FUNCTION__,
compact(
'head_frag',
'js_tag_frags',
'js_parts',
'cleaned_head_contents',
'compressed_js_tags',
'compressed_head_parts'
)
);
}
}
}
finale: // Target point; finale/return value.
if ($html) {
$html = trim($html);
} // Trim it up now!
if ($benchmark && !empty($time) && $html && empty($disabled)) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compressing/combining head JS in checksum: `%1$s`', md5($html))
);
}
return $html; // With possible compression having been applied here.
} | 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_combine_footer_js'])) {
if (!$this->options['compress_combine_footer_js']) {
$disabled = true; // Disabled flag.
}
}
if (!$html || !empty($disabled)) {
goto finale; // Nothing to do.
}
if (($footer_scripts_frag = $this->getFooterScriptsFrag($html)) /* e.g. <!-- footer-scripts --><!-- footer-scripts --> */) {
if (($js_tag_frags = $this->getJsTagFrags($footer_scripts_frag)) && ($js_parts = $this->compileJsTagFragsIntoParts($js_tag_frags, 'foot'))) {
$js_tag_frags_all_compiled = $this->compileKeyElementsDeep($js_tag_frags, 'all');
$html = $this->replaceOnce($footer_scripts_frag['all'], '%%htmlc-footer-scripts%%', $html);
$cleaned_footer_scripts = $this->replaceOnce($js_tag_frags_all_compiled, '', $footer_scripts_frag['contents']);
$compressed_js_tags = []; // Initialize.
foreach ($js_parts as $_js_part) {
if (isset($_js_part['exclude_frag'], $js_tag_frags[$_js_part['exclude_frag']]['all'])) {
$compressed_js_tags[] = $js_tag_frags[$_js_part['exclude_frag']]['all'];
} else {
$compressed_js_tags[] = $_js_part['tag'];
}
} // unset($_js_part); // Housekeeping.
$compressed_js_tags = implode("\n", $compressed_js_tags);
$compressed_footer_script_parts = [$footer_scripts_frag['open_tag'], $cleaned_footer_scripts, $compressed_js_tags, $footer_scripts_frag['closing_tag']];
$html = $this->replaceOnce('%%htmlc-footer-scripts%%', implode("\n", $compressed_footer_script_parts), $html);
if ($benchmark) {
$this->benchmark->addData(
__FUNCTION__,
compact(
'footer_scripts_frag',
'js_tag_frags',
'js_parts',
'cleaned_footer_scripts',
'compressed_js_tags',
'compressed_footer_script_parts'
)
);
}
}
}
finale: // Target point; finale/return value.
if ($html) {
$html = trim($html);
} // Trim it up now!
if ($benchmark && !empty($time) && $html && empty($disabled)) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compressing/combining footer JS in checksum: `%1$s`', md5($html))
);
}
return $html; // With possible compression having been applied here.
} | 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 = []; // Initialize.
$js_parts_checksum = ''; // Initialize.
if (!$js_tag_frags) {
goto finale; // Nothing to do.
}
$js_parts_checksum = $this->getTagFragsChecksum($js_tag_frags);
$public_cache_dir = $this->cacheDir($this::DIR_PUBLIC_TYPE, $js_parts_checksum);
$private_cache_dir = $this->cacheDir($this::DIR_PRIVATE_TYPE, $js_parts_checksum);
$public_cache_dir_url = $this->cacheDirUrl($this::DIR_PUBLIC_TYPE, $js_parts_checksum);
$cache_parts_file = $js_parts_checksum.'-compressor-parts.js-cache';
$cache_parts_file_path = $private_cache_dir.'/'.$cache_parts_file;
$cache_parts_file_path_tmp = $cache_parts_file_path.'.'.uniqid('', true).'.tmp';
// Cache file creation is atomic; i.e. tmp file w/ rename.
$cache_part_file = '%%code-checksum%%-compressor-part.js';
$cache_part_file_path = $public_cache_dir.'/'.$cache_part_file;
$cache_part_file_url = $public_cache_dir_url.'/'.$cache_part_file;
if (is_file($cache_parts_file_path) && filemtime($cache_parts_file_path) > strtotime('-'.$this->cache_expiration_time)) {
if (is_array($cached_parts = unserialize(file_get_contents($cache_parts_file_path)))) {
$js_parts = $cached_parts; // Use cached parts.
goto finale; // Using the cache; we're all done here.
}
}
$_js_part = 0; // Initialize part counter.
foreach ($js_tag_frags as $_js_tag_frag_pos => $_js_tag_frag) {
if ($_js_tag_frag['exclude']) {
if ($_js_tag_frag['script_src'] || $_js_tag_frag['script_js'] || $_js_tag_frag['script_json']) {
if ($js_parts) {
++$_js_part; // Starts new part.
}
$js_parts[$_js_part]['tag'] = '';
$js_parts[$_js_part]['exclude_frag'] = $_js_tag_frag_pos;
++$_js_part; // Always indicates a new part in the next iteration.
}
} elseif ($_js_tag_frag['script_src']) {
if (($_js_tag_frag['script_src'] = $this->resolveRelativeUrl($_js_tag_frag['script_src']))) {
if (($_js_code = $this->stripUtf8Bom($this->mustGetUrl($_js_tag_frag['script_src'])))) {
$_js_code = rtrim($_js_code, ';').';';
if ($_js_code) {
if (!empty($js_parts[$_js_part]['code'])) {
$js_parts[$_js_part]['code'] .= "\n\n".$_js_code;
} else {
$js_parts[$_js_part]['code'] = $_js_code;
}
}
}
}
} elseif ($_js_tag_frag['script_js']) {
$_js_code = $_js_tag_frag['script_js'];
$_js_code = $this->stripUtf8Bom($_js_code);
$_js_code = rtrim($_js_code, ';').';';
if ($_js_code) {
if (!empty($js_parts[$_js_part]['code'])) {
$js_parts[$_js_part]['code'] .= "\n\n".$_js_code;
} else {
$js_parts[$_js_part]['code'] = $_js_code;
}
}
} elseif ($_js_tag_frag['script_json']) {
if ($js_parts) {
++$_js_part; // Starts new part.
}
$js_parts[$_js_part]['tag'] = $_js_tag_frag['all'];
++$_js_part; // Always indicates a new part in the next iteration.
}
} // unset($_js_part, $_js_tag_frag_pos, $_js_tag_frag, $_js_code);
foreach (array_keys($js_parts = array_values($js_parts)) as $_js_part) {
if (!isset($js_parts[$_js_part]['exclude_frag']) && !empty($js_parts[$_js_part]['code'])) {
$_js_code = $js_parts[$_js_part]['code'];
$_js_code_cs = md5($_js_code); // Before compression.
$_js_code = $this->maybeCompressJsCode($_js_code);
$_js_code_path = str_replace('%%code-checksum%%', $_js_code_cs, $cache_part_file_path);
$_js_code_url = str_replace('%%code-checksum%%', $_js_code_cs, $cache_part_file_url);
$_js_code_url = $this->hook_api->applyFilters('part_url', $_js_code_url, $for);
$_js_code_path_tmp = $_js_code_path.'.'.uniqid('', true).'.tmp';
// Cache file creation is atomic; e.g. tmp file w/ rename.
if (!(file_put_contents($_js_code_path_tmp, $_js_code) && rename($_js_code_path_tmp, $_js_code_path))) {
throw new \Exception(sprintf('Unable to cache JS code file: `%1$s`.', $_js_code_path));
}
$js_parts[$_js_part]['tag'] = '<script type="text/javascript" src="'.htmlspecialchars($_js_code_url, ENT_QUOTES, 'UTF-8').'"></script>';
unset($js_parts[$_js_part]['code']); // Ditch this; no need to cache this code too.
}
} // unset($_js_part, $_js_code, $_js_code_cs, $_js_code_path, $_js_code_path_tmp, $_js_code_url);
if (!(file_put_contents($cache_parts_file_path_tmp, serialize($js_parts)) && rename($cache_parts_file_path_tmp, $cache_parts_file_path))) {
throw new \Exception(sprintf('Unable to cache JS parts into: `%1$s`.', $cache_parts_file_path));
}
finale: // Target point; finale/return value.
if ($benchmark && !empty($time) && $js_parts_checksum) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('building parts based on JS tag frags in checksum: `%1$s`', $js_parts_checksum)
);
}
return $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 array on failure. | 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; // Nothing to do.
}
$regex = '/(?P<all>'.// Entire match.
'(?P<if_open_tag>\<\![^[>]*?\[if\W[^\]]*?\][^>]*?\>\s*)?'.
'(?P<script_open_tag>\<script(?:\s+[^>]*?)?\>)(?P<script_js>.*?)(?P<script_closing_tag>\<\/script\>)'.
'(?P<if_closing_tag>\s*\<\![^[>]*?\[endif\][^>]*?\>)?'.
')/uis'; // Dot matches line breaks.
if (!empty($html_frag['contents']) && preg_match_all($regex, $html_frag['contents'], $_tag_frags, PREG_SET_ORDER)) {
foreach ($_tag_frags as $_tag_frag) {
if (isset($_tag_frag['script_js'])) {
$_tag_frag['script_json'] = $_tag_frag['script_js'];
} // Assume that this is either/or for the time being.
$_script_src = $_script_js = $_script_json = $_script_async = ''; // Initialize.
$_is_js = $this->isScriptTagFragJs($_tag_frag); // JavaScript or JSON?
$_is_json = !$_is_js && $this->isScriptTagFragJson($_tag_frag);
if ($_is_js || $_is_json) {
if ($_is_js && ($_script_src = $this->getScriptJsSrc($_tag_frag, false))) {
$_script_async = $this->getScriptJsAsync($_tag_frag, false);
} elseif ($_is_js && ($_script_js = $this->getScriptJs($_tag_frag, false))) {
$_script_async = $this->getScriptJsAsync($_tag_frag, false);
} elseif ($_is_json && ($_script_json = $this->getScriptJson($_tag_frag, false))) {
$_script_async = ''; // Not applicable.
}
if ($_script_src || $_script_js || $_script_json) {
$js_tag_frags[] = [
'all' => $_tag_frag['all'],
'if_open_tag' => isset($_tag_frag['if_open_tag']) ? $_tag_frag['if_open_tag'] : '',
'if_closing_tag' => isset($_tag_frag['if_closing_tag']) ? $_tag_frag['if_closing_tag'] : '',
'script_open_tag' => isset($_tag_frag['script_open_tag']) ? $_tag_frag['script_open_tag'] : '',
'script_src_external' => $_is_js && $_script_src ? $this->isUrlExternal($_script_src) : false,
'script_src' => $_is_js ? $_script_src : '', // This could also be empty.
'script_js' => $_is_js ? $_script_js : '', // This could also be empty.
'script_json' => $_is_json ? $_script_json : '', // This could also be empty.
'script_async' => $_is_js ? $_script_async : '', // This could also be empty.
'script_closing_tag' => isset($_tag_frag['script_closing_tag']) ? $_tag_frag['script_closing_tag'] : '',
'exclude' => false, // Default value.
];
$_tag_frag_r = &$js_tag_frags[count($js_tag_frags) - 1];
if ($_tag_frag_r['if_open_tag'] || $_tag_frag_r['if_closing_tag'] || $_tag_frag_r['script_async']) {
$_tag_frag_r['exclude'] = true;
} elseif ($_tag_frag_r['script_src'] && $_tag_frag_r['script_src_external'] && isset($this->options['compress_combine_remote_css_js']) && !$this->options['compress_combine_remote_css_js']) {
$_tag_frag_r['exclude'] = true;
} elseif ($this->regex_js_exclusions && preg_match($this->regex_js_exclusions, $_tag_frag_r['script_open_tag'].' '.$_tag_frag_r['script_js'].$_tag_frag_r['script_json'])) {
$_tag_frag_r['exclude'] = true;
} elseif ($this->built_in_regex_js_exclusions && preg_match($this->built_in_regex_js_exclusions, $_tag_frag_r['script_open_tag'].' '.$_tag_frag_r['script_js'].$_tag_frag_r['script_json'])) {
$_tag_frag_r['exclude'] = true;
}
}
}
} // unset($_tag_frags, $_tag_frag, $_tag_frag_r, $_script_src, $_script_js, $_script_json, $_script_async, $_is_js, $_is_json);
}
finale: // Target point; finale/return value.
if ($benchmark && !empty($time) && $html_frag) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compiling JS tag frags in checksum: `%1$s`', md5(serialize($html_frag)))
);
}
return $js_tag_frags;
} | 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/how-to-create-an-ie-only-stylesheet/
@see http://stackoverflow.com/a/12102131 | 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_tag'], 'type') !== 0) {
if (preg_match('/\stype\s*\=\s*(["\'])(?P<value>.+?)\\1/ui', $tag_frag['script_open_tag'], $_m)) {
$type = $_m['value'];
}
} // unset($_m); // Just a little housekeeping.
if (mb_stripos($tag_frag['script_open_tag'], 'language') !== 0) {
if (preg_match('/\slanguage\s*\=\s*(["\'])(?P<value>.+?)\\1/ui', $tag_frag['script_open_tag'], $_m)) {
$language = $_m['value'];
}
} // unset($_m); // Just a little housekeeping.
if (($type && mb_stripos($type, 'javascript') === false) || ($language && mb_stripos($language, 'javascript') === false)) {
if ($type && mb_stripos($type, 'json') !== false) {
return true; // Yes, this is JSON.
}
if ($language && mb_stripos($language, 'json') !== false) {
return true; // Yes, this is JSON.
}
}
return false; // No, not JSON.
} | 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_tag'], $_m)) {
return trim($this->nUrlAmps($_m['value']));
} // unset($_m); // Just a little housekeeping.
return ''; // Unable to find an `src` attribute value.
} | 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|async|defer)\\1)/ui', $tag_frag['script_open_tag'], $_m)) {
return 'async'; // Yes, load this asynchronously.
} // unset($_m); // Just a little housekeeping.
return ''; // Unable to find a TRUE `async|defer` attribute.
} | 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 an empty string. | 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 JavaScript.
}
return trim($tag_frag['script_js']); // JavaScript code.
} | 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 JSON.
}
return trim($tag_frag['script_json']); // JSON code.
} | 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 (if possible); else an empty string. | 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->removeNumericKeysDeep($html_frag);
}
return [];
} | 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->removeNumericKeysDeep($head_frag);
}
return [];
} | 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)) {
return $this->removeNumericKeysDeep($head_frag);
}
return [];
} | 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.
@return string MD5 checksum. | 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'])) {
if (!$this->options['compress_html_code']) {
$disabled = true; // Disabled flag.
}
}
if (!$html || !empty($disabled)) {
goto finale; // Nothing to do.
}
if (($compressed_html = $this->compressHtml($html))) {
$html = $compressed_html; // Use it :-)
}
finale: // Target point; finale/return value.
if ($html) {
$html = trim($html);
} // Trim it up now!
if ($benchmark && !empty($time) && $html && empty($disabled)) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compressing HTML w/ checksum: `%1$s`', md5($html))
);
}
return $html; // With possible compression having been applied here.
} | 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['preservations'] = [
'special_tags' => '\<(pre|code|script|style|textarea)(?:\s+[^>]*?)?\>.*?\<\/\\2>',
'ie_conditional_comments' => '\<\![^[>]*?\[if\W[^\]]*?\][^>]*?\>.*?\<\![^[>]*?\[endif\][^>]*?\>',
'special_attributes' => '\s(?:style|on[a-z]+)\s*\=\s*(["\']).*?\\3',
];
$static['preservations'] = // Implode for regex capture.
'/(?P<preservation>'.implode('|', $static['preservations']).')/uis';
$static['compressions']['remove_html_comments'] = '/\<\!\-{2}.*?\-{2}\>/uis';
$static['compress_with']['remove_html_comments'] = '';
$static['compressions']['remove_extra_whitespace'] = '/\s+/u';
$static['compress_with']['remove_extra_whitespace'] = ' ';
$static['compressions']['remove_extra_whitespace_in_self_closing_tags'] = '/\s+\/\>/u';
$static['compress_with']['remove_extra_whitespace_in_self_closing_tags'] = '/>';
}
if (preg_match_all($static['preservations'], $html, $preservation_matches, PREG_SET_ORDER)) {
foreach ($preservation_matches as $_preservation_match_key => $_preservation_match) {
$preservations[] = $_preservation_match['preservation'];
$preservation_placeholders[] = '%%minify-html-'.$_preservation_match_key.'%%';
} // unset($_preservation_match_key, $_preservation_match);
if (isset($preservations, $preservation_placeholders)) {
$html = $this->replaceOnce($preservations, $preservation_placeholders, $html);
}
}
$html = preg_replace($static['compressions'], $static['compress_with'], $html);
if (isset($preservations, $preservation_placeholders)) {
$html = $this->replaceOnce($preservation_placeholders, $preservations, $html);
}
return $html ? trim($html) : $html;
} | 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 `pre/code/script/style/textarea` tags.
It also preserves conditional comments and JavaScript `on(click|blur|etc)` attributes.
@see http://stackoverflow.com/a/12102131 | 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'])) {
if (!$this->options['compress_css_code']) {
$disabled = true; // Disabled flag.
}
}
if (!$css || !empty($disabled)) {
goto finale; // Nothing to do.
}
if (strlen($css) > 1000000) {
// Exclude VERY large files. Too time-consuming.
// Should really be compressed ahead-of-time anyway.
goto finale; // Don't compress HUGE files.
}
try { // Catch CSS compression-related exceptions.
if (!($compressed_css = \WebSharks\CssMinifier\Core::compress($css))) {
// `E_USER_NOTICE` to avoid a show-stopping problem.
trigger_error('CSS compression failure.', E_USER_NOTICE);
} else {
$css = $this->stripUtf8Bom($compressed_css);
} // Use compressed CSS file.
} catch (\Exception $exception) {
trigger_error($exception->getMessage(), E_USER_NOTICE);
}
finale: // Target point; finale/return value.
if ($css) {
$css = trim($css);
}
if ($benchmark && !empty($time) && $css && empty($disabled)) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compressing CSS w/ checksum: `%1$s`', md5($css))
);
}
return $css;
} | 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'])) {
if (!$this->options['compress_js_code']) {
$disabled = true; // Disabled flag.
}
}
if (!$js || !empty($disabled)) {
goto finale; // Nothing to do.
}
if (strlen($js) > 1000000) {
// Exclude VERY large files. Too time-consuming.
// Should really be compressed ahead-of-time anyway.
goto finale; // Don't compress HUGE files.
}
try { // Catch JS compression-related exceptions.
if (!($compressed_js = \WebSharks\JsMinifier\Core::compress($js))) {
// `E_USER_NOTICE` to avoid a show-stopping problem.
trigger_error('JS compression failure.', E_USER_NOTICE);
} else {
$js = $compressed_js;
} // Use compressed JS file.
} catch (\Exception $exception) {
trigger_error($exception->getMessage(), E_USER_NOTICE);
}
finale: // Target point; finale/return value.
if ($js) {
$js = trim($js);
}
if ($benchmark && !empty($time) && $js && empty($disabled)) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compressing JS w/ checksum: `%1$s`', md5($js))
);
}
return $js;
} | 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_code'])) {
if (!$this->options['compress_js_code']) {
$disabled = true; // Disabled flag.
}
}
if (isset($this->options['compress_inline_js_code'])) {
if (!$this->options['compress_inline_js_code']) {
$disabled = true; // Disabled flag.
}
}
if (!$html || !empty($disabled)) {
goto finale; // Nothing to do.
}
if (($html_frag = $this->getHtmlFrag($html)) && ($js_tag_frags = $this->getJsTagFrags($html_frag))) {
foreach ($js_tag_frags as $_js_tag_frag_key => $_js_tag_frag) {
if (!$_js_tag_frag['exclude'] && $_js_tag_frag['script_js']) {
$js_tag_frags_script_js_parts[] = $_js_tag_frag['all'];
$js_tag_frags_script_js_part_placeholders[] = '%%htmlc-'.$_js_tag_frag_key.'%%';
$js_tag_frags_script_js_part_placeholder_key_replacements[] = $_js_tag_frag_key;
}
} // unset($_js_tag_frag_key, $_js_tag_frag); // Housekeeping.
if (isset($js_tag_frags_script_js_parts, $js_tag_frags_script_js_part_placeholders, $js_tag_frags_script_js_part_placeholder_key_replacements)) {
$html = $this->replaceOnce($js_tag_frags_script_js_parts, $js_tag_frags_script_js_part_placeholders, $html);
foreach ($js_tag_frags_script_js_part_placeholder_key_replacements as &$_js_tag_frag_key_replacement) {
$_js_tag_frag = $js_tag_frags[$_js_tag_frag_key_replacement];
$_js_tag_frag_key_replacement = $_js_tag_frag['if_open_tag'];
$_js_tag_frag_key_replacement .= $_js_tag_frag['script_open_tag'];
$_js_tag_frag_key_replacement .= $this->compressInlineJsCode($_js_tag_frag['script_js']);
$_js_tag_frag_key_replacement .= $_js_tag_frag['script_closing_tag'];
$_js_tag_frag_key_replacement .= $_js_tag_frag['if_closing_tag'];
} // unset($_js_tag_frag_key_replacement, $_js_tag_frag); // Housekeeping.
$html = $this->replaceOnce($js_tag_frags_script_js_part_placeholders, $js_tag_frags_script_js_part_placeholder_key_replacements, $html);
if ($benchmark) {
$this->benchmark->addData(
__FUNCTION__,
compact(
'js_tag_frags',
'js_tag_frags_script_js_parts',
'js_tag_frags_script_js_part_placeholders',
'js_tag_frags_script_js_part_placeholder_key_replacements'
)
);
}
}
}
finale: // Target point; finale/return value.
if ($html) {
$html = trim($html);
} // Trim it up now!
if ($benchmark && !empty($time) && $html && empty($disabled)) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compressing inline JS in checksum: `%1$s`', md5($html))
);
}
return $html; // With possible compression having been applied here.
} | 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_code'])) {
if (!$this->options['compress_js_code']) {
$disabled = true; // Disabled flag.
}
}
if (isset($this->options['compress_inline_js_code'])) {
if (!$this->options['compress_inline_js_code']) {
$disabled = true; // Disabled flag.
}
}
if (!$html || !empty($disabled)) {
goto finale; // Nothing to do.
}
if (($html_frag = $this->getHtmlFrag($html)) && ($js_tag_frags = $this->getJsTagFrags($html_frag))) {
foreach ($js_tag_frags as $_js_tag_frag_key => $_js_tag_frag) {
if (!$_js_tag_frag['exclude'] && $_js_tag_frag['script_json']) {
$js_tag_frags_script_json_parts[] = $_js_tag_frag['all'];
$js_tag_frags_script_json_part_placeholders[] = '%%htmlc-'.$_js_tag_frag_key.'%%';
$js_tag_frags_script_json_part_placeholder_key_replacements[] = $_js_tag_frag_key;
}
} // unset($_js_tag_frag_key, $_js_tag_frag); // Housekeeping.
if (isset($js_tag_frags_script_json_parts, $js_tag_frags_script_json_part_placeholders, $js_tag_frags_script_json_part_placeholder_key_replacements)) {
$html = $this->replaceOnce($js_tag_frags_script_json_parts, $js_tag_frags_script_json_part_placeholders, $html);
foreach ($js_tag_frags_script_json_part_placeholder_key_replacements as &$_json_tag_frag_key_replacement) {
$_js_tag_frag = $js_tag_frags[$_json_tag_frag_key_replacement];
$_json_tag_frag_key_replacement = $_js_tag_frag['if_open_tag'];
$_json_tag_frag_key_replacement .= $_js_tag_frag['script_open_tag'];
$_json_tag_frag_key_replacement .= $this->compressInlineJsonCode($_js_tag_frag['script_json']);
$_json_tag_frag_key_replacement .= $_js_tag_frag['script_closing_tag'];
$_json_tag_frag_key_replacement .= $_js_tag_frag['if_closing_tag'];
} // unset($_json_tag_frag_key_replacement, $_js_tag_frag); // Housekeeping.
$html = $this->replaceOnce($js_tag_frags_script_json_part_placeholders, $js_tag_frags_script_json_part_placeholder_key_replacements, $html);
if ($benchmark) {
$this->benchmark->addData(
__FUNCTION__,
compact(
'js_tag_frags',
'js_tag_frags_script_json_parts',
'js_tag_frags_script_json_part_placeholders',
'js_tag_frags_script_json_part_placeholder_key_replacements'
)
);
}
}
}
finale: // Target point; finale/return value.
if ($html) {
$html = trim($html);
} // Trim it up now!
if ($benchmark && !empty($time) && $html && empty($disabled)) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compressing inline JSON in checksum: `%1$s`', md5($html))
);
}
return $html; // With possible compression having been applied here.
} | 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 $json;
} | 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_elements = []; // Initialize.
foreach ($array as $_key => $_value) {
if (in_array($_key, $keys, true)) {
if ($preserve_keys) {
$key_elements[$_key] = $_value;
} else {
$key_elements[] = $_value;
}
}
if (($search_dimensions < 1 || $___current_dimension < $search_dimensions) && is_array($_value)
&& ($_key_elements = $this->compileKeyElementsDeep($_value, $keys, $preserve_keys, $search_dimensions, $___current_dimension + 1))
) {
$key_elements = array_merge($key_elements, $_key_elements);
}
} // unset($_key, $_value, $_key_elements);
return $key_elements;
} | 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 compile.
In other words, elements with one of these array keys, are what we're looking for.
A string|integer is also accepted here (if only one key), and it's converted internally to an array.
@param bool $preserve_keys Optional. Defaults to a FALSE value.
If this is TRUE, the return array WILL preserve numeric/associative keys, instead of forcing a numerically indexed array.
This ALSO prevents duplicates in the return array, which may NOT be desirable in certain circumstances.
Particularly when/if searching a multidimensional array (where keys could be found in multiple dimensions).
In fact, in some cases, this could return data you did NOT want/expect, so please be cautious.
@param int $search_dimensions The number of dimensions to search. Defaults to `-1` (infinite).
If `$preserve_keys` is TRUE, consider setting this to a value of `1`.
@param int $___current_dimension For internal use only; used in recursion.
@return array The array of compiled key elements, else an empty array, if no key elements were found.
By default, the return array will be indexed numerically (e.g. keys are NOT preserved here).
If an associative array is preferred, please set `$preserve_keys` to a TRUE value,
and please consider setting `$search_dimensions` to `1`. | 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);
}
} // unset($_key, $_value);
return $array;
} | 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;
}
return preg_quote((string) $value, (string) $delimiter);
} | 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);
return $value;
}
$string = (string) $value;
if (!isset($string[0])) {
return $string; // Nothing to do.
}
$mb_strlen = mb_strlen($string);
if ($start < 0) {
$start = max(0, $mb_strlen + $start);
} elseif ($start > $mb_strlen) {
$start = $mb_strlen;
}
if ($length < 0) {
$length = max(0, $mb_strlen - $start + $length);
} elseif (!isset($length) || $length > $mb_strlen) {
$length = $mb_strlen;
}
if ($start + $length > $mb_strlen) {
$length = $mb_strlen - $start;
}
return mb_substr($string, 0, $start).
$replace.// The replacement string.
mb_substr($string, $start + $length, $mb_strlen - $start - $length);
} | 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/function.substr-replace.php
@warning Does NOT support mixed `$replace`, `$start`, `$length` params like `substr_replace()` does. | 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, $_value); // Housekeeping.
return $value;
}
$value = (string) $value; // Force string (always).
$mb_strpos = $caSe_insensitive ? 'mb_stripos' : 'mb_strpos';
if (is_array($needle) || is_object($needle)) {
$needle = (array) $needle; // Force array.
if (is_array($replace) || is_object($replace)) {
$replace = (array) $replace; // Force array.
foreach ($needle as $_key => $_needle) {
$_needle = (string) $_needle;
if (($_mb_strpos = $mb_strpos($value, $_needle)) !== false) {
$_mb_strlen = mb_strlen($_needle);
$_replace = isset($replace[$_key]) ? (string) $replace[$_key] : '';
$value = $this->substrReplace($value, $_replace, $_mb_strpos, $_mb_strlen);
}
} // unset($_key, $_needle, $_mb_strpos, $_mb_strlen, $_replace);
return $value;
} else {
$replace = (string) $replace; // Force string.
foreach ($needle as $_key => $_needle) {
$_needle = (string) $_needle;
if (($_mb_strpos = $mb_strpos($value, $_needle)) !== false) {
$_mb_strlen = mb_strlen($_needle);
$value = $this->substrReplace($value, $replace, $_mb_strpos, $_mb_strlen);
}
} // unset($_key, $_needle, $_mb_strpos, $_mb_strlen);
return $value;
}
} else {
$needle = (string) $needle; // Force string.
if (($_mb_strpos = $mb_strpos($value, $needle)) !== false) {
$_mb_strlen = mb_strlen($needle);
if (is_array($replace) || is_object($replace)) {
$replace = array_values((array) $replace); // Force array.
$_replace = isset($replace[0]) ? (string) $replace[0] : '';
} else {
$_replace = (string) $replace; // Force string.
}
$value = $this->substrReplace($value, $_replace, $_mb_strpos, $_mb_strlen);
// unset($_mb_strpos, $_mb_strlen, $_replace);
}
return $value;
}
} | 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 here.
@param bool $caSe_insensitive Case insensitive? Defaults to FALSE.
@return string|array|object Values after ONE string replacement deeply. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.