Initial commit: is_shoppingcart out of the box v3.0.1

v
This commit is contained in:
Isabelle Anno
2025-11-19 13:17:30 +01:00
committed by Isabelle
commit dda9ec045b
333 changed files with 33026 additions and 0 deletions

10
is_themecore/vendor/.htaccess vendored Normal file
View File

@ -0,0 +1,10 @@
# Apache 2.2
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
# Apache 2.4
<IfModule mod_authz_core.c>
Require all denied
</IfModule>

25
is_themecore/vendor/autoload.php vendored Normal file
View File

@ -0,0 +1,25 @@
<?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitf15e3531cda7d0057952c1e2751a9b0a::getLoader();

View File

@ -0,0 +1,579 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var \Closure(string):void */
private static $includeFile;
/** @var string|null */
private $vendorDir;
// PSR-4
/**
* @var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* List of PSR-0 prefixes
*
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
*
* @var array<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var string|null */
private $apcuPrefix;
/**
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return list<string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array<string, string> $classMap Class to filename map
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
$paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
$paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
$paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
$paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
$includeFile = self::$includeFile;
$includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders keyed by their corresponding vendor directories.
*
* @return array<string, self>
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = \Closure::bind(static function($file) {
include $file;
}, null, null);
}
}

View File

@ -0,0 +1,359 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*
* @final
*/
class InstalledVersions
{
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
if (self::$canGetVendors) {
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
$installed[] = self::$installedByVendor[$vendorDir] = $required;
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array()) {
$installed[] = self::$installed;
}
return $installed;
}
}

21
is_themecore/vendor/composer/LICENSE vendored Normal file
View File

@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,150 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'ExecWithFallback\\Availability' => $vendorDir . '/rosell-dk/exec-with-fallback/src/Availability.php',
'ExecWithFallback\\ExecWithFallback' => $vendorDir . '/rosell-dk/exec-with-fallback/src/ExecWithFallback.php',
'ExecWithFallback\\ExecWithFallbackNoMercy' => $vendorDir . '/rosell-dk/exec-with-fallback/src/ExecWithFallbackNoMercy.php',
'ExecWithFallback\\POpen' => $vendorDir . '/rosell-dk/exec-with-fallback/src/POpen.php',
'ExecWithFallback\\Passthru' => $vendorDir . '/rosell-dk/exec-with-fallback/src/Passthru.php',
'ExecWithFallback\\ProcOpen' => $vendorDir . '/rosell-dk/exec-with-fallback/src/ProcOpen.php',
'ExecWithFallback\\ShellExec' => $vendorDir . '/rosell-dk/exec-with-fallback/src/ShellExec.php',
'FileUtil\\FileExists' => $vendorDir . '/rosell-dk/file-util/src/FileExists.php',
'FileUtil\\FileExistsUsingExec' => $vendorDir . '/rosell-dk/file-util/src/FileExistsUsingExec.php',
'FileUtil\\PathValidator' => $vendorDir . '/rosell-dk/file-util/src/PathValidator.php',
'ImageMimeTypeGuesser\\Detectors\\AbstractDetector' => $vendorDir . '/rosell-dk/image-mime-type-guesser/src/Detectors/AbstractDetector.php',
'ImageMimeTypeGuesser\\Detectors\\ExifImageType' => $vendorDir . '/rosell-dk/image-mime-type-guesser/src/Detectors/ExifImageType.php',
'ImageMimeTypeGuesser\\Detectors\\FInfo' => $vendorDir . '/rosell-dk/image-mime-type-guesser/src/Detectors/FInfo.php',
'ImageMimeTypeGuesser\\Detectors\\GetImageSize' => $vendorDir . '/rosell-dk/image-mime-type-guesser/src/Detectors/GetImageSize.php',
'ImageMimeTypeGuesser\\Detectors\\MimeContentType' => $vendorDir . '/rosell-dk/image-mime-type-guesser/src/Detectors/MimeContentType.php',
'ImageMimeTypeGuesser\\Detectors\\SignatureSniffer' => $vendorDir . '/rosell-dk/image-mime-type-guesser/src/Detectors/SignatureSniffer.php',
'ImageMimeTypeGuesser\\Detectors\\Stack' => $vendorDir . '/rosell-dk/image-mime-type-guesser/src/Detectors/Stack.php',
'ImageMimeTypeGuesser\\GuessFromExtension' => $vendorDir . '/rosell-dk/image-mime-type-guesser/src/GuessFromExtension.php',
'ImageMimeTypeGuesser\\ImageMimeTypeGuesser' => $vendorDir . '/rosell-dk/image-mime-type-guesser/src/ImageMimeTypeGuesser.php',
'ImageMimeTypeGuesser\\MimeMap' => $vendorDir . '/rosell-dk/image-mime-type-guesser/src/MimeMap.php',
'ImageMimeTypeSniffer\\ImageMimeTypeSniffer' => $vendorDir . '/rosell-dk/image-mime-type-sniffer/src/ImageMimeTypeSniffer.php',
'LocateBinaries\\LocateBinaries' => $vendorDir . '/rosell-dk/locate-binaries/src/LocateBinaries.php',
'Oksydan\\Module\\IsThemeCore\\Controller\\Admin\\SettingsController' => $baseDir . '/src/Controller/Admin/SettingsController.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Breadcrumbs\\ThemeBreadcrumbs' => $baseDir . '/src/Core/Breadcrumbs/ThemeBreadcrumbs.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Htaccess\\HtaccessGenerator' => $baseDir . '/src/Core/Htaccess/HtaccessGenerator.php',
'Oksydan\\Module\\IsThemeCore\\Core\\ListingDisplay\\ThemeListDisplay' => $baseDir . '/src/Core/ListingDisplay/ThemeListDisplay.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Partytown\\FilesInstallation' => $baseDir . '/src/Core/Partytown/FilesInstallation.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Partytown\\PartytownScript' => $baseDir . '/src/Core/Partytown/PartytownScript.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Partytown\\PartytownScriptUriResolver' => $baseDir . '/src/Core/Partytown/PartytownScriptUriResolver.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Smarty\\SmartyHelperFunctions' => $baseDir . '/src/Core/Smarty/SmartyHelperFunctions.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\AbstractStructuredData' => $baseDir . '/src/Core/StructuredData/AbstractStructuredData.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\BreadcrumbStructuredData' => $baseDir . '/src/Core/StructuredData/BreadcrumbStructuredData.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Presenter\\StructuredDataBreadcrumbPresenter' => $baseDir . '/src/Core/StructuredData/Presenter/StructuredDataBreadcrumbPresenter.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Presenter\\StructuredDataPresenterInterface' => $baseDir . '/src/Core/StructuredData/Presenter/StructuredDataPresenterInterface.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Presenter\\StructuredDataProductPresenter' => $baseDir . '/src/Core/StructuredData/Presenter/StructuredDataProductPresenter.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Presenter\\StructuredDataShopPresenter' => $baseDir . '/src/Core/StructuredData/Presenter/StructuredDataShopPresenter.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Presenter\\StructuredDataWebsitePresenter' => $baseDir . '/src/Core/StructuredData/Presenter/StructuredDataWebsitePresenter.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\ProductStructuredData' => $baseDir . '/src/Core/StructuredData/ProductStructuredData.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Provider\\StructuredDataBreadcrumbProvider' => $baseDir . '/src/Core/StructuredData/Provider/StructuredDataBreadcrumbProvider.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Provider\\StructuredDataProductProvider' => $baseDir . '/src/Core/StructuredData/Provider/StructuredDataProductProvider.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Provider\\StructuredDataProviderInterface' => $baseDir . '/src/Core/StructuredData/Provider/StructuredDataProviderInterface.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Provider\\StructuredDataShopProvider' => $baseDir . '/src/Core/StructuredData/Provider/StructuredDataShopProvider.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Provider\\StructuredDataWebsiteProvider' => $baseDir . '/src/Core/StructuredData/Provider/StructuredDataWebsiteProvider.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\ShopStructuredData' => $baseDir . '/src/Core/StructuredData/ShopStructuredData.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\StructuredDataInterface' => $baseDir . '/src/Core/StructuredData/StructuredDataInterface.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\WebsiteStructuredData' => $baseDir . '/src/Core/StructuredData/WebsiteStructuredData.php',
'Oksydan\\Module\\IsThemeCore\\Core\\ThemeAssets\\ThemeAssetConfigProvider' => $baseDir . '/src/Core/ThemeAssets/ThemeAssetConfigProvider.php',
'Oksydan\\Module\\IsThemeCore\\Core\\ThemeAssets\\ThemeAssetsRegister' => $baseDir . '/src/Core/ThemeAssets/ThemeAssetsRegister.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Webp\\RelatedImageFileFinder' => $baseDir . '/src/Core/Webp/RelatedImageFileFinder.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Webp\\WebpConvertLibraries' => $baseDir . '/src/Core/Webp/WebpConvertLibraries.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Webp\\WebpFilesEraser' => $baseDir . '/src/Core/Webp/WebpFilesEraser.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Webp\\WebpGenerator' => $baseDir . '/src/Core/Webp/WebpGenerator.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Webp\\WebpPictureGenerator' => $baseDir . '/src/Core/Webp/WebpPictureGenerator.php',
'Oksydan\\Module\\IsThemeCore\\Form\\ChoiceProvider\\ListDisplayChoiceProvider' => $baseDir . '/src/Form/ChoiceProvider/ListDisplayChoiceProvider.php',
'Oksydan\\Module\\IsThemeCore\\Form\\ChoiceProvider\\WebpLibraryChoiceProvider' => $baseDir . '/src/Form/ChoiceProvider/WebpLibraryChoiceProvider.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\GeneralConfiguration' => $baseDir . '/src/Form/Settings/GeneralConfiguration.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\GeneralFormDataProvider' => $baseDir . '/src/Form/Settings/GeneralFormDataProvider.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\GeneralType' => $baseDir . '/src/Form/Settings/GeneralType.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\WebpConfiguration' => $baseDir . '/src/Form/Settings/WebpConfiguration.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\WebpFormDataProvider' => $baseDir . '/src/Form/Settings/WebpFormDataProvider.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\WebpType' => $baseDir . '/src/Form/Settings/WebpType.php',
'Oksydan\\Module\\IsThemeCore\\HookDispatcher' => $baseDir . '/src/HookDispatcher.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\AbstractHook' => $baseDir . '/src/Hook/AbstractHook.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\Assets' => $baseDir . '/src/Hook/Assets.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\Header' => $baseDir . '/src/Hook/Header.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\Htaccess' => $baseDir . '/src/Hook/Htaccess.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\HtmlOutput' => $baseDir . '/src/Hook/HtmlOutput.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\Smarty' => $baseDir . '/src/Hook/Smarty.php',
'WebPConvert\\Convert\\ConverterFactory' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/ConverterFactory.php',
'WebPConvert\\Convert\\Converters\\AbstractConverter' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/AbstractConverter.php',
'WebPConvert\\Convert\\Converters\\BaseTraits\\AutoQualityTrait' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/BaseTraits/AutoQualityTrait.php',
'WebPConvert\\Convert\\Converters\\BaseTraits\\DestinationPreparationTrait' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/BaseTraits/DestinationPreparationTrait.php',
'WebPConvert\\Convert\\Converters\\BaseTraits\\LoggerTrait' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/BaseTraits/LoggerTrait.php',
'WebPConvert\\Convert\\Converters\\BaseTraits\\OptionsTrait' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/BaseTraits/OptionsTrait.php',
'WebPConvert\\Convert\\Converters\\BaseTraits\\WarningLoggerTrait' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/BaseTraits/WarningLoggerTrait.php',
'WebPConvert\\Convert\\Converters\\ConverterTraits\\CloudConverterTrait' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/ConverterTraits/CloudConverterTrait.php',
'WebPConvert\\Convert\\Converters\\ConverterTraits\\CurlTrait' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/ConverterTraits/CurlTrait.php',
'WebPConvert\\Convert\\Converters\\ConverterTraits\\EncodingAutoTrait' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/ConverterTraits/EncodingAutoTrait.php',
'WebPConvert\\Convert\\Converters\\ConverterTraits\\ExecTrait' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/ConverterTraits/ExecTrait.php',
'WebPConvert\\Convert\\Converters\\Cwebp' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/Cwebp.php',
'WebPConvert\\Convert\\Converters\\Ewww' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/Ewww.php',
'WebPConvert\\Convert\\Converters\\FFMpeg' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/FFMpeg.php',
'WebPConvert\\Convert\\Converters\\Gd' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/Gd.php',
'WebPConvert\\Convert\\Converters\\Gmagick' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/Gmagick.php',
'WebPConvert\\Convert\\Converters\\GmagickBinary' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/GmagickBinary.php',
'WebPConvert\\Convert\\Converters\\GraphicsMagick' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/GraphicsMagick.php',
'WebPConvert\\Convert\\Converters\\ImageMagick' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/ImageMagick.php',
'WebPConvert\\Convert\\Converters\\Imagick' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/Imagick.php',
'WebPConvert\\Convert\\Converters\\ImagickBinary' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/ImagickBinary.php',
'WebPConvert\\Convert\\Converters\\Stack' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/Stack.php',
'WebPConvert\\Convert\\Converters\\Vips' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/Vips.php',
'WebPConvert\\Convert\\Converters\\Wpc' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Converters/Wpc.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailedException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailedException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\ConversionSkippedException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/ConversionSkippedException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\ConverterNotOperationalException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/ConverterNotOperationalException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\ConverterNotOperational\\InvalidApiKeyException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/ConverterNotOperational/InvalidApiKeyException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\ConverterNotOperational\\SystemRequirementsNotMetException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/ConverterNotOperational/SystemRequirementsNotMetException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\FileSystemProblemsException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/FileSystemProblemsException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\FileSystemProblems\\CreateDestinationFileException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/FileSystemProblems/CreateDestinationFileException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\FileSystemProblems\\CreateDestinationFolderException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/FileSystemProblems/CreateDestinationFolderException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\InvalidInputException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/InvalidInputException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\InvalidInput\\ConverterNotFoundException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/InvalidInput/ConverterNotFoundException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\InvalidInput\\InvalidImageTypeException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/InvalidInput/InvalidImageTypeException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\InvalidInput\\TargetNotFoundException' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/InvalidInput/TargetNotFoundException.php',
'WebPConvert\\Convert\\Helpers\\JpegQualityDetector' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Helpers/JpegQualityDetector.php',
'WebPConvert\\Convert\\Helpers\\PhpIniSizes' => $vendorDir . '/rosell-dk/webp-convert/src/Convert/Helpers/PhpIniSizes.php',
'WebPConvert\\Exceptions\\InvalidInputException' => $vendorDir . '/rosell-dk/webp-convert/src/Exceptions/InvalidInputException.php',
'WebPConvert\\Exceptions\\InvalidInput\\InvalidImageTypeException' => $vendorDir . '/rosell-dk/webp-convert/src/Exceptions/InvalidInput/InvalidImageTypeException.php',
'WebPConvert\\Exceptions\\InvalidInput\\TargetNotFoundException' => $vendorDir . '/rosell-dk/webp-convert/src/Exceptions/InvalidInput/TargetNotFoundException.php',
'WebPConvert\\Exceptions\\WebPConvertException' => $vendorDir . '/rosell-dk/webp-convert/src/Exceptions/WebPConvertException.php',
'WebPConvert\\Helpers\\InputValidator' => $vendorDir . '/rosell-dk/webp-convert/src/Helpers/InputValidator.php',
'WebPConvert\\Helpers\\MimeType' => $vendorDir . '/rosell-dk/webp-convert/src/Helpers/MimeType.php',
'WebPConvert\\Helpers\\PathChecker' => $vendorDir . '/rosell-dk/webp-convert/src/Helpers/PathChecker.php',
'WebPConvert\\Helpers\\Sanitize' => $vendorDir . '/rosell-dk/webp-convert/src/Helpers/Sanitize.php',
'WebPConvert\\Loggers\\BaseLogger' => $vendorDir . '/rosell-dk/webp-convert/src/Loggers/BaseLogger.php',
'WebPConvert\\Loggers\\BufferLogger' => $vendorDir . '/rosell-dk/webp-convert/src/Loggers/BufferLogger.php',
'WebPConvert\\Loggers\\EchoLogger' => $vendorDir . '/rosell-dk/webp-convert/src/Loggers/EchoLogger.php',
'WebPConvert\\Options\\ArrayOption' => $vendorDir . '/rosell-dk/webp-convert/src/Options/ArrayOption.php',
'WebPConvert\\Options\\BooleanOption' => $vendorDir . '/rosell-dk/webp-convert/src/Options/BooleanOption.php',
'WebPConvert\\Options\\Exceptions\\InvalidOptionTypeException' => $vendorDir . '/rosell-dk/webp-convert/src/Options/Exceptions/InvalidOptionTypeException.php',
'WebPConvert\\Options\\Exceptions\\InvalidOptionValueException' => $vendorDir . '/rosell-dk/webp-convert/src/Options/Exceptions/InvalidOptionValueException.php',
'WebPConvert\\Options\\Exceptions\\OptionNotFoundException' => $vendorDir . '/rosell-dk/webp-convert/src/Options/Exceptions/OptionNotFoundException.php',
'WebPConvert\\Options\\GhostOption' => $vendorDir . '/rosell-dk/webp-convert/src/Options/GhostOption.php',
'WebPConvert\\Options\\IntegerOption' => $vendorDir . '/rosell-dk/webp-convert/src/Options/IntegerOption.php',
'WebPConvert\\Options\\IntegerOrNullOption' => $vendorDir . '/rosell-dk/webp-convert/src/Options/IntegerOrNullOption.php',
'WebPConvert\\Options\\MetadataOption' => $vendorDir . '/rosell-dk/webp-convert/src/Options/MetadataOption.php',
'WebPConvert\\Options\\Option' => $vendorDir . '/rosell-dk/webp-convert/src/Options/Option.php',
'WebPConvert\\Options\\OptionFactory' => $vendorDir . '/rosell-dk/webp-convert/src/Options/OptionFactory.php',
'WebPConvert\\Options\\Options' => $vendorDir . '/rosell-dk/webp-convert/src/Options/Options.php',
'WebPConvert\\Options\\QualityOption' => $vendorDir . '/rosell-dk/webp-convert/src/Options/QualityOption.php',
'WebPConvert\\Options\\SensitiveArrayOption' => $vendorDir . '/rosell-dk/webp-convert/src/Options/SensitiveArrayOption.php',
'WebPConvert\\Options\\SensitiveStringOption' => $vendorDir . '/rosell-dk/webp-convert/src/Options/SensitiveStringOption.php',
'WebPConvert\\Options\\StringOption' => $vendorDir . '/rosell-dk/webp-convert/src/Options/StringOption.php',
'WebPConvert\\Serve\\Exceptions\\ServeFailedException' => $vendorDir . '/rosell-dk/webp-convert/src/Serve/Exceptions/ServeFailedException.php',
'WebPConvert\\Serve\\Header' => $vendorDir . '/rosell-dk/webp-convert/src/Serve/Header.php',
'WebPConvert\\Serve\\Report' => $vendorDir . '/rosell-dk/webp-convert/src/Serve/Report.php',
'WebPConvert\\Serve\\ServeConvertedWebP' => $vendorDir . '/rosell-dk/webp-convert/src/Serve/ServeConvertedWebP.php',
'WebPConvert\\Serve\\ServeConvertedWebPWithErrorHandling' => $vendorDir . '/rosell-dk/webp-convert/src/Serve/ServeConvertedWebPWithErrorHandling.php',
'WebPConvert\\Serve\\ServeFile' => $vendorDir . '/rosell-dk/webp-convert/src/Serve/ServeFile.php',
'WebPConvert\\WebPConvert' => $vendorDir . '/rosell-dk/webp-convert/src/WebPConvert.php',
);

View File

@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);

View File

@ -0,0 +1,16 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'WebPConvert\\' => array($vendorDir . '/rosell-dk/webp-convert/src'),
'Oksydan\\Module\\IsThemeCore\\' => array($baseDir . '/src'),
'LocateBinaries\\' => array($vendorDir . '/rosell-dk/locate-binaries/src'),
'ImageMimeTypeSniffer\\' => array($vendorDir . '/rosell-dk/image-mime-type-sniffer/src'),
'ImageMimeTypeGuesser\\' => array($vendorDir . '/rosell-dk/image-mime-type-guesser/src'),
'FileUtil\\' => array($vendorDir . '/rosell-dk/file-util/src'),
'ExecWithFallback\\' => array($vendorDir . '/rosell-dk/exec-with-fallback/src'),
);

View File

@ -0,0 +1,38 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitf15e3531cda7d0057952c1e2751a9b0a
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInitf15e3531cda7d0057952c1e2751a9b0a', 'loadClassLoader'), true, false);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInitf15e3531cda7d0057952c1e2751a9b0a', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitf15e3531cda7d0057952c1e2751a9b0a::getInitializer($loader));
$loader->register(false);
return $loader;
}
}

View File

@ -0,0 +1,221 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitf15e3531cda7d0057952c1e2751a9b0a
{
public static $prefixLengthsPsr4 = array (
'W' =>
array (
'WebPConvert\\' => 12,
),
'O' =>
array (
'Oksydan\\Module\\IsThemeCore\\' => 27,
),
'L' =>
array (
'LocateBinaries\\' => 15,
),
'I' =>
array (
'ImageMimeTypeSniffer\\' => 21,
'ImageMimeTypeGuesser\\' => 21,
),
'F' =>
array (
'FileUtil\\' => 9,
),
'E' =>
array (
'ExecWithFallback\\' => 17,
),
);
public static $prefixDirsPsr4 = array (
'WebPConvert\\' =>
array (
0 => __DIR__ . '/..' . '/rosell-dk/webp-convert/src',
),
'Oksydan\\Module\\IsThemeCore\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
'LocateBinaries\\' =>
array (
0 => __DIR__ . '/..' . '/rosell-dk/locate-binaries/src',
),
'ImageMimeTypeSniffer\\' =>
array (
0 => __DIR__ . '/..' . '/rosell-dk/image-mime-type-sniffer/src',
),
'ImageMimeTypeGuesser\\' =>
array (
0 => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src',
),
'FileUtil\\' =>
array (
0 => __DIR__ . '/..' . '/rosell-dk/file-util/src',
),
'ExecWithFallback\\' =>
array (
0 => __DIR__ . '/..' . '/rosell-dk/exec-with-fallback/src',
),
);
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'ExecWithFallback\\Availability' => __DIR__ . '/..' . '/rosell-dk/exec-with-fallback/src/Availability.php',
'ExecWithFallback\\ExecWithFallback' => __DIR__ . '/..' . '/rosell-dk/exec-with-fallback/src/ExecWithFallback.php',
'ExecWithFallback\\ExecWithFallbackNoMercy' => __DIR__ . '/..' . '/rosell-dk/exec-with-fallback/src/ExecWithFallbackNoMercy.php',
'ExecWithFallback\\POpen' => __DIR__ . '/..' . '/rosell-dk/exec-with-fallback/src/POpen.php',
'ExecWithFallback\\Passthru' => __DIR__ . '/..' . '/rosell-dk/exec-with-fallback/src/Passthru.php',
'ExecWithFallback\\ProcOpen' => __DIR__ . '/..' . '/rosell-dk/exec-with-fallback/src/ProcOpen.php',
'ExecWithFallback\\ShellExec' => __DIR__ . '/..' . '/rosell-dk/exec-with-fallback/src/ShellExec.php',
'FileUtil\\FileExists' => __DIR__ . '/..' . '/rosell-dk/file-util/src/FileExists.php',
'FileUtil\\FileExistsUsingExec' => __DIR__ . '/..' . '/rosell-dk/file-util/src/FileExistsUsingExec.php',
'FileUtil\\PathValidator' => __DIR__ . '/..' . '/rosell-dk/file-util/src/PathValidator.php',
'ImageMimeTypeGuesser\\Detectors\\AbstractDetector' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src/Detectors/AbstractDetector.php',
'ImageMimeTypeGuesser\\Detectors\\ExifImageType' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src/Detectors/ExifImageType.php',
'ImageMimeTypeGuesser\\Detectors\\FInfo' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src/Detectors/FInfo.php',
'ImageMimeTypeGuesser\\Detectors\\GetImageSize' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src/Detectors/GetImageSize.php',
'ImageMimeTypeGuesser\\Detectors\\MimeContentType' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src/Detectors/MimeContentType.php',
'ImageMimeTypeGuesser\\Detectors\\SignatureSniffer' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src/Detectors/SignatureSniffer.php',
'ImageMimeTypeGuesser\\Detectors\\Stack' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src/Detectors/Stack.php',
'ImageMimeTypeGuesser\\GuessFromExtension' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src/GuessFromExtension.php',
'ImageMimeTypeGuesser\\ImageMimeTypeGuesser' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src/ImageMimeTypeGuesser.php',
'ImageMimeTypeGuesser\\MimeMap' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-guesser/src/MimeMap.php',
'ImageMimeTypeSniffer\\ImageMimeTypeSniffer' => __DIR__ . '/..' . '/rosell-dk/image-mime-type-sniffer/src/ImageMimeTypeSniffer.php',
'LocateBinaries\\LocateBinaries' => __DIR__ . '/..' . '/rosell-dk/locate-binaries/src/LocateBinaries.php',
'Oksydan\\Module\\IsThemeCore\\Controller\\Admin\\SettingsController' => __DIR__ . '/../..' . '/src/Controller/Admin/SettingsController.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Breadcrumbs\\ThemeBreadcrumbs' => __DIR__ . '/../..' . '/src/Core/Breadcrumbs/ThemeBreadcrumbs.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Htaccess\\HtaccessGenerator' => __DIR__ . '/../..' . '/src/Core/Htaccess/HtaccessGenerator.php',
'Oksydan\\Module\\IsThemeCore\\Core\\ListingDisplay\\ThemeListDisplay' => __DIR__ . '/../..' . '/src/Core/ListingDisplay/ThemeListDisplay.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Partytown\\FilesInstallation' => __DIR__ . '/../..' . '/src/Core/Partytown/FilesInstallation.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Partytown\\PartytownScript' => __DIR__ . '/../..' . '/src/Core/Partytown/PartytownScript.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Partytown\\PartytownScriptUriResolver' => __DIR__ . '/../..' . '/src/Core/Partytown/PartytownScriptUriResolver.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Smarty\\SmartyHelperFunctions' => __DIR__ . '/../..' . '/src/Core/Smarty/SmartyHelperFunctions.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\AbstractStructuredData' => __DIR__ . '/../..' . '/src/Core/StructuredData/AbstractStructuredData.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\BreadcrumbStructuredData' => __DIR__ . '/../..' . '/src/Core/StructuredData/BreadcrumbStructuredData.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Presenter\\StructuredDataBreadcrumbPresenter' => __DIR__ . '/../..' . '/src/Core/StructuredData/Presenter/StructuredDataBreadcrumbPresenter.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Presenter\\StructuredDataPresenterInterface' => __DIR__ . '/../..' . '/src/Core/StructuredData/Presenter/StructuredDataPresenterInterface.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Presenter\\StructuredDataProductPresenter' => __DIR__ . '/../..' . '/src/Core/StructuredData/Presenter/StructuredDataProductPresenter.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Presenter\\StructuredDataShopPresenter' => __DIR__ . '/../..' . '/src/Core/StructuredData/Presenter/StructuredDataShopPresenter.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Presenter\\StructuredDataWebsitePresenter' => __DIR__ . '/../..' . '/src/Core/StructuredData/Presenter/StructuredDataWebsitePresenter.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\ProductStructuredData' => __DIR__ . '/../..' . '/src/Core/StructuredData/ProductStructuredData.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Provider\\StructuredDataBreadcrumbProvider' => __DIR__ . '/../..' . '/src/Core/StructuredData/Provider/StructuredDataBreadcrumbProvider.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Provider\\StructuredDataProductProvider' => __DIR__ . '/../..' . '/src/Core/StructuredData/Provider/StructuredDataProductProvider.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Provider\\StructuredDataProviderInterface' => __DIR__ . '/../..' . '/src/Core/StructuredData/Provider/StructuredDataProviderInterface.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Provider\\StructuredDataShopProvider' => __DIR__ . '/../..' . '/src/Core/StructuredData/Provider/StructuredDataShopProvider.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\Provider\\StructuredDataWebsiteProvider' => __DIR__ . '/../..' . '/src/Core/StructuredData/Provider/StructuredDataWebsiteProvider.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\ShopStructuredData' => __DIR__ . '/../..' . '/src/Core/StructuredData/ShopStructuredData.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\StructuredDataInterface' => __DIR__ . '/../..' . '/src/Core/StructuredData/StructuredDataInterface.php',
'Oksydan\\Module\\IsThemeCore\\Core\\StructuredData\\WebsiteStructuredData' => __DIR__ . '/../..' . '/src/Core/StructuredData/WebsiteStructuredData.php',
'Oksydan\\Module\\IsThemeCore\\Core\\ThemeAssets\\ThemeAssetConfigProvider' => __DIR__ . '/../..' . '/src/Core/ThemeAssets/ThemeAssetConfigProvider.php',
'Oksydan\\Module\\IsThemeCore\\Core\\ThemeAssets\\ThemeAssetsRegister' => __DIR__ . '/../..' . '/src/Core/ThemeAssets/ThemeAssetsRegister.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Webp\\RelatedImageFileFinder' => __DIR__ . '/../..' . '/src/Core/Webp/RelatedImageFileFinder.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Webp\\WebpConvertLibraries' => __DIR__ . '/../..' . '/src/Core/Webp/WebpConvertLibraries.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Webp\\WebpFilesEraser' => __DIR__ . '/../..' . '/src/Core/Webp/WebpFilesEraser.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Webp\\WebpGenerator' => __DIR__ . '/../..' . '/src/Core/Webp/WebpGenerator.php',
'Oksydan\\Module\\IsThemeCore\\Core\\Webp\\WebpPictureGenerator' => __DIR__ . '/../..' . '/src/Core/Webp/WebpPictureGenerator.php',
'Oksydan\\Module\\IsThemeCore\\Form\\ChoiceProvider\\ListDisplayChoiceProvider' => __DIR__ . '/../..' . '/src/Form/ChoiceProvider/ListDisplayChoiceProvider.php',
'Oksydan\\Module\\IsThemeCore\\Form\\ChoiceProvider\\WebpLibraryChoiceProvider' => __DIR__ . '/../..' . '/src/Form/ChoiceProvider/WebpLibraryChoiceProvider.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\GeneralConfiguration' => __DIR__ . '/../..' . '/src/Form/Settings/GeneralConfiguration.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\GeneralFormDataProvider' => __DIR__ . '/../..' . '/src/Form/Settings/GeneralFormDataProvider.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\GeneralType' => __DIR__ . '/../..' . '/src/Form/Settings/GeneralType.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\WebpConfiguration' => __DIR__ . '/../..' . '/src/Form/Settings/WebpConfiguration.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\WebpFormDataProvider' => __DIR__ . '/../..' . '/src/Form/Settings/WebpFormDataProvider.php',
'Oksydan\\Module\\IsThemeCore\\Form\\Settings\\WebpType' => __DIR__ . '/../..' . '/src/Form/Settings/WebpType.php',
'Oksydan\\Module\\IsThemeCore\\HookDispatcher' => __DIR__ . '/../..' . '/src/HookDispatcher.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\AbstractHook' => __DIR__ . '/../..' . '/src/Hook/AbstractHook.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\Assets' => __DIR__ . '/../..' . '/src/Hook/Assets.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\Header' => __DIR__ . '/../..' . '/src/Hook/Header.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\Htaccess' => __DIR__ . '/../..' . '/src/Hook/Htaccess.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\HtmlOutput' => __DIR__ . '/../..' . '/src/Hook/HtmlOutput.php',
'Oksydan\\Module\\IsThemeCore\\Hook\\Smarty' => __DIR__ . '/../..' . '/src/Hook/Smarty.php',
'WebPConvert\\Convert\\ConverterFactory' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/ConverterFactory.php',
'WebPConvert\\Convert\\Converters\\AbstractConverter' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/AbstractConverter.php',
'WebPConvert\\Convert\\Converters\\BaseTraits\\AutoQualityTrait' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/BaseTraits/AutoQualityTrait.php',
'WebPConvert\\Convert\\Converters\\BaseTraits\\DestinationPreparationTrait' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/BaseTraits/DestinationPreparationTrait.php',
'WebPConvert\\Convert\\Converters\\BaseTraits\\LoggerTrait' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/BaseTraits/LoggerTrait.php',
'WebPConvert\\Convert\\Converters\\BaseTraits\\OptionsTrait' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/BaseTraits/OptionsTrait.php',
'WebPConvert\\Convert\\Converters\\BaseTraits\\WarningLoggerTrait' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/BaseTraits/WarningLoggerTrait.php',
'WebPConvert\\Convert\\Converters\\ConverterTraits\\CloudConverterTrait' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/ConverterTraits/CloudConverterTrait.php',
'WebPConvert\\Convert\\Converters\\ConverterTraits\\CurlTrait' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/ConverterTraits/CurlTrait.php',
'WebPConvert\\Convert\\Converters\\ConverterTraits\\EncodingAutoTrait' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/ConverterTraits/EncodingAutoTrait.php',
'WebPConvert\\Convert\\Converters\\ConverterTraits\\ExecTrait' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/ConverterTraits/ExecTrait.php',
'WebPConvert\\Convert\\Converters\\Cwebp' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/Cwebp.php',
'WebPConvert\\Convert\\Converters\\Ewww' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/Ewww.php',
'WebPConvert\\Convert\\Converters\\FFMpeg' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/FFMpeg.php',
'WebPConvert\\Convert\\Converters\\Gd' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/Gd.php',
'WebPConvert\\Convert\\Converters\\Gmagick' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/Gmagick.php',
'WebPConvert\\Convert\\Converters\\GmagickBinary' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/GmagickBinary.php',
'WebPConvert\\Convert\\Converters\\GraphicsMagick' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/GraphicsMagick.php',
'WebPConvert\\Convert\\Converters\\ImageMagick' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/ImageMagick.php',
'WebPConvert\\Convert\\Converters\\Imagick' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/Imagick.php',
'WebPConvert\\Convert\\Converters\\ImagickBinary' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/ImagickBinary.php',
'WebPConvert\\Convert\\Converters\\Stack' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/Stack.php',
'WebPConvert\\Convert\\Converters\\Vips' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/Vips.php',
'WebPConvert\\Convert\\Converters\\Wpc' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Converters/Wpc.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailedException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailedException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\ConversionSkippedException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/ConversionSkippedException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\ConverterNotOperationalException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/ConverterNotOperationalException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\ConverterNotOperational\\InvalidApiKeyException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/ConverterNotOperational/InvalidApiKeyException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\ConverterNotOperational\\SystemRequirementsNotMetException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/ConverterNotOperational/SystemRequirementsNotMetException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\FileSystemProblemsException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/FileSystemProblemsException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\FileSystemProblems\\CreateDestinationFileException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/FileSystemProblems/CreateDestinationFileException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\FileSystemProblems\\CreateDestinationFolderException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/FileSystemProblems/CreateDestinationFolderException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\InvalidInputException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/InvalidInputException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\InvalidInput\\ConverterNotFoundException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/InvalidInput/ConverterNotFoundException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\InvalidInput\\InvalidImageTypeException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/InvalidInput/InvalidImageTypeException.php',
'WebPConvert\\Convert\\Exceptions\\ConversionFailed\\InvalidInput\\TargetNotFoundException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Exceptions/ConversionFailed/InvalidInput/TargetNotFoundException.php',
'WebPConvert\\Convert\\Helpers\\JpegQualityDetector' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Helpers/JpegQualityDetector.php',
'WebPConvert\\Convert\\Helpers\\PhpIniSizes' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Convert/Helpers/PhpIniSizes.php',
'WebPConvert\\Exceptions\\InvalidInputException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Exceptions/InvalidInputException.php',
'WebPConvert\\Exceptions\\InvalidInput\\InvalidImageTypeException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Exceptions/InvalidInput/InvalidImageTypeException.php',
'WebPConvert\\Exceptions\\InvalidInput\\TargetNotFoundException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Exceptions/InvalidInput/TargetNotFoundException.php',
'WebPConvert\\Exceptions\\WebPConvertException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Exceptions/WebPConvertException.php',
'WebPConvert\\Helpers\\InputValidator' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Helpers/InputValidator.php',
'WebPConvert\\Helpers\\MimeType' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Helpers/MimeType.php',
'WebPConvert\\Helpers\\PathChecker' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Helpers/PathChecker.php',
'WebPConvert\\Helpers\\Sanitize' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Helpers/Sanitize.php',
'WebPConvert\\Loggers\\BaseLogger' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Loggers/BaseLogger.php',
'WebPConvert\\Loggers\\BufferLogger' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Loggers/BufferLogger.php',
'WebPConvert\\Loggers\\EchoLogger' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Loggers/EchoLogger.php',
'WebPConvert\\Options\\ArrayOption' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/ArrayOption.php',
'WebPConvert\\Options\\BooleanOption' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/BooleanOption.php',
'WebPConvert\\Options\\Exceptions\\InvalidOptionTypeException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/Exceptions/InvalidOptionTypeException.php',
'WebPConvert\\Options\\Exceptions\\InvalidOptionValueException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/Exceptions/InvalidOptionValueException.php',
'WebPConvert\\Options\\Exceptions\\OptionNotFoundException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/Exceptions/OptionNotFoundException.php',
'WebPConvert\\Options\\GhostOption' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/GhostOption.php',
'WebPConvert\\Options\\IntegerOption' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/IntegerOption.php',
'WebPConvert\\Options\\IntegerOrNullOption' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/IntegerOrNullOption.php',
'WebPConvert\\Options\\MetadataOption' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/MetadataOption.php',
'WebPConvert\\Options\\Option' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/Option.php',
'WebPConvert\\Options\\OptionFactory' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/OptionFactory.php',
'WebPConvert\\Options\\Options' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/Options.php',
'WebPConvert\\Options\\QualityOption' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/QualityOption.php',
'WebPConvert\\Options\\SensitiveArrayOption' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/SensitiveArrayOption.php',
'WebPConvert\\Options\\SensitiveStringOption' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/SensitiveStringOption.php',
'WebPConvert\\Options\\StringOption' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Options/StringOption.php',
'WebPConvert\\Serve\\Exceptions\\ServeFailedException' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Serve/Exceptions/ServeFailedException.php',
'WebPConvert\\Serve\\Header' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Serve/Header.php',
'WebPConvert\\Serve\\Report' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Serve/Report.php',
'WebPConvert\\Serve\\ServeConvertedWebP' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Serve/ServeConvertedWebP.php',
'WebPConvert\\Serve\\ServeConvertedWebPWithErrorHandling' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Serve/ServeConvertedWebPWithErrorHandling.php',
'WebPConvert\\Serve\\ServeFile' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/Serve/ServeFile.php',
'WebPConvert\\WebPConvert' => __DIR__ . '/..' . '/rosell-dk/webp-convert/src/WebPConvert.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitf15e3531cda7d0057952c1e2751a9b0a::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitf15e3531cda7d0057952c1e2751a9b0a::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInitf15e3531cda7d0057952c1e2751a9b0a::$classMap;
}, null, ClassLoader::class);
}
}

View File

@ -0,0 +1,468 @@
{
"packages": [
{
"name": "rosell-dk/exec-with-fallback",
"version": "1.2.0",
"version_normalized": "1.2.0.0",
"source": {
"type": "git",
"url": "https://github.com/rosell-dk/exec-with-fallback.git",
"reference": "f88a6b29abd0b580566056b7c1eb0434eb5db20d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/rosell-dk/exec-with-fallback/zipball/f88a6b29abd0b580566056b7c1eb0434eb5db20d",
"reference": "f88a6b29abd0b580566056b7c1eb0434eb5db20d",
"shasum": ""
},
"require": {
"php": "^5.6 | ^7.0 | ^8.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*"
},
"suggest": {
"php-stan/php-stan": "Suggested for dev, in order to analyse code before committing"
},
"time": "2021-12-08T12:09:43+00:00",
"type": "library",
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"ExecWithFallback\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
}
],
"description": "An exec() with fallback to emulations (proc_open, etc)",
"keywords": [
"command",
"exec",
"fallback",
"open_proc",
"resiliant",
"sturdy"
],
"funding": [
{
"url": "https://github.com/rosell-dk",
"type": "github"
},
{
"url": "https://ko-fi.com/rosell",
"type": "ko_fi"
}
],
"install-path": "../rosell-dk/exec-with-fallback"
},
{
"name": "rosell-dk/file-util",
"version": "0.1.1",
"version_normalized": "0.1.1.0",
"source": {
"type": "git",
"url": "https://github.com/rosell-dk/file-util.git",
"reference": "2ff895308c37f448b34b031cfbfd8e45f43936fd"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/rosell-dk/file-util/zipball/2ff895308c37f448b34b031cfbfd8e45f43936fd",
"reference": "2ff895308c37f448b34b031cfbfd8e45f43936fd",
"shasum": ""
},
"require": {
"php": ">=5.4",
"rosell-dk/exec-with-fallback": "^1.0.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"mikey179/vfsstream": "^1.6",
"phpstan/phpstan": "^1.5",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*"
},
"time": "2022-04-19T10:12:31+00:00",
"type": "library",
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"FileUtil\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
}
],
"description": "Functions for dealing with files and paths",
"keywords": [
"files",
"path",
"util"
],
"funding": [
{
"url": "https://github.com/rosell-dk",
"type": "github"
},
{
"url": "https://ko-fi.com/rosell",
"type": "ko_fi"
}
],
"install-path": "../rosell-dk/file-util"
},
{
"name": "rosell-dk/image-mime-type-guesser",
"version": "1.1.1",
"version_normalized": "1.1.1.0",
"source": {
"type": "git",
"url": "https://github.com/rosell-dk/image-mime-type-guesser.git",
"reference": "72f7040e95a78937ae2edece452530224fcacea6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/rosell-dk/image-mime-type-guesser/zipball/72f7040e95a78937ae2edece452530224fcacea6",
"reference": "72f7040e95a78937ae2edece452530224fcacea6",
"shasum": ""
},
"require": {
"php": "^5.6 | ^7.0 | ^8.0",
"rosell-dk/image-mime-type-sniffer": "^1.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpstan/phpstan": "^1.5",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*"
},
"time": "2022-05-19T09:57:15+00:00",
"type": "library",
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"ImageMimeTypeGuesser\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
}
],
"description": "Guess mime type of images",
"keywords": [
"image",
"images",
"mime",
"mime type"
],
"funding": [
{
"url": "https://github.com/rosell-dk",
"type": "github"
},
{
"url": "https://ko-fi.com/rosell",
"type": "ko_fi"
}
],
"install-path": "../rosell-dk/image-mime-type-guesser"
},
{
"name": "rosell-dk/image-mime-type-sniffer",
"version": "1.1.1",
"version_normalized": "1.1.1.0",
"source": {
"type": "git",
"url": "https://github.com/rosell-dk/image-mime-type-sniffer.git",
"reference": "9ed14cc5d2c14c417660a4dd1946b5f056494691"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/rosell-dk/image-mime-type-sniffer/zipball/9ed14cc5d2c14c417660a4dd1946b5f056494691",
"reference": "9ed14cc5d2c14c417660a4dd1946b5f056494691",
"shasum": ""
},
"require": {
"php": ">=5.4"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"mikey179/vfsstream": "^1.6",
"phpstan/phpstan": "^1.5",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*"
},
"time": "2022-04-20T14:31:25+00:00",
"type": "library",
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"ImageMimeTypeSniffer\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
}
],
"description": "Sniff mime type (images only)",
"keywords": [
"image",
"images",
"mime",
"mime type"
],
"funding": [
{
"url": "https://github.com/rosell-dk",
"type": "github"
},
{
"url": "https://ko-fi.com/rosell",
"type": "ko_fi"
}
],
"install-path": "../rosell-dk/image-mime-type-sniffer"
},
{
"name": "rosell-dk/locate-binaries",
"version": "1.0",
"version_normalized": "1.0.0.0",
"source": {
"type": "git",
"url": "https://github.com/rosell-dk/locate-binaries.git",
"reference": "bd2f493383ecd55aa519828dd2898e30f3b9cbb0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/rosell-dk/locate-binaries/zipball/bd2f493383ecd55aa519828dd2898e30f3b9cbb0",
"reference": "bd2f493383ecd55aa519828dd2898e30f3b9cbb0",
"shasum": ""
},
"require": {
"php": ">=5.6",
"rosell-dk/exec-with-fallback": "^1.0.0",
"rosell-dk/file-util": "^0.1.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpstan/phpstan": "^1.5",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*"
},
"time": "2022-04-20T07:20:07+00:00",
"type": "library",
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"LocateBinaries\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
}
],
"description": "Locate a binaries by means of exec() or similar",
"keywords": [
"binary",
"discover",
"locate",
"whereis",
"which"
],
"funding": [
{
"url": "https://github.com/rosell-dk",
"type": "github"
},
{
"url": "https://ko-fi.com/rosell",
"type": "ko_fi"
}
],
"install-path": "../rosell-dk/locate-binaries"
},
{
"name": "rosell-dk/webp-convert",
"version": "2.9.2",
"version_normalized": "2.9.2.0",
"source": {
"type": "git",
"url": "https://github.com/rosell-dk/webp-convert.git",
"reference": "5ccba85ebe3b28ae229459fd0baed25314616ac9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/rosell-dk/webp-convert/zipball/5ccba85ebe3b28ae229459fd0baed25314616ac9",
"reference": "5ccba85ebe3b28ae229459fd0baed25314616ac9",
"shasum": ""
},
"require": {
"php": "^5.6 | ^7.0 | ^8.0",
"rosell-dk/exec-with-fallback": "^1.0.0",
"rosell-dk/image-mime-type-guesser": "^1.1.1",
"rosell-dk/locate-binaries": "^1.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpstan/phpstan": "^1.5",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*"
},
"suggest": {
"ext-gd": "to use GD extension for converting. Note: Gd must be compiled with webp support",
"ext-imagick": "to use Imagick extension for converting. Note: Gd must be compiled with webp support",
"ext-vips": "to use Vips extension for converting.",
"php-stan/php-stan": "Suggested for dev, in order to analyse code before committing"
},
"time": "2022-05-19T13:56:36+00:00",
"type": "library",
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"WebPConvert\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
},
{
"name": "Martin Folkers",
"homepage": "https://twobrain.io",
"role": "Collaborator"
}
],
"description": "Convert JPEG & PNG to WebP with PHP",
"keywords": [
"Webp",
"cwebp",
"gd",
"image conversion",
"images",
"imagick",
"jpg",
"jpg2webp",
"png",
"png2webp"
],
"funding": [
{
"url": "https://github.com/rosell-dk",
"type": "github"
},
{
"url": "https://ko-fi.com/rosell",
"type": "ko_fi"
}
],
"install-path": "../rosell-dk/webp-convert"
}
],
"dev": false,
"dev-package-names": []
}

View File

@ -0,0 +1,77 @@
<?php return array(
'root' => array(
'name' => 'oksydan/is_themecore',
'pretty_version' => 'dev-develop',
'version' => 'dev-develop',
'reference' => '151e70ae2811e504b191dd09240b953614d7185d',
'type' => 'prestashop-module',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => false,
),
'versions' => array(
'oksydan/is_themecore' => array(
'pretty_version' => 'dev-develop',
'version' => 'dev-develop',
'reference' => '151e70ae2811e504b191dd09240b953614d7185d',
'type' => 'prestashop-module',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'rosell-dk/exec-with-fallback' => array(
'pretty_version' => '1.2.0',
'version' => '1.2.0.0',
'reference' => 'f88a6b29abd0b580566056b7c1eb0434eb5db20d',
'type' => 'library',
'install_path' => __DIR__ . '/../rosell-dk/exec-with-fallback',
'aliases' => array(),
'dev_requirement' => false,
),
'rosell-dk/file-util' => array(
'pretty_version' => '0.1.1',
'version' => '0.1.1.0',
'reference' => '2ff895308c37f448b34b031cfbfd8e45f43936fd',
'type' => 'library',
'install_path' => __DIR__ . '/../rosell-dk/file-util',
'aliases' => array(),
'dev_requirement' => false,
),
'rosell-dk/image-mime-type-guesser' => array(
'pretty_version' => '1.1.1',
'version' => '1.1.1.0',
'reference' => '72f7040e95a78937ae2edece452530224fcacea6',
'type' => 'library',
'install_path' => __DIR__ . '/../rosell-dk/image-mime-type-guesser',
'aliases' => array(),
'dev_requirement' => false,
),
'rosell-dk/image-mime-type-sniffer' => array(
'pretty_version' => '1.1.1',
'version' => '1.1.1.0',
'reference' => '9ed14cc5d2c14c417660a4dd1946b5f056494691',
'type' => 'library',
'install_path' => __DIR__ . '/../rosell-dk/image-mime-type-sniffer',
'aliases' => array(),
'dev_requirement' => false,
),
'rosell-dk/locate-binaries' => array(
'pretty_version' => '1.0',
'version' => '1.0.0.0',
'reference' => 'bd2f493383ecd55aa519828dd2898e30f3b9cbb0',
'type' => 'library',
'install_path' => __DIR__ . '/../rosell-dk/locate-binaries',
'aliases' => array(),
'dev_requirement' => false,
),
'rosell-dk/webp-convert' => array(
'pretty_version' => '2.9.2',
'version' => '2.9.2.0',
'reference' => '5ccba85ebe3b28ae229459fd0baed25314616ac9',
'type' => 'library',
'install_path' => __DIR__ . '/../rosell-dk/webp-convert',
'aliases' => array(),
'dev_requirement' => false,
),
),
);

View File

@ -0,0 +1,26 @@
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 70100)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 7.1.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
trigger_error(
'Composer detected issues in your platform: ' . implode(' ', $issues),
E_USER_ERROR
);
}

View File

@ -0,0 +1,2 @@
github: rosell-dk
ko_fi: rosell

View File

@ -0,0 +1,36 @@
name: PHP
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
php80:
name: PHP 8.1
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04]
php: [8.1]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test

View File

@ -0,0 +1,262 @@
name: Large testsuite (run manually before releases)
on: workflow_dispatch
jobs:
php81:
name: PHP 8.1
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, windows-2016, macos-11, macos-10.15]
php: [8.1]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test
php80:
name: PHP 8.0
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [windows-2022]
php: [8.0]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test
php74:
name: PHP 7.4
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04, ubuntu-18.04, windows-2019, windows-2016]
php: [7.4]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test
php73:
name: PHP 7.3
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04]
php: [7.3]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test
php72:
name: PHP 7.2
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04]
php: [7.2]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
- name: Downgrade PHP unit to a version that supports PHP 7.2
run: composer require "phpunit/phpunit:^8.0" --dev
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test
php71:
name: PHP 7.1
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04]
php: [7.1]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
- name: Downgrade PHP unit to a version that supports PHP 7.1
run: composer require "phpunit/phpunit:^7.0" --dev
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test
php70:
name: PHP 7.0
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-18.04]
php: [7.0]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
- name: Downgrade PHP unit to a version that supports PHP 7.1
run: composer require "phpunit/phpunit:^6.0" --dev
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test
disabled:
name: Disabled functions
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04, windows-2019]
php: [8.0, 7.4]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Setup PHP (disable some functions)
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
# PS: I would have liked to test disabling ini_get, but then composer fails
# composer alse needs proc_open, so I cannot test without that either
ini-values: disable_functions="exec,passthru"
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test
- name: Re-setup PHP (disable other functions)
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
ini-values: disable_functions="exec"
- name: Run test suite
run: composer run-script test
- name: Re-setup PHP (disable yet other functions)
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
ini-values: disable_functions="passthru"
- name: Run test suite
run: composer run-script test

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,69 @@
# Exec with fallback
[![Latest Stable Version](http://poser.pugx.org/rosell-dk/exec-with-fallback/v)](https://packagist.org/packages/rosell-dk/exec-with-fallback)
[![Build Status](https://github.com/rosell-dk/exec-with-fallback/actions/workflows/php.yml/badge.svg)](https://github.com/rosell-dk/exec-with-fallback/actions/workflows/php.yml)
[![Software License](http://poser.pugx.org/rosell-dk/exec-with-fallback/license)](https://github.com/rosell-dk/exec-with-fallback/blob/master/LICENSE)
[![PHP Version Require](http://poser.pugx.org/rosell-dk/exec-with-fallback/require/php)](https://packagist.org/packages/rosell-dk/exec-with-fallback)
[![Daily Downloads](http://poser.pugx.org/rosell-dk/exec-with-fallback/d/daily)](https://packagist.org/packages/rosell-dk/exec-with-fallback)
Some shared hosts may have disabled *exec()*, but leaved *proc_open()*, *passthru()*, *popen()* or *shell_exec()* open. In case you want to easily fall back to emulating *exec()* with one of these, you have come to the right library.
This library can be useful if you a writing code that is meant to run on a broad spectrum of systems, as it makes your exec() call succeed on more of these systems.
## Usage:
Simply swap out your current *exec()* calls with *ExecWithFallback::exec()*. The signatures are exactly the same.
```php
use ExecWithFallback\ExecWithFallback;
$result = ExecWithFallback::exec('echo "hi"', $output, $result_code);
// $output (array) now holds the output
// $result_code (int) now holds the result code
// $return (string | false) is now false in case of failure or the last line of the output
```
Note that while the signatures are the same, errors are not exactly the same. There is a reason for that. On some systems, a real `exec()` call results in a FATAL error when the function has been disabled. That is: An error, that cannot be catched. You probably don't want to halt execution on some systems, but not on other. But if you do, use `ExecWithFallback::execNoMercy` instead of `ExecWithFallback::exec`. In case no emulations are available, it calls *exec()*, ensuring exact same error handling as normal *exec()*.
If you have `function_exists('exec')` in your code, you probably want to change them to `ExecWithFallback::anyAvailable()`
## Installing
`composer require rosell-dk/exec-with-fallback`
## Implementation
*ExecWithFallback::exec()* first checks if *exec()* is available and calls it, if it is. In case *exec* is unavailable (deactivated on server), or exec() returns false, it moves on to checking if *passthru()* is available and so on. The order is as follows:
- exec()
- passthru()
- popen()
- proc_open()
- shell_exec()
In case all functions are unavailable, a normal exception is thrown (class: Exception). This is more gentle behavior than real exec(), which on some systems throws FATAL error when the function is disabled. If you want exactly same errors, use `ExecWithFallback::execNoMercy` instead, which instead of throwing an exception calls *exec*, which will result in a throw (to support older PHP, you need to catch both Exception and Throwable. And note that you cannot catch on all systems, because some throws FATAL)
In case none succeeded, but at least one failed by returning false, false is returned. Again to mimic *exec()* behavior.
PS: As *shell_exec()* does not support *$result_code*, it will only be used when $result_code isn't supplied. *system()* is not implemented, as it cannot return the last line of output and there is no way to detect if your code relies on that.
If you for some reason want to run a specific exec() emulation, you can use the corresponding class directly, ie *ProcOpen::exec()*.
## Is it worth it?
Well, often these functions are often all enabled or all disabled. So on the majority of systems, it will not make a difference. But on the other hand: This library is easily installed, very lightweight and very well tested.
**easily installed**\
Install with composer (`composer require rosell-dk/exec-with-fallback`) and substitute your *exec()* calls.
**lightweight**\
The library is extremely lightweight. In case *exec()* is available, it is called immediately and only the main file is autoloaded. In case all are unavailable, it only costs a little loop, amounting to five *function_exists()* calls, and again, only the main file is autoloaded. In case *exec()* is unavailable, but one of the others are available, only that implementation is autoloaded, besides the main file.
**well tested**\
I made sure that the function behaves exactly like *exec()*, and wrote a lot of test cases. It is tested on ubuntu, windows, mac (all in several versions). It is tested in PHP 7.0, 7.1, 7.2, 7.3, 7.4 and 8.0. And it is tested in different combinations of disabled functions.
**going to be maintained**\
I'm going to use this library in [webp-convert](https://github.com/rosell-dk/webp-convert), which is used in many projects. So it is going to be widely used. While I don't expect much need for maintenance for this project, it is going to be there, if needed.
**Con: risk of being recognized as malware**
There is a slight risk that a lazy malware creator uses this library for his malware. The risk is however very small, as the library isn't suitable for malware. First off, the library doesn't try *system()*, as that function does not return output and thus cannot be used to emulate *exec()*. A malware creator would desire to try all possible ways to get his malware executed. Secondly, malware creators probably don't use composer for their malware and would probably want a single function instead of having it spread over multiple files. Third, the library here use a lot of efford in getting the emululated functions to behave exactly as exec(). This concern is probably non-existant for malware creators, who probably cares more about the effect of running the malware. Lastly, a malware creator would want to write his own function instead of copying code found on the internet. Copying stuff would impose a chance that the code is used by another malware creator which increases the risk of anti malware software recognizing it as malware.
## Do you like what I do?
Perhaps you want to support my work, so I can continue doing it :)
- [Become a backer or sponsor on Patreon](https://www.patreon.com/rosell).
- [Buy me a Coffee](https://ko-fi.com/rosell)

View File

@ -0,0 +1,67 @@
{
"name": "rosell-dk/exec-with-fallback",
"description": "An exec() with fallback to emulations (proc_open, etc)",
"type": "library",
"license": "MIT",
"keywords": ["exec", "open_proc", "command", "fallback", "sturdy", "resiliant"],
"scripts": {
"ci": [
"@test",
"@phpcs-all",
"@composer validate --no-check-all --strict",
"@phpstan-global"
],
"test": "./vendor/bin/phpunit --coverage-text",
"test-41": "phpunit --coverage-text --configuration 'phpunit-41.xml.dist'",
"phpunit": "phpunit --coverage-text",
"test-no-cov": "phpunit --no-coverage",
"cs-fix-all": [
"php-cs-fixer fix src"
],
"cs-fix": "php-cs-fixer fix",
"cs-dry": "php-cs-fixer fix --dry-run --diff",
"phpcs": "phpcs --standard=PSR2",
"phpcs-all": "phpcs --standard=PSR2 src",
"phpcbf": "phpcbf --standard=PSR2",
"phpstan": "vendor/bin/phpstan analyse src --level=4",
"phpstan-global-old": "~/.composer/vendor/bin/phpstan analyse src --level=4",
"phpstan-global": "~/.config/composer/vendor/bin/phpstan analyse src --level=4"
},
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"autoload": {
"psr-4": { "ExecWithFallback\\": "src/" }
},
"autoload-dev": {
"psr-4": { "ExecWithFallback\\Tests\\": "tests/" }
},
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
}
],
"require": {
"php": "^5.6 | ^7.0 | ^8.0"
},
"suggest": {
"php-stan/php-stan": "Suggested for dev, in order to analyse code before committing"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*"
},
"config": {
"sort-packages": true
}
}

View File

@ -0,0 +1,3 @@
parameters:
ignoreErrors:
- '#PHPDoc tag @param.*Unexpected token "&"#'

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="vendor/autoload.php" backupGlobals="false" backupStaticAttributes="false" colors="true" verbose="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<directory suffix=".php">src/</directory>
</include>
<report>
<clover outputFile="build/logs/clover.xml"/>
<html outputDirectory="build/coverage"/>
<text outputFile="build/coverage.txt"/>
</report>
</coverage>
<testsuites>
<testsuite name=":vendor Test Suite">
<directory suffix="Test.php">./tests/</directory>
</testsuite>
</testsuites>
<logging>
<junit outputFile="build/report.junit.xml"/>
</logging>
</phpunit>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name=":vendor Test Suite">
<directory suffix="Test.php">./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<logging>
<log type="junit" target="build/report.junit.xml"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<log type="coverage-text" target="build/coverage.txt"/>
<log type="coverage-html" target="build/coverage"/>
</logging>
</phpunit>

View File

@ -0,0 +1,39 @@
<?php
namespace ExecWithFallback;
/**
* Check if any of the methods are available on the system.
*
* @package ExecWithFallback
* @author Bjørn Rosell <it@rosell.dk>
*/
class Availability extends ExecWithFallback
{
/**
* Check if any of the methods are available on the system.
*
* @param boolean $needResultCode Whether the code using this library is going to supply $result_code to the exec
* call. This matters because shell_exec is only available when not.
*/
public static function anyAvailable($needResultCode = true)
{
foreach (self::$methods as $method) {
if (self::methodAvailable($method, $needResultCode)) {
return true;
}
}
return false;
}
public static function methodAvailable($method, $needResultCode = true)
{
if (!ExecWithFallback::functionEnabled($method)) {
return false;
}
if ($needResultCode) {
return ($method != 'shell_exec');
}
return true;
}
}

View File

@ -0,0 +1,127 @@
<?php
namespace ExecWithFallback;
/**
* Execute command with exec(), open_proc() or whatever available
*
* @package ExecWithFallback
* @author Bjørn Rosell <it@rosell.dk>
*/
class ExecWithFallback
{
protected static $methods = ['exec', 'passthru', 'popen', 'proc_open', 'shell_exec'];
/**
* Check if any of the methods are available on the system.
*
* @param boolean $needResultCode Whether the code using this library is going to supply $result_code to the exec
* call. This matters because shell_exec is only available when not.
*/
public static function anyAvailable($needResultCode = true)
{
return Availability::anyAvailable($needResultCode);
}
/**
* Check if a function is enabled (function_exists as well as ini is tested)
*
* @param string $functionName The name of the function
*
* @return boolean If the function is enabled
*/
public static function functionEnabled($functionName)
{
if (!function_exists($functionName)) {
return false;
}
if (function_exists('ini_get')) {
if (ini_get('safe_mode')) {
return false;
}
$d = ini_get('disable_functions') . ',' . ini_get('suhosin.executor.func.blacklist');
if ($d === false) {
$d = '';
}
$d = preg_replace('/,\s*/', ',', $d);
if (strpos(',' . $d . ',', ',' . $functionName . ',') !== false) {
return false;
}
}
return is_callable($functionName);
}
/**
* Execute. - A substitute for exec()
*
* Same signature and results as exec(): https://www.php.net/manual/en/function.exec.php
* In case neither exec(), nor emulations are available, it throws an Exception.
* This is more gentle than real exec(), which on some systems throws a FATAL when exec() is disabled
* If you want the more acurate substitute, which might halt execution, use execNoMercy() instead.
*
* @param string $command The command to execute
* @param string &$output (optional)
* @param int &$result_code (optional)
*
* @return string | false The last line of output or false in case of failure
* @throws \Exception If no methods are available
*/
public static function exec($command, &$output = null, &$result_code = null)
{
foreach (self::$methods as $method) {
if (self::functionEnabled($method)) {
if (func_num_args() >= 3) {
if ($method == 'shell_exec') {
continue;
}
$result = self::runExec($method, $command, $output, $result_code);
} else {
$result = self::runExec($method, $command, $output);
}
if ($result !== false) {
return $result;
}
}
}
if (isset($result) && ($result === false)) {
return false;
}
throw new \Exception('exec() is not available');
}
/**
* Execute. - A substitute for exec(), with exact same errors thrown if exec() is missing.
*
* Danger: On some systems, this results in a fatal (non-catchable) error.
*/
public static function execNoMercy($command, &$output = null, &$result_code = null)
{
if (func_num_args() == 3) {
return ExecWithFallbackNoMercy::exec($command, $output, $result_code);
} else {
return ExecWithFallbackNoMercy::exec($command, $output);
}
}
public static function runExec($method, $command, &$output = null, &$result_code = null)
{
switch ($method) {
case 'exec':
return exec($command, $output, $result_code);
case 'passthru':
return Passthru::exec($command, $output, $result_code);
case 'popen':
return POpen::exec($command, $output, $result_code);
case 'proc_open':
return ProcOpen::exec($command, $output, $result_code);
case 'shell_exec':
if (func_num_args() == 4) {
return ShellExec::exec($command, $output, $result_code);
} else {
return ShellExec::exec($command, $output);
}
}
return false;
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace ExecWithFallback;
/**
* Execute command with exec(), open_proc() or whatever available
*
* @package ExecWithFallback
* @author Bjørn Rosell <it@rosell.dk>
*/
class ExecWithFallbackNoMercy
{
/**
* Execute. - A substitute for exec()
*
* Same signature and results as exec(): https://www.php.net/manual/en/function.exec.php
*
* This is our hardcore version of our exec(). It does not merely throw an Exception, if
* no methods are available. It calls exec().
* This ensures exactly same behavior as normal exec() - the same error is thrown.
* You might want that. But do you really?
* DANGER: On some systems, calling a disabled exec() results in a fatal (non-catchable) error.
*
* @param string $command The command to execute
* @param string &$output (optional)
* @param int &$result_code (optional)
*
* @return string | false The last line of output or false in case of failure
* @throws \Exception|\Error If no methods are available. Note: On some systems, it is FATAL!
*/
public static function exec($command, &$output = null, &$result_code = null)
{
foreach (self::$methods as $method) {
if (self::functionEnabled($method)) {
if (func_num_args() >= 3) {
if ($method == 'shell_exec') {
continue;
}
$result = self::runExec($method, $command, $output, $result_code);
} else {
$result = self::runExec($method, $command, $output);
}
if ($result !== false) {
return $result;
}
}
}
if (isset($result) && ($result === false)) {
return false;
}
// MIGHT THROW FATAL!
return exec($command, $output, $result_code);
}
}

View File

@ -0,0 +1,60 @@
<?php
namespace ExecWithFallback;
/**
* Emulate exec() with system()
*
* @package ExecWithFallback
* @author Bjørn Rosell <it@rosell.dk>
*/
class POpen
{
/**
* Emulate exec() with system()
*
* @param string $command The command to execute
* @param string &$output (optional)
* @param int &$result_code (optional)
*
* @return string | false The last line of output or false in case of failure
*/
public static function exec($command, &$output = null, &$result_code = null)
{
$handle = @popen($command, "r");
if ($handle === false) {
return false;
}
$result = '';
while (!@feof($handle)) {
$result .= fread($handle, 1024);
}
//Note: Unix Only:
// pclose() is internally implemented using the waitpid(3) system call.
// To obtain the real exit status code the pcntl_wexitstatus() function should be used.
$result_code = pclose($handle);
$theOutput = preg_split('/\s*\r\n|\s*\n\r|\s*\n|\s*\r/', $result);
// remove the last element if it is blank
if ((count($theOutput) > 0) && ($theOutput[count($theOutput) -1] == '')) {
array_pop($theOutput);
}
if (count($theOutput) == 0) {
return '';
}
if (gettype($output) == 'array') {
foreach ($theOutput as $line) {
$output[] = $line;
}
} else {
$output = $theOutput;
}
return $theOutput[count($theOutput) -1];
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace ExecWithFallback;
/**
* Emulate exec() with passthru()
*
* @package ExecWithFallback
* @author Bjørn Rosell <it@rosell.dk>
*/
class Passthru
{
/**
* Emulate exec() with passthru()
*
* @param string $command The command to execute
* @param string &$output (optional)
* @param int &$result_code (optional)
*
* @return string | false The last line of output or false in case of failure
*/
public static function exec($command, &$output = null, &$result_code = null)
{
ob_start();
// Note: We use try/catch in order to close output buffering in case it throws
try {
passthru($command, $result_code);
} catch (\Exception $e) {
ob_get_clean();
passthru($command, $result_code);
} catch (\Throwable $e) {
ob_get_clean();
passthru($command, $result_code);
}
$result = ob_get_clean();
// split new lines. Also remove trailing space, as exec() does
$theOutput = preg_split('/\s*\r\n|\s*\n\r|\s*\n|\s*\r/', $result);
// remove the last element if it is blank
if ((count($theOutput) > 0) && ($theOutput[count($theOutput) -1] == '')) {
array_pop($theOutput);
}
if (count($theOutput) == 0) {
return '';
}
if (gettype($output) == 'array') {
foreach ($theOutput as $line) {
$output[] = $line;
}
} else {
$output = $theOutput;
}
return $theOutput[count($theOutput) -1];
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace ExecWithFallback;
/**
* Emulate exec() with proc_open()
*
* @package ExecWithFallback
* @author Bjørn Rosell <it@rosell.dk>
*/
class ProcOpen
{
/**
* Emulate exec() with proc_open()
*
* @param string $command The command to execute
* @param string &$output (optional)
* @param int &$result_code (optional)
*
* @return string | false The last line of output or false in case of failure
*/
public static function exec($command, &$output = null, &$result_code = null)
{
$descriptorspec = array(
//0 => array("pipe", "r"),
1 => array("pipe", "w"),
//2 => array("pipe", "w"),
//2 => array("file", "/tmp/error-output.txt", "a")
);
$cwd = getcwd(); // or is "/tmp" better?
$processHandle = proc_open($command, $descriptorspec, $pipes, $cwd);
$result = "";
if (is_resource($processHandle)) {
// Got this solution here:
// https://stackoverflow.com/questions/5673740/php-or-apache-exec-popen-system-and-proc-open-commands-do-not-execute-any-com
//fclose($pipes[0]);
$result = stream_get_contents($pipes[1]);
fclose($pipes[1]);
//fclose($pipes[2]);
$result_code = proc_close($processHandle);
// split new lines. Also remove trailing space, as exec() does
$theOutput = preg_split('/\s*\r\n|\s*\n\r|\s*\n|\s*\r/', $result);
// remove the last element if it is blank
if ((count($theOutput) > 0) && ($theOutput[count($theOutput) -1] == '')) {
array_pop($theOutput);
}
if (count($theOutput) == 0) {
return '';
}
if (gettype($output) == 'array') {
foreach ($theOutput as $line) {
$output[] = $line;
}
} else {
$output = $theOutput;
}
return $theOutput[count($theOutput) -1];
} else {
return false;
}
}
}

View File

@ -0,0 +1,69 @@
<?php
namespace ExecWithFallback;
/**
* Emulate exec() with system()
*
* @package ExecWithFallback
* @author Bjørn Rosell <it@rosell.dk>
*/
class ShellExec
{
/**
* Emulate exec() with shell_exec()
*
* @param string $command The command to execute
* @param string &$output (optional)
* @param int &$result_code (optional)
*
* @return string | false The last line of output or false in case of failure
*/
public static function exec($command, &$output = null, &$result_code = null)
{
$resultCodeSupplied = (func_num_args() >= 3);
if ($resultCodeSupplied) {
throw new \Exception('ShellExec::exec() does not support $result_code argument');
}
$result = shell_exec($command);
// result:
// - A string containing the output from the executed command,
// - false if the pipe cannot be established
// - or null if an error occurs or the command produces no output.
if ($result === false) {
return false;
}
if (is_null($result)) {
// hm, "null if an error occurs or the command produces no output."
// What were they thinking?
// And yes, it does return null, when no output, which is confirmed in the test "echo hi 1>/dev/null"
// What should we do? Throw or accept?
// Perhaps shell_exec throws in newer versions of PHP instead of returning null.
// We are counting on it until proved wrong.
return '';
}
$theOutput = preg_split('/\s*\r\n|\s*\n\r|\s*\n|\s*\r/', $result);
// remove the last element if it is blank
if ((count($theOutput) > 0) && ($theOutput[count($theOutput) -1] == '')) {
array_pop($theOutput);
}
if (count($theOutput) == 0) {
return '';
}
if (gettype($output) == 'array') {
foreach ($theOutput as $line) {
$output[] = $line;
}
} else {
$output = $theOutput;
}
return $theOutput[count($theOutput) -1];
}
}

View File

@ -0,0 +1,9 @@
<?php
include 'vendor/autoload.php';
//include 'src/ExecWithFallback.php';
use ExecWithFallback\ExecWithFallback;
use ExecWithFallback\Tests\ExecWithFallbackTest;
ExecWithFallback::exec('echo hello');
ExecWithFallbackTest::testExec();

View File

@ -0,0 +1,2 @@
github: rosell-dk
ko_fi: rosell

View File

@ -0,0 +1,122 @@
name: build
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest]
php: [8.1]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Determine which version of xdebug to use
run: |
# Set XDEBUG to "xdebug2" for PHP 7.2-7.4, but to "xdebug" for
if grep -oP '^7.[234]' <<< "$PHP" > /dev/null; then XDEBUG=xdebug2; else XDEBUG=xdebug; fi
# Store XDEBUG in github env, so we can access it later through env.XDEBUG
echo "XDEBUG=$XDEBUG" >> $GITHUB_ENV
echo "Result: ${{ env.XDEBUG }}"
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: ${{ env.XDEBUG }}
- name: Validate composer.json
run: composer validate --strict
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Removing phpstan, as it does not work on PHP 7.1"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Remove phpstan, as it does not work on PHP 7.0"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key, and for install
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-${{ matrix.php }}
${{ runner.os }}-php-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test
- name: Run phpstan on PHP>=7.2 (to check php syntax)
if: (matrix.php != '7.0') && (matrix.php != '7.1') && (matrix.php != '7.2')
run: composer run-script phpstan
- name: run phpcs (to check coding style)
run: composer run-script phpcs-all
- name: Create coverage badge json
run: |
# Extract total coverage
COVERAGE=$(grep -oP -m 1 'Lines:\s*\K[0-9.%]+' build/coverage.txt)
# Set COLOR based on COVERAGE
# 0-49%: red, 50%-69%: orange, 70%-80%: yellow, 90%-100%: brightgreen
if grep -oP '(^9\d.)|(^100.)' <<< "$COVERAGE" > /dev/null; then COLOR=brightgreen; elif grep -oP '[87]\d.' <<< "$COVERAGE" > /dev/null; then COLOR=yellow; elif grep -oP '[65]\d.' <<< "$COVERAGE" > /dev/null; then COLOR=orange; else COLOR=red; fi;
# Generate bagde json
echo \{\"schemaVersion\":1,\"label\":\"coverage\",\"message\":\"$COVERAGE\",\"color\":\"$COLOR\"\} | tee build/coverage-badge.json
# PS: If we needed COVERAGE elsewhere, we could store in ENV like this:
# echo "COVERAGE=$COVERAGE" >> $GITHUB_ENV
- name: Install SSH Key (for deployment of code coverage)
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.DEPLOY_KEY }}
known_hosts: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
- name: Upload code coverage report
run: |
sh -c "rsync -rtog --chown :www-data $GITHUB_WORKSPACE/build/ $DEPLOY_DESTINATION --delete"
env:
DEPLOY_DESTINATION: ${{ secrets.DEPLOY_DESTINATION }}

View File

@ -0,0 +1,83 @@
name: Big test (trigger manually before releasing)
on: workflow_dispatch
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, macos-11, macos-10.15]
php: [8.1, 8.0, 7.4, 7.3, 7.2, 7.1, 7.0]
#os: [windows-2022, macos-10.15]
#php: [8.1]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
- name: Validate composer.json
run: composer validate --strict
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Removing phpstan, as it does not work on PHP 7.1"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Remove phpstan, as it does not work on PHP 7.0"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-${{ matrix.php }}
${{ runner.os }}-php-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test-no-cov
- name: Run phpstan on PHP>=7.2 (to check php syntax)
if: (matrix.php != '7.0') && (matrix.php != '7.1') && (matrix.php != '7.2')
run: composer run-script phpstan
- name: run phpcs (to check coding style)
run: composer run-script phpcs-all

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2018 Bjørn Rosell
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,22 @@
# File Util
[![Build Status](https://github.com/rosell-dk/file-util/workflows/build/badge.svg)](https://github.com/rosell-dk/file-util/actions/workflows/php.yml)
[![Software License](https://img.shields.io/badge/license-MIT-418677.svg)](https://github.com/rosell-dk/file-util/blob/master/LICENSE)
[![Coverage](https://img.shields.io/endpoint?url=https://little-b.it/file-util/code-coverage/coverage-badge.json)](http://little-b.it/file-util/code-coverage/coverage/index.html)
[![Latest Stable Version](https://img.shields.io/packagist/v/rosell-dk/file-util.svg)](https://packagist.org/packages/rosell-dk/file-util)
[![Minimum PHP Version](https://img.shields.io/packagist/php-v/rosell-dk/file-util)](https://php.net)
Just a bunch of handy methods for dealing with files and paths:
- *FileExists::fileExists($path)*:\
A well-behaved version of *file_exists* that throws upon failure rather than emitting a warning
- *FileExists::fileExistsTryHarder($path)*:\
Also well-behaved. Tries FileExists::fileExists(). In case of failure, tries exec()-based implementation
- *PathValidator::checkPath($path)*:\
Check if path looks valid and doesn't contain suspecious patterns
- *PathValidator::checkFilePathIsRegularFile($path)*:\
Check if path points to a regular file (and doesnt match suspecious patterns)

View File

@ -0,0 +1,69 @@
{
"name": "rosell-dk/file-util",
"description": "Functions for dealing with files and paths",
"type": "library",
"license": "MIT",
"keywords": ["files", "path", "util"],
"scripts": {
"ci": [
"@test",
"@phpcs-all",
"@composer validate --no-check-all --strict",
"@phpstan-global"
],
"phpunit": "phpunit --coverage-text",
"test": "phpunit --coverage-text=build/coverage.txt --coverage-clover=build/coverage.clover --coverage-html=build/coverage --whitelist=src tests",
"test-no-cov": "phpunit --no-coverage tests",
"test-41": "phpunit --no-coverage --configuration 'phpunit-41.xml.dist'",
"test-with-coverage": "phpunit --coverage-text --configuration 'phpunit-with-coverage.xml.dist'",
"test-41-with-coverage": "phpunit --coverage-text --configuration 'phpunit-41.xml.dist'",
"cs-fix-all": [
"php-cs-fixer fix src"
],
"cs-fix": "php-cs-fixer fix",
"cs-dry": "php-cs-fixer fix --dry-run --diff",
"phpcs": "phpcs --standard=phpcs-ruleset.xml",
"phpcs-all": "phpcs --standard=phpcs-ruleset.xml src",
"phpcbf": "phpcbf --standard=PSR2",
"phpstan": "vendor/bin/phpstan analyse src --level=4",
"phpstan-global-old": "~/.composer/vendor/bin/phpstan analyse src --level=4",
"phpstan-global": "~/.config/composer/vendor/bin/phpstan analyse src --level=4"
},
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"autoload": {
"psr-4": { "FileUtil\\": "src/" }
},
"autoload-dev": {
"psr-4": { "FileUtil\\Tests\\": "tests/" }
},
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
}
],
"require": {
"php": ">=5.4",
"rosell-dk/exec-with-fallback": "^1.0.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*",
"phpstan/phpstan": "^1.5",
"mikey179/vfsstream": "^1.6"
},
"config": {
"sort-packages": true
}
}

View File

@ -0,0 +1,8 @@
<?xml version="1.0"?>
<ruleset name="Custom Standard">
<description>PSR2 without line ending rule - let git manage the EOL cross the platforms</description>
<rule ref="PSR2" />
<rule ref="Generic.Files.LineEndings">
<exclude name="Generic.Files.LineEndings.InvalidEOLChar"/>
</rule>
</ruleset>

View File

@ -0,0 +1,96 @@
<?php
namespace FileUtil;
use FileUtil\FileExistsUsingExec;
/**
* A fileExist function free of deception
*
* @package FileUtil
* @author Bjørn Rosell <it@rosell.dk>
*/
class FileExists
{
private static $lastWarning;
/**
* A warning handler that registers that a warning has occured and suppresses it.
*
* The function is a callback used with "set_error_handler".
* It is declared public because it needs to be accessible from the point where the warning is triggered.
*
* @param integer $errno
* @param string $errstr
* @param string $errfile
* @param integer $errline
*
* @return void
*/
public static function warningHandler($errno, $errstr, $errfile, $errline)
{
self::$lastWarning = [$errstr, $errno];
// Suppress the warning by returning void
return;
}
/**
* A well behaved replacement for file_exist that throws upon failure rather than emitting a warning.
*
* @throws \Exception Throws an exception in case file_exists emits a warning
* @return boolean True if file exists. False if it doesn't.
*/
public static function fileExists($path)
{
// There is a challenges here:
// We want to suppress warnings, but at the same time we want to know that it happened.
// We achieve this by registering an error handler
set_error_handler(
array('FileUtil\FileExists', "warningHandler"),
E_WARNING | E_USER_WARNING | E_NOTICE | E_USER_NOTICE
);
self::$lastWarning = null;
$found = @file_exists($path);
// restore previous error handler immediately
restore_error_handler();
// If file_exists returns true, we can rely on there being a file there
if ($found) {
return true;
}
// file_exists returned false.
// this result is only trustworthy if no warning was emitted.
if (is_null(self::$lastWarning)) {
return false;
}
list($errstr, $errno) = self::$lastWarning;
throw new \Exception($errstr, $errno);
}
/**
* A fileExist doing the best it can.
*
* @throws \Exception If it cannot be determined if the file exists
* @return boolean|null True if file exists. False if it doesn't.
*/
public static function fileExistsTryHarder($path)
{
try {
$result = self::fileExists($path);
} catch (\Exception $e) {
try {
$result = FileExistsUsingExec::fileExists($path);
} catch (\Exception $e) {
throw new \Exception('Cannot determine if file exists or not');
} catch (\Throwable $e) {
throw new \Exception('Cannot determine if file exists or not');
}
}
return $result;
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace FileUtil;
use ExecWithFallback\ExecWithFallback;
/**
* A fileExist implementation using exec()
*
* @package FileUtil
* @author Bjørn Rosell <it@rosell.dk>
*/
class FileExistsUsingExec
{
/**
* A fileExist based on an exec call.
*
* @throws \Exception If exec cannot be called
* @return boolean|null True if file exists. False if it doesn't.
*/
public static function fileExists($path)
{
if (!ExecWithFallback::anyAvailable()) {
throw new \Exception(
'cannot determine if file exists using exec() or similar - the function is unavailable'
);
}
// Lets try to find out by executing "ls path/to/cwebp"
ExecWithFallback::exec('ls ' . $path, $output, $returnCode);
if (($returnCode == 0) && (isset($output[0]))) {
return true;
}
// We assume that "ls" command is general available!
// As that failed, we can conclude the file does not exist.
return false;
}
}

View File

@ -0,0 +1,70 @@
<?php
namespace FileUtil;
use FileUtil\FileExists;
/**
*
*
* @package FileUtil
* @author Bjørn Rosell <it@rosell.dk>
*/
class PathValidator
{
/**
* Check if path looks valid and doesn't contain suspecious patterns.
* The path must meet the following criteria:
*
* - It must be a string
* - No NUL character
* - No control characters between 0-20
* - No phar stream wrapper
* - No php stream wrapper
* - No glob stream wrapper
* - Not empty path
*
* @throws \Exception In case the path doesn't meet all criteria
*/
public static function checkPath($path)
{
if (gettype($path) !== 'string') {
throw new \Exception('File path must be string');
}
if (strpos($path, chr(0)) !== false) {
throw new \Exception('NUL character is not allowed in file path!');
}
if (preg_match('#[\x{0}-\x{1f}]#', $path)) {
// prevents line feed, new line, tab, charater return, tab, ets.
throw new \Exception('Control characters #0-#20 not allowed in file path!');
}
// Prevent phar stream wrappers (security threat)
if (preg_match('#^phar://#', $path)) {
throw new \Exception('phar stream wrappers are not allowed in file path');
}
if (preg_match('#^(php|glob)://#', $path)) {
throw new \Exception('php and glob stream wrappers are not allowed in file path');
}
if (empty($path)) {
throw new \Exception('File path is empty!');
}
}
/**
* Check if path points to a regular file (and doesnt match suspecious patterns).
*
* @throws \Exception In case the path doesn't point to a regular file or matches suspecious patterns
*/
public static function checkFilePathIsRegularFile($path)
{
self::checkPath($path);
if (!FileExists::fileExists($path)) {
throw new \Exception('File does not exist');
}
if (@is_dir($path)) {
throw new \Exception('Expected a regular file, not a dir');
}
}
}

View File

@ -0,0 +1,76 @@
# PHP CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-php/ for more details
#
version: 2
jobs:
build71:
docker:
- image: circleci/php:7.1
steps:
- checkout
- run: sudo apt update
- run: sudo docker-php-ext-install zip
- restore_cache:
keys:
# "composer.lock" can be used if it is committed to the repo
- v1-dependencies-{{ checksum "composer.json" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run: composer install -n --prefer-dist
- save_cache:
key: v1-dependencies-{{ checksum "composer.json" }}
paths:
- ./vendor
- run: ./vendor/bin/phpunit
- run: wget https://scrutinizer-ci.com/ocular.phar
- run: php ocular.phar code-coverage:upload --format=php-clover coverage.clover
build70:
docker:
- image: circleci/php:7.0
steps:
- checkout
- run: sudo apt update
- restore_cache:
keys:
- v0-dependencies-{{ checksum "composer.json" }}
- v0-dependencies-
- run: composer install -n --prefer-dist
- save_cache:
key: v0-dependencies-{{ checksum "composer.json" }}
paths:
- ./vendor
- run: composer test
build56:
docker:
- image: circleci/php:5.6
steps:
- checkout
- run: sudo apt update
- restore_cache:
keys:
- v56-dependencies-{{ checksum "composer.json" }}
- v56-dependencies-
- run: composer install -n --prefer-dist
- save_cache:
key: v56-dependencies-{{ checksum "composer.json" }}
paths:
- ./vendor
- run: composer test
workflows:
version: 2
build_and_test_all:
jobs:
#- build71
#- build70
#- build56

View File

@ -0,0 +1,2 @@
github: rosell-dk
ko_fi: rosell

View File

@ -0,0 +1,123 @@
name: build
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest]
php: [8.1]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Determine which version of xdebug to use
run: |
# Set XDEBUG to "xdebug2" for PHP 7.2-7.4, but to "xdebug" for
if grep -oP '^7.[234]' <<< "$PHP" > /dev/null; then XDEBUG=xdebug2; else XDEBUG=xdebug; fi
# Store XDEBUG in github env, so we can access it later through env.XDEBUG
echo "XDEBUG=$XDEBUG" >> $GITHUB_ENV
echo "Result: ${{ env.XDEBUG }}"
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: ${{ env.XDEBUG }}
extensions: exif, mbstring, fileinfo, gd
- name: Validate composer.json
run: composer validate --strict
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Removing phpstan, as it does not work on PHP 7.1"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Remove phpstan, as it does not work on PHP 7.0"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key, and for install
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-${{ matrix.php }}
${{ runner.os }}-php-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test
- name: Run phpstan on PHP>=7.2 (to check php syntax)
if: (matrix.php != '7.0') && (matrix.php != '7.1') && (matrix.php != '7.2')
run: composer run-script phpstan
- name: run phpcs (to check coding style)
run: composer run-script phpcs-all
- name: Create coverage badge json
run: |
# Extract total coverage
COVERAGE=$(grep -oP -m 1 'Lines:\s*\K[0-9.%]+' build/coverage.txt)
# Set COLOR based on COVERAGE
# 0-49%: red, 50%-69%: orange, 70%-80%: yellow, 90%-100%: brightgreen
if grep -oP '(^9\d.)|(^100.)' <<< "$COVERAGE" > /dev/null; then COLOR=brightgreen; elif grep -oP '[87]\d.' <<< "$COVERAGE" > /dev/null; then COLOR=yellow; elif grep -oP '[65]\d.' <<< "$COVERAGE" > /dev/null; then COLOR=orange; else COLOR=red; fi;
# Generate bagde json
echo \{\"schemaVersion\":1,\"label\":\"coverage\",\"message\":\"$COVERAGE\",\"color\":\"$COLOR\"\} | tee build/coverage-badge.json
# PS: If we needed COVERAGE elsewhere, we could store in ENV like this:
# echo "COVERAGE=$COVERAGE" >> $GITHUB_ENV
- name: Install SSH Key (for deployment of code coverage)
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.DEPLOY_KEY }}
known_hosts: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
- name: Upload code coverage report
run: |
sh -c "rsync -rtog --chown :www-data $GITHUB_WORKSPACE/build/ $DEPLOY_DESTINATION --delete"
env:
DEPLOY_DESTINATION: ${{ secrets.DEPLOY_DESTINATION }}

View File

@ -0,0 +1,85 @@
name: Big test (trigger manually before releasing)
on: workflow_dispatch
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, macos-11, macos-10.15]
#os: [windows-2022, windows-2019]
php: [8.1, 8.0, 7.4, 7.3, 7.2, 7.1, 7.0]
#os: [windows-2022]
#php: [8.1, 7.0]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
extensions: exif, mbstring, fileinfo, gd
- name: Validate composer.json
run: composer validate --strict
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Removing phpstan, as it does not work on PHP 7.1"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Remove phpstan, as it does not work on PHP 7.0"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-${{ matrix.php }}
${{ runner.os }}-php-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test-no-cov
- name: Run phpstan on PHP>=7.2 (to check php syntax)
if: (matrix.php != '7.0') && (matrix.php != '7.1') && (matrix.php != '7.2')
run: composer run-script phpstan
- name: run phpcs (to check coding style)
run: composer run-script phpcs-all

View File

@ -0,0 +1,19 @@
<?php
$finder = PhpCsFixer\Finder::create()
->exclude('tests')
->in(__DIR__)
;
$config = PhpCsFixer\Config::create();
$config
->setRules([
'@PSR2' => true,
'array_syntax' => [
'syntax' => 'short',
],
])
->setFinder($finder)
;
return $config;

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2018 Bjørn Rosell
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,110 @@
# image-mime-type-guesser
[![Latest Stable Version](https://img.shields.io/packagist/v/rosell-dk/image-mime-type-guesser.svg?style=flat-square)](https://packagist.org/packages/rosell-dk/image-mime-type-guesser)
[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%205.6-8892BF.svg?style=flat-square)](https://php.net)
[![Build Status](https://img.shields.io/github/workflow/status/rosell-dk/image-mime-type-guesser/PHP?logo=GitHub&style=flat-square)](https://github.com/rosell-dk/image-mime-type-guesser/actions/workflows/php.yml)
[![Coverage](https://img.shields.io/endpoint?url=https://little-b.it/image-mime-type-guesser/code-coverage/coverage-badge.json)](http://little-b.it/image-mime-type-guesser/code-coverage/coverage/index.html)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/rosell-dk/image-mime-type-guesser/blob/master/LICENSE)
[![Monthly Downloads](http://poser.pugx.org/rosell-dk/image-mime-type-guesser/d/monthly)](https://packagist.org/packages/rosell-dk/image-mime-type-guesser)
[![Dependents](http://poser.pugx.org/rosell-dk/image-mime-type-guesser/dependents)](https://packagist.org/packages/rosell-dk/image-mime-type-guesser/dependents?order_by=downloads)
*Detect / guess mime type of an image*
Do you need to determine if a file is an image?<br>
And perhaps you also want to know the mime type of the image?<br>
&ndash; You come to the right library.
Ok, actually the library cannot offer mime type detection for images which works *on all platforms*, but it can try a whole stack of methods and optionally fall back to guess from the file extension.
The stack of detect methods are currently (and in that order):
- [This signature sniffer](https://github.com/rosell-dk/image-mime-type-sniffer) *Does not require any extensions. Recognizes popular image formats only*
- [`finfo`](https://www.php.net/manual/en/class.finfo.php) *Requires fileinfo extension to be enabled. (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)*
- [`exif_imagetype`](https://www.php.net/manual/en/function.exif-imagetype.php) *Requires that PHP is compiled with exif (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)*
- [`mime_content_type`](https://www.php.net/manual/en/function.mime-content-type.php) *Requires fileinfo. (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)*
Note that all these methods except the signature sniffer relies on the mime type mapping on the server (the `mime.types` file in Apache). If the server doesn't know about a certain mime type, it will not be detected. This does however not mean that the methods relies on the file extension. A png file renamed to "png.jpeg" will be correctly identified as *image/png*.
Besides the detection methods, the library also comes with a method for mapping file extension to mime type. It is rather limited, though.
## Installation
Install with composer:
```
composer require rosell-dk/image-mime-type-guesser
```
## Usage
To detect the mime type of a file, use `ImageMimeTypeGuesser::detect($filePath)`. It returns the mime-type, if the file is recognized as an image. *false* is returned if it is not recognized as an image. *null* is returned if the mime type could not be determined (ie due to none of the methods being available).
Example:
```php
use ImageMimeTypeGuesser\ImageMimeTypeGuesser;
$result = ImageMimeTypeGuesser::detect($filePath);
if (is_null($result)) {
// the mime type could not be determined
} elseif ($result === false) {
// it is NOT an image (not a mime type that the server knows about anyway)
// This happens when:
// a) The mime type is identified as something that is not an image (ie text)
// b) The mime type isn't identified (ie if the image type is not known by the server)
} else {
// it is an image, and we know its mime type!
$mimeType = $result;
}
```
For convenience, you can use *detectIsIn* method to test if a detection is in a list of mimetypes.
```php
if (ImageMimeTypeGuesser::detectIsIn($filePath, ['image/jpeg','image/png'])) {
// The file is a jpeg or a png
}
```
The `detect` method does not resort to mapping from file extension. In most cases you do not want to do that. In some cases it can be insecure to do that. For example, if you want to prevent a user from uploading executable files, you probably do not want to allow her to upload executable files with innocent looking file extenions, such as "evil-exe.jpg".
In some cases, though, you simply want a best guess, and in that case, falling back to mapping from file extension makes sense. In that case, you can use the *guess* method instead of the *detect* method. Or you can use *lenientGuess*. Lenient guess is even more slacky and will turn to mapping not only when dectect return *null*, but even when it returns *false*.
*Warning*: Beware that guessing from file extension is unsuited when your aim is to protect the server from harmful uploads.
*Notice*: Only a limited set of image extensions is recognized by the extension to mimetype mapper - namely the following: { apng, avif, bmp, gif, ico, jpg, jpeg, png, tif, tiff, webp, svg }. If you need some other specifically, feel free to add a PR, or ask me to do it by creating an issue.
Example:
```php
$result = ImageMimeTypeGuesser::guess($filePath);
if ($result !== false) {
// It appears to be an image
// BEWARE: This is only a guess, as we resort to mapping from file extension,
// when the file cannot be properly detected.
// DO NOT USE THIS GUESS FOR PROTECTING YOUR SERVER
$mimeType = $result;
} else {
// It does not appear to be an image
}
```
The guess functions also have convenience methods for testing against a list of mime types. They are called `ImageMimeTypeGuesser::guessIsIn` and `ImageMimeTypeGuesser::lenientGuessIsIn`.
Example:
```php
if (ImageMimeTypeGuesser::guessIsIn($filePath, ['image/jpeg','image/png'])) {
// The file appears to be a jpeg or a png
}
```
## Alternatives
Other sniffers:
- https://github.com/Intervention/mimesniffer
- https://github.com/zjsxwc/mime-type-sniffer
- https://github.com/Tinram/File-Identifier
## Do you like what I do?
Perhaps you want to support my work, so I can continue doing it :)
- [Become a backer or sponsor on Patreon](https://www.patreon.com/rosell).
- [Buy me a Coffee](https://ko-fi.com/rosell)

View File

@ -0,0 +1,63 @@
{
"name": "rosell-dk/image-mime-type-guesser",
"description": "Guess mime type of images",
"type": "library",
"license": "MIT",
"keywords": ["mime", "mime type", "image", "images"],
"scripts": {
"ci": [
"@test",
"@phpcs-all",
"@composer validate --no-check-all --strict",
"@phpstan"
],
"cs-fix-all": [
"php-cs-fixer fix src"
],
"cs-fix": "php-cs-fixer fix",
"cs-dry": "php-cs-fixer fix --dry-run --diff",
"test": "phpunit --coverage-text=build/coverage.txt --coverage-clover=build/coverage.clover --coverage-html=build/coverage --whitelist=src tests",
"test-no-cov": "phpunit tests",
"test2": "phpunit tests",
"phpcs": "phpcs --standard=phpcs-ruleset.xml",
"phpcs-all": "phpcs --standard=phpcs-ruleset.xml src",
"phpcbf": "phpcbf --standard=PSR2",
"phpstan": "vendor/bin/phpstan analyse src --level=4"
},
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"autoload": {
"psr-4": { "ImageMimeTypeGuesser\\": "src/" }
},
"autoload-dev": {
"psr-4": { "ImageMimeTypeGuesser\\Tests\\": "tests/" }
},
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
}
],
"require": {
"php": "^5.6 | ^7.0 | ^8.0",
"rosell-dk/image-mime-type-sniffer": "^1.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*",
"phpstan/phpstan": "^1.5"
},
"config": {
"sort-packages": true
}
}

View File

@ -0,0 +1,8 @@
<?xml version="1.0"?>
<ruleset name="Custom Standard">
<description>PSR2 without line ending rule - let git manage the EOL cross the platforms</description>
<rule ref="PSR2" />
<rule ref="Generic.Files.LineEndings">
<exclude name="Generic.Files.LineEndings.InvalidEOLChar"/>
</rule>
</ruleset>

View File

@ -0,0 +1,4 @@
parameters:
reportUnmatchedIgnoredErrors: false
ignoreErrors:
- '#Unsafe usage of new static#'

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name=":vendor Test Suite">
<directory suffix="Test.php">./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,54 @@
<?php
namespace ImageMimeTypeGuesser\Detectors;
use ImageMimeTypeGuesser\Detectors\AbstractDetector;
abstract class AbstractDetector
{
/**
* Try to detect mime type of image
*
* Returns:
* - mime type (string) (if it is in fact an image, and type could be determined)
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
abstract protected function doDetect($filePath);
/**
* Create an instance of this class
*
* @return static
*/
public static function createInstance()
{
return new static();
}
/**
* Detect mime type of file (for images only)
*
* Returns:
* - mime type (string) (if it is in fact an image, and type could be determined)
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
public static function detect($filePath)
{
if (!@file_exists($filePath)) {
return false;
}
return self::createInstance()->doDetect($filePath);
}
}

View File

@ -0,0 +1,43 @@
<?php
namespace ImageMimeTypeGuesser\Detectors;
use \ImageMimeTypeGuesser\Detectors\AbstractDetector;
class ExifImageType extends AbstractDetector
{
/**
* Try to detect mime type of image using *exif_imagetype*.
*
* Returns:
* - mime type (string) (if it is in fact an image, and type could be determined)
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
protected function doDetect($filePath)
{
// exif_imagetype is fast, however not available on all systems,
// It may return false. In that case we can rely on that the file is not an image (and return false)
if (function_exists('exif_imagetype')) {
try {
$imageType = exif_imagetype($filePath);
return ($imageType ? image_type_to_mime_type($imageType) : false);
} catch (\Exception $e) {
// Might for example get "Read error!"
// (for some reason, this happens on very small files)
// We handle such errors as indeterminable (null)
return null;
// well well, don't let this stop us
//echo $e->getMessage();
//throw($e);
}
}
return null;
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace ImageMimeTypeGuesser\Detectors;
class FInfo extends AbstractDetector
{
/**
* Try to detect mime type of image using *finfo* class.
*
* Returns:
* - mime type (string) (if it is in fact an image, and type could be determined)
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
protected function doDetect($filePath)
{
if (class_exists('finfo')) {
// phpcs:ignore PHPCompatibility.PHP.NewClasses.finfoFound
$finfo = new \finfo(FILEINFO_MIME);
$result = $finfo->file($filePath);
if ($result === false) {
// false means an error occured
return null;
} else {
$mime = explode('; ', $result);
$result = $mime[0];
if (strpos($result, 'image/') === 0) {
return $result;
} else {
return false;
}
}
}
return null;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace ImageMimeTypeGuesser\Detectors;
class GetImageSize extends AbstractDetector
{
/**
* Try to detect mime type of image using *getimagesize()*.
*
* Returns:
* - mime type (string) (if it is in fact an image, and type could be determined)
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
protected function doDetect($filePath)
{
// getimagesize is slower than exif_imagetype
// It may not return "mime". In that case we can rely on that the file is not an image (and return false)
if (function_exists('getimagesize')) {
try {
$imageSize = getimagesize($filePath);
return (isset($imageSize['mime']) ? $imageSize['mime'] : false);
} catch (\Exception $e) {
// well well, don't let this stop us either
return null;
}
}
return null;
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace ImageMimeTypeGuesser\Detectors;
class MimeContentType extends AbstractDetector
{
/**
* Try to detect mime type of image using *mime_content_type()*.
*
* Returns:
* - mime type (string) (if it is in fact an image, and type could be determined)
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
protected function doDetect($filePath)
{
// mime_content_type supposedly used to be deprecated, but it seems it isn't anymore
// it may return false on failure.
if (function_exists('mime_content_type')) {
try {
$result = mime_content_type($filePath);
if ($result !== false) {
if (strpos($result, 'image/') === 0) {
return $result;
} else {
return false;
}
}
} catch (\Exception $e) {
// we are unstoppable!
// TODO:
// We should probably throw... - we will do in version 1.0.0
//throw $e;
}
}
return null;
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace ImageMimeTypeGuesser\Detectors;
use \ImageMimeTypeGuesser\Detectors\AbstractDetector;
use \ImageMimeTypeSniffer\ImageMimeTypeSniffer;
class SignatureSniffer extends AbstractDetector
{
/**
* Try to detect mime type by sniffing the first four bytes.
*
* Returns:
* - mime type (string) (if it is in fact an image, and type could be determined)
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
protected function doDetect($filePath)
{
return ImageMimeTypeSniffer::detect($filePath);
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace ImageMimeTypeGuesser\Detectors;
class Stack extends AbstractDetector
{
/**
* Try to detect mime type of image using all available detectors.
*
* Returns:
* - mime type (string) (if it is in fact an image, and type could be determined)
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
protected function doDetect($filePath)
{
$detectors = [
'SignatureSniffer',
'FInfo',
'ExifImageType',
//'GetImageSize', // Disabled, as documentation says it is unreliable
'MimeContentType',
];
foreach ($detectors as $className) {
$result = call_user_func(
array("\\ImageMimeTypeGuesser\\Detectors\\" . $className, 'detect'),
$filePath
);
if (!is_null($result)) {
return $result;
}
}
return null; // undetermined
}
}

View File

@ -0,0 +1,56 @@
<?php
/**
* ImageMimeTypeGuesser - Detect / guess mime type of an image
*
* @link https://github.com/rosell-dk/image-mime-type-guesser
* @license MIT
*/
namespace ImageMimeTypeGuesser;
class GuessFromExtension
{
/**
* Make a wild guess based on file extension.
*
* - and I mean wild!
*
* Only most popular image types are recognized.
* Many are not. See this list: https://www.iana.org/assignments/media-types/media-types.xhtml
* - and the constants here: https://secure.php.net/manual/en/function.exif-imagetype.php
*
* If no mapping found, nothing is returned
*
* Returns:
* - mimetype (if file extension could be mapped to an image type),
* - false (if file extension could be mapped to a type known not to be an image type)
* - null (if file extension could not be mapped to any mime type, using our little list)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if file extension could be mapped to an image type),
* false (if file extension could be mapped to a type known not to be an image type)
* or null (if file extension could not be mapped to any mime type, using our little list)
*/
public static function guess($filePath)
{
if (!@file_exists($filePath)) {
return false;
}
/*
Not using pathinfo, as it is locale aware, and I'm not sure if that could lead to problems
if (!function_exists('pathinfo')) {
// This is really a just in case! - We do not expect this to happen.
// - in fact we have a test case asserting that this does not happen.
return null;
//
$fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
$fileExtension = strtolower($fileExtension);
}*/
return MimeMap::filenameToMime($filePath);
}
}

View File

@ -0,0 +1,134 @@
<?php
/**
* ImageMimeTypeGuesser - Detect / guess mime type of an image
*
* The library is born out of a discussion here:
* https://github.com/rosell-dk/webp-convert/issues/98
*
* @link https://github.com/rosell-dk/image-mime-type-guesser
* @license MIT
*/
namespace ImageMimeTypeGuesser;
use \ImageMimeTypeGuesser\Detectors\Stack;
class ImageMimeTypeGuesser
{
/**
* Try to detect mime type of image using all available detectors (the "stack" detector).
*
* Returns:
* - mime type (string) (if it is in fact an image, and type could be determined)
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
public static function detect($filePath)
{
return Stack::detect($filePath);
}
/**
* Try to detect mime type of image. If that fails, make a guess based on the file extension.
*
* Try to detect mime type of image using "stack" detector (all available methods, until one succeeds)
* If that fails (null), fall back to wild west guessing based solely on file extension.
*
* Returns:
* - mime type (string) (if it is an image, and type could be determined / mapped from file extension))
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
public static function guess($filePath)
{
$detectionResult = self::detect($filePath);
if (!is_null($detectionResult)) {
return $detectionResult;
}
// fall back to the wild west method
return GuessFromExtension::guess($filePath);
}
/**
* Try to detect mime type of image. If that fails, make a guess based on the file extension.
*
* Try to detect mime type of image using "stack" detector (all available methods, until one succeeds)
* If that fails (false or null), fall back to wild west guessing based solely on file extension.
*
* Returns:
* - mime type (string) (if it is an image, and type could be determined / mapped from file extension)
* - false (if it is not an image type that the server knowns about)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|false|null mimetype (if it is an image, and type could be determined / guessed),
* false (if it is not an image type that the server knowns about)
* or null (if nothing can be determined)
*/
public static function lenientGuess($filePath)
{
$detectResult = self::detect($filePath);
if ($detectResult === false) {
// The server does not recognize this image type.
// - but perhaps it is because it does not know about this image type.
// - so we turn to mapping the file extension
return GuessFromExtension::guess($filePath);
} elseif (is_null($detectResult)) {
// the mime type could not be determined
// perhaps we also in this case want to turn to mapping the file extension
return GuessFromExtension::guess($filePath);
}
return $detectResult;
}
/**
* Check if the *detected* mime type is in a list of accepted mime types.
*
* @param string $filePath The path to the file
* @param string[] $mimeTypes Mime types to accept
* @return bool Whether the detected mime type is in the $mimeTypes array or not
*/
public static function detectIsIn($filePath, $mimeTypes)
{
return in_array(self::detect($filePath), $mimeTypes);
}
/**
* Check if the *guessed* mime type is in a list of accepted mime types.
*
* @param string $filePath The path to the file
* @param string[] $mimeTypes Mime types to accept
* @return bool Whether the detected / guessed mime type is in the $mimeTypes array or not
*/
public static function guessIsIn($filePath, $mimeTypes)
{
return in_array(self::guess($filePath), $mimeTypes);
}
/**
* Check if the *leniently guessed* mime type is in a list of accepted mime types.
*
* @param string $filePath The path to the file
* @param string[] $mimeTypes Mime types to accept
* @return bool Whether the detected / leniently guessed mime type is in the $mimeTypes array or not
*/
public static function lenientGuessIsIn($filePath, $mimeTypes)
{
return in_array(self::lenientGuess($filePath), $mimeTypes);
}
}

View File

@ -0,0 +1,77 @@
<?php
/**
* ImageMimeTypeGuesser - Detect / guess mime type of an image
*
* @link https://github.com/rosell-dk/image-mime-type-guesser
* @license MIT
*/
namespace ImageMimeTypeGuesser;
class MimeMap
{
/**
* Map image file extension to mime type
*
*
* @param string $filePath The filename (or path), ie "image.jpg"
* @return string|false|null mimetype (if file extension could be mapped to an image type),
* false (if file extension could be mapped to a type known not to be an image type)
* or null (if file extension could not be mapped to any mime type, using our little list)
*/
public static function filenameToMime($filePath)
{
$result = preg_match('#\\.([^.]*)$#', $filePath, $matches);
if ($result !== 1) {
return null;
}
$fileExtension = $matches[1];
return self::extToMime($fileExtension);
}
/**
* Map image file extension to mime type
*
*
* @param string $fileExtension The file extension (ie "jpg")
* @return string|false|null mimetype (if file extension could be mapped to an image type),
* false (if file extension could be mapped to a type known not to be an image type)
* or null (if file extension could not be mapped to any mime type, using our little list)
*/
public static function extToMime($fileExtension)
{
$fileExtension = strtolower($fileExtension);
// Trivial image mime types
if (in_array($fileExtension, ['apng', 'avif', 'bmp', 'gif', 'jpeg', 'png', 'tiff', 'webp'])) {
return 'image/' . $fileExtension;
}
// Common extensions that are definitely not images
if (in_array($fileExtension, ['txt', 'doc', 'zip', 'gz', 'exe'])) {
return false;
}
// Non-trivial image mime types
switch ($fileExtension) {
case 'ico':
case 'cur':
return 'image/x-icon'; // or perhaps 'vnd.microsoft.icon' ?
case 'jpg':
return 'image/jpeg';
case 'svg':
return 'image/svg+xml';
case 'tif':
return 'image/tiff';
}
// We do not know this extension, return null
return null;
}
}

View File

@ -0,0 +1,2 @@
github: rosell-dk
ko_fi: rosell

View File

@ -0,0 +1,122 @@
name: build
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest]
php: [8.1]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Determine which version of xdebug to use
run: |
# Set XDEBUG to "xdebug2" for PHP 7.2-7.4, but to "xdebug" for
if grep -oP '^7.[234]' <<< "$PHP" > /dev/null; then XDEBUG=xdebug2; else XDEBUG=xdebug; fi
# Store XDEBUG in github env, so we can access it later through env.XDEBUG
echo "XDEBUG=$XDEBUG" >> $GITHUB_ENV
echo "Result: ${{ env.XDEBUG }}"
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: ${{ env.XDEBUG }}
- name: Validate composer.json
run: composer validate --strict
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Removing phpstan, as it does not work on PHP 7.1"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Remove phpstan, as it does not work on PHP 7.0"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key, and for install
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-${{ matrix.php }}
${{ runner.os }}-php-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test
- name: Run phpstan on PHP>=7.2 (to check php syntax)
if: (matrix.php != '7.0') && (matrix.php != '7.1') && (matrix.php != '7.2')
run: composer run-script phpstan
- name: run phpcs (to check coding style)
run: composer run-script phpcs-all
- name: Create coverage badge json
run: |
# Extract total coverage
COVERAGE=$(grep -oP -m 1 'Lines:\s*\K[0-9.%]+' build/coverage.txt)
# Set COLOR based on COVERAGE
# 0-49%: red, 50%-69%: orange, 70%-80%: yellow, 90%-100%: brightgreen
if grep -oP '(^9\d.)|(^100.)' <<< "$COVERAGE" > /dev/null; then COLOR=brightgreen; elif grep -oP '[87]\d.' <<< "$COVERAGE" > /dev/null; then COLOR=yellow; elif grep -oP '[65]\d.' <<< "$COVERAGE" > /dev/null; then COLOR=orange; else COLOR=red; fi;
# Generate bagde json
echo \{\"schemaVersion\":1,\"label\":\"coverage\",\"message\":\"$COVERAGE\",\"color\":\"$COLOR\"\} | tee build/coverage-badge.json
# PS: If we needed COVERAGE elsewhere, we could store in ENV like this:
# echo "COVERAGE=$COVERAGE" >> $GITHUB_ENV
- name: Install SSH Key (for deployment of code coverage)
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.DEPLOY_KEY }}
known_hosts: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
- name: Upload code coverage report
run: |
sh -c "rsync -rtog --chown :www-data $GITHUB_WORKSPACE/build/ $DEPLOY_DESTINATION --delete"
env:
DEPLOY_DESTINATION: ${{ secrets.DEPLOY_DESTINATION }}

View File

@ -0,0 +1,83 @@
name: Big test (trigger manually before releasing)
on: workflow_dispatch
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, macos-11, macos-10.15]
php: [8.1, 8.0, 7.4, 7.3, 7.2, 7.1, 7.0]
#os: [ubuntu-20.04]
#php: [8.1]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
- name: Validate composer.json
run: composer validate --strict
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Removing phpstan, as it does not work on PHP 7.1"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Remove phpstan, as it does not work on PHP 7.0"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-${{ matrix.php }}
${{ runner.os }}-php-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test-no-cov
- name: Run phpstan on PHP>=7.2 (to check php syntax)
if: (matrix.php != '7.0') && (matrix.php != '7.1') && (matrix.php != '7.2')
run: composer run-script phpstan
- name: run phpcs (to check coding style)
run: composer run-script phpcs-all

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2018 Bjørn Rosell
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,65 @@
# Image Mime Type Sniffer
[![Latest Stable Version](https://img.shields.io/packagist/v/rosell-dk/image-mime-type-sniffer.svg)](https://packagist.org/packages/rosell-dk/image-mime-type-sniffer)
[![Minimum PHP Version](https://img.shields.io/packagist/php-v/rosell-dk/image-mime-type-sniffer)](https://php.net)
[![Build Status](https://github.com/rosell-dk/image-mime-type-sniffer/actions/workflows/php.yml/badge.svg)](https://github.com/rosell-dk/image-mime-type-sniffer/actions/workflows/php.yml)
[![Software License](https://img.shields.io/badge/license-MIT-418677.svg)](https://github.com/rosell-dk/image-mime-type-sniffer/blob/master/LICENSE)
[![Coverage](https://img.shields.io/endpoint?url=https://little-b.it/image-mime-type-sniffer/code-coverage/coverage-badge.json)](http://little-b.it/image-mime-type-sniffer/code-coverage/coverage/index.html)
[![Monthly Downloads](http://poser.pugx.org/rosell-dk/image-mime-type-sniffer/d/monthly)](https://packagist.org/packages/rosell-dk/image-mime-type-sniffer)
[![Dependents](http://poser.pugx.org/rosell-dk/image-mime-type-sniffer/dependents)](https://packagist.org/packages/rosell-dk/image-mime-type-sniffer/dependents?order_by=downloads)
Gets mime type of common *image* files by sniffing the file content, looking for signatures.
The fact that this library limits its ambition to sniff images makes it light and simple. It is also quite fast. Most other sniffers iterates through all common signatures, however this library uses a mix of finite-state machine approach and iteration to achieve a good balance of speed, compactness, simplicity and readability.
The library recognizes the most widespread image formats, such as GIF, JPEG, WEBP, AVIF, JPEG-2000 and HEIC.
# Usage
```php
use \ImageMimeTypeSniffer\ImageMimeTypeSniffer;
$mimeType = ImageMimeTypeSniffer::detect($fileName);
if (is_null($mimeType)) {
// mimetype was not detected, which means the file is probably not an image (unless it is a rare type)
} else {
// It is an image, and we know the mimeType
}
```
PS: An `\Exception` is thrown if the file is unreadable.
# List of recognized image types:
- application/psd
- image/avif
- image/bmp
- image/gif
- image/heic
- image/jp2
- image/jp20
- image/jpeg
- image/jpm
- image/jpx
- image/png
- image/svg+xml
- image/tiff
- image/webp
- image/x-icon
- video/mj2
TODO: image/heif
# Alternatives
I have created a library that uses this library as well as other methods (*finfo*, *exif_imagetype*, etc) for determining image type. You might want to use that instead, to cover all bases. It is available here: [image-mime-type-guesser](https://github.com/rosell-dk/image-mime-type-guesser).
There are also other PHP mime type sniffers out there:
- https://github.com/Intervention/mimesniffer
- https://github.com/Tinram/File-Identifier
- https://github.com/shanept/MimeSniffer
- https://github.com/zjsxwc/mime-type-sniffer
- https://github.com/thephpleague/mime-type-detection/tree/main/src

View File

@ -0,0 +1,63 @@
{
"name": "rosell-dk/image-mime-type-sniffer",
"description": "Sniff mime type (images only)",
"type": "library",
"license": "MIT",
"keywords": ["mime", "mime type", "image", "images"],
"scripts": {
"ci": [
"@test",
"@phpcs-all",
"@composer validate --no-check-all --strict",
"@phpstan"
],
"cs-fix-all": [
"php-cs-fixer fix src"
],
"cs-fix": "php-cs-fixer fix",
"cs-dry": "php-cs-fixer fix --dry-run --diff",
"test": "phpunit --coverage-text=build/coverage.txt --coverage-clover=build/coverage.clover --coverage-html=build/coverage --whitelist=src tests",
"test-no-cov": "phpunit --no-coverage tests",
"test2": "phpunit tests",
"phpcs": "phpcs --standard=phpcs-ruleset.xml",
"phpcs-all": "phpcs --standard=phpcs-ruleset.xml src",
"phpcbf": "phpcbf --standard=PSR2",
"phpstan": "vendor/bin/phpstan analyse src --level=4"
},
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"autoload": {
"psr-4": { "ImageMimeTypeSniffer\\": "src/" }
},
"autoload-dev": {
"psr-4": { "ImageMimeTypeSniffer\\Tests\\": "tests/" }
},
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
}
],
"require": {
"php": ">=5.4"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*",
"phpstan/phpstan": "^1.5",
"mikey179/vfsstream": "^1.6"
},
"config": {
"sort-packages": true
}
}

View File

@ -0,0 +1,8 @@
<?xml version="1.0"?>
<ruleset name="Custom Standard">
<description>PSR2 without line ending rule - let git manage the EOL cross the platforms</description>
<rule ref="PSR2" />
<rule ref="Generic.Files.LineEndings">
<exclude name="Generic.Files.LineEndings.InvalidEOLChar"/>
</rule>
</ruleset>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd" backupGlobals="false" backupStaticAttributes="false" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="false" processIsolation="false" stopOnFailure="false" bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit>

View File

@ -0,0 +1,177 @@
<?php
namespace ImageMimeTypeSniffer;
class ImageMimeTypeSniffer
{
private static function checkFilePathIsRegularFile($input)
{
if (gettype($input) !== 'string') {
throw new \Exception('File path must be string');
}
if (strpos($input, chr(0)) !== false) {
throw new \Exception('NUL character is not allowed in file path!');
}
if (preg_match('#[\x{0}-\x{1f}]#', $input)) {
// prevents line feed, new line, tab, charater return, tab, ets.
throw new \Exception('Control characters #0-#20 not allowed in file path!');
}
// Prevent phar stream wrappers (security threat)
if (preg_match('#^phar://#', $input)) {
throw new \Exception('phar stream wrappers are not allowed in file path');
}
if (preg_match('#^(php|glob)://#', $input)) {
throw new \Exception('php and glob stream wrappers are not allowed in file path');
}
if (empty($input)) {
throw new \Exception('File path is empty!');
}
if (!@file_exists($input)) {
throw new \Exception('File does not exist');
}
if (@is_dir($input)) {
throw new \Exception('Expected a regular file, not a dir');
}
}
/**
* Try to detect mime type by sniffing the signature
*
* Returns:
* - mime type (string) (if it is in fact an image, and type could be determined)
* - null (if nothing can be determined)
*
* @param string $filePath The path to the file
* @return string|null mimetype (if it is an image, and type could be determined),
* or null (if the file does not match any of the signatures tested)
* @throws \Exception if file cannot be opened/read
*/
public static function detect($filePath)
{
self::checkFilePathIsRegularFile($filePath);
$handle = @fopen($filePath, 'r');
if ($handle === false) {
throw new \Exception('File could not be opened');
}
// 20 bytes is sufficient for all our sniffers, except image/svg+xml.
// The svg sniffer takes care of reading more
$sampleBin = @fread($handle, 20);
if ($sampleBin === false) {
throw new \Exception('File could not be read');
}
if (strlen($sampleBin) < 20) {
return null; // File is too small for us to deal with
}
$firstByte = $sampleBin[0];
$sampleHex = strtoupper(bin2hex($sampleBin));
$hexPatterns = [];
$binPatterns = [];
//$hexPatterns[] = ['image/heic', "/667479706865(6963|6978|7663|696D|6973|766D|7673)/"];
//$hexPatterns[] = ['image/heif', "/667479706D(69|73)6631)/"];
// heic:
// HEIC signature: https://github.com/strukturag/libheif/issues/83#issuecomment-421427091
// https://nokiatech.github.io/heif/technical.html
// https://perkeep.org/internal/magic/magic.go
// https://www.file-recovery.com/mp4-signature-format.htm
$binPatterns[] = ['image/heic', "/^(.{4}|.{8})ftyphe(ic|ix|vc|im|is|vm|vs)/"];
//$binPatterns[] = ['image/heif', "/^(.{4}|.{8})ftypm(i|s)f1/"];
// https://www.rapidtables.com/convert/number/hex-to-ascii.html
switch ($firstByte) {
case "\x00":
$hexPatterns[] = ['image/x-icon', "/^00000(1?2)00/"];
$binPatterns[] = ['image/avif', "/^(.{4}|.{8})ftypavif/"];
if (preg_match("/^.{8}6A502020/", $sampleHex) === 1) {
// jpeg-2000 - a bit more complex, as block size may vary
// https://www.file-recovery.com/jp2-signature-format.htm
$block1Size = hexdec("0x" . substr($sampleHex, 0, 8));
$moreBytes = @fread($handle, $block1Size + 4 + 8);
if ($moreBytes !== false) {
$sampleBin .= $moreBytes;
}
if (substr($sampleBin, $block1Size + 4, 4) == 'ftyp') {
$subtyp = substr($sampleBin, $block1Size + 8, 4);
// "jp2 " (.JP2), "jp20" (.JPA), "jpm " (.JPM), "jpx " (.JPX).
if ($subtyp == 'mjp2') {
return 'video/mj2';
} else {
return 'image/' . rtrim($subtyp);
}
}
}
break;
case "8":
$binPatterns[] = ['application/psd', "/^8BPS/"];
break;
case "B":
$binPatterns[] = ['image/bmp', "/^BM/"];
break;
case "G":
$binPatterns[] = ['image/gif', "/^GIF8(7|9)a/"];
break;
case "I":
$hexPatterns[] = ['image/tiff', "/^(49492A00|4D4D002A)/"];
break;
case "R":
// PS: Another library is more specific: /^RIFF.{4}WEBPVP/
// Is "VP" always there?
$binPatterns[] = ['image/webp', "/^RIFF.{4}WEBP/"];
break;
case "<":
// Another library looks for end bracket for svg.
// We do not, as it requires more bytes read.
// Note that <xml> tag might be big too... - so we read in 200 extra
$moreBytes = @fread($handle, 200);
if ($moreBytes !== false) {
$sampleBin .= $moreBytes;
}
$binPatterns[] = ['image/svg+xml', "/^(<\?xml[^>]*\?>.*)?<svg/is"];
break;
case "\x89":
$hexPatterns[] = ['image/png', "/^89504E470D0A1A0A/"];
break;
case "\xFF":
$hexPatterns[] = ['image/jpeg', "/^FFD8FF(DB|E0|EE|E1)/"];
break;
}
foreach ($hexPatterns as list($mime, $pattern)) {
if (preg_match($pattern, $sampleHex) === 1) {
return $mime;
}
}
foreach ($binPatterns as list($mime, $pattern)) {
if (preg_match($pattern, $sampleBin) === 1) {
return $mime;
}
}
return null;
/*
https://en.wikipedia.org/wiki/List_of_file_signatures
https://github.com/zjsxwc/mime-type-sniffer/blob/master/src/MimeTypeSniffer/MimeTypeSniffer.php
http://phil.lavin.me.uk/2011/12/php-accurately-detecting-the-type-of-a-file/
*/
}
}

View File

@ -0,0 +1,2 @@
github: rosell-dk
ko_fi: rosell

View File

@ -0,0 +1,122 @@
name: build
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest]
php: [8.1]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Determine which version of xdebug to use
run: |
# Set XDEBUG to "xdebug2" for PHP 7.2-7.4, but to "xdebug" for
if grep -oP '^7.[234]' <<< "$PHP" > /dev/null; then XDEBUG=xdebug2; else XDEBUG=xdebug; fi
# Store XDEBUG in github env, so we can access it later through env.XDEBUG
echo "XDEBUG=$XDEBUG" >> $GITHUB_ENV
echo "Result: ${{ env.XDEBUG }}"
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: ${{ env.XDEBUG }}
- name: Validate composer.json
run: composer validate --strict
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Removing phpstan, as it does not work on PHP 7.1"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Remove phpstan, as it does not work on PHP 7.0"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key, and for install
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-${{ matrix.php }}
${{ runner.os }}-php-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test
- name: Run phpstan on PHP>=7.2 (to check php syntax)
if: (matrix.php != '7.0') && (matrix.php != '7.1') && (matrix.php != '7.2')
run: composer run-script phpstan
- name: run phpcs (to check coding style)
run: composer run-script phpcs-all
- name: Create coverage badge json
run: |
# Extract total coverage
COVERAGE=$(grep -oP -m 1 'Lines:\s*\K[0-9.%]+' build/coverage.txt)
# Set COLOR based on COVERAGE
# 0-49%: red, 50%-69%: orange, 70%-80%: yellow, 90%-100%: brightgreen
if grep -oP '(^9\d.)|(^100.)' <<< "$COVERAGE" > /dev/null; then COLOR=brightgreen; elif grep -oP '[87]\d.' <<< "$COVERAGE" > /dev/null; then COLOR=yellow; elif grep -oP '[65]\d.' <<< "$COVERAGE" > /dev/null; then COLOR=orange; else COLOR=red; fi;
# Generate bagde json
echo \{\"schemaVersion\":1,\"label\":\"coverage\",\"message\":\"$COVERAGE\",\"color\":\"$COLOR\"\} | tee build/coverage-badge.json
# PS: If we needed COVERAGE elsewhere, we could store in ENV like this:
# echo "COVERAGE=$COVERAGE" >> $GITHUB_ENV
- name: Install SSH Key (for deployment of code coverage)
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.DEPLOY_KEY }}
known_hosts: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
- name: Upload code coverage report
run: |
sh -c "rsync -rtog --chown :www-data $GITHUB_WORKSPACE/build/ $DEPLOY_DESTINATION --delete"
env:
DEPLOY_DESTINATION: ${{ secrets.DEPLOY_DESTINATION }}

View File

@ -0,0 +1,84 @@
name: Big test (trigger manually before releasing)
on: workflow_dispatch
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, macos-11, macos-10.15]
#os: [macos-11, macos-10.15, windows-2022, windows-2019]
php: [8.1, 8.0, 7.4, 7.3, 7.2, 7.1, 7.0]
#os: [windows-2022]
#php: [8.1, 7.0]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
- name: Validate composer.json
run: composer validate --strict
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Removing phpstan, as it does not work on PHP 7.1"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Remove phpstan, as it does not work on PHP 7.0"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-${{ matrix.php }}
${{ runner.os }}-php-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test-no-cov
- name: Run phpstan on PHP>=7.2 (to check php syntax)
if: (matrix.php != '7.0') && (matrix.php != '7.1') && (matrix.php != '7.2')
run: composer run-script phpstan
- name: run phpcs (to check coding style)
run: composer run-script phpcs-all

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2018 Bjørn Rosell
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,39 @@
# Locate Binaries
[![Build Status](https://github.com/rosell-dk/locate-binaries/workflows/build/badge.svg)](https://github.com/rosell-dk/locate-binaries/actions/workflows/php.yml)
[![Coverage](https://img.shields.io/endpoint?url=https://little-b.it/locate-binaries/code-coverage/coverage-badge.json)](http://little-b.it/locate-binaries/code-coverage/coverage/index.html)
[![Software License](https://img.shields.io/badge/license-MIT-418677.svg)](https://github.com/rosell-dk/locate-binary/blob/master/LICENSE)
[![Latest Stable Version](https://img.shields.io/packagist/v/rosell-dk/locate-binaries.svg)](https://packagist.org/packages/rosell-dk/locate-binaries)
[![Minimum PHP Version](https://img.shields.io/packagist/php-v/rosell-dk/locate-binaries)](https://php.net)
Just a little class for locating binaries.
You need `exec()`, `shell_exec()` or similar enabled for it to work. Otherwise, it will throw.
Works on Linux, Windows and Mac.
## Usage
To locate installed `cwebp` binaries (found on Linux with `which -a`, falling back to `whereis -b`; on Windows found using `where`):
```
$cwebBinariesFound = LocateBinaries::locateInstalledBinaries('cwebp');
```
Note that you get an array of matches - there may be several versions of a binary on a system.
The library also adds another method for locating binaries by peeking in common system paths, such as *usr/bin* and `C:\Windows\System32`
However, beware that these dirs could be subject to open_basedir restrictions which can lead to warning entries in the error log. The other method is therefore best.
Well warned, here it is the alternative, which you in some cases might want to fall back to after trying the first.
```
$imagickBinariesFound = LocateBinaries::locateInCommonSystemPaths('convert');
```
## Notes
The library uses the [exec-with-fallback](https://github.com/rosell-dk/exec-with-fallback) library in order to be able to use alternatives to exec() when exec() is disabled.
## Do you like what I do?
Perhaps you want to support my work, so I can continue doing it :)
- [Become a backer or sponsor on Patreon](https://www.patreon.com/rosell).
- [Buy me a Coffee](https://ko-fi.com/rosell)
Thanks!

View File

@ -0,0 +1,69 @@
{
"name": "rosell-dk/locate-binaries",
"description": "Locate a binaries by means of exec() or similar",
"type": "library",
"license": "MIT",
"keywords": ["locate", "binary", "whereis", "which", "discover"],
"scripts": {
"ci": [
"@test",
"@phpcs-all",
"@composer validate --no-check-all --strict",
"@phpstan"
],
"phpunit": "phpunit --coverage-text",
"test": "phpunit --coverage-text=build/coverage.txt --coverage-clover=build/coverage.clover --coverage-html=build/coverage --whitelist=src tests",
"test-no-cov": "phpunit --no-coverage tests",
"test-41": "phpunit --no-coverage --configuration 'phpunit-41.xml.dist'",
"test-with-coverage": "phpunit --coverage-text --configuration 'phpunit-with-coverage.xml.dist'",
"test-41-with-coverage": "phpunit --coverage-text --configuration 'phpunit-41.xml.dist'",
"cs-fix-all": [
"php-cs-fixer fix src"
],
"cs-fix": "php-cs-fixer fix",
"cs-dry": "php-cs-fixer fix --dry-run --diff",
"phpcs": "phpcs --standard=phpcs-ruleset.xml",
"phpcs-all": "phpcs --standard=phpcs-ruleset.xml src",
"phpcbf": "phpcbf --standard=PSR2",
"phpstan": "vendor/bin/phpstan analyse src --level=4",
"phpstan-global-old": "~/.composer/vendor/bin/phpstan analyse src --level=4",
"phpstan-global": "~/.config/composer/vendor/bin/phpstan analyse src --level=4"
},
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"autoload": {
"psr-4": { "LocateBinaries\\": "src/" }
},
"autoload-dev": {
"psr-4": { "LocateBinaries\\Tests\\": "tests/" }
},
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
}
],
"require": {
"php": ">=5.6",
"rosell-dk/exec-with-fallback": "^1.0.0",
"rosell-dk/file-util": "^0.1.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*",
"phpstan/phpstan": "^1.5"
},
"config": {
"sort-packages": true
}
}

View File

@ -0,0 +1,8 @@
<?xml version="1.0"?>
<ruleset name="Custom Standard">
<description>PSR2 without line ending rule - let git manage the EOL cross the platforms</description>
<rule ref="PSR2" />
<rule ref="Generic.Files.LineEndings">
<exclude name="Generic.Files.LineEndings.InvalidEOLChar"/>
</rule>
</ruleset>

View File

@ -0,0 +1,163 @@
<?php
namespace LocateBinaries;
use FileUtil\FileExists;
use ExecWithFallback\ExecWithFallback;
/**
* Locate path (or multiple paths) of a binary
*
* @package LocateBinaries
* @author Bjørn Rosell <it@rosell.dk>
*/
class LocateBinaries
{
/**
* Locate binaries by looking in common system paths.
*
* We try a small set of common system paths, such as "/usr/bin".
* On Windows, we only try C:\Windows\System32
* Note that you do not have to add ".exe" file extension on Windows, it is taken care of
*
* @param string $binary the binary to look for (ie "cwebp")
*
* @return array binaries found in common system locations
*/
public static function locateInCommonSystemPaths($binary)
{
$binaries = [];
$commonSystemPaths = [];
if (stripos(PHP_OS, 'WIN') === 0) {
$commonSystemPaths = [
'C:\Windows\System32',
];
$binary .= '.exe';
} else {
$commonSystemPaths = [
'/usr/bin',
'/usr/local/bin',
'/usr/gnu/bin',
'/usr/syno/bin',
'/bin',
];
}
foreach ($commonSystemPaths as $dir) {
// PS: FileExists might throw if exec() or similar is unavailable. We let it.
// - this class assumes exec is available
if (FileExists::fileExistsTryHarder($dir . DIRECTORY_SEPARATOR . $binary)) {
$binaries[] = $dir . DIRECTORY_SEPARATOR . $binary;
}
}
return $binaries;
}
/**
* Locate installed binaries using ie "whereis -b cwebp" (for Linux, Mac, etc)
*
* @return array Array of paths locateed (possibly empty)
*/
private static function locateBinariesUsingWhereIs($binary)
{
$isMac = (PHP_OS == 'Darwin');
$command = 'whereis ' . ($isMac ? '' : '-b ') . $binary . ' 2>&1';
ExecWithFallback::exec($command, $output, $returnCode);
//echo 'command:' . $command;
//echo 'output:' . print_r($output, true);
if (($returnCode == 0) && (isset($output[0]))) {
// On linux, result looks like this:
// "cwebp: /usr/bin/cwebp /usr/local/bin/cwebp"
// or, for empty: "cwebp:"
if ($output[0] == ($binary . ':')) {
return [];
}
// On mac, it is not prepended with name of binary.
// I don't know if mac returns one result per line or is space seperated
// As I don't know if some systems might return several lines,
// I assume that some do and convert to space-separation:
$result = implode(' ', $output);
// Next, lets remove the prepended binary (if exists)
$result = preg_replace('#\b' . $binary . ':\s?#', '', $result);
// And back to array
return explode(' ', $result);
}
return [];
}
/**
* locate installed binaries using "which -a cwebp"
*
* @param string $binary the binary to look for (ie "cwebp")
*
* @return array Array of paths locateed (possibly empty)
*/
private static function locateBinariesUsingWhich($binary)
{
// As suggested by @cantoute here:
// https://wordpress.org/support/topic/sh-1-usr-local-bin-cwebp-not-found/
ExecWithFallback::exec('which -a ' . $binary . ' 2>&1', $output, $returnCode);
if ($returnCode == 0) {
return $output;
}
return [];
}
/**
* Locate binaries using where.exe (for Windows)
*
* @param string $binary the binary to look for (ie "cwebp")
*
* @return array binaries found
*/
private static function locateBinariesUsingWhere($binary)
{
ExecWithFallback::exec('where.exe ' . $binary . ' 2>&1', $output, $returnCode);
if ($returnCode == 0) {
return $output;
}
return [];
}
/**
* Locate installed binaries
*
* For linuk, we use "which -a" or, if that fails "whereis -b"
* For Windows, we use "where.exe"
* These commands only searces within $PATH. So it only finds installed binaries (which is good,
* as it would be unsafe to deal with binaries found scattered around)
*
* @param string $binary the binary to look for (ie "cwebp")
*
* @return array binaries found
*/
public static function locateInstalledBinaries($binary)
{
if (stripos(PHP_OS, 'WIN') === 0) {
$paths = self::locateBinariesUsingWhere($binary);
if (count($paths) > 0) {
return $paths;
}
} else {
$paths = self::locateBinariesUsingWhich($binary);
if (count($paths) > 0) {
return $paths;
}
$paths = self::locateBinariesUsingWhereIs($binary);
if (count($paths) > 0) {
return $paths;
}
}
return [];
}
}

View File

@ -0,0 +1,2 @@
github: rosell-dk
ko_fi: rosell

View File

@ -0,0 +1,74 @@
# https://duntuk.com/how-install-graphicsmagick-gmagick-php-extension
# https://gist.github.com/basimhennawi/21c39f9758b0b1cb5e0bd5ee08b5be58
# https://github.com/rosell-dk/webp-convert/wiki/Installing-gmagick-extension
#if [ -d "$HOME/vips/bin" ]; then
#fi;
$HOME/opt/bin/gm -version | grep -i 'WebP.*yes' && {
gmagick_installed_with_webp=1
}
if [[ $gmagick_installed_with_webp == 1 ]]; then
echo "Gmagick is already compiled with webp. Nothing to do :)"
echo ":)"
else
echo "Gmagick is is not installed or not compiled with webp."
compile_libwebp=1
compile_gmagick=1
fi;
#ls $HOME/opt/bin
cores=$(nproc)
LIBWEBP_VERSION=1.0.2
if [[ $compile_libwebp == 2 ]]; then
echo "We are going to be compiling libwebp..."
echo "Using $cores cores."
echo "Downloading libwebp version $LIBWEBP_VERSION"
cd /tmp
curl -O https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-$LIBWEBP_VERSION.tar.gz
tar xzf libwebp-$LIBWEBP_VERSION.tar.gz
cd libwebp-*
echo "./configure --prefix=$HOME/opt"
./configure --prefix=$HOME/opt
echo "make -j$CORES"
make -j$CORES
echo "make install -j$CORES"
make install -j$CORES
fi;
if [[ $compile_gmagick == 2 ]]; then
echo "Compiling Gmagick"
echo "Using $cores cores."
cd /tmp
echo "Downloading GraphicsMagick-LATEST.tar.gz"
wget http://78.108.103.11/MIRROR/ftp/GraphicsMagick/GraphicsMagick-LATEST.tar.gz
tar xfz GraphicsMagick-LATEST.tar.gz
cd GraphicsMagick-*
echo "Configuring"
./configure --prefix=$HOME/opt --enable-shared --with-webp=yes
echo "make -j$CORES"
make -j$CORES
echo "make install -j$CORES"
make install -j$CORES
fi;
#./configure --prefix=$HOME/opt --with-webp=yes &&
#$HOME/opt/bin/gm -version
#convert -version | grep 'webp' || {
#convert -list delegate | grep 'webp =>' || {
#}
##libgraphicsmagick1-dev

View File

@ -0,0 +1,40 @@
# Install imagick with webp support (if not already there) and update library paths
# Got the script from here:
# https://stackoverflow.com/questions/41138404/how-to-install-newer-imagemagick-with-webp-support-in-travis-ci-container
if ! [[ $IMAGEMAGICK_VERSION ]]; then
export IMAGEMAGICK_VERSION="7.0.8-43"
fi;
convert -list delegate | grep 'webp =>' && {
echo "Imagick is already compiled with webp. Nothing to do :)" &&
echo ":)"
}
#convert -version | grep 'webp' || {
convert -list delegate | grep 'webp =>' || {
export CORES=$(nproc) &&
export LIBWEBP_VERSION=1.0.2 &&
echo "Using $CORES cores for compiling..." &&
cd /tmp &&
curl -O https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-$LIBWEBP_VERSION.tar.gz &&
tar xzf libwebp-$LIBWEBP_VERSION.tar.gz &&
cd libwebp-* &&
./configure --prefix=$HOME/opt &&
make -j$CORES &&
make install -j$CORES &&
cd /tmp &&
curl -O https://www.imagemagick.org/download/ImageMagick-$IMAGEMAGICK_VERSION.tar.gz &&
tar xzf ImageMagick-$IMAGEMAGICK_VERSION.tar.gz &&
cd ImageMagick-* &&
./configure --prefix=$HOME/opt --with-webp=yes &&
make -j$CORES &&
make install -j$CORES &&
$HOME/opt/bin/magick -version | grep $IMAGEMAGICK_VERSION
}
export LD_FLAGS=-L$HOME/opt/lib
export LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib:$HOME/opt/lib
export CPATH=$CPATH:$HOME/opt/include

View File

@ -0,0 +1,40 @@
#!/bin/bash
if ! [[ $VIPS_VERSION ]]; then
export VIPS_VERSION="8.10.6"
fi;
export PATH=$HOME/vips/bin:$PATH
export LD_LIBRARY_PATH=$HOME/vips/lib:$LD_LIBRARY_PATH
export PKG_CONFIG_PATH=$HOME/vips/lib/pkgconfig:$PKG_CONFIG_PATH
export PYTHONPATH=$HOME/vips/lib/python2.7/site-packages:$PYTHONPATH
export GI_TYPELIB_PATH=$HOME/vips/lib/girepository-1.0:$GI_TYPELIB_PATH
vips_site=https://github.com/libvips/libvips/releases/download
set -e
# do we already have the correct vips built? early exit if yes
# we could check the configure params as well I guess
if [ -d "$HOME/vips/bin" ]; then
installed_version=$($HOME/vips/bin/vips --version)
escaped_version="${VIPS_VERSION//\./\\.}"
echo "Need vips-$version"
echo "Found $installed_version"
if [[ "$installed_version" =~ ^vips-$escaped_version ]]; then
echo "Using cached directory"
exit 0
fi
fi
rm -rf $HOME/vips
echo "wget: $vips_site/v$VIPS_VERSION/vips-$VIPS_VERSION.tar.gz"
wget $vips_site/v$VIPS_VERSION/vips-$VIPS_VERSION.tar.gz
tar xf vips-$VIPS_VERSION.tar.gz
cd vips-$VIPS_VERSION
CXXFLAGS=-D_GLIBCXX_USE_CXX11_ABI=0 ./configure --prefix=$HOME/vips --disable-debug --disable-dependency-tracking --disable-introspection --disable-static --enable-gtk-doc-html=no --enable-gtk-doc=no --enable-pyvips8=no --without-orc --without-python
make && make install
# Install PHP extension
# ----------------------
yes '' | pecl install vips

View File

@ -0,0 +1,61 @@
name: Code Coverage
on: workflow_dispatch
jobs:
codecov:
runs-on: ubuntu-20.04
env:
WEBPCONVERT_EWWW_API_KEY: ${{ secrets.WEBPCONVERT_EWWW_API_KEY }}
WEBPCONVERT_WPC_API_URL: ${{ secrets.WEBPCONVERT_WPC_API_URL }}
WEBPCONVERT_WPC_API_KEY: ${{ secrets.WEBPCONVERT_WPC_API_KEY }}
WEBPCONVERT_WPC_API_URL_API0: ${{ secrets.WEBPCONVERT_WPC_API_URL_API0 }}
steps:
- name: Checkout
uses: actions/checkout@v2
# - name: Setup vips
# run: |
# chmod +x ./.github/install-vips.sh
# ./.github/install-vips.sh
- name: Setup ffmpeg
uses: FedericoCarboni/setup-ffmpeg@v1
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.1'
# Note: Currently, gmagick and imagick are mutually exclusive.
# It seems they are installed in the order indicated in "extensions" and the latter cancels the former
extensions: exif, mbstring, fileinfo, gd, vips, gmagick, imagick
- name: Setup problem matchers for PHP
run: echo "::add-matcher::${{ runner.tool_cache }}/php.json"
- name: Setup problem matchers for PHPUnit
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
with:
path: vendor
key: ${{ runner.os }}-codecov-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-codecov-
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test-with-coverage
- name: Upload Scrutinizer coverage
uses: sudo-bot/action-scrutinizer@latest
with:
cli-args: "--format=php-clover build/coverage.clover"

View File

@ -0,0 +1,51 @@
name: Debug
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
php73:
runs-on: ${{ matrix.os }}
env:
WEBPCONVERT_EWWW_API_KEY: ${{ secrets.WEBPCONVERT_EWWW_API_KEY }}
strategy:
fail-fast: true
matrix:
os: [macos-11]
php: [7.3]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: exif, mbstring, fileinfo, gd
- name: Setup problem matchers for PHP
run: echo "::add-matcher::${{ runner.tool_cache }}/php.json"
- name: Setup problem matchers for PHPUnit
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
with:
path: vendor
key: ${{ runner.os }}-php73-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php73-
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test

View File

@ -0,0 +1,131 @@
name: build
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
env:
WEBPCONVERT_EWWW_API_KEY: ${{ secrets.WEBPCONVERT_EWWW_API_KEY }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest]
php: [8.1]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup ffmpeg
uses: FedericoCarboni/setup-ffmpeg@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Determine which version of xdebug to use
run: |
# Set XDEBUG to "xdebug2" for PHP 7.2-7.4, but to "xdebug" for
if grep -oP '^7.[234]' <<< "$PHP" > /dev/null; then XDEBUG=xdebug2; else XDEBUG=xdebug; fi
# Store XDEBUG in github env, so we can access it later through env.XDEBUG
echo "XDEBUG=$XDEBUG" >> $GITHUB_ENV
echo "Result: ${{ env.XDEBUG }}"
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: ${{ env.XDEBUG }}
extensions: exif, mbstring, fileinfo, gd, vips, imagick, gmagick
- name: Validate composer.json
run: composer validate --strict
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Removing phpstan, as it does not work on PHP 7.1"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Remove phpstan, as it does not work on PHP 7.0"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key, and for install
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-${{ matrix.php }}
${{ runner.os }}-php-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test
#- name: Run phpstan on PHP>=7.2 (to check php syntax)
# if: (matrix.php != '7.0') && (matrix.php != '7.1') && (matrix.php != '7.2')
# run: composer run-script phpstan
- name: run phpcs (to check coding style)
run: composer run-script phpcs-all
- name: Create coverage badge json
run: |
# Extract total coverage
COVERAGE=$(grep -oP -m 1 'Lines:\s*\K[0-9.%]+' build/coverage.txt)
# Set COLOR based on COVERAGE
# 0-49%: red, 50%-69%: orange, 70%-80%: yellow, 90%-100%: brightgreen
if grep -oP '(^9\d.)|(^100.)' <<< "$COVERAGE" > /dev/null; then COLOR=brightgreen; elif grep -oP '[87]\d.' <<< "$COVERAGE" > /dev/null; then COLOR=yellow; elif grep -oP '[65]\d.' <<< "$COVERAGE" > /dev/null; then COLOR=orange; else COLOR=red; fi;
# Generate bagde json
echo \{\"schemaVersion\":1,\"label\":\"coverage\",\"message\":\"$COVERAGE\",\"color\":\"$COLOR\"\} | tee build/coverage-badge.json
# PS: If we needed COVERAGE elsewhere, we could store in ENV like this:
# echo "COVERAGE=$COVERAGE" >> $GITHUB_ENV
- name: Install SSH Key (for deployment of code coverage)
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.DEPLOY_KEY }}
known_hosts: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
- name: Upload code coverage report
run: |
sh -c "rsync -rtog --chown :www-data $GITHUB_WORKSPACE/build/ $DEPLOY_DESTINATION --delete"
env:
DEPLOY_DESTINATION: ${{ secrets.DEPLOY_DESTINATION }}

View File

@ -0,0 +1,186 @@
name: Big test (trigger manually before releasing)
on: workflow_dispatch
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
env:
WEBPCONVERT_EWWW_API_KEY: ${{ secrets.WEBPCONVERT_EWWW_API_KEY }}
#WEBPCONVERT_WPC_API_URL: ${{ secrets.WEBPCONVERT_WPC_API_URL }}
#WEBPCONVERT_WPC_API_KEY: ${{ secrets.WEBPCONVERT_WPC_API_KEY }}
#WEBPCONVERT_WPC_API_URL_API0: ${{ secrets.WEBPCONVERT_WPC_API_URL_API0 }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest, ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, macos-11, macos-10.15]
php: [8.1, 8.0, 7.4, 7.3, 7.2, 7.1, 7.0]
#php: [8.1, 7.0]
#os: [windows-2022, macos-11]
#os: [windows-2022, windows-2019]
#os: [macos-11]
os: [macos-11, macos-10.15]
#os: [ubuntu-18.04]
#os: [ubuntu-18.04]
#os: [ubuntu-latest]
#os: [ubuntu-18.04,windows-2022, macos-11]
#php: [8.1]
# For some reason PHP 7.0 testing fails on Windows, so we exclude
exclude:
- os: windows-2019
php: 7.0
- os: windows-2022
php: 7.0
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup ffmpeg
uses: FedericoCarboni/setup-ffmpeg@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
extensions: exif, mbstring, fileinfo, gd, vips, imagick, gmagick
- name: Validate composer.json
run: composer validate --strict
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Removing phpstan, as it does not work on PHP 7.1"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Remove phpstan, as it does not work on PHP 7.0"
composer remove phpstan/phpstan --dev --no-update
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-${{ matrix.php }}
${{ runner.os }}-php-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test-no-cov
- name: Run phpstan on PHP>=7.2 (to check php syntax)
if: (matrix.php != '7.0') && (matrix.php != '7.1') && (matrix.php != '7.2')
run: composer run-script phpstan
- name: run phpcs (to check coding style)
run: composer run-script phpcs-all
with_disabled_functions:
runs-on: ${{ matrix.os }}
env:
WEBPCONVERT_EWWW_API_KEY: ${{ secrets.WEBPCONVERT_EWWW_API_KEY }}
strategy:
fail-fast: true
matrix:
#os: [ubuntu-18.04,windows-2022, windows-2019, macos-11]
#php: [8.1, 7.1]
os: [ubuntu-18.04]
php: [8.1]
# unfortunately, proc_open is needed by phpunit, so we cannot disable proc_open
disabled_functions: ["exec", "exec,passthru,shell_exec,popen"]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup ffmpeg
uses: FedericoCarboni/setup-ffmpeg@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: exif, mbstring, fileinfo, gd, vips, imagick, gmagick
ini-values: disable_functions="${{ matrix.disabled_functions }}"
- name: Validate composer.json
run: composer validate --strict
- name: Remove PHP stan
run: |
echo "Removing phpstan, as we have PHP stan test in other tests"
composer remove phpstan/phpstan --dev --no-update
- name: Composer alterations for PHP 7.2
if: matrix.php == '7.2'
run: |
echo "Downgrading phpunit to ^8.0, which is the highest version that supports PHP 7.2"
composer require "phpunit/phpunit:^8.0" --dev --no-update
- name: Composer alterations for PHP 7.1
if: matrix.php == '7.1'
run: |
echo "Downgrading phpunit to ^7.0, which is the highest version that supports PHP 7.1"
composer require "phpunit/phpunit:^7.0" --dev --no-update
- name: Composer alterations for PHP 7.0
if: matrix.php == '7.0'
run: |
echo "Downgrading phpunit to ^6.0, which is the highest version that supports PHP 7.0"
composer require "phpunit/phpunit:^6.0" --dev --no-update
# Create composer.lock, which is going to be used in the cache key
- name: Create composer.lock for cache key (this is a library, so composer.lock is not part of repo)
run: composer update --no-install
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-disabled-functions-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-disabled-functions-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
${{ runner.os }}-php-disabled-functions-${{ matrix.php }}
${{ runner.os }}-php-disabled-functions-
- name: Composer install
run: composer install --prefer-dist --no-progress
- name: Run phpunit (test cases)
run: composer run-script test-no-cov

View File

@ -0,0 +1,32 @@
# Backers
WebP Convert is an MIT-licensed open source project. It is free and always will be.
How is it financed then? Well, it isn't exactly. However, some people choose to support the development by buying the developer a cup of coffee, and some go even further, by becoming backers. Backers are nice folks making recurring monthly donations, and by doing this, they give me an excuse to put more work into the library than I really should.
To become a backer yourself, visit [my page at patreon](https://www.patreon.com/rosell)
## Active backers via Patron
| Name | Since date |
| ---------------------- | -------------- |
| Max Kreminsky | 2019-08-02 |
| [Mathieu Gollain-Dupont](https://www.linkedin.com/in/mathieu-gollain-dupont-9938a4a/) | 2020-08-26 |
| Nodeflame | 2019-10-31 |
| Ruben Solvang | 2020-01-08 |
Hi-scores:
| Name | Life time contribution |
| ------------------------ | ------------------------ |
| Tammy Valgardson | $90 |
| Max Kreminsky | $65 |
| Ruben Solvang | $14 |
| Dmitry Verzjikovsky | $5 |
## Former backers - I'm still grateful :)
- Dmitry Verzjikovsky
- Tammy Valgardson

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2018 Bjørn Rosell
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,171 @@
# WebP Convert
[![Latest Stable Version](https://img.shields.io/packagist/v/rosell-dk/webp-convert.svg)](https://packagist.org/packages/rosell-dk/webp-convert)
[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%205.6-8892BF.svg)](https://php.net)
[![Build Status](https://img.shields.io/github/workflow/status/rosell-dk/webp-convert/PHP?logo=GitHub)](https://github.com/rosell-dk/webp-convert/actions/workflows/php.yml)
[![Coverage](https://img.shields.io/endpoint?url=https://little-b.it/webp-convert/code-coverage/coverage-badge.json)](http://little-b.it/webp-convert/code-coverage/coverage/index.html)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://github.com/rosell-dk/webp-convert/blob/master/LICENSE)
[![Monthly Downloads](http://poser.pugx.org/rosell-dk/webp-convert/d/monthly)](https://packagist.org/packages/rosell-dk/webp-convert)
[![Dependents](http://poser.pugx.org/rosell-dk/webp-convert/dependents)](https://packagist.org/packages/rosell-dk/webp-convert/dependents?order_by=downloads)
*Convert JPEG & PNG to WebP with PHP*
This library enables you to do webp conversion with PHP. It supports an abundance of methods for converting and automatically selects the most capable of these that is available on the system.
The library can convert using the following methods:
- *cwebp* (executing [cwebp](https://developers.google.com/speed/webp/docs/cwebp) binary using an `exec` call)
- *vips* (using [Vips PHP extension](https://github.com/libvips/php-vips-ext))
- *imagick* (using [Imagick PHP extension](https://github.com/Imagick/imagick))
- *gmagick* (using [Gmagick PHP extension](https://www.php.net/manual/en/book.gmagick.php))
- *imagemagick* (executing [imagemagick](https://imagemagick.org/index.php) binary using an `exec` call)
- *graphicsmagick* (executing [graphicsmagick](http://www.graphicsmagick.org/) binary using an `exec` call)
- *ffmpeg* (executing [ffmpeg](https://ffmpeg.org/) binary using an `exec` call)
- *wpc* (using [WebPConvert Cloud Service](https://github.com/rosell-dk/webp-convert-cloud-service/) - an open source webp converter for PHP - based on this library)
- *ewwww* (using the [ewww](https://ewww.io/plans/) cloud converter (1 USD startup and then free webp conversion))
- *gd* (using the [Gd PHP extension](https://www.php.net/manual/en/book.image.php))
In addition to converting, the library also has a method for *serving* converted images, and we have instructions here on how to set up a solution for automatically serving webp images to browsers that supports webp.
## Installation
Require the library with *Composer*, like this:
```text
composer require rosell-dk/webp-convert
```
## Converting images
Here is a minimal example of converting using the *WebPConvert::convert* method:
```php
// Initialise your autoloader (this example is using Composer)
require 'vendor/autoload.php';
use WebPConvert\WebPConvert;
$source = __DIR__ . '/logo.jpg';
$destination = $source . '.webp';
$options = [];
WebPConvert::convert($source, $destination, $options);
```
The *WebPConvert::convert* method comes with a bunch of options. The following introduction is a *must-read*:
[docs/v2.0/converting/introduction-for-converting.md](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md).
If you are migrating from 1.3.9, [read this](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/migrating-to-2.0.md)
## Serving converted images
The *WebPConvert::serveConverted* method tries to serve a converted image. If there already is an image at the destination, it will take that, unless the original is newer or smaller. If the method cannot serve a converted image, it will serve original image, a 404, or whatever the 'fail' option is set to. It also adds *X-WebP-Convert-Log* headers, which provides insight into what happened.
Example (version 2.0):
```php
require 'vendor/autoload.php';
use WebPConvert\WebPConvert;
$source = __DIR__ . '/logo.jpg';
$destination = $source . '.webp';
WebPConvert::serveConverted($source, $destination, [
'fail' => 'original', // If failure, serve the original image (source). Other options include 'throw', '404' and 'report'
//'show-report' => true, // Generates a report instead of serving an image
'serve-image' => [
'headers' => [
'cache-control' => true,
'vary-accept' => true,
// other headers can be toggled...
],
'cache-control-header' => 'max-age=2',
],
'convert' => [
// all convert option can be entered here (ie "quality")
],
]);
```
The following introduction is a *must-read* (for 2.0):
[docs/v2.0/serving/introduction-for-serving.md](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/serving/introduction-for-serving.md).
The old introduction (for 1.3.9) is available here: [docs/v1.3/serving/convert-and-serve.md](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/serving/convert-and-serve.md)
## WebP on demand
The library can be used to create a *WebP On Demand* solution, which automatically serves WebP images instead of jpeg/pngs for browsers that supports WebP. To set this up, follow what's described [in this tutorial (not updated for 2.0 yet)](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/webp-on-demand/webp-on-demand.md).
## Projects using WebP Convert
### CMS plugins using WebP Convert
This library is used as the engine to provide webp conversions to a handful of platforms. Hopefully this list will be growing over time. Currently there are plugins / extensions / modules / whatever the term is for the following CMS'es (ordered by [market share](https://w3techs.com/technologies/overview/content_management/all)):
- [Wordpress](https://github.com/rosell-dk/webp-express)
- [Drupal 7](https://github.com/HDDen/Webp-Drupal-7)
- [Contao](https://github.com/postyou/contao-webp-bundle)
- [Kirby](https://github.com/S1SYPHOS/kirby-webp)
- [October CMS](https://github.com/OFFLINE-GmbH/oc-responsive-images-plugin/)
### Other projects using WebP Convert
- [webp-convert-cloud-service](https://github.com/rosell-dk/webp-convert-cloud-service)
A cloud service based on WebPConvert
- [webp-convert-concat](https://github.com/rosell-dk/webp-convert-concat)
The webp-convert library and its dependents as a single PHP file (or two)
## Supporting WebP Convert
Bread on the table don't come for free, even though this library does, and always will. I enjoy developing this, and supporting you guys, but I kind of need the bread too. Please make it possible for me to have both:
- [Become a backer or sponsor on Patreon](https://www.patreon.com/rosell).
- [Buy me a Coffee](https://ko-fi.com/rosell)
## Supporters
*Persons currently backing the project via patreon - Thanks!*
- Max Kreminsky
- Nodeflame
- [Mathieu Gollain-Dupont](https://www.linkedin.com/in/mathieu-gollain-dupont-9938a4a/)
- Ruben Solvang
*Persons who recently contributed with [ko-fi](https://ko-fi.com/rosell) - Thanks!*
* 3 Dec: Dallas
* 29 Nov: tadesco.org
* 20 Nov: Ben J
* 13 Nov: @sween
* 9 Nov: @utrenkner
*Persons who contributed with extra generously amounts of coffee / lifetime backing (>50$) - thanks!:*
- Justin - BigScoots ($105)
- Sebastian ($99)
- Tammy Lee ($90)
- Max Kreminsky ($65)
- Steven Sullivan ($51)
## New in 2.9.0 (released 7 dec 2021, on my daughters 10 years birthday!)
- When exec() is unavailable, alternatives are now tried (emulations with proc_open(), passthru() etc). Using [this library](https://github.com/rosell-dk/exec-with-fallback) to do it.
- Gd is now marked as not operational when the needed functions for converting palette images to RGB is missing. Rationale: A half-working converter causes more trouble than one that is marked as not operational
- Improved CI tests. It is now tested on Windows, Mac and with deactivated functions (such as when exec() is disabled)
- And more (view closed issues [here](https://github.com/rosell-dk/webp-convert/milestone/25?closed=1)
## New in 2.8.0:
- Converter option definitions are now accessible along with suggested UI and helptexts. This allows one to auto-generate a frontend based on conversion options. The feature is already in use in the [webp-convert file manager](https://github.com/rosell-dk/webp-convert-filemanager), which is used in WebP Express. New method: `WebPConvert::getConverterOptionDefinitions()`
- The part of the log that displays the options are made more readable. It also now warns about deprecated options.
- Bumped image-mime-type guesser library to 0.4. This version is able to dectect more mime types by sniffing the first couple of bytes.
- And more (view closed issues [here](https://github.com/rosell-dk/webp-convert/milestone/23?closed=1)
## New in 2.7.0:
- ImageMagick now supports the "near-lossless" option (provided Imagick >= 7.0.10-54) [#299](https://github.com/rosell-dk/webp-convert/issues/299)
- Added "try-common-system-paths" option for ImageMagick (default: true). So ImageMagick will now peek for "convert" in common system paths [#293](https://github.com/rosell-dk/webp-convert/issues/293)
- Fixed memory leak in Gd on very old versions of PHP [#264](https://github.com/rosell-dk/webp-convert/issues/264)
- And more (view closed issues [here](https://github.com/rosell-dk/webp-convert/milestone/24?closed=1)
## New in 2.6.0:
- Introduced [auto-limit](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#auto-limit) option which replaces setting "quality" to "auto" [#281](https://github.com/rosell-dk/webp-convert/issues/281)
- Added "sharp-yuv" option and made it default on. [Its great](https://www.ctrl.blog/entry/webp-sharp-yuv.html), use it! Works in most converters (works in cwebp, vips, imagemagick, graphicsmagick, imagick and gmagick) [#267](https://github.com/rosell-dk/webp-convert/issues/267), [#280](https://github.com/rosell-dk/webp-convert/issues/280), [#284](https://github.com/rosell-dk/webp-convert/issues/284)
- Bumped cwebp binaries to 1.2.0 [#273](https://github.com/rosell-dk/webp-convert/issues/273)
- vips now supports "method" option and "preset" option.
- graphicsmagick now supports "auto-filter" potion
- vips, imagick, imagemagick, graphicsmagick and gmagick now supports "preset" option [#275](https://github.com/rosell-dk/webp-convert/issues/275)
- cwebp now only validates hash of supplied precompiled binaries when necessary. This cuts down conversion time. [#287](https://github.com/rosell-dk/webp-convert/issues/287)
- Added [new option](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#cwebp-skip-these-precompiled-binaries) to cwebp for skipping precompiled binaries that are known not to work on current system. This will cut down on conversion time. [#288](https://github.com/rosell-dk/webp-convert/issues/288)
- And more (view closed issues [here](https://github.com/rosell-dk/webp-convert/milestone/22?closed=1))

View File

@ -0,0 +1,75 @@
{
"name": "rosell-dk/webp-convert",
"description": "Convert JPEG & PNG to WebP with PHP",
"type": "library",
"license": "MIT",
"keywords": ["webp", "images", "cwebp", "imagick", "gd", "jpg2webp", "png2webp", "jpg", "png", "image conversion"],
"scripts": {
"ci": [
"@test",
"@phpcs-all",
"@composer validate --no-check-all --strict",
"@phpstan-global"
],
"test": "phpunit --coverage-text",
"phpunit": "phpunit --coverage-text",
"test-no-cov": "phpunit --no-coverage",
"cs-fix-all": [
"php-cs-fixer fix src"
],
"cs-fix": "php-cs-fixer fix",
"cs-dry": "php-cs-fixer fix --dry-run --diff",
"phpcs": "phpcs --standard=PSR2",
"phpcs-all": "phpcs --standard=PSR2 src",
"phpcbf": "phpcbf --standard=PSR2",
"phpstan": "vendor/bin/phpstan analyse src --level=4",
"phpstan-global-old": "~/.composer/vendor/bin/phpstan analyse src --level=4",
"phpstan-global": "~/.config/composer/vendor/bin/phpstan analyse src --level=4"
},
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"autoload": {
"psr-4": { "WebPConvert\\": "src/" }
},
"autoload-dev": {
"psr-4": { "WebPConvert\\Tests\\": "tests/" }
},
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
},
{
"name": "Martin Folkers",
"homepage": "https://twobrain.io",
"role": "Collaborator"
}
],
"require": {
"php": "^5.6",
"rosell-dk/image-mime-type-guesser": "^0.3"
},
"suggest": {
"ext-gd": "to use GD extension for converting. Note: Gd must be compiled with webp support",
"ext-imagick": "to use Imagick extension for converting. Note: Gd must be compiled with webp support",
"ext-vips": "to use Vips extension for converting.",
"php-stan/php-stan": "Suggested for dev, in order to analyse code before committing"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpunit/phpunit": "5.7.27",
"squizlabs/php_codesniffer": "3.*"
},
"config": {
"sort-packages": true
}
}

View File

@ -0,0 +1,75 @@
{
"name": "rosell-dk/webp-convert",
"description": "Convert JPEG & PNG to WebP with PHP",
"type": "library",
"license": "MIT",
"keywords": ["webp", "images", "cwebp", "imagick", "gd", "jpg2webp", "png2webp", "jpg", "png", "image conversion"],
"scripts": {
"ci": [
"@test",
"@phpcs-all",
"@composer validate --no-check-all --strict",
"@phpstan-global"
],
"test": "phpunit --coverage-text",
"phpunit": "phpunit --coverage-text",
"test-no-cov": "phpunit --no-coverage",
"cs-fix-all": [
"php-cs-fixer fix src"
],
"cs-fix": "php-cs-fixer fix",
"cs-dry": "php-cs-fixer fix --dry-run --diff",
"phpcs": "phpcs --standard=PSR2",
"phpcs-all": "phpcs --standard=PSR2 src",
"phpcbf": "phpcbf --standard=PSR2",
"phpstan": "vendor/bin/phpstan analyse src --level=4",
"phpstan-global-old": "~/.composer/vendor/bin/phpstan analyse src --level=4",
"phpstan-global": "~/.config/composer/vendor/bin/phpstan analyse src --level=4"
},
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"autoload": {
"psr-4": { "WebPConvert\\": "src/" }
},
"autoload-dev": {
"psr-4": { "WebPConvert\\Tests\\": "tests/" }
},
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
},
{
"name": "Martin Folkers",
"homepage": "https://twobrain.io",
"role": "Collaborator"
}
],
"require": {
"php": "^7.2",
"rosell-dk/image-mime-type-guesser": "^0.3"
},
"suggest": {
"ext-gd": "to use GD extension for converting. Note: Gd must be compiled with webp support",
"ext-imagick": "to use Imagick extension for converting. Note: Gd must be compiled with webp support",
"ext-vips": "to use Vips extension for converting.",
"php-stan/php-stan": "Suggested for dev, in order to analyse code before committing"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpunit/phpunit": "^8.0",
"squizlabs/php_codesniffer": "3.*"
},
"config": {
"sort-packages": true
}
}

View File

@ -0,0 +1,81 @@
{
"name": "rosell-dk/webp-convert",
"description": "Convert JPEG & PNG to WebP with PHP",
"type": "library",
"license": "MIT",
"keywords": ["webp", "images", "cwebp", "imagick", "gd", "jpg2webp", "png2webp", "jpg", "png", "image conversion"],
"scripts": {
"ci": [
"@test",
"@phpcs-all",
"@composer validate --no-check-all --strict",
"@phpstan-global"
],
"phpunit": "phpunit --coverage-text",
"test": "phpunit --coverage-text=build/coverage.txt --coverage-clover=build/coverage.clover --coverage-html=build/coverage --whitelist=src tests",
"test-41": "phpunit --no-coverage --configuration 'phpunit-41.xml.dist'",
"test-with-coverage": "phpunit --coverage-text --configuration 'phpunit-with-coverage.xml.dist'",
"test-41-with-coverage": "phpunit --coverage-text --configuration 'phpunit-41.xml.dist'",
"test-no-cov": "phpunit --no-coverage tests",
"cs-fix-all": [
"php-cs-fixer fix src"
],
"cs-fix": "php-cs-fixer fix",
"cs-dry": "php-cs-fixer fix --dry-run --diff",
"phpcs": "phpcs --standard=phpcs-ruleset.xml",
"phpcs-all": "phpcs --standard=phpcs-ruleset.xml src",
"phpcbf": "phpcbf --standard=PSR2",
"phpstan": "vendor/bin/phpstan analyse src --level=4",
"phpstan-global-old": "~/.composer/vendor/bin/phpstan analyse src --level=4",
"phpstan-global": "~/.config/composer/vendor/bin/phpstan analyse src --level=4"
},
"extra": {
"scripts-descriptions": {
"ci": "Run tests before CI",
"phpcs": "Checks coding styles (PSR2) of file/dir, which you must supply. To check all, supply 'src'",
"phpcbf": "Fix coding styles (PSR2) of file/dir, which you must supply. To fix all, supply 'src'",
"cs-fix-all": "Fix the coding style of all the source files, to comply with the PSR-2 coding standard",
"cs-fix": "Fix the coding style of a PHP file or directory, which you must specify.",
"test": "Launches the preconfigured PHPUnit"
}
},
"autoload": {
"psr-4": { "WebPConvert\\": "src/" }
},
"autoload-dev": {
"psr-4": { "WebPConvert\\Tests\\": "tests/" }
},
"authors": [
{
"name": "Bjørn Rosell",
"homepage": "https://www.bitwise-it.dk/contact",
"role": "Project Author"
},
{
"name": "Martin Folkers",
"homepage": "https://twobrain.io",
"role": "Collaborator"
}
],
"require": {
"php": "^5.6 | ^7.0 | ^8.0",
"rosell-dk/exec-with-fallback": "^1.0.0",
"rosell-dk/image-mime-type-guesser": "^1.1.1",
"rosell-dk/locate-binaries": "^1.0"
},
"suggest": {
"ext-gd": "to use GD extension for converting. Note: Gd must be compiled with webp support",
"ext-imagick": "to use Imagick extension for converting. Note: Gd must be compiled with webp support",
"ext-vips": "to use Vips extension for converting.",
"php-stan/php-stan": "Suggested for dev, in order to analyse code before committing"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.11",
"phpunit/phpunit": "^9.3",
"squizlabs/php_codesniffer": "3.*",
"phpstan/phpstan": "^1.5"
},
"config": {
"sort-packages": true
}
}

View File

@ -0,0 +1,79 @@
# Development
## Setting up the environment.
First, clone the repository:
```
cd whatever/folder/you/want
git clone https://github.com/rosell-dk/webp-convert.git
```
Then install the dev tools with composer:
```
composer install
```
If you don't have composer yet:
- Get it ([download phar](https://getcomposer.org/composer.phar) and move it to /usr/local/bin/composer)
- PS: PHPUnit requires php-xml, php-mbstring and php-curl. To install: `sudo apt install php-xml php-mbstring curl php-curl`
## Unit Testing
To run all the unit tests do this:
```
composer test
```
This also runs tests on the builds.
Individual test files can be executed like this:
```
composer phpunit tests/Convert/Converters/WPCTest
composer phpunit tests/Serve/ServeConvertedTest
```
## Coding styles
WebPConvert complies with the [PSR-2](https://www.php-fig.org/psr/psr-2/) coding standard.
To validate coding style of all files, do this:
```
composer phpcs src
```
To automatically fix the coding style of all files, using [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer), do this:
```
composer phpcbf src
```
Or, alternatively, you can fix with the use the [PHP-CS-FIXER](https://github.com/FriendsOfPHP/PHP-CS-Fixer) library instead:
```
composer cs-fix
```
## Running all tests in one command
The following script runs the unit tests, checks the coding styles, validates `composer.json` and runs the builds.
Run this before pushing anything to github. "ci" btw stands for *continuous integration*.
```
composer ci
```
## Generating api docs
Install phpdox and run it in the project root:
```
phpdox
```
## Committing
Before committing, first make sure to:
- run `composer ci`
## Releasing
Before releasing:
- Update the version number in `Converters/AbstractConverter.php` (search for "WebP Convert")
- Make sure that ci build is successful
When releasing:
- update the [webp-convert-concat](https://github.com/rosell-dk/webp-convert-concat) library
- consider updating the require in the composer file in libraries that uses webp-convert (ie `webp-convert-cloud-service` and `webp-express`)

View File

@ -0,0 +1,322 @@
# The webp converters
## The converters at a glance
When it comes to webp conversion, there is actually only one library in town: *libwebp* from Google. All conversion methods below ultimately uses that very same library for conversion. This means that it does not matter much, which conversion method you use. Whatever works. There is however one thing to take note of, if you set *quality* to *auto*, and your system cannot determine the quality of the source (this requires imagick or gmagick), and you do not have access to install those, then the only way to get quality-detection is to connect to a *wpc* cloud converter. However, with *cwebp*, you can specify the desired reduction (the *size-in-percentage* option) - at the cost of doubling the conversion time. Read more about those considerations in the API.
Speed-wise, there is too little difference for it to matter, considering that images usually needs to be converted just once. Anyway, here are the results: *cweb* is the fastest (with method=3). *gd* is right behind, merely 3% slower than *cwebp*. *gmagick* are third place, ~8% slower than *cwebp*. *imagick* comes in ~22% slower than *cwebp*. *ewww* depends on connection speed. On my *digital ocean* account, it takes ~2 seconds to upload, convert, and download a tiny image (10 times longer than the local *cwebp*). A 1MB image however only takes ~4.5 seconds to upload, convert and download (1.5 seconds longer). A 2 MB image takes ~5 seconds to convert (only 16% longer than my *cwebp*). The *ewww* thus converts at a very decent speeds. Probably faster than your average shared host. If multiple big images needs to be converted at the same time, *ewww* will probably perform much better than the local converters.
[`cwebp`](#cwebp) works by executing the *cwebp* binary from Google, which is build upon the *libwebp* (also from Google). That library is actually the only library in town for generating webp images, which means that the other conversion methods ultimately uses that very same library. Which again means that the results using the different methods are very similar. However, with *cwebp*, we have more parameters to tweak than with the rest. We for example have the *method* option, which controls the trade off between encoding speed and the compressed file size and quality. Setting this to max, we can squeeze the images a few percent extra - without loosing quality (the converter is still pretty fast, so in most cases it is probably worth it).
Of course, as we here have to call a binary directly, *cwebp* requires the *exec* function to be enabled, and that the webserver user is allowed to execute the `cwebp` binary (either at known system locations, or one of the precompiled binaries, that comes with this library).
[`vips`](#vips) (**new in 2.0**) works by using the vips extension, if available. Vips is great! It offers many webp options, it is fast and installation is easier than imagick and gd, as it does not need to be configured for webp support.
[`imagick`](#imagick) does not support any special webp options, but is at least able to strip all metadata, if metadata is set to none. Imagick has a very nice feature - that it is able to detect the quality of a jpeg file. This enables it to automatically use same quality for destination as for source, which eliminates the risk of setting quality higher for the destination than for source (the result of that is that the file size gets higher, but the quality remains the same). As the other converters lends this capability from Imagick, this is however no reason for using Imagick rather than the other converters. Requirements: Imagick PHP extension compiled with WebP support
[`gmagick`](#gmagick) uses the *gmagick* extension. It is very similar to *imagick*. Requirements: Gmagick PHP extension compiled with WebP support.
[`gd`](#gd) uses the *Gd* extension to do the conversion. The *Gd* extension is pretty common, so the main feature of this converter is that it may work out of the box. It does not support any webp options, and does not support stripping metadata. Requirements: GD PHP extension compiled with WebP support.
[`wpc`](#wpc) is an open source cloud service for converting images to webp. To use it, you must either install [webp-convert-cloud-service](https://github.com/rosell-dk/webp-convert-cloud-service) directly on a remote server, or install the Wordpress plugin, [WebP Express](https://github.com/rosell-dk/webp-express) in Wordpress. Btw: Beware that upload limits will prevent conversion of big images. The converter checks your *php.ini* settings and abandons upload right away, if an image is larger than your *upload_max_filesize* or your *post_max_size* setting. Requirements: Access to a running service. The service can be installed [directly](https://github.com/rosell-dk/webp-convert-cloud-service) or by using [this Wordpress plugin](https://wordpress.org/plugins/webp-express/)
[`ewww`](#ewww) is also a cloud service. Not free, but cheap enough to be considered *practically* free. It supports lossless encoding, but this cannot be controlled. *Ewww* always uses lossy encoding for jpeg and lossless for png. For jpegs this is usually a good choice, however, many pngs are compressed better using lossy encoding. As lossless cannot be controlled, the "lossless:auto" option cannot be used for automatically trying both lossy and lossless and picking the smallest file. Also, unfortunately, *ewww* does not support quality=auto, like *wpc*, and it does not support *size-in-percentage* like *cwebp*, either. I have requested such features, and he is considering... As with *wpc*, beware of upload limits. Requirements: A key to the *EWWW Image Optimizer* cloud service. Can be purchaced [here](https://ewww.io/plans/)
[`stack`](#stack) takes a stack of converters and tries it from the top, until success. The main convert method actually calls this converter. Stacks within stacks are supported (not really needed, though).
**Summary:**
| | cwebp | vips | imagick / gmagick | imagickbinary | gd | ewww |
| ------------------------------------------ | --------- | ------ | ----------------- | ------------- | --------- | ------ |
| supports lossless encoding ? | yes | yes | no | no | no | yes |
| supports lossless auto ? | yes | yes | no | no | no | no |
| supports near-lossless ? | yes | yes | no | no | no | ? |
| supports metadata stripping / preserving | yes | yes | yes | no | no | ? |
| supports setting alpha quality | no | yes | no | no | no | no |
| supports fixed quality (for lossy) | yes | yes | yes | yes | yes | yes |
| supports auto quality without help | no | no | yes | yes | no | no |
*WebPConvert* currently supports the following converters:
| Converter | Method | Requirements |
| ------------------------------------ | ------------------------------------------------ | -------------------------------------------------- |
| [`cwebp`](#cwebp) | Calls `cwebp` binary directly | `exec()` function *and* that the webserver user has permission to run `cwebp` binary |
| [`vips`](#vips) (new in 2.0) | Vips extension | Vips extension |
| [`imagick`](#imagick) | Imagick extension (`ImageMagick` wrapper) | Imagick PHP extension compiled with WebP support |
| [`gmagick`](#gmagick) | Gmagick extension (`ImageMagick` wrapper) | Gmagick PHP extension compiled with WebP support |
| [`gd`](#gd) | GD Graphics (Draw) extension (`LibGD` wrapper) | GD PHP extension compiled with WebP support |
| [`imagickbinary`](#imagickbinary) | Calls imagick binary directly | exec() and imagick installed and compiled with WebP support |
| [`wpc`](#wpc) | Connects to an open source cloud service | Access to a running service. The service can be installed [directly](https://github.com/rosell-dk/webp-convert-cloud-service) or by using [this Wordpress plugin](https://wordpress.org/plugins/webp-express/).
| [`ewww`](#ewww) | Connects to *EWWW Image Optimizer* cloud service | Purchasing a key |
## Installation
Instructions regarding getting the individual converters to work are [on the wiki](https://github.com/rosell-dk/webp-convert/wiki)
## cwebp
<table>
<tr><th>Requirements</th><td><code>exec()</code> function and that the webserver has permission to run `cwebp` binary (either found in system path, or a precompiled version supplied with this library)</td></tr>
<tr><th>Performance</th><td>~40-120ms to convert a 40kb image (depending on *method* option)</td></tr>
<tr><th>Reliability</th><td>No problems detected so far!</td></tr>
<tr><th>Availability</th><td>According to ewww docs, requirements are met on surprisingly many webhosts. Look <a href="https://docs.ewww.io/article/43-supported-web-hosts">here</a> for a list</td></tr>
<tr><th>General options supported</th><td>All (`quality`, `metadata`, `lossless`)</td></tr>
<tr><th>Extra options</th><td>`method` (0-6)<br>`use-nice` (boolean)<br>`try-common-system-paths` (boolean)<br> `try-supplied-binary-for-os` (boolean)<br>`autofilter` (boolean)<br>`size-in-percentage` (number / null)<br>`command-line-options` (string)<br>`low-memory` (boolean)</td></tr>
</table>
[cwebp](https://developers.google.com/speed/webp/docs/cwebp) is a WebP conversion command line converter released by Google. Our implementation ships with precompiled binaries for Linux, FreeBSD, WinNT, Darwin and SunOS. If however a cwebp binary is found in a usual location, that binary will be preferred. It is executed with [exec()](http://php.net/manual/en/function.exec.php).
In more detail, the implementation does this:
- It is tested whether cwebp is available in a common system path (eg `/usr/bin/cwebp`, ..)
- If not, then supplied binary is selected from `Converters/Binaries` (according to OS) - after validating checksum
- Command-line options are generated from the options
- If [`nice`]( https://en.wikipedia.org/wiki/Nice_(Unix)) command is found on host, binary is executed with low priority in order to save system resources
- Permissions of the generated file are set to be the same as parent folder
### Cwebp options
The following options are supported, besides the general options (such as quality, lossless etc):
| Option | Type | Default |
| -------------------------- | ------------------------- | -------------------------- |
| autofilter | boolean | false |
| command-line-options | string | '' |
| low-memory | boolean | false |
| method | integer (0-6) | 6 |
| near-lossless | integer (0-100) | 60 |
| size-in-percentage | integer (0-100) (or null) | null |
| rel-path-to-precompiled-binaries | string | './Binaries' |
| size-in-percentage | number (or null) | is_null |
| try-common-system-paths | boolean | true |
| try-supplied-binary-for-os | boolean | true |
| use-nice | boolean | false |
Descriptions (only of some of the options):
#### the `autofilter` option
Turns auto-filter on. This algorithm will spend additional time optimizing the filtering strength to reach a well-balanced quality. Unfortunately, it is extremely expensive in terms of computation. It takes about 5-10 times longer to do a conversion. A 1MB picture which perhaps typically takes about 2 seconds to convert, will takes about 15 seconds to convert with auto-filter. So in most cases, you will want to leave this at its default, which is off.
#### the `command-line-options` option
This allows you to set any parameter available for cwebp in the same way as you would do when executing *cwebp*. You could ie set it to "-sharpness 5 -mt -crop 10 10 40 40". Read more about all the available parameters in [the docs](https://developers.google.com/speed/webp/docs/cwebp)
#### the `low-memory` option
Reduce memory usage of lossy encoding at the cost of ~30% longer encoding time and marginally larger output size. Default: `false`. Read more in [the docs](https://developers.google.com/speed/webp/docs/cwebp). Default: *false*
#### The `method` option
This parameter controls the trade off between encoding speed and the compressed file size and quality. Possible values range from 0 to 6. 0 is fastest. 6 results in best quality.
#### the `near-lossless` option
Specify the level of near-lossless image preprocessing. This option adjusts pixel values to help compressibility, but has minimal impact on the visual quality. It triggers lossless compression mode automatically. The range is 0 (maximum preprocessing) to 100 (no preprocessing). The typical value is around 60. Read more [here](https://groups.google.com/a/webmproject.org/forum/#!topic/webp-discuss/0GmxDmlexek). Default: 60
#### The `size-in-percentage` option
This option sets the file size, *cwebp* should aim for, in percentage of the original. If you for example set it to *45*, and the source file is 100 kb, *cwebp* will try to create a file with size 45 kb (we use the `-size` option). This is an excellent alternative to the "quality:auto" option. If the quality detection isn't working on your system (and you do not have the rights to install imagick or gmagick), you should consider using this options instead. *Cwebp* is generally able to create webp files with the same quality at about 45% the size. So *45* would be a good choice. The option overrides the quality option. And note that it slows down the conversion - it takes about 2.5 times longer to do a conversion this way, than when quality is specified. Default is *off* (null)
#### final words on cwebp
The implementation is based on the work of Shane Bishop for his plugin, [EWWW Image Optimizer](https://ewww.io). Thanks for letting us do that!
See [the wiki](https://github.com/rosell-dk/webp-convert/wiki/Installing-cwebp---using-official-precompilations) for instructions regarding installing cwebp or using official precompilations.
## vips
<table>
<tr><th>Requirements</th><td>Vips extension</td></tr>
<tr><th>Performance</th><td>Great</td></tr>
<tr><th>Reliability</th><td>No problems detected so far!</td></tr>
<tr><th>Availability</th><td>Not that widespread yet, but gaining popularity</td></tr>
<tr><th>General options supported</th><td>All (`quality`, `metadata`, `lossless`)</td></tr>
<tr><th>Extra options</th><td>`smart-subsample`(boolean)<br>`alpha-quality`(0-100)<br>`near-lossless` (0-100)<br> `preset` (0-6)</td></tr>
</table>
For installation instructions, go [here](https://github.com/libvips/php-vips-ext).
The options are described [here](https://jcupitt.github.io/libvips/API/current/VipsForeignSave.html#vips-webpsave)
*near-lossless* is however an integer (0-100), in order to have the option behave like in cwebp.
## wpc
*WebPConvert Cloud Service*
<table>
<tr><th>Requirements</th><td>Access to a server with [webp-convert-cloud-service](https://github.com/rosell-dk/webp-convert-cloud-service) installed, <code>cURL</code> and PHP >= 5.5.0</td></tr>
<tr><th>Performance</th><td>Depends on the server where [webp-convert-cloud-service](https://github.com/rosell-dk/webp-convert-cloud-service) is set up, and the speed of internet connections. But perhaps ~1000ms to convert a 40kb image</td></tr>
<tr><th>Reliability</th><td>Great (depends on the reliability on the server where it is set up)</td></tr>
<tr><th>Availability</th><td>Should work on <em>almost</em> any webhost</td></tr>
<tr><th>General options supported</th><td>All (`quality`, `metadata`, `lossless`)</td></tr>
<tr><th>Extra options (old api)</th><td>`url`, `secret`</td></tr>
<tr><th>Extra options (new api)</th><td>`url`, `api-version`, `api-key`, `crypt-api-key-in-transfer`</td></tr>
</table>
[wpc](https://github.com/rosell-dk/webp-convert-cloud-service) is an open source cloud service. You do not buy a key, you set it up on a server, or you set up [the Wordpress plugin](https://wordpress.org/plugins/webp-express/). As WebPConvert Cloud Service itself is based on WebPConvert, all options are supported.
To use it, you need to set the `converter-options` (to add url etc).
#### Example, where api-key is not crypted, on new API:
```php
WebPConvert::convert($source, $destination, [
'max-quality' => 80,
'converters' => ['cwebp', 'wpc'],
'converter-options' => [
'wpc' => [
'api-version' => 1, /* from wpc release 1.0.0 */
'url' => 'http://example.com/wpc.php',
'api-key' => 'my dog is white',
'crypt-api-key-in-transfer' => false
]
]
));
```
#### Example, where api-key is crypted:
```php
WebPConvert::convert($source, $destination, [
'max-quality' => 80,
'converters' => ['cwebp', 'wpc'],
'converter-options' => [
'wpc' => [
'api-version' => 1,
'url' => 'https://example.com/wpc.php',
'api-key' => 'my dog is white',
'crypt-api-key-in-transfer' => true
],
]
));
```
In 2.0, you can alternatively set the api key and urls through through the *WPC_API_KEY* and *WPC_API_URL* environment variables. This is a safer place to store it.
To set an environment variable in Apache, you can use the `SetEnv` directory. Ie, place something like the following in your virtual host / or .htaccess file (replace the key with the one you purchased!)
```
SetEnv WPC_API_KEY my-dog-is-dashed
SetEnv WPC_API_URL https://wpc.example.com/wpc.php
```
#### Example, old API:
```php
WebPConvert::convert($source, $destination, [
'max-quality' => 80,
'converters' => ['cwebp', 'wpc'],
'converter-options' => [
'wpc' => [
'url' => 'https://example.com/wpc.php',
'secret' => 'my dog is white',
],
]
));
```
## ewww
<table>
<tr><th>Requirements</th><td>Valid EWWW Image Optimizer <a href="https://ewww.io/plans/">API key</a>, <code>cURL</code> and PHP >= 5.5.0</td></tr>
<tr><th>Performance</th><td>~1300ms to convert a 40kb image</td></tr>
<tr><th>Reliability</th><td>Great (but, as with any cloud service, there is a risk of downtime)</td></tr>
<tr><th>Availability</th><td>Should work on <em>almost</em> any webhost</td></tr>
<tr><th>General options supported</th><td>`quality`, `metadata` (partly)</td></tr>
<tr><th>Extra options</th><td>`key`</td></tr>
</table>
EWWW Image Optimizer is a very cheap cloud service for optimizing images. After purchasing an API key, add the converter in the `extra-converters` option, with `key` set to the key. Be aware that the `key` should be stored safely to avoid exploitation - preferably in the environment, ie with [dotenv](https://github.com/vlucas/phpdotenv).
The EWWW api doesn't support the `lossless` option, but it does automatically convert PNG's losslessly. Metadata is either all or none. If you have set it to something else than one of these, all metadata will be preserved.
In more detail, the implementation does this:
- Validates that there is a key, and that `curl` extension is working
- Validates the key, using the [/verify/ endpoint](https://ewww.io/api/) (in order to [protect the EWWW service from unnecessary file uploads, when key has expired](https://github.com/rosell-dk/webp-convert/issues/38))
- Converts, using the [/ endpoint](https://ewww.io/api/).
<details>
<summary><strong>Roadmap</strong> 👁</summary>
The converter could be improved by using `fsockopen` when `cURL` is not available - which is extremely rare. PHP >= 5.5.0 is also widely available (PHP 5.4.0 reached end of life [more than two years ago!](http://php.net/supported-versions.php)).
</details>
#### Example:
```php
WebPConvert::convert($source, $destination, [
'max-quality' => 80,
'converters' => ['gd', 'ewww'],
'converter-options' => [
'ewww' => [
'key' => 'your-api-key-here'
],
]
));
```
In 2.0, you can alternatively set the api key by through the *EWWW_API_KEY* environment variable. This is a safer place to store it.
To set an environment variable in Apache, you can use the `SetEnv` directory. Ie, place something like the following in your virtual host / or .htaccess file (replace the key with the one you purchased!)
```
SetEnv EWWW_API_KEY sP3LyPpsKWZy8CVBTYegzEGN6VsKKKKA
```
## gd
<table>
<tr><th>Requirements</th><td>GD PHP extension and PHP >= 5.5.0 (compiled with WebP support)</td></tr>
<tr><th>Performance</th><td>~30ms to convert a 40kb image</td></tr>
<tr><th>Reliability</th><td>Not sure - I have experienced corrupted images, but cannot reproduce</td></tr>
<tr><th>Availability</th><td>Unfortunately, according to <a href="https://stackoverflow.com/questions/25248382/how-to-create-a-webp-image-in-php">this link</a>, WebP support on shared hosts is rare.</td></tr>
<tr><th>General options supported</th><td>`quality`</td></tr>
<tr><th>Extra options</th><td>`skip-pngs`</td></tr>
</table>
[imagewebp](http://php.net/manual/en/function.imagewebp.php) is a function that comes with PHP (>5.5.0), *provided* that PHP has been compiled with WebP support.
`gd` neither supports copying metadata nor exposes any WebP options. Lacking the option to set lossless encoding results in poor encoding of PNGs - the filesize is generally much larger than the original. For this reason, PNG conversion is *disabled* by default, but it can be enabled my setting `skip-pngs` option to `false`.
Installaition instructions are [available in the wiki](https://github.com/rosell-dk/webp-convert/wiki/Installing-Gd-extension).
<details>
<summary><strong>Known bugs</strong> 👁</summary>
Due to a [bug](https://bugs.php.net/bug.php?id=66590), some versions sometimes created corrupted images. That bug can however easily be fixed in PHP (fix was released [here](https://stackoverflow.com/questions/30078090/imagewebp-php-creates-corrupted-webp-files)). However, I have experienced corrupted images *anyway* (but cannot reproduce that bug). So use this converter with caution. The corrupted images look completely transparent in Google Chrome, but have the correct size.
</details>
## imagick
<table>
<tr><th>Requirements</th><td>Imagick PHP extension (compiled with WebP support)</td></tr>
<tr><th>Quality</th><td>Poor. [See this issue]( https://github.com/rosell-dk/webp-convert/issues/43)</td></tr>
<tr><th>General options supported</th><td>`quality`</td></tr>
<tr><th>Extra options</th><td>None</td></tr>
<tr><th>Performance</th><td>~20-320ms to convert a 40kb image</td></tr>
<tr><th>Reliability</th><td>No problems detected so far</td></tr>
<tr><th>Availability</th><td>Probably only available on few shared hosts (if any)</td></tr>
</table>
WebP conversion with `imagick` is fast and [exposes many WebP options](http://www.imagemagick.org/script/webp.php). Unfortunately, WebP support for the `imagick` extension is pretty uncommon. At least not on the systems I have tried (Ubuntu 16.04 and Ubuntu 17.04). But if installed, it works great and has several WebP options.
See [this page](https://github.com/rosell-dk/webp-convert/wiki/Installing-Imagick-extension) in the Wiki for instructions on installing the extension.
## imagickbinary
<table>
<tr><th>Requirements</th><td><code>exec()</code> function and that imagick is installed on webserver, compiled with webp support</td></tr>
<tr><th>Performance</th><td>just fine</td></tr>
<tr><th>Reliability</th><td>No problems detected so far!</td></tr>
<tr><th>Availability</th><td>Not sure</td></tr>
<tr><th>General options supported</th><td>`quality`</td></tr>
<tr><th>Extra options</th><td>`use-nice` (boolean)</td></tr>
</table>
This converter tryes to execute `convert source.jpg webp:destination.jpg.webp`.
## stack
<table>
<tr><th>General options supported</th><td>all (passed to the converters in the stack )</td></tr>
<tr><th>Extra options</th><td>`converters` (array) and `converter-options` (array)</td></tr>
</table>
Stack implements the functionality you know from `WebPConvert::convert`. In fact, all `WebPConvert::convert` does is to call `Stack::convert($source, $destination, $options, $logger);`
It has two special options: `converters` and `converter-options`. You can read about those in `docs/api/convert.md`

View File

@ -0,0 +1,96 @@
# API: The convert() method
**WebPConvert::convert($source, $destination, $options, $logger)**
| Parameter | Type | Description |
| ---------------- | ------- | ------------------------------------------------------------------------------------------ |
| `$source` | String | Absolute path to source image (only forward slashes allowed) |
| `$destination` | String | Absolute path to converted image (only forward slashes allowed) |
| `$options` (optional) | Array | Array of conversion (option) options |
| `$logger` (optional) | Baselogger | Information about the conversion process will be passed to this object. Read more below |
Returns true if success or false if no converters are *operational*. If any converter seems to have its requirements met (are *operational*), but fails anyway, and no other converters in the stack could convert the image, an the exception from that converter is rethrown (either *ConverterFailedException* or *ConversionDeclinedException*). Exceptions are also thrown if something is wrong entirely (*InvalidFileExtensionException*, *TargetNotFoundException*, *ConverterNotFoundException*, *CreateDestinationFileException*, *CreateDestinationFolderException*, or any unanticipated exceptions thrown by the converters).
### Available options for all converters
Many options correspond to options of *cwebp*. These are documented [here](https://developers.google.com/speed/webp/docs/cwebp)
| Option | Type | Default | Description |
| ----------------- | ------- | -------------------------- | -------------------------------------------------------------------- |
| quality | An integer between 0-100, or "auto" | "auto" | Lossy quality of converted image (JPEG only - PNGs are always losless).<br><br> If set to "auto", *WebPConvert* will try to determine the quality of the JPEG (this is only possible, if Imagick or GraphicsMagic is installed). If successfully determined, the quality of the webp will be set to the same as that of the JPEG. however not to more than specified in the new `max-quality` option. If quality cannot be determined, quality will be set to what is specified in the new `default-quality` option (however, if you use the *wpc* converter, it will also get a shot at detecting the quality) |
| max-quality | An integer between 0-100 | 85 | See the `quality` option. Only relevant, when quality is set to "auto".
| default-quality | An integer between 0-100 | 75 | See the `quality` option. Only relevant, when quality is set to "auto".
| metadata | String | 'none' | Valid values: all, none, exif, icc, xmp. Note: Only *cwebp* supports all values. *gd* will always remove all metadata. *ewww*, *imagick* and *gmagick* can either strip all, or keep all (they will keep all, unless metadata is set to *none*) |
| lossless | Boolean | false ("auto" for pngs in 2.0) | Encode the image without any loss. The option is ignored for PNG's (forced true). In 2.0, it can also be "auto", and it is not forced to anything - rather it deafaults to false for Jpegs and "auto" for PNGs |
| converters | Array | ['cwebp', 'gd', 'imagick'] | Specify conversion methods to use, and their order. Also optionally set converter options (see below) |
| converter-options | Array | [] | Set options of the individual converters (see below) |
| jpeg | Array | null | These options will be merged into the other options when source is jpeg |
| png | Array | null | These options will be merged into the other options when source is jpeg |
| skip (new in 2.0) | Boolean | false | If true, conversion will be skipped (ie for skipping png conversion for some converters) |
| skip-png (removed in 2.0) | Boolean | false | If true, conversion will be skipped for png (ie for skipping png conversion for some converters) |
#### More on quality=auto
Unfortunately, *libwebp* does not provide a way to use the same quality for the converted image, as for source. This feature is implemented by *imagick* and *gmagick*. No matter which conversion method you choose, if you set *quality* to *auto*, our library will try to detect the quality of the source file using one of these libraries. If this isn't available, it will revert to the value set in the *default-quality* option (75 per default). *However*, with the *wpc* converter you have a second chance: If quality cannot be detected locally, it will send quality="auto" to *wpc*.
The bottom line is: If you do not have imagick or gmagick installed on your host (and have no way to install it), your best option quality-wise is to install *wpc* on a server that you do have access to, and connect to that. However,... read on:
**How much does it matter?**
The effect of not having quality detection is that jpeg images with medium quality (say 50) will be converted with higher quality (say 75). Converting a q=50 to a q=50 would typically result in a ~60% reduction. But converting it to q=75 will only result in a ~45% reduction. When converting low quality jpeg images, it gets worse. Converting q=30 to q=75 only achieves ~25% reduction.
I guess it is a rare case having jpeg images in low quality. Even having middle quality is rare, as there seems to have been a tendency to choose higher quality than actually needed for web. So, in many cases, the impact of not having quality detection is minor. If you set the *default-quality* a bit low, ie 65, you will further minimize the effect.
To determine if *webp-convert* is able to autodetect quality on your system, run a conversion with the *$logger* parameter set to `new EchoLogger()` (see api).
#### More on the `converter-options` option
You use this option to set options for the individual converters. Example:
```
'converter-options' => [
'ewww' => [
'key' => 'your-api-key-here'
],
'wpc' => [
'url' => 'https://example.com/wpc.php',
'secret' => 'my dog is white'
]
]
```
Besides options that are special to a converter, you can also override general options. For example, you may generally want the `max-quality` to be 85, but for a single converter, you would like it to be 100 (sorry, it is hard to come up with a useful example).
#### More on the `converters` option
The *converters* option specifies the conversion methods to use and their order. But it can also be used as an alternative way of setting converter options. Usually, you probably want to use the *converter-options* for that, but there may be cases where it is more convenient to specify them here. Also, specifying here allows you to put the same converter method to the stack multiple times, with different options (this could for example be used to have an extra *ewww* converter as a fallback).
Example:
```
WebPConvert::convert($source, $destination, [
'converters' => [
'cwebp',
'imagick',
[
'converter' => 'ewww',
'options' => [
'key' => 'your api key here',
],
],
];
)
```
In 2.0, it will be possible to use your own custom converter. Instead of the "converter id" (ie "ewww"), specify the full class name of your custom converter. Ie '\\MyProject\\BraveConverter'. The converter must extend `\WebPConvert\Convert\Converters\AbstractConverters\AbstractConverter` and you must implement `doConvert()` and the define the extra options it takes (check out how it is done in the build-in converters).
### More on the `$logger` parameter
WebPConvert and the individual converters can provide information regarding the conversion process. Per default (when the parameter isn't provided), they write this to `\WebPConvert\Loggers\VoidLogger`, which does nothing with it.
In order to get this information echoed out, you can use `\WebPConvert\Loggers\EchoLogger` - like this:
```php
use WebPConvert\Loggers\EchoLogger;
WebPConvert::convert($source, $destination, $options, new EchoLogger());
```
In order to do something else with the information (perhaps write it to a log file?), you can extend `\WebPConvert\Loggers\BaseLogger`.
## Converters
In the most basic design, a converter consists of a static convert function which takes the same arguments as `WebPConvert::convert`. Its job is then to convert `$source` to WebP and save it at `$destination`, preferably taking the options specified in $options into account.
The converters may be called directly. But you probably don't want to do that, as it really doesn't hurt having other converters ready to take over, in case your preferred converter should fail.

View File

@ -0,0 +1,322 @@
# The webp converters
## The converters at a glance
When it comes to webp conversion, there is actually only one library in town: *libwebp* from Google. All conversion methods below ultimately uses that very same library for conversion. This means that it does not matter much, which conversion method you use. Whatever works. There is however one thing to take note of, if you set *quality* to *auto*, and your system cannot determine the quality of the source (this requires imagick or gmagick), and you do not have access to install those, then the only way to get quality-detection is to connect to a *wpc* cloud converter. However, with *cwebp*, you can specify the desired reduction (the *size-in-percentage* option) - at the cost of doubling the conversion time. Read more about those considerations in the API.
Speed-wise, there is too little difference for it to matter, considering that images usually needs to be converted just once. Anyway, here are the results: *cweb* is the fastest (with method=3). *gd* is right behind, merely 3% slower than *cwebp*. *gmagick* are third place, ~8% slower than *cwebp*. *imagick* comes in ~22% slower than *cwebp*. *ewww* depends on connection speed. On my *digital ocean* account, it takes ~2 seconds to upload, convert, and download a tiny image (10 times longer than the local *cwebp*). A 1MB image however only takes ~4.5 seconds to upload, convert and download (1.5 seconds longer). A 2 MB image takes ~5 seconds to convert (only 16% longer than my *cwebp*). The *ewww* thus converts at a very decent speeds. Probably faster than your average shared host. If multiple big images needs to be converted at the same time, *ewww* will probably perform much better than the local converters.
[`cwebp`](#cwebp) works by executing the *cwebp* binary from Google, which is build upon the *libwebp* (also from Google). That library is actually the only library in town for generating webp images, which means that the other conversion methods ultimately uses that very same library. Which again means that the results using the different methods are very similar. However, with *cwebp*, we have more parameters to tweak than with the rest. We for example have the *method* option, which controls the trade off between encoding speed and the compressed file size and quality. Setting this to max, we can squeeze the images a few percent extra - without loosing quality (the converter is still pretty fast, so in most cases it is probably worth it).
Of course, as we here have to call a binary directly, *cwebp* requires the *exec* function to be enabled, and that the webserver user is allowed to execute the `cwebp` binary (either at known system locations, or one of the precompiled binaries, that comes with this library).
[`vips`](#vips) (**new in 2.0**) works by using the vips extension, if available. Vips is great! It offers many webp options, it is fast and installation is easier than imagick and gd, as it does not need to be configured for webp support.
[`imagick`](#imagick) does not support any special webp options, but is at least able to strip all metadata, if metadata is set to none. Imagick has a very nice feature - that it is able to detect the quality of a jpeg file. This enables it to automatically use same quality for destination as for source, which eliminates the risk of setting quality higher for the destination than for source (the result of that is that the file size gets higher, but the quality remains the same). As the other converters lends this capability from Imagick, this is however no reason for using Imagick rather than the other converters. Requirements: Imagick PHP extension compiled with WebP support
[`gmagick`](#gmagick) uses the *gmagick* extension. It is very similar to *imagick*. Requirements: Gmagick PHP extension compiled with WebP support.
[`gd`](#gd) uses the *Gd* extension to do the conversion. The *Gd* extension is pretty common, so the main feature of this converter is that it may work out of the box. It does not support any webp options, and does not support stripping metadata. Requirements: GD PHP extension compiled with WebP support.
[`wpc`](#wpc) is an open source cloud service for converting images to webp. To use it, you must either install [webp-convert-cloud-service](https://github.com/rosell-dk/webp-convert-cloud-service) directly on a remote server, or install the Wordpress plugin, [WebP Express](https://github.com/rosell-dk/webp-express) in Wordpress. Btw: Beware that upload limits will prevent conversion of big images. The converter checks your *php.ini* settings and abandons upload right away, if an image is larger than your *upload_max_filesize* or your *post_max_size* setting. Requirements: Access to a running service. The service can be installed [directly](https://github.com/rosell-dk/webp-convert-cloud-service) or by using [this Wordpress plugin](https://wordpress.org/plugins/webp-express/)
[`ewww`](#ewww) is also a cloud service. Not free, but cheap enough to be considered *practically* free. It supports lossless encoding, but this cannot be controlled. *Ewww* always uses lossy encoding for jpeg and lossless for png. For jpegs this is usually a good choice, however, many pngs are compressed better using lossy encoding. As lossless cannot be controlled, the "lossless:auto" option cannot be used for automatically trying both lossy and lossless and picking the smallest file. Also, unfortunately, *ewww* does not support quality=auto, like *wpc*, and it does not support *size-in-percentage* like *cwebp*, either. I have requested such features, and he is considering... As with *wpc*, beware of upload limits. Requirements: A key to the *EWWW Image Optimizer* cloud service. Can be purchaced [here](https://ewww.io/plans/)
[`stack`](#stack) takes a stack of converters and tries it from the top, until success. The main convert method actually calls this converter. Stacks within stacks are supported (not really needed, though).
**Summary:**
| | cwebp | vips | imagickbinary | imagick / gmagick | gd | ewww |
| ------------------------------------------ | --------- | ------ | -------------- | ----------------- | --------- | ------ |
| supports lossless encoding ? | yes | yes | yes | no | no | yes |
| supports lossless auto ? | yes | yes | yes | no | no | no |
| supports near-lossless ? | yes | yes | no | no | no | ? |
| supports metadata stripping / preserving | yes | yes | yes | yes | no | ? |
| supports setting alpha quality | yes | yes | yes | no | no | no |
| supports fixed quality (for lossy) | yes | yes | yes | yes | yes | yes |
| supports auto quality without help | no | no | yes | yes | no | no |
*WebPConvert* currently supports the following converters:
| Converter | Method | Requirements |
| ------------------------------------ | ------------------------------------------------ | -------------------------------------------------- |
| [`cwebp`](#cwebp) | Calls `cwebp` binary directly | `exec()` function *and* that the webserver user has permission to run `cwebp` binary |
| [`vips`](#vips) (new in 2.0) | Vips extension | Vips extension |
| [`imagick`](#imagick) | Imagick extension (`ImageMagick` wrapper) | Imagick PHP extension compiled with WebP support |
| [`gmagick`](#gmagick) | Gmagick extension (`ImageMagick` wrapper) | Gmagick PHP extension compiled with WebP support |
| [`gd`](#gd) | GD Graphics (Draw) extension (`LibGD` wrapper) | GD PHP extension compiled with WebP support |
| [`imagickbinary`](#imagickbinary) | Calls imagick binary directly | exec() and imagick installed and compiled with WebP support |
| [`wpc`](#wpc) | Connects to an open source cloud service | Access to a running service. The service can be installed [directly](https://github.com/rosell-dk/webp-convert-cloud-service) or by using [this Wordpress plugin](https://wordpress.org/plugins/webp-express/).
| [`ewww`](#ewww) | Connects to *EWWW Image Optimizer* cloud service | Purchasing a key |
## Installation
Instructions regarding getting the individual converters to work are [on the wiki](https://github.com/rosell-dk/webp-convert/wiki)
## cwebp
<table>
<tr><th>Requirements</th><td><code>exec()</code> function and that the webserver has permission to run `cwebp` binary (either found in system path, or a precompiled version supplied with this library)</td></tr>
<tr><th>Performance</th><td>~40-120ms to convert a 40kb image (depending on *method* option)</td></tr>
<tr><th>Reliability</th><td>No problems detected so far!</td></tr>
<tr><th>Availability</th><td>According to ewww docs, requirements are met on surprisingly many webhosts. Look <a href="https://docs.ewww.io/article/43-supported-web-hosts">here</a> for a list</td></tr>
<tr><th>General options supported</th><td>All (`quality`, `metadata`, `lossless`)</td></tr>
<tr><th>Extra options</th><td>`method` (0-6)<br>`use-nice` (boolean)<br>`try-common-system-paths` (boolean)<br> `try-supplied-binary-for-os` (boolean)<br>`autofilter` (boolean)<br>`size-in-percentage` (number / null)<br>`command-line-options` (string)<br>`low-memory` (boolean)</td></tr>
</table>
[cwebp](https://developers.google.com/speed/webp/docs/cwebp) is a WebP conversion command line converter released by Google. Our implementation ships with precompiled binaries for Linux, FreeBSD, WinNT, Darwin and SunOS. If however a cwebp binary is found in a usual location, that binary will be preferred. It is executed with [exec()](http://php.net/manual/en/function.exec.php).
In more detail, the implementation does this:
- It is tested whether cwebp is available in a common system path (eg `/usr/bin/cwebp`, ..)
- If not, then supplied binary is selected from `Converters/Binaries` (according to OS) - after validating checksum
- Command-line options are generated from the options
- If [`nice`]( https://en.wikipedia.org/wiki/Nice_(Unix)) command is found on host, binary is executed with low priority in order to save system resources
- Permissions of the generated file are set to be the same as parent folder
### Cwebp options
The following options are supported, besides the general options (such as quality, lossless etc):
| Option | Type | Default |
| -------------------------- | ------------------------- | -------------------------- |
| autofilter | boolean | false |
| command-line-options | string | '' |
| low-memory | boolean | false |
| method | integer (0-6) | 6 |
| near-lossless | integer (0-100) | 60 |
| size-in-percentage | integer (0-100) (or null) | null |
| rel-path-to-precompiled-binaries | string | './Binaries' |
| size-in-percentage | number (or null) | is_null |
| try-common-system-paths | boolean | true |
| try-supplied-binary-for-os | boolean | true |
| use-nice | boolean | false |
Descriptions (only of some of the options):
#### the `autofilter` option
Turns auto-filter on. This algorithm will spend additional time optimizing the filtering strength to reach a well-balanced quality. Unfortunately, it is extremely expensive in terms of computation. It takes about 5-10 times longer to do a conversion. A 1MB picture which perhaps typically takes about 2 seconds to convert, will takes about 15 seconds to convert with auto-filter. So in most cases, you will want to leave this at its default, which is off.
#### the `command-line-options` option
This allows you to set any parameter available for cwebp in the same way as you would do when executing *cwebp*. You could ie set it to "-sharpness 5 -mt -crop 10 10 40 40". Read more about all the available parameters in [the docs](https://developers.google.com/speed/webp/docs/cwebp)
#### the `low-memory` option
Reduce memory usage of lossy encoding at the cost of ~30% longer encoding time and marginally larger output size. Default: `false`. Read more in [the docs](https://developers.google.com/speed/webp/docs/cwebp). Default: *false*
#### The `method` option
This parameter controls the trade off between encoding speed and the compressed file size and quality. Possible values range from 0 to 6. 0 is fastest. 6 results in best quality.
#### the `near-lossless` option
Specify the level of near-lossless image preprocessing. This option adjusts pixel values to help compressibility, but has minimal impact on the visual quality. It triggers lossless compression mode automatically. The range is 0 (maximum preprocessing) to 100 (no preprocessing). The typical value is around 60. Read more [here](https://groups.google.com/a/webmproject.org/forum/#!topic/webp-discuss/0GmxDmlexek). Default: 60
#### The `size-in-percentage` option
This option sets the file size, *cwebp* should aim for, in percentage of the original. If you for example set it to *45*, and the source file is 100 kb, *cwebp* will try to create a file with size 45 kb (we use the `-size` option). This is an excellent alternative to the "quality:auto" option. If the quality detection isn't working on your system (and you do not have the rights to install imagick or gmagick), you should consider using this options instead. *Cwebp* is generally able to create webp files with the same quality at about 45% the size. So *45* would be a good choice. The option overrides the quality option. And note that it slows down the conversion - it takes about 2.5 times longer to do a conversion this way, than when quality is specified. Default is *off* (null)
#### final words on cwebp
The implementation is based on the work of Shane Bishop for his plugin, [EWWW Image Optimizer](https://ewww.io). Thanks for letting us do that!
See [the wiki](https://github.com/rosell-dk/webp-convert/wiki/Installing-cwebp---using-official-precompilations) for instructions regarding installing cwebp or using official precompilations.
## vips
<table>
<tr><th>Requirements</th><td>Vips extension</td></tr>
<tr><th>Performance</th><td>Great</td></tr>
<tr><th>Reliability</th><td>No problems detected so far!</td></tr>
<tr><th>Availability</th><td>Not that widespread yet, but gaining popularity</td></tr>
<tr><th>General options supported</th><td>All (`quality`, `metadata`, `lossless`)</td></tr>
<tr><th>Extra options</th><td>`smart-subsample`(boolean)<br>`alpha-quality`(0-100)<br>`near-lossless` (0-100)<br> `preset` (0-6)</td></tr>
</table>
For installation instructions, go [here](https://github.com/libvips/php-vips-ext).
The options are described [here](https://jcupitt.github.io/libvips/API/current/VipsForeignSave.html#vips-webpsave)
*near-lossless* is however an integer (0-100), in order to have the option behave like in cwebp.
## wpc
*WebPConvert Cloud Service*
<table>
<tr><th>Requirements</th><td>Access to a server with [webp-convert-cloud-service](https://github.com/rosell-dk/webp-convert-cloud-service) installed, <code>cURL</code> and PHP >= 5.5.0</td></tr>
<tr><th>Performance</th><td>Depends on the server where [webp-convert-cloud-service](https://github.com/rosell-dk/webp-convert-cloud-service) is set up, and the speed of internet connections. But perhaps ~1000ms to convert a 40kb image</td></tr>
<tr><th>Reliability</th><td>Great (depends on the reliability on the server where it is set up)</td></tr>
<tr><th>Availability</th><td>Should work on <em>almost</em> any webhost</td></tr>
<tr><th>General options supported</th><td>All (`quality`, `metadata`, `lossless`)</td></tr>
<tr><th>Extra options (old api)</th><td>`url`, `secret`</td></tr>
<tr><th>Extra options (new api)</th><td>`url`, `api-version`, `api-key`, `crypt-api-key-in-transfer`</td></tr>
</table>
[wpc](https://github.com/rosell-dk/webp-convert-cloud-service) is an open source cloud service. You do not buy a key, you set it up on a server, or you set up [the Wordpress plugin](https://wordpress.org/plugins/webp-express/). As WebPConvert Cloud Service itself is based on WebPConvert, all options are supported.
To use it, you need to set the `converter-options` (to add url etc).
#### Example, where api-key is not crypted, on new API:
```php
WebPConvert::convert($source, $destination, [
'max-quality' => 80,
'converters' => ['cwebp', 'wpc'],
'converter-options' => [
'wpc' => [
'api-version' => 1, /* from wpc release 1.0.0 */
'url' => 'http://example.com/wpc.php',
'api-key' => 'my dog is white',
'crypt-api-key-in-transfer' => false
]
]
));
```
#### Example, where api-key is crypted:
```php
WebPConvert::convert($source, $destination, [
'max-quality' => 80,
'converters' => ['cwebp', 'wpc'],
'converter-options' => [
'wpc' => [
'api-version' => 1,
'url' => 'https://example.com/wpc.php',
'api-key' => 'my dog is white',
'crypt-api-key-in-transfer' => true
],
]
));
```
In 2.0, you can alternatively set the api key and urls through through the *WPC_API_KEY* and *WPC_API_URL* environment variables. This is a safer place to store it.
To set an environment variable in Apache, you can use the `SetEnv` directory. Ie, place something like the following in your virtual host / or .htaccess file (replace the key with the one you purchased!)
```
SetEnv WPC_API_KEY my-dog-is-dashed
SetEnv WPC_API_URL https://wpc.example.com/wpc.php
```
#### Example, old API:
```php
WebPConvert::convert($source, $destination, [
'max-quality' => 80,
'converters' => ['cwebp', 'wpc'],
'converter-options' => [
'wpc' => [
'url' => 'https://example.com/wpc.php',
'secret' => 'my dog is white',
],
]
));
```
## ewww
<table>
<tr><th>Requirements</th><td>Valid EWWW Image Optimizer <a href="https://ewww.io/plans/">API key</a>, <code>cURL</code> and PHP >= 5.5.0</td></tr>
<tr><th>Performance</th><td>~1300ms to convert a 40kb image</td></tr>
<tr><th>Reliability</th><td>Great (but, as with any cloud service, there is a risk of downtime)</td></tr>
<tr><th>Availability</th><td>Should work on <em>almost</em> any webhost</td></tr>
<tr><th>General options supported</th><td>`quality`, `metadata` (partly)</td></tr>
<tr><th>Extra options</th><td>`key`</td></tr>
</table>
EWWW Image Optimizer is a very cheap cloud service for optimizing images. After purchasing an API key, add the converter in the `extra-converters` option, with `key` set to the key. Be aware that the `key` should be stored safely to avoid exploitation - preferably in the environment, ie with [dotenv](https://github.com/vlucas/phpdotenv).
The EWWW api doesn't support the `lossless` option, but it does automatically convert PNG's losslessly. Metadata is either all or none. If you have set it to something else than one of these, all metadata will be preserved.
In more detail, the implementation does this:
- Validates that there is a key, and that `curl` extension is working
- Validates the key, using the [/verify/ endpoint](https://ewww.io/api/) (in order to [protect the EWWW service from unnecessary file uploads, when key has expired](https://github.com/rosell-dk/webp-convert/issues/38))
- Converts, using the [/ endpoint](https://ewww.io/api/).
<details>
<summary><strong>Roadmap</strong> 👁</summary>
The converter could be improved by using `fsockopen` when `cURL` is not available - which is extremely rare. PHP >= 5.5.0 is also widely available (PHP 5.4.0 reached end of life [more than two years ago!](http://php.net/supported-versions.php)).
</details>
#### Example:
```php
WebPConvert::convert($source, $destination, [
'max-quality' => 80,
'converters' => ['gd', 'ewww'],
'converter-options' => [
'ewww' => [
'key' => 'your-api-key-here'
],
]
));
```
In 2.0, you can alternatively set the api key by through the *EWWW_API_KEY* environment variable. This is a safer place to store it.
To set an environment variable in Apache, you can use the `SetEnv` directory. Ie, place something like the following in your virtual host / or .htaccess file (replace the key with the one you purchased!)
```
SetEnv EWWW_API_KEY sP3LyPpsKWZy8CVBTYegzEGN6VsKKKKA
```
## gd
<table>
<tr><th>Requirements</th><td>GD PHP extension and PHP >= 5.5.0 (compiled with WebP support)</td></tr>
<tr><th>Performance</th><td>~30ms to convert a 40kb image</td></tr>
<tr><th>Reliability</th><td>Not sure - I have experienced corrupted images, but cannot reproduce</td></tr>
<tr><th>Availability</th><td>Unfortunately, according to <a href="https://stackoverflow.com/questions/25248382/how-to-create-a-webp-image-in-php">this link</a>, WebP support on shared hosts is rare.</td></tr>
<tr><th>General options supported</th><td>`quality`</td></tr>
<tr><th>Extra options</th><td>`skip-pngs`</td></tr>
</table>
[imagewebp](http://php.net/manual/en/function.imagewebp.php) is a function that comes with PHP (>5.5.0), *provided* that PHP has been compiled with WebP support.
`gd` neither supports copying metadata nor exposes any WebP options. Lacking the option to set lossless encoding results in poor encoding of PNGs - the filesize is generally much larger than the original. For this reason, PNG conversion is *disabled* by default, but it can be enabled my setting `skip-pngs` option to `false`.
Installaition instructions are [available in the wiki](https://github.com/rosell-dk/webp-convert/wiki/Installing-Gd-extension).
<details>
<summary><strong>Known bugs</strong> 👁</summary>
Due to a [bug](https://bugs.php.net/bug.php?id=66590), some versions sometimes created corrupted images. That bug can however easily be fixed in PHP (fix was released [here](https://stackoverflow.com/questions/30078090/imagewebp-php-creates-corrupted-webp-files)). However, I have experienced corrupted images *anyway* (but cannot reproduce that bug). So use this converter with caution. The corrupted images look completely transparent in Google Chrome, but have the correct size.
</details>
## imagick
<table>
<tr><th>Requirements</th><td>Imagick PHP extension (compiled with WebP support)</td></tr>
<tr><th>Quality</th><td>Poor. [See this issue]( https://github.com/rosell-dk/webp-convert/issues/43)</td></tr>
<tr><th>General options supported</th><td>`quality`</td></tr>
<tr><th>Extra options</th><td>None</td></tr>
<tr><th>Performance</th><td>~20-320ms to convert a 40kb image</td></tr>
<tr><th>Reliability</th><td>No problems detected so far</td></tr>
<tr><th>Availability</th><td>Probably only available on few shared hosts (if any)</td></tr>
</table>
WebP conversion with `imagick` is fast and [exposes many WebP options](http://www.imagemagick.org/script/webp.php). Unfortunately, WebP support for the `imagick` extension is pretty uncommon. At least not on the systems I have tried (Ubuntu 16.04 and Ubuntu 17.04). But if installed, it works great and has several WebP options.
See [this page](https://github.com/rosell-dk/webp-convert/wiki/Installing-Imagick-extension) in the Wiki for instructions on installing the extension.
## imagickbinary
<table>
<tr><th>Requirements</th><td><code>exec()</code> function and that imagick is installed on webserver, compiled with webp support</td></tr>
<tr><th>Performance</th><td>just fine</td></tr>
<tr><th>Reliability</th><td>No problems detected so far!</td></tr>
<tr><th>Availability</th><td>Not sure</td></tr>
<tr><th>General options supported</th><td>`quality`</td></tr>
<tr><th>Extra options</th><td>`use-nice` (boolean)</td></tr>
</table>
This converter tryes to execute `convert source.jpg webp:destination.jpg.webp`.
## stack
<table>
<tr><th>General options supported</th><td>all (passed to the converters in the stack )</td></tr>
<tr><th>Extra options</th><td>`converters` (array) and `converter-options` (array)</td></tr>
</table>
Stack implements the functionality you know from `WebPConvert::convert`. In fact, all `WebPConvert::convert` does is to call `Stack::convert($source, $destination, $options, $logger);`
It has two special options: `converters` and `converter-options`. You can read about those in `docs/api/convert.md`

View File

@ -0,0 +1,167 @@
# API: The WebPConvert::convertAndServe() method
*NOTE:* In 2.0, the method is renamed to *serveConverted* ("convertAndServe" was implying that a conversion was always made, but the method simply serves destination if it exists and is smaller and newer than source)
The method tries to serve a converted image. If destination already exists, the already converted image will be served. Unless the original is newer or smaller. If the method fails, it will serve original image, a 404, or whatever the 'fail' option is set to.
**WebPConvert::convertAndServe($source, $destination, $options)**
| Parameter | Type | Description |
| ---------------- | ------- | ------------------------------------------------------------------- |
| `$source` | String | Absolute path to source image (only forward slashes allowed) |
| `$destination` | String | Absolute path to converted image (only forward slashes allowed) |
| `$options` | Array | Array of options (see below) |
## The *$options* argument
The options argument is a named array. Besides the options described below, you can also use any options that the *convert* method takes (if a fresh convertion needs to be created, this method will call the *convert* method and hand over the options argument)
### *convert*
Conversion options, handed over to the convert method, in case a conversion needs to be made. The convert options are documented [here](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md).
### *fail*
Indicate what to do, in case of normal conversion failure.
Default value: *"original"*
| Possible values | Meaning |
| ----------------- | ----------------------------------------------- |
| "serve-original" | Serve the original image. |
| "404" | Serve 404 status (not found) |
| "report-as-image" | Serve an image with text explaining the problem |
| "report" | Serve a textual report explaining the problem |
### *fail-when-original-unavailable*
Possible values: Same as above, except that "original" is not an option.
Default value: *"404"*
### *show-report*
Produce a report rather than serve an image.
Default value: *false*
### *reconvert*
Force a conversion, discarding existing converted image (if any).
Default value: *false*
### *serve-original*
Forces serving original image. This will skip conversion.
Default value: *false*
### *add-x-header-status*
When set to *true*, a *X-WebP-Convert-Status* header will be added describing how things went.
Default value: *true*
Depending on how things goes, the header will be set to one of the following:
- "Failed (missing source argument)"
- "Failed (source not found)""
- "Failed (missing destination argument)"
- "Reporting..."
- "Serving original image (was explicitly told to)"
- "Serving original image - because it is smaller than the converted!"
- "Serving freshly converted image (the original had changed)"
- "Serving existing converted image"
- "Converting image (handed over to WebPConvertAndServe)"
- "Serving freshly converted image"
- "Failed (could not convert image)"
### *add-vary-header*
Add a "Vary: Accept" header when an image is served. Experimental.
Default value: *true*
### *add-content-type-header*
Add a "Content-Type" header
Default value: *true*
If set, a *Content-Type* header will be added. It will be set to "image/webp" if a converted image is served, "image/jpeg" or "image/png", if the original is served or "image/gif", if an error message is served (as image). You can set it to false when debugging (to check if any errors are being outputted)
### *add-last-modified-header*
Add a "Last-Modified" header
Default value: *true*
If set, a *Last-Modified* header will be added. When a cached image is served, it will be set to the modified time of the converted file. When a fresh image is served, it is set to current time.
### *cache-control-header*
Specify a cache control header, which will be served when caching is appropriate.
Default value: "public, max-age=86400" (1 day)
Caching is "deemed appropriate", when destination is served, source is served, because it is lighter or a fresh conversion is made, due to there not being any converted image at the destination yet. Caching is not deemed appropriate when something fails, a report is requested, or the *reconvert* option have been set. Note: in version 1.3.2 and below, the *serve-original* option also prevented caching, but it no longer does. previous In those cases, standard headers will be used for preventing caching.
For your convenience, here is a little table:
| duration | max-age |
| -------- | ---------------- |
| 1 second | max-age=1 |
| 1 minute | max-age=60 |
| 1 hour | max-age=3600 |
| 1 day | max-age=86400 |
| 1 week | max-age=604800 |
| 1 month | max-age=2592000 |
| 1 year | max-age=31536000 |
To learn about the options for the Cache-Control header, go [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
### *error-reporting*
Set error reporting
Allowed values: *"auto"*, *"dont-mess"*, *true*, *false*
Default value: *"auto"*
If set to true, error reporting will be turned on, like this:
```
error_reporting(E_ALL);
ini_set('display_errors', 'On');
```
If set to false, error reporting will be turned off, like this:
```
error_reporting(0);
ini_set('display_errors', 'Off');
```
If set to "auto", errors will be turned off, unless the `show-report` option is set, in which case errors will be turned off.
If set to "dont-mess", error reporting will not be touched.
### *aboutToServeImageCallBack*
This callback is called right before response headers and image is served. This is a great chance to adding headers. You can stop the image and the headers from being served by returning *false*.
**Arguments:**
The first argument to the callback contains a string that tells what is about to be served. It can be 'fresh-conversion', 'destination' or 'source'.
The second argument tells you why that is served. It can be one of the following:
for 'source':
- "explicitly-told-to" (when the "serve-original" option is set)
- "source-lighter" (when original image is actually smaller than the converted)
for 'fresh-conversion':
- "explicitly-told-to" (when the "reconvert" option is set)
- "source-modified" (when source is newer than existing)
- "no-existing" (when there is no existing at the destination)
for 'destination':
- "no-reason-not-to" (it is lighter than source, its not older, and we were not told to do otherwise)
Example of callback:
```
function aboutToServeImageCallBack($servingWhat, $whyServingThis, $obj)
{
echo 'about to serve: ' . $servingWhat . '<br>';
echo 'Why? - because: ' . $whyServingThis;
return false; // Do not serve! (this also prevents any response headers from being added)
}
```
### *aboutToPerformFailActionCallback*
This callback is called right before doing the action specified in the `fail` option, or the `fail-when-original-unavailable` option. You can stop the fail action from being executod by returning *false*.
Documentation by example:
```
function aboutToPerformFailActionCallback($errorTitle, $errorDescription, $actionAboutToBeTaken, $serveConvertedObj)
{
echo '<h1>' . $errorTitle . '</h1>';
echo $errorDescription;
if (actionAboutToBeTaken == '404') {
// handle 404 differently than webp-convert would
$protocol = isset($_SERVER["SERVER_PROTOCOL"]) ? $_SERVER["SERVER_PROTOCOL"] : 'HTTP/1.0';
$serveConvertedObj->header($protocol . " 404 Not Found. We take this very seriously. Heads will roll.");
return false; // stop webp-convert from doing what it would do
}
}
```
### *require-for-conversion*
If set, makes the library 'require in' a file just before doing an actual conversion with `ConvertAndServe::convertAndServe()`. This is not needed for composer projects, as composer takes care of autoloading classes when needed.
Default value: *null*

View File

@ -0,0 +1,167 @@
# Tweaks
## Store converted images in separate folder
In most cases, you probably want the cache of converted images to be stored in their own folder rather than have them mingled with the source files.
To have have the cache folder contain a file structure mirroring the structure of the original files, you can do this:
```php
$applicationRoot = $_SERVER["DOCUMENT_ROOT"]; // If your application is not in document root, you can change accordingly.
$imageRoot = $applicationRoot . '/webp-images'; // Change to where you want the webp images to be saved
$sourceRel = substr($source, strlen($applicationRoot));
$destination = $imageRoot . $sourceRel . '.webp';
```
If your images are stored outside document root (a rare case), you can simply use the complete absolute path:
```php
$destination = $imageRoot . $source . '.webp'; // pst: $source is an absolute path, and starts with '/'
```
This will ie store a converted image in */var/www/example.com/public_html/app/webp-images/var/www/example.com/images/logo.jpg.webp*
If your application can be configured to store outside document root, but rarely is, you can go for this structure:
```php
$docRoot = $_SERVER["DOCUMENT_ROOT"];
$imageRoot = $contentDirAbs . '/webp-images';
if (substr($source, 0, strlen($docRoot)) === $docRoot) {
// Source file is residing inside document root.
// We can store relative to that.
$sourceRel = substr($source, strlen($docRoot));
$destination = $imageRoot . '/doc-root' . $sourceRel . '.webp';
} else {
// Source file is residing outside document root.
// we must add complete path to structure
$destination = $imageRoot . '/abs' . $source . '.webp';
}
```
If you do not know the application root beforehand, and thus do not know the appropriate root for the converted images, see next tweak.
## Get the application root automatically
When you want destination files to be put in their own folder, you need to know the root of the application (the folder in which the .htaccess rules resides). In most applications, you know the root. In many cases, it is simply the document root. However, if you are writing an extension, plugin or module to a framework that can be installed in a subfolder, you may have trouble finding it. Many applications have a *index.php* in the root, which can get it with `__DIR__`. However, you do not want to run an entire bootstrap each time you serve an image. Obviously, to get around this, you can place *webp-on-demand.php* in the webroot. However, some frameworks, such as Wordpress, will not allow a plugin to put a file in the root. Now, how could we determine the application root from a file inside some subdir? Here are three suggestions:
1. You could traverse parent folders until you find a file you expect to be in application root (ie a .htaccess containing the string "webp-on-demand.php"). This should work.
2. If the rules in the *.htaccess* file are generated by your application, you probably have access to the path at generation time. You can then simply put the path in the *.htaccess*, as an extra parameter to the script (or better: the relative path from document root to the application).
3. You can use the following hack:
### The hack
The idea is to grab the URL path of the image in the *.htaccess* and pass it to the script. Assuming that the URL paths always matches the file paths, we can get the application root by subtracting that relative path to source from the absolute path to source.
In *.htaccess*, we grab the url-path by appending "&url-path=$1.$2" to the rewrite rule:
```
RewriteRule ^(.*)\.(jpe?g|png)$ webp-on-demand.php?source=%{SCRIPT_FILENAME}&url-path=$1.$2 [NC,L]
```
In the script, we can then calculate the application root like this:
```php
$applicationRoot = substr($_GET['source'], 0, -strlen($_GET['url-path']));
```
## CDN
To work properly with a CDN, a "Vary Accept" header should be added when serving images. This is a declaration that the response varies with the *Accept* header (recall that we inspect *Accept* header in the .htaccess to determine if the browsers supports webp images). If this header is missing, the CDN will see no reason to cache separate images depending on the Accept header.
Add this snippet to the *.htaccess* to make webp-on-demand work with CDN's:
```
<IfModule mod_headers.c>
SetEnvIf Request_URI "\.(jpe?g|png)" ADDVARY
# Declare that the response varies depending on the accept header.
# The purpose is to make CDN cache both original images and converted images.
Header append "Vary" "Accept" env=ADDVARY
</IfModule>
```
***Note:*** When configuring the CDN, you must make sure to set it up to forward the the "Accept" header to your origin server.
## Make .htaccess route directly to existing images
There may be a performance benefit of using the *.htaccess* file to route to already converted images, instead of letting the PHP script serve it. Note however:
- If you do the routing in .htaccess, the solution will not be able to discard converted images when original images are updated.
- Performance benefit may be insignificant (*WebPConvertAndServe* class is not autoloaded when serving existing images)
Add the following to the *.htaccess* to make it route to existing converted images. Place it above the # Redirect images to webp-on-demand.php" comment. Take care of replacing [[your-base-path]] with the directory your *.htaccess* lives in (relative to document root, and [[your-destination-root]] with the directory the converted images resides.
```
# Redirect to existing converted image (under appropriate circumstances)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/[[your-base-path]]/[[your-destination-root]]/$1.$2.webp -f
RewriteRule ^\/?(.*)\.(jpe?g|png)$ /[[your-base-path]]/[[your-destination-root]]/$1.$2.webp [NC,T=image/webp,L]
```
*edit:* Removed the QSD flag from the RewriteRule because it is not supported in Apache < 2.4 (and it [triggers error](https://github.com/rosell-dk/webp-express/issues/155))
### Redirect with CDN support
If you are using a CDN, and want to redirect to existing images with the .htaccess, it is a good idea to add a "Vary Accept" header. This instructs the CDN that the response varies with the *Accept* header (we do not need to do that when routing to webp-on-demand.php, because the script takes care of adding this header, when appropriate.)
You can achieve redirect with CDN support with the following rules:
```
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect to existing converted image (under appropriate circumstances)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/[[your-base-path]]/[[your-destination-root]]/$1.$2.webp -f
RewriteRule ^\/?(.*)\.(jpe?g|png)$ /[[your-base-path]]/[[your-destination-root]]/$1.$2.webp [NC,T=image/webp,QSD,E=WEBPACCEPT:1,L]
# Redirect images to webp-on-demand.php (if browser supports webp)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteRule ^(.*)\.(jpe?g|png)$ webp-on-demand.php?source=%{SCRIPT_FILENAME}&url-path=$1.$2 [NC,L]
</IfModule>
<IfModule mod_headers.c>
# Apache appends "REDIRECT_" in front of the environment variables, but LiteSpeed does not.
# These next line is for Apache, in order to set environment variables without "REDIRECT_"
SetEnvIf REDIRECT_WEBPACCEPT 1 WEBPACCEPT=1
# Make CDN caching possible.
# The effect is that the CDN will cache both the webp image and the jpeg/png image and return the proper
# image to the proper clients (for this to work, make sure to set up CDN to forward the "Accept" header)
Header append Vary Accept env=WEBPACCEPT
</IfModule>
AddType image/webp .webp
```
## Forward the querystring
By forwarding the query string, you can allow control directly from the URL. You could for example make it possible to add "?debug" to an image URL, and thereby getting a conversion report. Or make "?reconvert" force reconversion.
In order to forward the query string, you need to add this condition before the RewriteRule that redirects to *webp-on-demand.php*:
```
RewriteCond %{QUERY_STRING} (.*)
```
That condition will always be met. The side effect is that it stores the match (the complete querystring). That match will be available as %1 in the RewriteRule. So, in the RewriteRule, we will have to add "&%1" after the last argument. Here is a complete solution:
```
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect images to webp-on-demand.php (if browser supports webp)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{QUERY_STRING} (.*)
RewriteRule ^(.*)\.(jpe?g|png)$ webp-on-demand.php?source=%{SCRIPT_FILENAME}&%1 [NC,L]
</IfModule>
AddType image/webp .webp
```
Of course, in order to *do* something with that querystring, you must use them in your *webp-on-demand.php* script. You could for example use them directly in the options array sent to the *convertAndServe()* method. To achieve the mentioned "debug" and "reconvert" features, do this:
```php
$options = [
'show-report' => isset($_GET['debug']),
'reconvert' => isset($_GET['reconvert']),
'serve-original' => isset($_GET['original']),
];
```
*EDIT:*
I have just discovered a simpler way to achieve the querystring forward: The [QSA flag](https://httpd.apache.org/docs/trunk/rewrite/flags.html).
So, simply set the QSA flag in the RewriteRule, and nothing more:
```
RewriteRule ^(.*)\.(jpe?g|png)$ webp-on-demand.php?source=%{SCRIPT_FILENAME} [NC,QSA,L]
```

View File

@ -0,0 +1,133 @@
# WebP on demand
This is a solution for automatically serving WebP images instead of jpeg/pngs [for browsers that supports WebP](https://caniuse.com/#feat=webp) (At the time of writing, 78% of all mobile users and 72% of all desktop users uses browsers supporting webp)
Once set up, it will automatically convert images, no matter how they are referenced. It for example also works on images referenced in CSS. As the solution does not require any change in the HTML, it can easily be integrated into any website / framework
## Overview
A setup consists of a PHP script that serves converted images and some *redirect rules* that redirects JPG/PNG images to the script.
## Requirements
* *Apache* or *LiteSpeed* web server. Can be made to work with *NGINX* as well. Documentation is on the roadmap.
* *mod_rewrite* module for Apache
* PHP >= 5.6 (we are only testing down to 5.6. It should however work in 5.5 as well)
* That one of the *webp-convert* converters are working (these have different requirements)
## Installation
Here we assume you are using Composer. [Not using composer? - Follow me!](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/webp-on-demand/without-composer.md)
### 1. Require the webp-convert library with composer
```
composer require rosell-dk/webp-convert
```
### 2. Create the script
Create a file *webp-on-demand.php*, and place it in webroot, or where-ever you like in you web-application.
Here is a minimal example to get started with:
```php
<?php
require 'vendor/autoload.php'; // Make sure to point this correctly
use WebPConvert\WebPConvert;
$source = $_GET['source']; // Absolute file path to source file. Comes from the .htaccess
$destination = $source . '.webp'; // Store the converted images besides the original images (other options are available!)
$options = [
// UNCOMMENT NEXT LINE, WHEN YOU ARE UP AND RUNNING!
'show-report' => true // Show a conversion report instead of serving the converted image.
// More options available!
];
WebPConvert::convertAndServe($source, $destination, $options);
```
### 3. Add redirect rules
Place the following rewrite rules in a *.htaccess* file in the directory where you want the solution to take effect:
```
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect images to webp-on-demand.php (if browser supports webp)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)\.(jpe?g|png)$ webp-on-demand.php?source=%{SCRIPT_FILENAME} [NC,L]
</IfModule>
AddType image/webp .webp
```
If you have placed *webp-on-demand.php* in a subfolder, you will need to change the rewrite rule accordingly.
The `RewriteCond %{REQUEST_FILENAME} -f` is not strictly necessary, but there to be sure that we got an existing file, and it could perhaps also prevent some undiscovered way of misuse.
### 4. Validate that it works
Browse to a JPEG image. Instead of an image, you should see a conversion report. Hopefully, you get a success. Otherwise, you need to hook up to a cloud converter or try to meet the requirements for cwebp, gd or imagick.
Once you get a successful conversion, you can uncomment the "show-report" option in the script.
It should work now, but to be absolute sure:
- Visit a page on your site with an image on it, using *Google Chrome*.
- Right-click the page and choose "Inspect"
- Click the "Network" tab
- Reload the page
- Find a jpeg or png image in the list. In the "type" column, it should say "webp". There should also be a *X-WebP-Convert-Status* header on the image that provides some insights on how things went.
### 5. Try this improvement and see if it works
It seems that it is not necessary to pass the filename in the query string.
Try replacing `$source = $_GET['source'];` in the script with the following:
```php
$docRoot = rtrim($_SERVER["DOCUMENT_ROOT"], '/');
$requestUriNoQS = explode('?', $_SERVER['REQUEST_URI'])[0];
$source = $docRoot . urldecode($requestUriNoQS);
```
And you can then remove `?source=%{SCRIPT_FILENAME}` from the `.htaccess` file.
There are some benefits of not passing in query string:
1. Passing a path in the query string may be blocked by a firewall, as it looks suspicious.
2. The script called to convert arbitrary files
3. One person experienced problems with spaces in filenames passed in the query string. See [this issue](https://github.com/rosell-dk/webp-convert/issues/95)
### 6. Customizing and tweaking
Basic customizing is done by setting options in the `$options` array. Check out the [docs on convert()](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/converting/convert.md) and the [docs on convertAndServe()](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/serving/convert-and-serve.md)
Other tweaking is described in *docs/webp-on-demand/tweaks.md*:
- [Store converted images in separate folder](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/webp-on-demand/tweaks.md#store-converted-images-in-separate-folder)
- [CDN](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/webp-on-demand/tweaks.md#cdn)
- [Make .htaccess route directly to existing images](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/webp-on-demand/tweaks.md#make-htaccess-route-directly-to-existing-images)
- [Forward the query string](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/webp-on-demand/tweaks.md#forward-the-querystring)
## Troubleshooting
### The redirect rule doesn't seem to be working
If images are neither routed to the converter or a 404, it means that the redirect rule isn't taking effect. Common reasons for this includes:
- Perhaps there are other rules in your *.htaccess* that interfere with the rules?
- Perhaps your site is on *Apache*, but it has been configured to use *Nginx* to serve image files. To find out which server that is handling the images, browse to an image and eximine the "Server" response header. In case *NGINX* are serving images, see if you can reconfigure your server setup. Alternatively, you can create *NGINX* rewrite rules. There are some [here](https://github.com/S1SYPHOS/kirby-webp#nginx) and [there](https://github.com/uhop/grunt-tight-sprite/wiki/Recipe:-serve-WebP-with-nginx-conditionally).
- Perhaps the server isn't configured to allow *.htaccess* files? Try inserting rubbish in the top of the *.htaccess* file and refresh. You should now see an *Internal Server Error* error page. If you don't, your *.htaccess* file is ignored. Probably you will need to set *AllowOverride All* in your Virtual Host. [Look here for more help](
https://docs.bolt.cm/3.4/howto/making-sure-htaccess-works#test-if-htaccess-is-working)
- Perhaps the Apache *mod_rewrite* extension isn't enabled? Try removing both `<IfModule mod_rewrite.c>` and `</IfModule>` lines: if you get an *Internal Server Error* error page after this change, it's probably that it's indeed not enabled.
## Related
* https://www.maxcdn.com/blog/how-to-reduce-image-size-with-webp-automagically/
* https://www.digitalocean.com/community/tutorials/how-to-create-and-serve-webp-images-to-speed-up-your-website

View File

@ -0,0 +1,45 @@
# WebP On Demand without composer
For your convenience, the library has been cooked down to two files: *webp-on-demand-1.inc* and *webp-on-demand-2.inc*. The second one is loaded when the first one decides it needs to do a conversion (and not simply serve existing image).
## Installing
### 1. Copy the latest build files into your website
Copy *webp-on-demand-1.inc* and *webp-on-demand-2.inc* from the *build* folder into your website (in 2.0, they are located in "src-build"). They can be located wherever you like.
### 2. Create a *webp-on-demand.php*
Create a file *webp-on-demand.php*, and place it in webroot, or where-ever you like in you web-application.
Here is a minimal example to get started with. Note that this example only works in version 1.x. In 2.0, the `require-for-conversion` option has been removed, so the [procedure is different](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/webp-on-demand/without-composer.md).
```php
<?php
// To start with, lets display any errors.
// You can later comment these out
error_reporting(E_ALL);
ini_set("display_errors", 1);
require 'webp-on-demand-1.inc';
use WebPConvert\WebPConvert;
$source = $_GET['source']; // Absolute file path to source file. Comes from the .htaccess
$destination = $source . '.webp'; // Store the converted images besides the original images (other options are available!)
$options = [
// Tell where to find the webp-convert-and-serve library, which will
// be dynamically loaded, if need be.
'require-for-conversion' => 'webp-on-demand-2.inc',
// UNCOMMENT NEXT LINE, WHEN YOU ARE UP AND RUNNING!
'show-report' => true // Show a conversion report instead of serving the converted image.
// More options available!
];
WebPConvert::convertAndServe($source, $destination, $options);
```
### 3. Continue the main install instructions from step 3
[Click here to continue...](https://github.com/rosell-dk/webp-on-demand#3-add-redirect-rules)

Some files were not shown because too many files have changed in this diff Show More