Add X13 WebP module for image conversion to next-generation formats

- Implemented the X13Webp class with core functionalities for converting images to WebP format.
- Added support for different PHP versions and defined constants for versioning.
- Included translation strings for various user interface elements and messages.
- Created XML file for module versioning.
This commit is contained in:
2025-09-12 00:41:29 +02:00
parent fa0f4b590b
commit 9003eede2d
247 changed files with 55597 additions and 1 deletions

View File

@@ -77,6 +77,25 @@
"lmtime": 0,
"modified": false
},
"export-csv.php": {
"type": "-",
"size": 12387,
"lmtime": 0,
"modified": false
},
"export_images": {},
"export.php": {
"type": "-",
"size": 2442,
"lmtime": 0,
"modified": false
},
"export_products.csv": {
"type": "-",
"size": 8799634,
"lmtime": 0,
"modified": false
},
"files": {},
".gitignore": {
"type": "-",
@@ -98,7 +117,7 @@
},
"google-merchant_id-1.xml": {
"type": "-",
"size": 18748057,
"size": 18717429,
"lmtime": 0,
"modified": true
},

View File

@@ -0,0 +1,5 @@
/* This stylesheet should be used to add your custom styles to the back-office without using the Sass sources. It will be loaded after all the default styles.
You should NOT edit any other exisiting back-office CSS file manually: they are generated by the Sass preprocessor: http://www.sass-lang.com/ . */
.alert-warning:contains("WebP - konwersja zdjęć") {
display: none !important;
}

View File

@@ -0,0 +1,174 @@
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
import refreshNotifications from '@js/notifications.js';
const $ = window.$;
export default class Header {
constructor() {
$(() => {
this.initQuickAccess();
this.initMultiStores();
this.initNotificationsToggle();
this.initSearch();
this.initContentDivOffset();
refreshNotifications();
});
}
initQuickAccess() {
$('.js-quick-link').on('click', (e) => {
e.preventDefault();
let method = $(e.target).data('method');
let name = null;
if (method === 'add') {
let text = $(e.target).data('prompt-text');
let link = $(e.target).data('link');
name = prompt(text, link);
}
if (method === 'add' && name || method === 'remove') {
let postLink = $(e.target).data('post-link');
let quickLinkId = $(e.target).data('quicklink-id');
let rand = $(e.target).data('rand');
let url = $(e.target).data('url');
let icon = $(e.target).data('icon');
$.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
async: true,
url: `${postLink}&action=GetUrl&rand=${rand}&ajax=1&method=${method}&id_quick_access=${quickLinkId}`,
data: {
"url": url,
"name": name,
"icon": icon
},
dataType: "json",
success: (data) => {
var quicklink_list = '';
$.each(data, (index) => {
if (typeof data[index]['name'] !== 'undefined')
quicklink_list += '<li><a href="' + data[index]['link'] + '"><i class="icon-chevron-right"></i> ' + data[index]['name'] + '</a></li>';
});
if (typeof data['has_errors'] !== 'undefined' && data['has_errors'])
$.each(data, (index) => {
if (typeof data[index] === 'string')
$.growl.error({
title: '',
message: data[index]
});
});
else if (quicklink_list) {
$('#header_quick ul.dropdown-menu .divider').prevAll().remove();
$('#header_quick ul.dropdown-menu').prepend(quicklink_list);
$(e.target).remove();
window.showSuccessMessage(window.update_success_msg);
}
}
});
}
});
}
initMultiStores() {
$('.js-link').on('click', (e) => {
window.open($(e.target).parents('.link').attr('href'), '_blank');
});
}
initNotificationsToggle() {
$('.notification.dropdown-toggle').on('click', () => {
if(!$('.mobile-nav').hasClass('expanded')) {
this.updateEmployeeNotifications();
}
});
$('body').on('click', function (e) {
if (!$('div.notification-center.dropdown').is(e.target)
&& $('div.notification-center.dropdown').has(e.target).length === 0
&& $('.open').has(e.target).length === 0
) {
if ($('div.notification-center.dropdown').hasClass('open')) {
$('.mobile-layer').removeClass('expanded');
refreshNotifications();
}
}
});
$('.notification-center .nav-link').on('shown.bs.tab', () => {
this.updateEmployeeNotifications();
});
}
initSearch() {
$('.js-items-list').on('click', (e) => {
$('.js-form-search').attr('placeholder', $(e.target).data('placeholder'));
$('.js-search-type').val($(e.target).data('value'));
$('.js-dropdown-toggle').text($(e.target).data('item'));
});
}
updateEmployeeNotifications() {
$.post(
admin_notification_push_link,
{
"type": $('.notification-center .nav-link.active').attr('data-type')
}
);
}
/**
* Updates the offset of the content div in whenever the header changes size
*/
initContentDivOffset() {
const onToolbarResize = function() {
const toolbar = $('.header-toolbar').last();
const header = $('.main-header');
const content = $('.content-div');
const spacing = 15;
if (toolbar.length && header.length && content.length) {
content.css('padding-top', toolbar.outerHeight() + header.outerHeight() + spacing);
}
};
// update the offset now
onToolbarResize();
// update when resizing the window
$(window).resize(onToolbarResize);
// update when replacing the header with a vue header
$(document).on('vueHeaderMounted', onToolbarResize);
}
}

View File

@@ -0,0 +1,70 @@
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
const $ = global.$;
// Dependencies
import 'prestakit/dist/js/prestashop-ui-kit';
import 'jquery-ui-dist/jquery-ui';
import 'bootstrap-tokenfield';
import 'eonasdan-bootstrap-datetimepicker';
import 'jwerty';
import 'magnific-popup';
import 'dropzone';
import 'typeahead.js/dist/typeahead.jquery';
import 'typeahead.js/dist/bloodhound.min';
import 'sprintf-js';
// Plugins CSS
import 'dropzone/dist/min/dropzone.min.css';
import 'magnific-popup/dist/magnific-popup.css';
// Theme SCSS
import '@scss/theme.scss';
// Theme Javascript
window.Dropzone.autoDiscover = false;
import NavBar from '@js/nav_bar';
// this needs to be ported into the UI kit
import '@js/clickable-dropdown';
import '@js/maintenance-page';
import '@js/translation-page/index';
import Header from '@js/header';
new NavBar();
new Header();
import initDatePickers from '@js/app/utils/datepicker';
import initInvalidFields from '@js/app/utils/fields';
import initEmailFields from '@js/app/utils/email-idn';
$(() => {
initDatePickers();
initInvalidFields();
initEmailFields('input[type="email"]');
});

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,100 @@
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
// if (!defined('_PS_ADMIN_DIR_'))
// define('_PS_ADMIN_DIR_', getcwd());
// include(_PS_ADMIN_DIR_ . '/../config/config.inc.php');
// /* Getting cookie or logout */
// require_once(_PS_ADMIN_DIR_ . '/init.php');
include(dirname(__FILE__) . '/../../config/config.inc.php');
/* Check security token */
if (!Tools::isPHPCLI()) {
include(dirname(__FILE__) . '/../../init.php');
}
$query = Tools::getValue('q', false);
if (!$query or $query == '' or strlen($query) < 1) {
die();
}
$module = Module::getInstanceByName('x13webp');
if(!$module){
die();
} else if(Tools::getValue('token') != $module->getProductsAjaxToken()){
die('Bad token');
}
if ($pos = strpos($query, ' (ref:')) {
$query = substr($query, 0, $pos);
}
$excludeIds = Tools::getValue('excludeIds', false);
if ($excludeIds && $excludeIds != 'NaN'){
$excludeIds = implode(',', array_map('intval', explode(',', $excludeIds)));
} else{
$excludeIds = '';
}
$excludeVirtuals = (bool)Tools::getValue('excludeVirtuals', false);
$exclude_packs = (bool)Tools::getValue('exclude_packs', false);
$limit = Tools::getValue('limit', false);
$sql = 'SELECT p.`id_product`, pl.`link_rewrite`, p.`reference`, pl.`name`, MAX(image_shop.`id_image`) id_image, il.`legend`, p.`cache_default_attribute`
FROM `' . _DB_PREFIX_ . 'product` p
' . Shop::addSqlAssociation('product', 'p') . '
LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (pl.id_product = p.id_product AND pl.id_lang = ' . (int)Context::getContext()->language->id . Shop::addSqlRestrictionOnLang('pl') . ')
LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product`)' .
Shop::addSqlAssociation('image', 'i', false, 'image_shop.cover=1') . '
LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int)Context::getContext()->language->id . ')
WHERE (pl.name LIKE \'%' . pSQL($query) . '%\' OR p.reference LIKE \'%' . pSQL($query) . '%\')' .
(!empty($excludeIds) ? ' AND p.id_product NOT IN (' . $excludeIds . ') ' : ' ') .
($excludeVirtuals ? 'AND p.id_product NOT IN (SELECT pd.id_product FROM `' . _DB_PREFIX_ . 'product_download` pd WHERE (pd.id_product = p.id_product))' : '') .
($exclude_packs ? 'AND (p.cache_is_pack IS NULL OR p.cache_is_pack = 0)' : '') .
' GROUP BY p.id_product' .
($limit ? ' LIMIT ' . (int)$limit : '');
$items = Db::getInstance()->executeS($sql);
if ($items) {
// packs
$results = array();
foreach ($items as $item) {
$product = array(
'id' => (int)($item['id_product']),
'name' => $item['name'],
'ref' => (!empty($item['reference']) ? $item['reference'] : ''),
'image' => str_replace('http://', Tools::getShopProtocol(), Context::getContext()->link->getImageLink($item['link_rewrite'], $item['id_image'], 'home_default')),
);
array_push($results, $product);
}
$results = array_values($results);
echo json_encode($results);
} else {
json_encode(new stdClass);
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>x13webp</name>
<displayName><![CDATA[WebP - konwersja zdjęć do formatu nowej generacji]]></displayName>
<version><![CDATA[1.1.0]]></version>
<description><![CDATA[Zaawansowany moduł umożliwiający szybką konwersję zdjęć do formatu nowej generacji zdjęć. Moduł umożliwia konwersję wszystkich zdjęć ze sklepu do formatu WebP za pomocą AJAXA, zadań CRON oraz generowania zdjęć w locie.]]></description>
<author><![CDATA[X13.pl]]></author>
<tab><![CDATA[front_office_features]]></tab>
<confirmUninstall><![CDATA[Przed odinstalowaniem modułu, upewnij się że wszystkie zdjęcia WebP zostały usunięte]]></confirmUninstall>
<is_configurable>1</is_configurable>
<need_instance>0</need_instance>
<limited_countries></limited_countries>
</module>

View File

@@ -0,0 +1,758 @@
<?php
use X13Webp\Core\Configurator\ConfiguratorBase;
$translations_name = 'form';
$fields_form = array();
$ssl = false;
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") {
// jeśli weszliśmy z https (nawet jeśli sklep nie ma włączonego SSL)
$ssl = true;
}
$shop = Context::getContext()->shop;
$base = ($ssl ? 'https://' . $shop->domain_ssl : 'http://' . $shop->domain);
$search_products_url = $base . __PS_BASE_URI__ . 'modules/' . $this->name . '/ajax_products_list.php?token=' . $this->getProductsAjaxToken();
$convert_image_url = $this->context->link->getAdminLink('AdminX13WebpConverter'). '&ajax=1&action=convertImage';
$product_image_url = $this->context->link->getAdminLink('AdminX13WebpConverter'). '&ajax=1&action=getProductImage';
if($ssl){
$convert_image_url = str_replace('http://', 'https://', $convert_image_url);
$product_image_url = str_replace('http://', 'https://', $product_image_url);
}
$fields_form[] = array(
'form' => array(
'legend' => array(
'title' => static::getTranslationByKey('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'type' => 'switch',
'label' => $this->l('Enable support for WebP', $translations_name),
'name' => $this->options_prefix . 'WEBP_SUPPORT_ENABLE',
'values' => array(
array(
'id' => 'WEBP_SUPPORT_ENABLE_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'WEBP_SUPPORT_ENABLE_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 1
),
array(
'type' => 'switch',
'label' => $this->l('Enable WebP for new products categories etc.', $translations_name),
'name' => $this->options_prefix . 'WEBP_AUTO_GENERATOR_ENABLE',
'values' => array(
array(
'id' => 'webp_auto_generator_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'webp_auto_generator_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 1
),
array(
'type' => 'select',
'label' => $this->l('Operation mode', $translations_name),
'name' => $this->options_prefix . 'OPERATION_MODE',
'validation' => 'isAnything',
'options' => array(
'query' => array(
array(
'id' => 1,
'name' => $this->l('Generates all missing WebP images the first time a page is loaded', $translations_name),
),
array(
'id' => 2,
'name' => $this->l('Use only the generated images', $translations_name),
)
),
'id' => 'id',
'name' => 'name',
),
'default' => 1,
),
array(
'type' => 'checkbox',
'label' => $this->l('Items allowed to generate', $translations_name),
'name' => $this->options_prefix . 'ALLOWED_GENERATED_IMAGES[]',
'default' => array('products', 'categories', 'manufacturers', 'suppliers', 'stores', 'cms', 'modules', 'theme', 'logo', 'others'),
'required' => false,
'values' => array(
'query' => $this->x13helper->getImageTypes(),
'value_field' => 'val',
'id' => 'val',
'name' => 'name',
),
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'OPERATION_MODE' => 2,
)
),
'callback' => 'saveAsJson',
),
array(
'type' => 'html',
'name' => 'generated_info',
'html_content' => '
<p class="alert alert-info">' . $this->l('We recommend that you generate the images for the first time using the following ', $translations_name) . '
<a href="#conversion-fieldset" class="scrollto"><b>'.$this->l('generating by AJAX', $translations_name).'</b></a>
</p>
',
'ignore' => true,
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'OPERATION_MODE' => 2,
)
),
),
array(
'type' => 'html',
'name' => 'separator_compression_settings',
'html_content' => '<h4 style="font-size:18px;">' . $this->l('Compression settings', $translations_name) . '</h4>',
'ignore' => true,
),
array(
'type' => 'radio',
'label' => $this->l('WebP coversion type', $translations_name),
'name' => $this->options_prefix . 'CONVERSION_TYPE',
'default' => 'cwebp',
'values' => $this->getConversionTypes(),
'form_group_class' => 'conversion-types'
),
array(
'type' => 'text',
'label' => $this->l('EWW - api key', $translations_name),
'name' => $this->options_prefix . 'EWW_API_KEY',
'validate' => 'isAnything',
'default' => '',
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'ewww',
)
),
),
array(
'type' => 'text',
'label' => $this->l('WPC - api key', $translations_name),
'name' => $this->options_prefix . 'WPC_API_KEY',
'validate' => 'isAnything',
'default' => '',
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'wpc',
)
),
),
array(
'type' => 'text',
'label' => $this->l('WPC - secret', $translations_name),
'name' => $this->options_prefix . 'WPC_SECRET',
'validate' => 'isAnything',
'default' => '',
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'wpc',
)
),
),
array(
'type' => 'text',
'label' => $this->l('WPC - api url', $translations_name),
'name' => $this->options_prefix . 'WPC_API_URL',
'validate' => 'isAnything',
'default' => '',
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'wpc',
)
),
),
array(
'type' => 'radio',
'label' => $this->l('WPC - api version', $translations_name),
'name' => $this->options_prefix . 'WPC_API_VERSION',
'default' => 2,
'validate' => 'isInt',
'values' => array(
array(
'id' => 0,
'value' => 0,
'label' => 0
),
array(
'id' => 1,
'value' => 1,
'label' => 1
),
array(
'id' => 2,
'value' => 2,
'label' => 2
),
),
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'wpc',
)
)
),
array(
'type' => 'switch',
'label' => $this->l('WPC - crypt api key in transfer', $translations_name),
'name' => $this->options_prefix . 'WPC_CRYPT_API_KEY_IN_TRANSFER',
'values' => array(
array(
'id' => 'wpc_crypt_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'wpc_crypt_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 0,
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'wpc',
)
)
),
array(
'type' => 'select',
'label' => $this->l('Encoding', $translations_name),
'name' => $this->options_prefix . 'ENCODING',
'validation' => 'isAnything',
'options' => array(
'query' => array(
array(
'val' => 'auto',
'name' => $this->l('Auto', $translations_name),
),
array(
'val' => 'lossless',
'name' => $this->l('Lossless', $translations_name),
),
array(
'val' => 'lossy',
'name' => $this->l('Lossy', $translations_name),
)
),
'id' => 'val',
'name' => 'name',
),
'default' => 'auto',
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueNotEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'gd',
)
),
),
array(
'type' => 'rangeSlider',
'label' => $this->l('Image quality (%)', $translations_name),
'name' => $this->options_prefix . 'IMAGE_QUALITY',
'default' => 90,
'validate' => 'isInt',
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueNotEqualTo,
array(
$this->options_prefix . 'ENCODING' => 'lossless',
)
). ' force-shown-gd'
),
array(
'type' => 'switch',
'label' => $this->l('Auto limit', $translations_name),
'name' => $this->options_prefix . 'AUTO_LIMIT',
'values' => array(
array(
'id' => 'auto_limit_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'auto_limit_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 1,
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueNotEqualTo,
array(
$this->options_prefix . 'ENCODING' => 'lossless',
)
),
),
array(
'type' => 'rangeSlider',
'label' => $this->l('Alpha quality (%)', $translations_name),
'name' => $this->options_prefix . 'ALPHA_QUALITY',
'default' => 85,
'validate' => 'isInt',
'desc' => $this->l('It doesn\'t support jpeg images', $translations_name),
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueNotEqualTo,
array(
$this->options_prefix . 'ENCODING' => 'lossless',
$this->options_prefix . 'CONVERSION_TYPE' => 'gd',
)
)
),
array(
'type' => 'rangeSlider',
'label' => $this->l('Near lossless', $translations_name),
'name' => $this->options_prefix . 'NEAR_LOSSLESS',
'default' => 60,
'validate' => 'isInt',
'desc' => $this->l('The level of near-lossless image preprocessing', $translations_name),
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueNotEqualTo,
array(
$this->options_prefix . 'ENCODING' => 'lossy',
$this->options_prefix . 'CONVERSION_TYPE' => 'gd',
)
)
),
array(
'type' => 'radio',
'label' => $this->l('Migrate meta data of selected products', $translations_name),
'name' => $this->options_prefix . 'METADATA',
'default' => 'none',
'values' => array(
array(
'id' => 1,
'value' => 'none',
'label' => $this->l('None', $translations_name),
),
array(
'id' => 2,
'value' => 'all',
'label' => $this->l('All', $translations_name),
),
array(
'id' => 3,
'value' => 'exif',
'label' => $this->l('EXIF', $translations_name),
),
array(
'id' => 4,
'value' => 'icc',
'label' => $this->l('ICC', $translations_name),
),
array(
'id' => 5,
'value' => 'xmp',
'label' => $this->l('XMP', $translations_name),
),
),
'desc' => $this->l('The option depends on the selected type of photo conversion. The cwebp library works with any of the options, GD does not transfer any data, the other libraries can transfer the selected data', $translations_name),
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueNotEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'gd',
)
),
),
array(
'type' => 'radio',
'label' => $this->l('Method', $translations_name),
'name' => $this->options_prefix . 'METHOD',
'default' => 6,
'values' => array(
array(
'id' => 0,
'value' => 0,
'label' => $this->l('0 (top performance)', $translations_name),
),
array(
'id' => 1,
'value' => 1,
'label' => $this->l('1 (good performance)', $translations_name),
),
array(
'id' => 2,
'value' => 2,
'label' => $this->l('2 (decent performance with better quality)', $translations_name),
),
array(
'id' => 3,
'value' => 3,
'label' => $this->l('3 (quality equal to performance)', $translations_name),
),
array(
'id' => 4,
'value' => 4,
'label' => $this->l('4 (decent quality with better performance)', $translations_name),
),
array(
'id' => 5,
'value' => 5,
'label' => $this->l('5 (good quality)', $translations_name),
),
array(
'id' => 6,
'value' => 6,
'label' => $this->l('6 (top quality)', $translations_name),
),
),
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueNotEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'gd',
)
),
),
array(
'type' => 'switch',
'label' => $this->l('Sharp YUV', $translations_name),
'name' => $this->options_prefix . 'SHARP_YUV',
'values' => array(
array(
'id' => 'sharp_yuv_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'sharp_yuv_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 1,
'desc' => $this->l('Use more accurate and sharper RGB->YUV conversion if needed. Note that this process is slower than the default \'fast\' RGB->YUV conversion.', $translations_name).'<br/>'.
'https://www.ctrl.blog/entry/webp-sharp-yuv.html',
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueNotEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'gd',
)
)
),
array(
'type' => 'switch',
'label' => $this->l('Auto filter', $translations_name),
'name' => $this->options_prefix . 'AUTO_FILTER',
'values' => array(
array(
'id' => 'auto_filter_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'auto_filter_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 0,
'desc' => $this->l('This algorithm will spend additional time optimizing the filtering strength to reach a well-balanced quality.', $translations_name)
),
array(
'type' => 'switch',
'label' => $this->l('Low memory', $translations_name),
'name' => $this->options_prefix . 'LOW_MEMORY',
'values' => array(
array(
'id' => 'low_memory_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'low_memory_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 0,
'desc' => $this->l('Reduce memory usage of lossy encoding by saving four times the compressed size (typically). This will make the encoding slower and the output slightly different in size and distortion.', $translations_name),
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueNotEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'gd',
)
),
),
array(
'type' => 'text',
'label' => $this->l('Command', $translations_name),
'name' => $this->options_prefix . 'COMMAND',
'validate' => 'isAnything',
'default' => '',
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'cwebp',
)
),
'desc' => $this->l('You can add additional parameters when using the command line for the cwebp library.', $translations_name),
),
array(
'type' => 'switch',
'label' => $this->l('Try common system paths', $translations_name),
'name' => $this->options_prefix . 'TRY_COMMON_SYSTEM_PATHS',
'values' => array(
array(
'id' => 'tcsp_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'tcsp_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 0,
'desc' => $this->l('If the cwebP library is available on the server, but you have an error generating the pictures. The module will try to substitute the most popular paths to the library.', $translations_name),
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'cwebp',
)
),
),
array(
'type' => 'switch',
'label' => $this->l('Generate picture with nice (for cron jobs)', $translations_name),
'name' => $this->options_prefix . 'USE_NICE',
'values' => array(
array(
'id' => 'use_nice_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'use_nice_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 0,
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'CONVERSION_TYPE' => 'cwebp',
$this->options_prefix . 'CONVERSION_TYPE' => 'graphicsmagick',
$this->options_prefix . 'CONVERSION_TYPE' => 'imagemagick',
)
),
),
array(
'type' => 'html',
'name' => 'separator_test_compression',
'html_content' => '<h4 style="font-size:18px;">' . $this->l('Test compression', $translations_name) . '</h4>',
'ignore' => true,
),
array(
'type' => 'converTest',
'name' => 'webpConverterTest',
'label' => '',
'template' => 'module:'.$this->name.'/views/templates/admin/conversion_test.tpl',
'vars' => array(
'search_products_url' => $search_products_url,
'convert_image_url' => $convert_image_url,
'product_image_url' => $product_image_url,
'options_prefix' => $this->options_prefix
),
'ignore' => true,
),
array(
'type' => 'html',
'name' => 'separator_troubleshooting',
'html_content' => '<h4 style="font-size:18px;">' . $this->l('Troubleshooting', $translations_name) . '</h4>',
'ignore' => true,
),
array(
'type' => 'switch',
'label' => $this->l('Handle WebP support detection in the browser', $translations_name),
'name' => $this->options_prefix . 'BROWSER_SUPPORT',
'values' => array(
array(
'id' => 'browser_support_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'browser_support_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 1,
'desc' => $this->l('New browsers will display files in the WebP format, and old browsers, such as Internet Explorer, will receive the image in JPG format', $translations_name),
),
array(
'type' => 'switch',
'label' => $this->l('Force WebP as', $translations_name) . ' &lt;picture&gt; ' . $this->l('tag', $translations_name),
'name' => $this->options_prefix . 'FORCE_WEBP_PICTURE',
'values' => array(
array(
'id' => 'force_webp_picture_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'force_webp_picture_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 0,
'desc' => $this->l('Suggested solution only for external modules and error CloudFlare', $translations_name) . '<br/>' .
'&lt;picture&gt; &lt;source srcset="img.webp" type="image/webp"&gt; &lt;img src="img.png" alt="" > &lt;/picture&gt;',
),
array(
'type' => 'switch',
'label' => $this->l('Force .webp extension', $translations_name),
'name' => $this->options_prefix . 'FORCE_WEBP',
'values' => array(
array(
'id' => 'force_webp_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'force_webp_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 0,
'desc' => $this->l('The generated photos will be displayed with the file extension as .webp instead of .jpg', $translations_name),
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'FORCE_WEBP_PICTURE' => '0'
)
),
),
array(
'type' => 'html',
'name' => 'separator_cron_jobs',
'html_content' => '<h4 style="font-size:18px;">' . $this->l('CRON jobs', $translations_name) . '</h4>',
'ignore' => true,
),
array(
'type' => 'select',
'label' => $this->l('CRON operation mode', $translations_name),
'name' => $this->options_prefix . 'CRON_OPERATION_MODE',
'validation' => 'isAnything',
'options' => array(
'query' => array(
array(
'id' => 1,
'name' => $this->l('Generate only missing WebP images', $translations_name),
),
array(
'id' => 2,
'name' => $this->l('Re-generate all WebP images', $translations_name),
)
),
'id' => 'id',
'name' => 'name',
),
'default' => 1,
),
array(
'type' => 'readonly',
'label' => $this->l('Url to CRON jobs', $translations_name),
'name' => $this->options_prefix . 'CRON_URL',
'readonly' => true,
'default' => Context::getContext()->shop->getBaseURL(true) . 'modules/'.$this->name.'/cron.php?token='.$this->x13helper->getCronToken(),
'ignore' => true,
'desc' => $this->l('Last run date:', $translations_name).' '.Configuration::get($this->options_prefix . 'CRON_DATE', null, null, null, '--')
)
),
'submit' => array(
'title' => static::getTranslationByKey('Save'),
),
),
);
if(Module::isInstalled('x13import')){
$key = array_search($this->options_prefix . 'WEBP_AUTO_GENERATOR_ENABLE', array_column($fields_form[0]['form']['input'], 'name'));
array_splice($fields_form[0]['form']['input'], $key + 1, 0, array(array(
'type' => 'switch',
'label' => $this->l('Skip WebP image generation during import product XML/CSV', $translations_name),
'name' => $this->options_prefix . 'IMPORT_SKIP',
'values' => array(
array(
'id' => 'IMPORT_SKIP_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'IMPORT_SKIP_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 0,
'desc' => $this->l('Generally, generating WebP files will make the import of products take longer. You can turn off photo generation when importing products, and the photos themselves will be generated on the fly.', $translations_name),
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'WEBP_AUTO_GENERATOR_ENABLE' => '1',
)
),
)));
}
if(Module::isInstalled('x13lazyload')){
$key = array_search($this->options_prefix . 'FORCE_WEBP_PICTURE', array_column($fields_form[0]['form']['input'], 'name'));
array_splice($fields_form[0]['form']['input'], $key + 1, 0, array(array(
'type' => 'switch',
'label' => $this->l('Enable support for LazyLoad module', $translations_name),
'name' => $this->options_prefix . 'FIX_LAZYLOAD_MODULE',
'values' => array(
array(
'id' => 'FIX_LAZYLOAD_MODULE_enable_on',
'value' => 1,
'label' => $this->l('Yes', $translations_name),
),
array(
'id' => 'FIX_LAZYLOAD_MODULE_enable_off',
'value' => 0,
'label' => $this->l('No', $translations_name),
),
),
'default' => 1,
'form_group_class' => $this->fieldDependsOn(
$this->dependsOnValueEqualTo,
array(
$this->options_prefix . 'FORCE_WEBP_PICTURE' => '1',
)
),
)));
}
return $fields_form;

View File

@@ -0,0 +1,456 @@
<?php
use X13Webp\Helpers\X13Db;
class AdminX13WebpConverterController extends ModuleAdminController
{
public static $available_extensions;
public $bootstrap = true;
public function __construct()
{
$this->bootstrap = true;
$this->lang = true;
parent::__construct();
if (!$this->module->active) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminHome'));
}
}
public function initContent()
{
if ($this->module->initModule()) {
parent::initContent();
}
}
public function initToolbar()
{
parent::initToolbar();
}
/**
* This method is workaround for a colorpicker bug
*
* @see https://github.com/PrestaShop/PrestaShop/pull/25012
*/
public function addJqueryPlugin($name, $folder = null, $css = true)
{
if ($name == 'colorpicker') {
return;
}
parent::addJqueryPlugin($name, $folder, $css);
}
public function ajaxProcessConvertImage()
{
if(Tools::getValue('test_conversion')){
return $this->module->x13converter->covertTestImage();
} else {
$done = Tools::getValue('done');
$output = [];
if(!empty($done)) {
foreach ($done as $format => $amount) {
if ($format == 'jpg') {
Configuration::updateValue($this->module->options_prefix . 'JPG_CONVERSION_PROCESS', 1);
$output[] = $this->module->x13converter->convertJpgImages(
$amount,
Tools::getValue('total', 0),
Tools::getValue('type'),
Tools::getValue('image_type'),
$format
);
Configuration::updateValue($this->module->options_prefix . 'JPG_CONVERSION_PROCESS', 0);
} else {
$output[] = $this->module->x13converter->convertImages(
$amount,
Tools::getValue('total', 0),
Tools::getValue('type'),
Tools::getValue('image_type'),
$format
);
}
}
}
die(json_encode($output));
}
}
public function ajaxProcessConvertOthersItem()
{
$success = true;
$error = false;
$warning = false;
$complete = false;
$dir = false;
if($item = Tools::getValue('item')){
$file = _PS_ROOT_DIR_ . '/' . $item;
if(is_dir($file)){
$dir = true;
$diritem = $this->module->x13helper->scanForNextDirImage($file, array_merge($this->module->x13helper->getExcludedOthersFiles(), array_map(function($dbitem) use ($item){
// return str_replace($item.'/', '', $dbitem['image_name']);
return str_replace($item.'/', '', $dbitem);
// }, (array) Db::getInstance()->executeS('SELECT image_name FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "others"'))), $this->module->x13helper->getExcludedOthersDirs());
}, (array) X13Db::getDoneImagesByType('others'))), $this->module->x13helper->getExcludedOthersDirs());
if($diritem) {
$item .= '/' . $diritem;
$file = $file . '/' . $diritem;
} else {
$file = false;
}
}
if($file){
$output_img = str_replace(['.jpg', '.png'], '.webp', $file);
$output = $this->module->x13converter->imageConversion($output_img, $file);
$warning = $output['error'];
$success = $output['success'];
X13Db::insertX13WebpImage(0, 'others', 'all', $item, $output['error']);
} else {
$complete = true;
}
} else {
$error = $this->l('A problem occured');
}
die(json_encode([
'success' => $success,
'error' => $error,
'warning' => $warning,
'image_type' => 'all',
'image' => $item,
'complete' => $complete,
'dir' => $dir,
'object_name' => $this->module->x13helper->getTypeName('others')
]));
}
public function ajaxProcessRefreshOthersItems()
{
$success = true;
$error = false;
$warning = false;
$items = X13Db::getDoneImagesByType('others');
// Db::getInstance()->executeS('SELECT image_name FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "others"')
if (!$this->module->x13cleaner->forceDeleteWebpImages('others', 'all')) {
$error = $this->l('A problem occured');
}
die(json_encode([
'success' => $success,
'error' => $error,
'warning' => $warning,
'items' => $items
]));
}
public function ajaxProcessGetProductImage()
{
if(!$id_product = Tools::getValue('id_product')) die();
$product = new Product($id_product, false, $this->context->language->id);
$cover = Product::getCover($id_product);
$id_image = false;
if($cover){
$id_image = $cover['id_image'];
} else {
$images = $product->getImages($this->context->language->id);
if(!empty($images) && is_array($images)){
$id_image = $images[0]['id_image'];
}
}
$error = false;
if($id_image){
$data['url'] = $this->context->link->getimageLink($product->link_rewrite, $id_image);
$image = $this->module->x13helper->getImageLink('products', $id_image, '', 'jpg');
if(file_exists($image)){
$size = filesize($image);
$data['size'] = Tools::ps_round($size / 1024, 2) . 'KB';
}
} else {
$error = $this->l('Images doesn\'t exists');
}
$data['error'] = $error;
die(json_encode($data));
}
public function ajaxProcessFileManager()
{
$tree = false;
$error = false;
$tree = $this->module->x13helper->getFilesList(_PS_ROOT_DIR_, Tools::getValue('file'));
die(json_encode(['error' => $error, 'tree' => $tree]));
}
public function ajaxProcessCleanProgressItem()
{
$error = false;
if(!$this->module->x13cleaner->forceDeleteWebpImages(Tools::getValue('type'), Tools::getValue('image_type'))){
$error = $this->l('A problem occured');
}
die(json_encode(['error' => $error]));
}
public function ajaxProcessGetTotals()
{
$output = [];
$success = true;
$error = false;
if($type = Tools::getValue('type')){
$types = $this->module->x13helper->getImageTypes();
if(isset($types[$type])){
$output = $this->module->x13filter->mapImageType($types[$type]);
} else {
$success = false;
$error = $this->l('A problem occured');
}
} else {
$success = false;
$error = $this->l('A problem occured');
}
die(json_encode(['success' => $success, 'error' => $error, 'output' => $output]));
}
public function processCleanProductImages()
{
$alert = false;
$types = ImageType::getImagesTypes('products');
$images = $this->module->x13filter->productImagesToUriPath(Image::getAllImages());
$images_to_remove = array_diff($this->module->x13helper->scanProductDirForMainImages(_PS_PROD_IMG_DIR_), $images);
$amount = 0;
if (!empty($images_to_remove)) {
foreach ($images_to_remove as $itr) {
$itr = _PS_PROD_IMG_DIR_ . $itr;
if (!empty($types)) {
foreach ($types as $type) {
$ext = pathinfo($itr, PATHINFO_EXTENSION);
$type_image = str_replace('.' . $ext, '', $itr) . '-' . $type['name'] . '.' . $ext;
if (file_exists($type_image)) {
$webp = str_replace('jpg', 'webp', $type_image);
if (file_exists($webp)) {
unlink($webp);
}
unlink($type_image);
$amount++;
}
}
}
$explode = explode('/', $itr);
$id_object = (int) filter_var(end($explode), FILTER_SANITIZE_NUMBER_INT);
$webp = str_replace('jpg', 'webp', $itr);
if (file_exists($webp)) {
unlink($webp);
}
if (file_exists($itr)) {
unlink($itr);
$amount++;
}
Db::getInstance()->delete('x13webp', 'type = "products" AND id_image = ' . $id_object . '');
}
$alert = 'cleaned';
} else {
$alert = 'no_images';
}
$url = $this->context->link->getAdminLink('AdminModules') . '&configure=' . $this->module->name;
if($alert){
$url .= '&products_clean='.$alert;
}
$url .= '&amount='.$amount;
return Tools::redirectAdmin($url);
}
public function processCleanTmpDir()
{
$amount = $this->module->x13cleaner->clearTmpDir();
return Tools::redirectAdmin($this->context->link->getAdminLink('AdminModules') . '&configure=' . $this->module->name.'&clean_tmp='.(int)$amount);
}
public function processCleanImageTypes()
{
$amount = $this->module->x13cleaner->cleanImageTypes(Tools::getValue('type'));
$url = $this->context->link->getAdminLink('AdminModules') . '&configure=' . $this->module->name;
$url .= '&format_clean=' . $amount;
Tools::redirectAdmin($url);
}
public function ajaxProcessDeleteAllWebp()
{
$output = [
'alert' => false,
'error' => false,
'warning' => false,
'type' => false,
'image_type' => false,
'complete' => false,
'type_name' => false
];
$type = X13Db::getGeneratedWebpType();
if(!$type) {
$output['alert'] = $this->l('All images has been deleted');
$output['complete'] = true;
} else {
$output['type'] = $type;
$output['type_name'] = $this->module->x13helper->getDeleteTypeName($type);
$image_type = X13Db::getGeneratedImageType($type);
if($image_type !== false) {
$output['image_type'] = empty($image_type) ? 'main' : $image_type;
if($this->module->x13cleaner->forceDeleteWebpImages($type, $image_type)){
$output['alert'] = $this->l('Success');
} else {
$output['warning'] = $this->l('There was a problem with deleting WebP');
}
} else {
$output['error'] = $this->l('A problem occured');
}
}
die(json_encode($output));
}
public function ajaxProcessUpdateConfig()
{
if(!$name = Tools::getValue('name', false)) {
return;
} else if(!$val = Tools::getValue('val', false)) {
return;
}
Configuration::updateValue($name, $val);
}
public function ajaxProcessRegenerateWarnings()
{
$id_x13webp = Tools::getValue('id_x13webp');
$item = X13Db::getNextWarningItem($id_x13webp);
$output = $this->module->x13converter->regenerateWarning($item);
$output['warning_exists'] = X13Db::checkForWarnings();
die(json_encode($output));
}
}

View File

@@ -0,0 +1,34 @@
<?php
class X13WebpAjaxModuleFrontController extends ModuleFrontController
{
public function init()
{
parent::init();
if($x13images = (array)Tools::getValue('x13images')){
$this->convertImages($x13images);
}
}
public function convertImages($x13images)
{
if (Configuration::get($this->module->options_prefix . 'OPERATION_MODE') == 0) {
return;
}
foreach($x13images as $img){
$ext = pathinfo($img, PATHINFO_EXTENSION);
if (in_array($ext, $this->module->x13helper->getAvailableExtensions()) && !$this->module->x13helper->checkWebpExistsFromUrl($img)) {
$this->module->x13converter->convertWebpFromUrl($img);
}
}
}
}

137
modules/x13webp/cron.php Normal file
View File

@@ -0,0 +1,137 @@
<?php
use X13Webp\Helpers\X13Db;
include(dirname(__FILE__) . '/../../config/config.inc.php');
/* Check security token */
if (!Tools::isPHPCLI()) {
include(dirname(__FILE__) . '/../../init.php');
}
class x13webpCron {
private $module;
private $done_images = 0;
public function __construct()
{
$this->module = Module::getInstanceByName('x13webp');
if (Tools::getValue('token') == $this->module->x13helper->getCronToken()) {
$cron_activity = Configuration::get($this->module->options_prefix . 'CRON_ACTIVITY');
if ($cron_activity && $cron_activity > time()) {
die('Cron has already been started');
} else {
Configuration::updateValue($this->module->options_prefix . 'CRON_ACTIVITY', strtotime('+ 1 minutes', time()));
}
$this->start_time = time();
$this->max_execution_time = (int) ini_get('max_execution_time');
if (Configuration::get($this->module->options_prefix . 'CRON_OPERATION_MODE') == 2) {
$this->deleteAllWebp();
}
$this->generateMissingWebp();
Configuration::updateValue($this->module->options_prefix . 'CRON_DATE', date('Y-m-d H:i:s'));
die('Done: ' . $this->getCronLog());
} else {
die('Bad token');
}
}
public function getCronLog()
{
return $this->done_images . ' images generated';
}
public function checkMaxExecutionTime()
{
if (time() - $this->start_time > $this->max_execution_time - 4) die('Timeout: ' . $this->getCronLog());
}
public function generateMissingWebp()
{
$allowed = json_decode(Configuration::get($this->module->options_prefix . 'ALLOWED_GENERATED_IMAGES'), true);
$types = $this->module->x13helper->getImageTypes();
if (!empty($types)) foreach ($types as $type) {
if (!in_array($type['val'], $allowed)) continue;
$total = $this->module->x13helper->getTotalImages($type['val']);
if ($type['has_types']) {
$image_types = ImageType::getImagesTypes($type['val']);
array_unshift($image_types, [
'name' => 'main'
]);
if (!empty($image_types)) foreach ($image_types as $image_type) {
$done = X13Db::getTotalDoneImages($type['val'], $image_type['name']);
$output = $this->module->x13converter->convertImages($done, $total, $type['val'], $image_type['name'], 'webp');
while ($output && !$output['complete'] && !$output['error']) {
$this->checkMaxExecutionTime();
$output = $this->module->x13converter->convertImages($output['done'], $total, $type['val'], $image_type['name'], 'webp');
$this->done_images += 1;
}
}
} else {
if ($type['val'] == 'theme') {
$done = X13Db::getTotalDoneImages($type['val'] . '_' . _THEME_NAME_, '');
if (defined('_PARENT_THEME_NAME_') && !empty(_PARENT_THEME_NAME_)) {
$done += X13Db::getTotalDoneImages($type['val'] . '_' . _PARENT_THEME_NAME_, '');
}
} else {
$done = X13Db::getTotalDoneImages($type['val']);
}
$output = $this->module->x13converter->convertImages($done, $total, $type['val'], 'all', 'webp');
while ($output && !$output['complete'] && !$output['error']) {
$this->checkMaxExecutionTime();
$output = $this->module->x13converter->convertImages($output['done'], $total, $type['val'], '', 'webp');
$this->done_images += 1;
};
}
}
}
public function deleteAllWebp()
{
$type = X13Db::getGeneratedWebpType();
if (!$type) return true;
$image_type = X13Db::getGeneratedImageType($type);
if ($image_type !== false) {
$this->module->x13cleaner->forceDeleteWebpImages($type, $image_type);
}
$this->deleteAllWebp();
}
}
new x13webpCron();

View File

@@ -0,0 +1,24 @@
Server restriction: redline.com.pl,www.redline.com.pl,*.redline.com.pl,*.local,*.loc,*.localhost,*.test,test.*,dev.*,*.dev,*.dev.*
------ LICENSE FILE DATA -------
070XW843Vy6RHnaULTxek7tZQ35OOd0S
o29lQeWBOk1tDDeiFuU7S+OKam3xfbo+
Bjbqn+zyihQBGV3ey602GCO0Hbz9xsI2
P6iEcqoW0mPhYcU/8DvSH2Pu9drzH8CV
aW9jzXEB6aRVfK686e+tMHC9+ZKxp+8s
8XILkrznvXSU+GflkeXO/ZMpkJZjPOdN
CBJYpCiSMUUG7hB1mwN8dJyTkNAhukdp
m51FLVeTidJ9VIT9FUE7LOJ8kf6cHXFX
e2k8X+oXeOKwZZ4Ha7O3HT+X4S1b2D/+
Vpj7HmQBFpM5KjhaJ8mzNQJivpZHnhyX
76nCyMcIH01GwGSlDlzaPHxZWrONW58E
DX5TlYHm4BVz1A1BqWY1LJ5AZvXoslaG
r8n+OZoXoy+1B5Kk7u+MmHtfdTINWIFa
voaiSrrsQxNzLHW7zmTneALMimzcwdru
t5e7hXx6rSStQ7QNIa3BTBcsTGZtUdHt
bCYwqV65aQZNDslQLaEUuKMTn4tvoYzU
00koMig8Fi9nFpBVPDMb45fgwVrGn7XR
QaNN61shxRhSfFhRHD+mafkFpAQk16kW
cPx1TcK5fyCi9fAH/iU7IoI1taOjfiXe
yRKxJJhbNWLnNoMmGHkztFN=
--------------------------------

BIN
modules/x13webp/logo.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

BIN
modules/x13webp/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

BIN
modules/x13webp/logo.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

View File

@@ -0,0 +1,13 @@
<?php
class ImageManager extends ImageManagerCore {
public static function resize($src_file, $dst_file, $dst_width = null, $dst_height = null, $file_type = 'jpg', $force_type = false, &$error = 0, &$targetWidth = null, &$targetHeight = null, $quality = 5, &$sourceWidth = null, &$sourceHeight = null){
$parent = parent::resize($src_file, $dst_file, $dst_width, $dst_height, $file_type, $force_type, $error, $targetWidth, $targetHeight, $quality, $sourceWidth, $sourceHeight);
Hook::exec('actionOnImageResizeAfter', ['dst_file' => $dst_file, 'file_type' => $file_type]);
return $parent;
}
}

View File

@@ -0,0 +1,17 @@
<?php
class FrontController extends FrontControllerCore
{
public function smartyOutputContent($content)
{
ob_start();
parent::smartyOutputContent($content);
$html = ob_get_contents();
ob_clean();
Hook::exec('actionOutputHTMLBefore', array('html' => &$html));
echo $html;
}
}

View File

@@ -0,0 +1,388 @@
<?php
namespace X13Webp\Core\Configurator;
use AdminController;
use Configuration;
use Context;
use HelperForm;
use Language;
use Shop;
use Tools;
use Validate;
trait ConfiguratorBase
{
public $configuratorVersion = '1.0.9';
public $options_prefix;
protected $fields_form = array();
protected $form_errors = array();
public $dependsOnValueEqualTo = 'match';
public $dependsOnValueNotEqualTo = 'not_match';
/**
* Render form using HelperForm
* @return array HelperForm form
*/
protected function renderForm()
{
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$this->renderConfigurationForm();
$helper = new HelperForm();
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->identifier = $this->identifier;
$helper->token = Tools::getAdminTokenLite('AdminModules');
foreach (Language::getLanguages(false) as $lang) {
$helper->languages[] = array(
'id_lang' => $lang['id_lang'],
'iso_code' => $lang['iso_code'],
'name' => $lang['name'],
'is_default' => ($default_lang == $lang['id_lang'] ? 1 : 0),
);
}
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
$helper->toolbar_scroll = true;
$helper->title = $this->displayName;
$helper->submit_action = 'save'.$this->name;
$helper->toolbar_btn = array(
'save' => array(
'desc' => $this->l('Save'),
'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'),
),
);
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFieldsValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm($this->fields_form);
}
/**
* Get configuration field values
* @return array
*/
public function getConfigFieldsValues()
{
$id_shop = Shop::getContextShopID(true);
$id_shop_group = Shop::getContextShopGroupID(true);
$fields_values = array();
foreach ($this->fields_form as $k => $f) {
foreach ($f['form']['input'] as $i => $input) {
if (isset($input['ignore']) && $input['ignore'] == true) {
continue;
}
if (isset($input['lang']) && $input['lang'] == true) {
foreach (Language::getLanguages(false) as $lang) {
$values = Tools::getValue($input['name'].'_'.$lang['id_lang'], ($this->checkConfigurationHasKey($input['name'], $lang['id_lang'], (int) $id_shop_group, $id_shop) ? Configuration::get($input['name'], $lang['id_lang'], (int) $id_shop_group, (int) $id_shop) : $input['default']));
$fields_values[$input['name']][$lang['id_lang']] = $values;
}
} else {
if ($input['type'] == 'checkbox' && isset($input['values'])) {
$input['name'] = str_replace(array('[]'), array(''), $input['name']);
$values = ($this->checkConfigurationHasKey($input['name'], null, (int) $id_shop_group, (int) $id_shop) ? json_decode(Configuration::get($input['name'], null, (int) $id_shop_group, (int) $id_shop), true) : $input['default']);
$valueField = isset($input['values']['value_field']) ? $input['values']['value_field'] : $input['values']['id'];
if (is_array($values)) {
foreach ($input['values']['query'] as $entry) {
if (in_array($entry[$valueField], $values)) {
$fields_values[$input['name'].'[]_'.$entry[$valueField]] = $entry[$valueField];
}
}
}
} elseif ($input['type'] == 'select' && isset($input['multiple']) && $input['multiple'] && isset($input['options'])) {
$input['name'] = str_replace(array('[]'), array(''), $input['name']);
if ($this->checkConfigurationHasKey($input['name'], null, (int) $id_shop_group, (int) $id_shop)) {
$values = Configuration::get($input['name'], null, (int) $id_shop_group, (int) $id_shop);
if (isset($input['callback']) && 'saveAsJson' == $input['callback']) {
$values = json_decode($values, true);
}
} else {
$values = $input['default'];
}
if(isset($input['options']['optiongroup']) && isset($input['options']['options'])){
$valueField = isset($input['options']['options']['value_field']) ? $input['options']['options']['value_field'] : $input['options']['options']['id'];
$queryField = $input['options']['options']['query'];
$fields_values[$input['name'].'[]'] = array();
if (is_array($values)) {
foreach ($input['options']['optiongroup']['query'] as $query) {
foreach ($query[$queryField] as $entry) {
if (in_array($entry[$valueField], $values)) {
$fields_values[$input['name'].'[]'][] = $entry[$valueField];
}
}
}
}
}else{
$valueField = isset($input['options']['value_field']) ? $input['options']['value_field'] : $input['options']['id'];
$fields_values[$input['name'].'[]'] = array();
if (is_array($values)) {
foreach ($input['options']['query'] as $entry) {
if (in_array($entry[$valueField], $values)) {
$fields_values[$input['name'].'[]'][] = $entry[$valueField];
}
}
}
}
} else {
$values = Tools::getValue($input['name'], ($this->checkConfigurationHasKey($input['name'], null, (int) $id_shop_group, (int) $id_shop) ? Configuration::get($input['name'], null, (int) $id_shop_group, (int) $id_shop) : $input['default']));
$fields_values[$input['name']] = $values;
}
}
}
}
$this->assignCustomConfigs($fields_values);
return $fields_values;
}
protected function checkConfigurationHasKey($key, $idLang = null, $idShopGroup = null, $idShop = null)
{
return Configuration::hasKey($key, $idLang, (int) $idShopGroup, (int) $idShop) ||
Configuration::hasKey($key, $idLang, (int) $idShopGroup) ||
Configuration::hasKey($key, $idLang);
}
/**
* Batch update configuration fields
* @return bool
*/
public function batchUpdateConfigs()
{
foreach ($this->fields_form as $k => &$f) {
foreach ($f['form']['input'] as $i => &$input) {
$input_name = str_replace(array('[]'), array(''), $input['name']);
$field_errors = array();
// $input['name'] = str_replace(array('[]'), array(''), $input['name']);
if (isset($input['ignore']) && $input['ignore'] == true) {
continue;
}
if (isset($input['lang']) && $input['lang'] == true) {
$data = array();
foreach (Language::getLanguages(false) as $lang) {
$val = Tools::getValue($input_name.'_'.$lang['id_lang'], $input['default']);
$data[$lang['id_lang']] = $val;
if (isset($input['validate']) && !Validate::{$input['validate']}($data[$lang['id_lang']])) {
$field_errors[] = sprintf($this->l('Field %s is invalid for language %s'), $input['label'], $lang['iso_code']);
}
if (isset($input['callback']) && method_exists($this, $input['callback'])) {
$data[$lang['id_lang']] = $this->{$input['callback']}($data[$lang['id_lang']]);
}
}
} else {
$data = Tools::getValue($input_name, $input['default']);
if (isset($input['validate']) && !Validate::{$input['validate']}($data)) {
$field_errors[] = sprintf($this->l('Field %s is invalid'), $input['label']);
}
if (isset($input['callback']) && method_exists($this, $input['callback'])) {
$data = $this->{$input['callback']}($data);
}
}
if (!empty($field_errors)) {
$input['errors'] = implode('<br>', $field_errors);
$this->form_errors = array_merge($this->form_errors, $field_errors);
} else {
Configuration::updateValue(trim($input_name), $data, true);
}
}
}
$this->batchUpdateCustomConfigs();
return empty($this->form_errors);
}
/**
* Delete entire custom configuration
* @return bool
*/
public function deleteConfigs()
{
foreach ($this->fields_form as $k => $f) {
foreach ($f['form']['input'] as $i => $input) {
if (isset($input['ignore']) && $input['ignore'] == true) {
continue;
}
Configuration::deleteByName(str_replace('[]', '', $input['name']));
}
}
$this->deleteCustomConfigs();
return true;
}
/**
* Get all configuration values for both single and multi-lang keys
* @param int $idLang we get configuration for given language
* @return array module configuration
*/
public function getConfigurationValues($idLang = false)
{
$this->renderConfigurationForm();
$configs = $this->getConfigFieldsValues();
$idLang = $idLang ? $idLang : Context::getContext()->language->id;
$moduleConfiguration = array();
foreach ($configs as $key => $value) {
$moduleConfiguration[$key] = Configuration::get($key, is_array($value) ? $idLang : null);
}
return $moduleConfiguration;
}
public function getConfiguratorValue($name, $idLang = null, $json = false)
{
$formattedName = $this->options_prefix.$name;
if ($idLang) {
return Configuration::get($formattedName, $idLang);
}
return Configuration::get($this->options_prefix.$name);
}
public function getDefaultContentByLanguage($isoCode, $file)
{
$path = _PS_MODULE_DIR_.$this->name.'/defaults/'.$isoCode.'/';
if (file_exists($path.$file)) {
return file_get_contents($path.$file);
}
$fallbackPath = _PS_MODULE_DIR_.$this->name.'/defaults/';
if (file_exists($fallbackPath.$file)) {
return file_get_contents($fallbackPath.$file);
}
return '';
}
/**
* Create array for a custom configs, this method could be used as an override
* @param $array &$fields_values
* @return array
*/
public function assignCustomConfigs(&$fields_values)
{
return array();
}
/**
* Update custom configs
* @return bool
*/
public function batchUpdateCustomConfigs()
{
return true;
}
/**
* Delete custom configs
* @return bool
*/
public function deleteCustomConfigs()
{
return true;
}
/**
* Returns provided array as Json
* @param array $input
* @return json
*/
public function saveAsJson($array)
{
return json_encode($array);
}
/**
* Helper for JS field dependencies
*
* @param string $method
* @param array $restrictions
*/
public function fieldDependsOn(
$method,
array $restrictions = array()
) {
if (!count($restrictions) || !in_array($method, array($this->dependsOnValueNotEqualTo, $this->dependsOnValueEqualTo))) {
return;
}
$classes = array('depends-on');
switch ($method) {
case $this->dependsOnValueNotEqualTo:
$classes[] = 'depends-where-is-not';
break;
default:
$classes[] = 'depends-where-is';
break;
}
if (count($restrictions) > 1) {
$classes[] = 'depends-on-multiple';
}
foreach ($restrictions as $fieldName => $values) {
if (is_array($values)) {
$classes[] = 'depends-field-'.$fieldName.':'.implode(',', $values).'';
} else {
$classes[] = 'depends-field-'.$fieldName.':'.$values;
}
}
return implode(' ', $classes);
}
public function fillSettingsForNewLanguage(Language $language)
{
if (Validate::isLoadedObject($language)) {
$this->renderConfigurationForm();
foreach ($this->fields_form as $k => $f) {
foreach ($f['form']['input'] as $i => $input) {
if (isset($input['ignore']) && true == $input['ignore']) {
continue;
}
if (isset($input['lang']) && true == $input['lang']) {
$data = array();
if (isset($input['callback']) && method_exists($this, $input['callback'])) {
$data[(int)$language->id] = $this->{$input['callback']}($input['default']);
} else {
$data[(int)$language->id] = $input['default'];
}
if (Shop::isFeatureActive()) {
foreach (Shop::getShops(false, null, true) as $id_shop) {
Configuration::updateValue(trim($input['name']), $data, false, null, $id_shop);
}
} else {
Configuration::updateValue(trim($input['name']), $data);
}
}
}
}
}
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace X13Webp\Core\Configurator;
use CMS;
use CMSCategory;
use Group;
use Language;
trait ConfiguratorHelpers
{
/**
* Return value with every available language
* @param string Value
* @return array
*/
public static function prepareValueForLangs($value)
{
$output = array();
foreach (Language::getLanguages(false) as $lang) {
$output[$lang['id_lang']] = $value;
}
return $output;
}
/**
* Get CMS categories list for a HelperOption select field
* @return array
*/
public function getCMSCategoriesList()
{
$cms_categories = CMSCategory::getSimpleCategories($this->context->language->id);
$output[] = array(
'id_cms_category' => 0,
'name' => $this->l('--- Choose ---'),
);
return array_merge($output, $cms_categories);
}
/**
* Get CMS pages list for a HelperOption checkbox/select field
* @return array
*/
public function getCMSPages()
{
$cms_pages = CMS::listCms($this->context->language->id);
$output = array();
foreach ($cms_pages as $cms_page) {
$output[(int) $cms_page['id_cms']] = array(
'id_cms' => (int) $cms_page['id_cms'],
'val' => (int) $cms_page['id_cms'],
'meta_title' => $cms_page['meta_title'],
);
}
return $output;
}
/**
* Get customer groups for HelperOption checkbox/select field
* @return array
*/
public function getCustomerGroups()
{
$output = array();
$output[] = array(
'id_group' => 0,
'name' => $this->l('--- Choose ---'),
);
return array_merge($output, Group::getGroups($this->context->language->id));
}
/**
* Show nice notification message in back-office
* @param string $message Message to display
* @param string $className name of the bootstrap component class
* @return string
*/
public function renderAdminMessage($message, $className = 'warning')
{
if (is_array($message)) {
$message = join(', ', $message);
}
$content = '<span class="badge badge-'.$className.'">';
$content .= $message;
$content .= '</span>';
$content .= ' - ';
$content .= '<b>'.$this->name.'</b>';
return $content;
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace X13Webp\Core\Configurator;
interface ConfiguratorInterface
{
public function setOptionsPrefix();
public function batchUpdateConfigs();
public function deleteConfigs();
public function renderConfigurationForm();
public function getConfigFieldsValues();
}

View File

@@ -0,0 +1,35 @@
<?php
/*
* 2007-2014 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2014 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,35 @@
<?php
/*
* 2007-2014 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2014 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,396 @@
<?php
namespace X13Webp\Helpers;
use Configuration;
use Context;
use Db;
use ImageType;
use Module;
class X13Cleaner {
private $module;
public function __construct(Module $module)
{
$this->module = $module;
}
public function forceDeleteWebpImages($type, $image_type)
{
$parent = defined('_PARENT_THEME_NAME_') ? 'theme_' . _PARENT_THEME_NAME_ : 'theme';
$images = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "' . $type . '" AND image_type = "' . $image_type . '"');
$generate_hight_dpi_images = (bool) Configuration::get('PS_HIGHT_DPI');
$image_type = $image_type == 'main' ? '' : $image_type;
switch ($type) {
case 'products':
if (!empty($images)) {
foreach ($images as $image) {
$input = $this->module->x13helper->getImageLink('products', $image['id_image'], $image_type, 'webp');
if (file_exists($input)) {
unlink($input);
}
if($generate_hight_dpi_images){
$input2x = $this->module->x13helper->getImageLink('products', $image['id_image'], $image_type . '2x', 'webp');
if (file_exists($input2x)) {
unlink($input2x);
}
}
}
}
return Db::getInstance()->delete('x13webp', 'type = "' . $type . '" AND image_type = "' . $image_type . '"');
break;
case 'categories':
if (!empty($images)) foreach ($images as $image) {
$text_image_type = !empty($image_type) ? '-' . $image_type : '';
$input = $this->module->x13helper->getImageLink('categories', $image['id_image'], $text_image_type, 'webp');
if (file_exists($input)) unlink($input);
if ($generate_hight_dpi_images) {
$input2x = $this->module->x13helper->getImageLink('categories', $image['id_image'], $text_image_type . '2x', 'webp');
if (file_exists($input2x)) {
unlink($input2x);
}
}
$miniature_webp = $this->module->x13helper->getImageLink('categories', $image['id_image'], '_thumb', 'webp');
if (file_exists($input)) unlink($miniature_webp);
$imageFiles = scandir(_PS_CAT_IMG_DIR_);
if (count(preg_grep('/^' . $image['id_image'] . '-([0-9])?_thumb.jpg/i', $imageFiles)) > 0) {
foreach ($imageFiles as $file) {
if (
preg_match('/^' . $image['id_image'] . '-([0-9])?_thumb.webp/i', $file) === 1
) {
unlink(_PS_CAT_IMG_DIR_ . $file);
}
}
}
}
return Db::getInstance()->delete('x13webp', 'type = "' . $type . '" AND image_type = "' . $image_type . '"');
break;
case 'manufacturers':
if (!empty($images)) foreach ($images as $image) {
$input = $this->module->x13helper->getImageLink('manufacturers', $image['id_image'], $image_type, 'webp');
if (file_exists($input)) {
unlink($input);
}
if ($generate_hight_dpi_images) {
$input2x = $this->module->x13helper->getImageLink('manufacturers', $image['id_image'], $image_type . '2x', 'webp');
if (file_exists($input2x)) {
unlink($input2x);
}
}
}
return Db::getInstance()->delete('x13webp', 'type = "' . $type . '" AND image_type = "' . $image_type . '"');
break;
case 'suppliers':
if (!empty($images)) foreach ($images as $image) {
$input = $this->module->x13helper->getImageLink('suppliers', $image['id_image'], $image_type, 'webp');
if (file_exists($input)) unlink($input);
if ($generate_hight_dpi_images) {
$input2x = $this->module->x13helper->getImageLink('suppliers', $image['id_image'], $image_type . '2x', 'webp');
if (file_exists($input2x)) {
unlink($input2x);
}
}
}
return Db::getInstance()->delete('x13webp', 'type = "' . $type . '" AND image_type = "' . $image_type . '"');
break;
case 'stores':
if (!empty($images)) foreach ($images as $image) {
$input = $this->module->x13helper->getImageLink('stores', $image['id_image'], $image_type, 'webp');
if (file_exists($input)) unlink($input);
if ($generate_hight_dpi_images) {
$input2x = $this->module->x13helper->getImageLink('stores', $image['id_image'], $image_type . '2x', 'webp');
if (file_exists($input2x)) {
unlink($input2x);
}
}
}
return Db::getInstance()->delete('x13webp', 'type = "' . $type . '" AND image_type = "' . $image_type . '"');
break;
case 'cms':
if (!empty($images)) foreach ($images as $image) {
$input = _PS_IMG_DIR_ . 'cms/' . $image['image_name'];
$ext = pathinfo($input, PATHINFO_EXTENSION);
$output_img = str_replace($ext, 'webp', $input);
$output_img_2 = false;
if ($ext == 'png') {
$output_img_2 = str_replace('.webp', '_png.webp', $output_img);
} else if ($ext == 'jpg') {
$output_img_2 = str_replace('.webp', '_jpg.webp', $output_img);
}
if ($output_img_2 && file_exists($output_img_2)) unlink($output_img_2);
if (file_exists($output_img)) unlink($output_img);
}
return Db::getInstance()->delete('x13webp', 'type = "' . $type . '" AND image_type = "' . $image_type . '"');
break;
case 'modules':
if (!empty($images)) foreach ($images as $image) {
$input = _PS_MODULE_DIR_ . $image['image_name'];
$ext = pathinfo($input, PATHINFO_EXTENSION);
$output_img = str_replace($ext, 'webp', $input);
if (file_exists($output_img)) unlink($output_img);
$output_img_2 = false;
if ($ext == 'png') {
$output_img_2 = str_replace('.webp', '_png.webp', $output_img);
} else if ($ext == 'jpg') {
$output_img_2 = str_replace('.webp', '_jpg.webp', $output_img);
}
if ($output_img_2 && file_exists($output_img_2)) unlink($output_img_2);
}
return Db::getInstance()->delete('x13webp', 'type = "' . $type . '" AND image_type = "' . $image_type . '"');
break;
case 'theme':
case 'theme_' . _THEME_NAME_:
case $parent:
$parent_theme = defined('_PS_PARENT_THEME_DIR_') ? ' OR type = "theme_' . _PARENT_THEME_NAME_ . '"' : '';
$images = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'x13webp` WHERE (type = "theme_' . _THEME_NAME_ . '" ' . $parent_theme . ') AND image_type = "' . $image_type . '"');
if (!empty($images)) foreach ($images as $image) {
$ext = pathinfo($image['image_name'], PATHINFO_EXTENSION);
$del_img = str_replace($ext, 'webp', $image['image_name']);
$theme_image = _PS_THEME_DIR_ . $del_img;
if (!file_exists($theme_image) && defined('_PS_PARENT_THEME_DIR_')) {
$theme_image = _PS_PARENT_THEME_DIR_ . $del_img;
}
if (file_exists($theme_image)) {
unlink($theme_image);
}
$output_img_2 = false;
if ($ext == 'png') {
$output_img_2 = str_replace('.webp', '_png.webp', $theme_image);
} else if ($ext == 'jpg') {
$output_img_2 = str_replace('.webp', '_jpg.webp', $theme_image);
}
if ($output_img_2 && file_exists($output_img_2)) unlink($output_img_2);
}
return Db::getInstance()->delete('x13webp', '(type = "theme_' . _THEME_NAME_ . '" ' . $parent_theme . ') AND image_type = "' . $image_type . '"');
break;
case 'logo':
if (!empty($images)) {
foreach ($images as $image) {
$input = _PS_IMG_DIR_ . $image['image_name'];
$ext = pathinfo($input, PATHINFO_EXTENSION);
$output = str_replace($ext, 'webp', $input);
if (file_exists($output)) unlink($output);
}
}
return Db::getInstance()->delete('x13webp', 'type = "' . $type . '" AND image_type = "' . $image_type . '"');
break;
case 'others':
if (!empty($images)) {
foreach ($images as $image) {
$input = _PS_ROOT_DIR_ . $image['image_name'];
$ext = pathinfo($input, PATHINFO_EXTENSION);
$output = str_replace($ext, 'webp', $input);
if (file_exists($output)) unlink($output);
}
}
return Db::getInstance()->delete('x13webp', 'type = "' . $type . '" AND image_type = "' . $image_type . '"');
break;
default:
return false;
break;
}
}
public function deleteTestImage()
{
$dir = dirname(__DIR__) . '/../test';
if (!file_exists($dir)) {
mkdir($dir);
} else {
$files = array_diff(scandir($dir), ['.', '..', 'index.php']);
if (!empty($files)) foreach ($files as $file) {
if (!is_dir("$dir/$file")) {
unlink("$dir/$file");
}
}
}
}
public function removeProductImageDir($dir)
{
$items = array_diff(scandir($dir), ['.', '..']);
if (!empty($items)) foreach ($items as $item) {
unlink($dir . '/' . $item);
}
rmdir($dir);
$up = dirname($dir, 1);
if ($up . '/' != _PS_PROD_IMG_DIR_) {
if (empty(array_diff(scandir($up), ['.', '..', 'index.php', 'fileType']))) {
$this->removeProductImageDir($up);
}
}
}
public function cleanImageTypes($type)
{
if (empty($type)) {
return 'error';
}
if(!$dir = $this->module->x13helper->getImgDirFromType($type)){
return 'error';
}
$scan = $this->module->x13helper->scanImageDirForMainObjectImages($dir);
$image_types = ImageType::getImagesTypes($type);
$generate_hight_dpi_images = (bool) Configuration::get('PS_HIGHT_DPI');
$watermarkHash = null;
if (Module::isInstalled('watermark') && Module::isEnabled('watermark')) {
$watermarkHash = Configuration::get('WATERMARK_HASH');
}
$items = [];
$allowed = [];
$current_dirs[] = '';
$amount = 0;
if (!empty($scan)) {
foreach ($scan as $image) {
$explode = explode('/', $image);
$id_object = (int) filter_var(end($explode), FILTER_SANITIZE_NUMBER_INT);
if (!empty($image_types)) {
foreach ($image_types as $image_type) {
$allowed[] = $this->module->x13helper->getImageLink($type, $id_object,($type == 'categories' ? '-' : '') . $image_type['name'], 'jpg');
$allowed[] = $this->module->x13helper->getImageLink($type, $id_object,($type == 'categories' ? '-' : '') . $image_type['name'], 'webp');
if($generate_hight_dpi_images){
$allowed[] = $this->module->x13helper->getImageLink($type, $id_object,($type == 'categories' ? '-' : '') . $image_type['name'] . '2x', 'jpg');
$allowed[] = $this->module->x13helper->getImageLink($type, $id_object,($type == 'categories' ? '-' : '') . $image_type['name'] . '2x', 'webp');
}
if(!empty($watermarkHash)){
$allowed[] = $this->module->x13helper->getImageLink($type, $id_object,($type == 'categories' ? '-' : '') . $image_type['name'] . '-' .$watermarkHash, 'jpg');
$allowed[] = $this->module->x13helper->getImageLink($type, $id_object,($type == 'categories' ? '-' : '') . $image_type['name'] . '-' .$watermarkHash, 'webp');
}
}
}
$allowed[] = $this->module->x13helper->getImageLink($type, $id_object, '', 'jpg');
$allowed[] = $this->module->x13helper->getImageLink($type, $id_object, '', 'webp');
$current_dir = dirname($image) == '.' ? '' : dirname($image) . '/';
if (!empty($current_dir)) {
$current_dirs[] = $current_dir;
}
}
}
if (!empty($current_dirs)) {
foreach ($current_dirs as $cd) {
$items = array_merge($items, array_map(function ($item) use ($cd, $dir) {
return $dir . $cd . $item;
}, array_filter(preg_grep('/^([0-9]+)(.*).[jpg, webp]/i', scandir($dir . $cd)), function ($item) {
return strpos($item, '_thumb') === false ? $item : false;
})));
}
}
$items_to_remove = array_diff($items, $allowed);
if (!empty($items_to_remove)) {
foreach ($items_to_remove as $itr) {
if (file_exists($itr)) {
unlink($itr);
$amount++;
}
}
}
return $amount;
}
public function deleteObjectImages($object_id, $type)
{
$image_types = ImageType::getImagesTypes($type);
array_unshift($image_types, [
'name' => ''
]);
if (!empty($image_types)) {
foreach ($image_types as $image_type) {
$image = $this->module->x13helper->getImageLink($type, $object_id, $image_type['name'], 'webp');
if (file_exists($image)) unlink($image);
}
}
Db::getInstance()->delete('x13webp', 'id_image = ' . (int) $object_id);
}
public function clearTmpDir($dir = _PS_TMP_IMG_DIR_)
{
$amount = 0;
foreach (array_diff(scandir($dir, SCANDIR_SORT_NONE), ['.', '..', 'index.php']) as $d) {
$ext = pathinfo($dir . $d, PATHINFO_EXTENSION);
if (in_array($ext, ['jpg','webp','png','gif'])) {
unlink($dir . $d);
$amount++;
} else if(is_dir($dir . $d)){
$this->clearTmpDir($dir . $d . '/');
rmdir($dir . $d);
}
}
return $amount;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,244 @@
<?php
namespace X13Webp\Helpers;
use Configuration;
use Context;
use Db;
use DbQuery;
use Shop;
class X13Db
{
public static function insertX13WebpImage($id_image, $type, $image_type, $image_name = '', $warning = null)
{
return Db::getInstance()->insert('x13webp', ['id_image' => $id_image, 'type' => $type, 'image_type' => $image_type, 'image_name' => $image_name, 'warning' => addslashes($warning)]);
}
public static function getGeneratedWebpType()
{
return Db::getInstance()->getValue('SELECT DISTINCT type FROM `' . _DB_PREFIX_ . 'x13webp`');
}
public static function getGeneratedImageType($type)
{
return Db::getInstance()->getValue('SELECT DISTINCT image_type FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "' . $type . '"');
}
public static function getTotalDoneImages($type, $image_type = '')
{
$sql = 'SELECT count(id_image) as amount FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "' . $type . '"';
if (!empty($image_type)) {
$image_type = $image_type == 'main' ? '' : $image_type;
$sql .= ' AND image_type = "' . $image_type . '"';
}
return (int)Db::getInstance()->getValue($sql);
}
public static function checkFileExists($id_object, $type, $image_type, $image_name)
{
return (bool) Db::getInstance()->getValue('SELECT id_x13webp FROM `' . _DB_PREFIX_ . 'x13webp` WHERE id_image = ' . (int)$id_object . ' AND type = "' . $type . '" AND image_type = "' . $image_type . '" AND image_name = "' . $image_name . '"');
}
public static function getNextProductImage($image_type)
{
return Db::getInstance()->getRow('
SELECT i.id_image, i.id_product FROM
`' . _DB_PREFIX_ . 'image` i,
`' . _DB_PREFIX_ . 'image_shop` image_shop
WHERE i.id_image = image_shop.id_image
AND image_shop.id_shop = ' . (int)Context::getContext()->shop->id . '
AND i.id_image NOT IN (
SELECT id_image FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "products" AND image_type = "' . $image_type . '"
)
ORDER BY i.id_image ASC
');
}
public static function getNextCategory($image_type, $excluded = [])
{
$q = '';
if (!empty($excluded)) {
$q .= 'AND c.`id_category` NOT IN (' . implode(',', $excluded) . ')';
}
$category = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT c.`id_category`, cl.`name`, cl.`link_rewrite`
FROM `' . _DB_PREFIX_ . 'category` c
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . ')
' . Shop::addSqlAssociation('category', 'c') . '
WHERE cl.`id_lang` = ' . (int) Context::getContext()->language->id . '
AND c.`id_category` NOT IN (
SELECT id_image FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "categories" AND image_type = "' . $image_type . '"
)
' . $q . '
AND c.`id_category` != ' . Configuration::get('PS_ROOT_CATEGORY') . '
GROUP BY c.id_category
ORDER BY c.`id_category`, category_shop.`position`', true, false);
if (!$category) {
return false;
} else if (!file_exists(_PS_CAT_IMG_DIR_ . (int) $category['id_category'] . '.jpg')) {
$excluded[] = $category['id_category'];
return self::getNextCategory($image_type, $excluded);
} else {
return $category;
}
}
public static function getNextManufacturer($image_type, $excluded = [])
{
$q = '';
if (!empty($excluded)) {
$q .= 'AND c.`id_manufacturer` NOT IN (' . implode(',', $excluded) . ')';
}
$manufacturer = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT m.`id_manufacturer`
FROM `' . _DB_PREFIX_ . 'manufacturer` m'
. Shop::addSqlAssociation('manufacturer', 'm') .
' WHERE m.`id_manufacturer` NOT IN (
SELECT id_image FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "manufacturers" AND image_type = "' . $image_type . '"
)
' . $q . '
GROUP BY m.`id_manufacturer` ORDER BY m.`name` ASC');
if (!$manufacturer) {
return false;
} else if (!file_exists(_PS_MANU_IMG_DIR_ . $manufacturer['id_manufacturer'] . '.jpg') && !file_exists(_PS_MANU_IMG_DIR_ . Context::getContext()->language->iso_code . '.jpg')) {
$excluded[] = $manufacturer['id_manufacturer'];
return self::getNextManufacturer($image_type, $excluded);
} else {
return $manufacturer;
}
}
public static function getNextSupplier($image_type, $excluded = [])
{
$q = '';
if (!empty($excluded)) {
$q .= 's.`id_supplier` NOT IN (' . implode(',', $excluded) . ')';
}
$query = new DbQuery();
$query->select('s.`id_supplier`');
$query->from('supplier', 's');
$query->join(Shop::addSqlAssociation('supplier', 's'));
$query->where('s.`id_supplier` NOT IN (SELECT id_image FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "suppliers" AND image_type = "' . $image_type . '")');
if (!empty($q)) {
$query->where($q);
}
$query->orderBy('s.`name` ASC');
$query->groupBy('s.id_supplier');
$supplier = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query);
if (!$supplier) {
return false;
} else if (!file_exists(_PS_SUPP_IMG_DIR_ . $supplier['id_supplier'] . '.jpg') && !file_exists(_PS_SUPP_IMG_DIR_ . Context::getContext()->language->iso_code . '.jpg')) {
$excluded[] = $supplier['id_supplier'];
return self::getNextSupplier($image_type, $excluded);
} else {
return $supplier;
}
}
public static function getNextStore($image_type, $excluded = [])
{
$q = '';
if (!empty($excluded)) {
$q .= 'AND s.`id_store` NOT IN (' . implode(',', $excluded) . ')';
}
$store = Db::getInstance()->getRow(
'
SELECT s.`id_store`
FROM ' . _DB_PREFIX_ . 'store s
' . Shop::addSqlAssociation('store', 's') . '
WHERE s.active = 1
AND s.`id_store` NOT IN (
SELECT id_image FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "stores" AND image_type = "' . $image_type . '"
)
' . $q . '
GROUP BY s.`id_store`'
);
if (!$store) {
return false;
} else if (!file_exists(_PS_STORE_IMG_DIR_ . $store['id_store'] . '.jpg') && !file_exists(_PS_STORE_IMG_DIR_ . Context::getContext()->language->iso_code . '.jpg')) {
$excluded[] = $store['id_store'];
return self::getNextStore($image_type, $excluded);
} else {
return $store;
}
}
public static function getDoneImagesByType($type)
{
return array_map(function ($img) {
return $img['image_name'];
}, (array) Db::getinstance()->executeS('SELECT image_name FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "' . $type . '"'));
}
public static function checkForWarnings()
{
return (bool) Db::getinstance()->getValue('SELECT id_x13webp FROM `'._DB_PREFIX_.'x13webp` WHERE warning != ""');
}
public static function countWarningItems()
{
return (int) Db::getinstance()->getValue('SELECT count(x13webp) as amount FROM `'._DB_PREFIX_.'x13webp` WHERE warning != ""');
}
public static function getNextWarningItem($last)
{
$sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'x13webp` WHERE warning != ""';
if($last){
$sql .= ' AND id_x13webp > '.(int)$last;
}
$sql .= ' ORDER BY id_x13webp ASC';
return Db::getinstance()->getRow($sql);
}
public static function deleteImage($id_x13webp)
{
return Db::getInstance()->delete('x13webp', 'id_x13webp = '.(int)$id_x13webp);
}
public static function updateImageWarning($id_x13webp, $warning)
{
return Db::getInstance()->update('x13webp', ['warning' => $warning] ,'id_x13webp = '.(int)$id_x13webp);
}
public static function updateImageWarningCount($id_x13webp, $count)
{
return Db::getInstance()->update('x13webp', ['warning_count' => $count] ,'id_x13webp = '.(int)$id_x13webp);
}
}

View File

@@ -0,0 +1,184 @@
<?php
namespace X13Webp\Helpers;
use Configuration;
use Context;
use Image;
use ImageType;
use Module;
use Shop;
use Tools;
class X13Filter {
private $module;
public function __construct(Module $module)
{
$this->module = $module;
}
public function mapImageTypes(array $types)
{
$allowed = json_decode(Configuration::get($this->module->options_prefix . 'ALLOWED_GENERATED_IMAGES'), true);
return array_map(function ($item) use ($allowed) {
if ($item['has_types']) {
$item['types'] = ImageType::getImagesTypes($item['val']);
array_unshift($item['types'], [
'name' => 'main'
]);
} else {
$item['types'] = false;
}
$item['allowed'] = is_array($allowed) ? in_array($item['val'], $allowed) : false;
return $item;
}, $types);
}
public function mapImageType(array $item)
{
$item['all_items_done'] = false;
if ($item['has_types']) {
$image_types = ImageType::getImagesTypes($item['val']);
array_unshift($image_types, [
'name' => 'main'
]);
$item['total'] = $this->module->x13helper->getTotalImages($item['val']);
if (!empty($image_types)) {
foreach ($image_types as &$type) {
$type['done']['webp'] = X13Db::getTotalDoneImages($item['val'], $type['name']);
$type['done']['jpg'] = $item['total'];
$type['percent']['webp'] = $item['total'] != 0 ? Tools::ps_round($type['done']['webp'] * 100 / $item['total'], 2) : 100;
$type['percent']['jpg'] = 100;
}
}
unset($type);
$item['types'] = $image_types;
} else {
$item['types'] = false;
$item['total'] = $this->module->x13helper->getTotalImages($item['val']);
if ($item['val'] == 'theme') {
$done['webp'] = X13Db::getTotalDoneImages($item['val'] . '_' . _THEME_NAME_, '');
if (defined('_PARENT_THEME_NAME_') && !empty(_PARENT_THEME_NAME_)) {
$done['webp'] += X13Db::getTotalDoneImages($item['val'] . '_' . _PARENT_THEME_NAME_, '');
}
$item['done'] = $done;
} else {
$item['done']['webp'] = X13Db::getTotalDoneImages($item['val'], 'all');
}
$item['done']['jpg'] = $item['total'];
$item['percent']['webp'] = $item['total'] != 0 ? Tools::ps_round($item['done']['webp'] * 100 / $item['total'], 2) : 100;
$item['percent']['jpg'] = 100;
}
return $item;
}
public function productImagesToUriPath($images)
{
return array_map(function ($image) {
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_ . $image['id_image'] . '-' . Context::getContext()->shop->theme_name . '.jpg')) ? '-' . Context::getContext()->shop->theme_name : '');
$uriPath = Image::getImgFolderStatic($image['id_image']) . $image['id_image'] . $theme . '.jpg';
return $uriPath;
},$images);
}
public function filterHtmlForPicture($html)
{
// fix for x13lazyload module
$lazyload_fix = (bool)Configuration::get($this->module->options_prefix . 'FIX_LAZYLOAD_MODULE');
return preg_replace_callback('/(<img[^>]+>)/i', function ($matches) use($lazyload_fix){
$img = $matches[0];
$results = [];
if($lazyload_fix){
preg_match('/\bdata-original\s*=\s*([\'"])(.*?)([\'"])/u', $matches[0], $results);
}
if(empty($results)){
preg_match('/\bsrc\s*=\s*([\'"])(.*?)([\'"])/u', $matches[0], $results);
}
if (isset($results[2]) && !empty($results[2])) {
$quot = $results[1];
$webp_src = str_replace(array('.jpg', '.png'), '.webp', $results[2]);
if ($this->module->x13helper->checkWebpExistsFromUrl($webp_src)) {
$img = str_replace($img, '<picture><source srcset='. $quot . $webp_src . $quot.' type=' . $quot . 'image/webp' . $quot . '>' . str_replace('<img', '<img', $img) . '</picture>', $img);
}
}
return $img;
}, $html);
}
public function filterHtmlForWebpExtension($html)
{
return preg_replace_callback('/(<img[^>]+>)/i', function ($matches) {
$img = $matches[0];
$lazyload_fix = (bool)Configuration::get($this->module->options_prefix . 'FIX_LAZYLOAD_MODULE');
$results = [];
if($lazyload_fix){
preg_match('/\bdata-original\s*=\s*[\'"](.*?)[\'"]/u', $matches[0], $results);
}
if(empty($results)){
preg_match('/\bsrc\s*=\s*[\'"](.*?)[\'"]/u', $matches[0], $results);
}
if (isset($results[1]) && !empty($results[1])) {
$webp_src = str_replace(array('.jpg', '.png'), '.webp', $results[1]);
if ($this->module->x13helper->checkWebpExistsFromUrl($webp_src)) {
$img = str_replace(['png', 'jpg'], 'webp', $img);
}
}
return $img;
}, $html);
}
}

View File

@@ -0,0 +1,756 @@
<?php
namespace X13Webp\Helpers;
use Category;
use Configuration;
use Context;
use Db;
use Image;
use Manufacturer;
use Module;
use Shop;
use Supplier;
use Tools;
use X13Webp;
class X13Helper {
private $module;
public function __construct(Module $module)
{
$this->module = $module;
}
public function getExcludedOthersFiles()
{
$files = [];
for ($i = 0; $i < 10; $i++) {
$files[] = _PS_ROOT_DIR_ . '/img/p/' . $i . '.jpg';
}
return $files;
}
public function getExcludedOthersDirs()
{
return [
_PS_ROOT_DIR_ . '/modules',
_PS_ROOT_DIR_ . '/themes',
_PS_ROOT_DIR_ . '/img/cms',
_PS_ROOT_DIR_ . '/img/tmp',
_PS_ROOT_DIR_ . '/img/p/0',
_PS_ROOT_DIR_ . '/img/p/1',
_PS_ROOT_DIR_ . '/img/p/2',
_PS_ROOT_DIR_ . '/img/p/3',
_PS_ROOT_DIR_ . '/img/p/4',
_PS_ROOT_DIR_ . '/img/p/5',
_PS_ROOT_DIR_ . '/img/p/6',
_PS_ROOT_DIR_ . '/img/p/7',
_PS_ROOT_DIR_ . '/img/p/8',
_PS_ROOT_DIR_ . '/img/p/9',
_PS_ROOT_DIR_ . '/img/c',
_PS_ROOT_DIR_ . '/img/m',
_PS_ROOT_DIR_ . '/img/su',
_PS_ROOT_DIR_ . '/img/st'
];
}
public function getCronToken()
{
return md5(_COOKIE_KEY_ . Configuration::get('PS_SHOP_NAME') . 'sd3deebdc10c5');
}
public function getAvailableExtensions()
{
return ['jpg', 'png'];
}
public function scanForNextDirImage($dir, $excluded, $exluded_dirs = [])
{
foreach (scandir($dir) as $filename) {
if (in_array($filename, ['.', '..', 'index.php'])) continue;
$filePath = $dir . '/' . $filename;
if (in_array($filePath, $exluded_dirs)) continue;
if (in_array($filePath, $excluded)) continue;
if (is_dir($filePath)) {
foreach ($this->scanAllDirForImages($filePath, $exluded_dirs) as $childFilename) {
if (!in_array($filename . '/' . $childFilename, $excluded)) {
if (in_array($dir . '/' . $filename . '/' . $childFilename, $excluded)) continue;
return $filename . '/' . $childFilename;
}
}
} else {
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($ext, $this->getAvailableExtensions()) && !in_array($filename, $excluded)) {
return $filename;
}
}
}
return false;
}
public function scanAllDirForImages($dir, $excluded = [])
{
$result = [];
foreach (scandir($dir) as $filename) {
if (in_array($filename, ['.', '..', 'index.php'])) continue;
$filePath = $dir . '/' . $filename;
if (in_array($filePath, $excluded)) {
continue;
}
if (is_dir($filePath)) {
foreach ($this->scanAllDirForImages($filePath, $excluded) as $childFilename) {
$result[] = $filename . '/' . $childFilename;
}
} else {
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($ext, $this->getAvailableExtensions())) {
$result[] = $filename;
}
}
}
return $result;
}
public function getTotalCategoryImages($categories)
{
$total = 0;
$exists = [];
if (!empty($categories)) foreach ($categories as $category) {
if (file_exists(_PS_CAT_IMG_DIR_ . (int) $category['id_category'] . '.jpg')) {
$exists[] = [
'id_category' => $category['id_category']
];
$total += 1;
}
}
if (!empty($exists)) {
$str_exists = implode(',', array_map(function ($item) {
return $item['id_category'];
}, $exists));
$images = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'x13webp` WHERE id_image NOT IN (' . $str_exists . ') AND type = "categories"');
if (!empty($images)) foreach ($images as $image) {
$file = $this->getImageLink('categories', $image['id_image'], '-' . $image['image_type'], 'webp');
if (file_exists($file)) unlink($file);
}
Db::getInstance()->delete('x13webp', 'id_image NOT IN (' . $str_exists . ') AND type = "categories"');
}
return $exists;
}
public function getTotalManufacturerImages($manufacturers)
{
$images = [];
if (!empty($manufacturers)) foreach ($manufacturers as $manufacturer) {
if (file_exists(_PS_MANU_IMG_DIR_ . $manufacturer['id_manufacturer'] . '.jpg') || file_exists(_PS_MANU_IMG_DIR_ . Context::getContext()->language->iso_code . '.jpg')) {
$images[] = [
'id_manufacturer' => $manufacturer['id_manufacturer']
];
}
}
return $images;
}
public function getTotalSupplierImages($suppliers)
{
$images = [];
if (!empty($suppliers)) foreach ($suppliers as $supplier) {
if (file_exists(_PS_SUPP_IMG_DIR_ . $supplier['id_supplier'] . '.jpg') || file_exists(_PS_SUPP_IMG_DIR_ . Context::getContext()->language->iso_code . '.jpg')) {
$images[] = [
'id_supplier' => $supplier['id_supplier']
];
}
}
return $images;
}
public function getTotalStoreImages($stores)
{
$images = [];
if (!empty($stores)) foreach ($stores as $store) {
if (file_exists(_PS_STORE_IMG_DIR_ . $store['id_store'] . '.jpg') || file_exists(_PS_STORE_IMG_DIR_ . Context::getContext()->language->iso_code . '.jpg')) {
$images[] = [
'id_store' => $store['id_store']
];
}
}
return $images;
}
public function getTotalLogo()
{
if (!Configuration::hasKey('PS_LOGO')) {
return 0;
}
$logoFileName = Configuration::get('PS_LOGO');
$logoFileDir = _PS_IMG_DIR_ . $logoFileName;
if (!file_exists($logoFileDir)) {
return 0;
} else {
return 1;
}
}
public function scanProductDirForMainImages($dir)
{
$result = [];
foreach (scandir($dir) as $filename) {
if (in_array($filename, ['.', '..', 'index.php'])) continue;
$filePath = $dir . '/' . $filename;
if (is_dir($filePath)) {
if (empty(array_diff(scandir($filePath), ['.', '..', 'index.php', 'fileType']))) {
$this->module->x13cleaner->removeProductImageDir($filePath);
} else {
foreach ($this->scanProductDirForMainImages($filePath) as $childFilename) {
$ext = pathinfo($childFilename, PATHINFO_EXTENSION);
if (!is_numeric(str_replace('.' . $ext, '', basename($childFilename)))) continue;
$result[] = $filename . '/' . $childFilename;
}
}
} else {
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($ext, $this->getAvailableExtensions()) && is_numeric(str_replace('.' . $ext, '', $filename))) {
$result[] = $filename;
}
}
}
return $result;
}
public function getImgDirFromType($type)
{
switch ($type) {
case 'products':
return _PS_PROD_IMG_DIR_;
break;
case 'categories':
return _PS_CAT_IMG_DIR_;
break;
case 'manufacturers':
return _PS_MANU_IMG_DIR_;
break;
case 'stores':
return _PS_STORE_IMG_DIR_;
break;
case 'suppliers':
return _PS_SUPP_IMG_DIR_;
break;
default:
return false;
break;
}
}
// public function scanForEmptyDir($dir)
// {
// $result = [];
// foreach (scandir($dir) as $filename) {
// if (in_array($filename, ['.', '..', 'index.php', 'fileType'])) continue;
// $filePath = $dir . '/' . $filename;
// if (is_dir($filePath)) {
// if (empty(array_diff(scandir($filePath), ['.', '..', 'index.php', 'fileType']))) {
// $result[] = $filePath;
// }
// foreach ($this->scanForEmptyDir($filePath) as $childFilename) {
// $result[] = $childFilename;
// }
// }
// }
// return $result;
// }
public function getFilesList($dir, $subdir = false)
{
$output = false;
if ($subdir) {
$dir = $dir . '/' . $subdir;
}
if (is_dir($dir)) {
$output = array_values(array_filter(array_map(function ($file) use ($dir, $subdir) {
$path = $dir . '/' . $file;
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($path, $this->getExcludedOthersFiles())) {
return false;
} else if (is_dir($dir . '/' . $file) && !in_array($path, $this->getExcludedOthersDirs())) {
$curdir = $subdir ? $subdir . '/' . $file : $file;
$others = (array) Db::getInstance()->executeS('SELECT image_name FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "others" AND image_name LIKE "%' . $curdir . '%"');
return [
'name' => $file,
'path' => $path,
'type' => 'dir',
'exists' => (bool) !$this->scanForNextDirImage($path, array_merge($this->getExcludedOthersFiles(), array_map(function ($dbitem) use ($curdir) {
return str_replace($curdir . '/', '', $dbitem['image_name']);
}, $others)), $this->getExcludedOthersDirs())
];
} else if (in_array($ext, $this->getAvailableExtensions()) && $file != Configuration::get('PS_LOGO')) {
$item = !empty($subdir) ? $subdir . '/' . $file : $file;
return [
'name' => $file,
'path' => $path,
'type' => 'image',
'exists' => X13Db::checkFileExists(0, 'others', 'all', $item)
];
} else {
return false;
}
}, array_diff(scandir($dir), array_merge(['.', '..', 'index.php'], $this->getExcludedOthersFiles())))));
}
return $output;
}
public function getImageTypes()
{
return array(
'products' => array(
'val' => 'products',
'name' => X13Webp::getTranslationByKey('Products'),
'image_name' => X13Webp::getTranslationByKey('Product image'),
'image_name_del' => X13Webp::getTranslationByKey('Product images'),
'has_types' => true,
'types_info' => false
),
'categories' => array(
'val' => 'categories',
'name' => X13Webp::getTranslationByKey('Categories'),
'image_name' => X13Webp::getTranslationByKey('Category image'),
'image_name_del' => X13Webp::getTranslationByKey('Category images'),
'has_types' => true,
'types_info' => false
),
'manufacturers' => array(
'val' => 'manufacturers',
'name' => X13Webp::getTranslationByKey('Manufacturers'),
'image_name' => X13Webp::getTranslationByKey('Manufacturers image'),
'image_name_del' => X13Webp::getTranslationByKey('Manufacturers images'),
'has_types' => true,
'types_info' => false
),
'suppliers' => array(
'val' => 'suppliers',
'name' => X13Webp::getTranslationByKey('Suppliers'),
'image_name' => X13Webp::getTranslationByKey('Suppliers image'),
'image_name_del' => X13Webp::getTranslationByKey('Suppliers images'),
'has_types' => true,
'types_info' => false
),
'stores' => array(
'val' => 'stores',
'name' => X13Webp::getTranslationByKey('Stores'),
'image_name' => X13Webp::getTranslationByKey('Stores image'),
'image_name_del' => X13Webp::getTranslationByKey('Stores images'),
'has_types' => true,
'types_info' => false
),
'cms' => array(
'val' => 'cms',
'name' => X13Webp::getTranslationByKey('CMS images'),
'image_name' => X13Webp::getTranslationByKey('CMS image'),
'image_name_del' => X13Webp::getTranslationByKey('CMS images'),
'has_types' => false,
'types_info' => X13Webp::getTranslationByKey('All images in the /img/cms/ folder')
),
'modules' => array(
'val' => 'modules',
'name' => X13Webp::getTranslationByKey('Module images'),
'image_name' => X13Webp::getTranslationByKey('Module image'),
'image_name_del' => X13Webp::getTranslationByKey('Module images'),
'has_types' => false,
'types_info' => X13Webp::getTranslationByKey('All images in the /modules/ folder')
),
'theme' => array(
'val' => 'theme',
'name' => X13Webp::getTranslationByKey('Theme images'),
'image_name' => X13Webp::getTranslationByKey('Theme image'),
'image_name_del' => X13Webp::getTranslationByKey('Theme images'),
'has_types' => false,
'types_info' => X13Webp::getTranslationByKey('All images in theme')
),
'logo' => array(
'val' => 'logo',
'name' => X13Webp::getTranslationByKey('Store logo'),
'image_name' => X13Webp::getTranslationByKey('Store logo'),
'image_name_del' => X13Webp::getTranslationByKey('Store logo'),
'has_types' => false,
'types_info' => X13Webp::getTranslationByKey('Logo')
),
'others' => array(
'val' => 'others',
'name' => X13Webp::getTranslationByKey('Others'),
'image_name' => X13Webp::getTranslationByKey('Others image'),
'image_name_del' => X13Webp::getTranslationByKey('Others images'),
'has_types' => false,
'types_info' => X13Webp::getTranslationByKey('Others')
)
);
}
public function scanImageDirForMainObjectImages($dir, $main_dir_only = false)
{
$result = [];
foreach (scandir($dir) as $filename) {
if (in_array($filename, ['.', '..', 'index.php'])) continue;
$filePath = $dir . '/' . $filename;
if (is_dir($filePath)) {
if (!$main_dir_only) {
foreach ($this->scanImageDirForMainObjectImages($filePath) as $childFilename) {
$ext = pathinfo($childFilename, PATHINFO_EXTENSION);
if (!is_numeric(str_replace('.' . $ext, '', basename($childFilename)))) continue;
$result[] = $filename . '/' . $childFilename;
}
}
} else {
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($ext, $this->getAvailableExtensions()) && is_numeric(str_replace('.' . $ext, '', $filename))) {
$result[] = $filename;
}
}
}
return $result;
}
public static function getImageLink($format, $id, $nameImageType, $type)
{
$id = (int)$id;
$uriPath = '';
switch ($format) {
case "products":
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_ . $id . ($nameImageType ? '-' . $nameImageType : '') . '-' . Context::getContext()->shop->theme_name . '.jpg')) ? '-' . Context::getContext()->shop->theme_name : '');
$uriPath = Image::getImgFolderStatic($id) . $id . ($nameImageType ? '-' . $nameImageType : '') . $theme . '.' . $type;
$uriPath = _PS_PROD_IMG_DIR_ . $uriPath;
break;
case "categories":
$uriPath_webp = $id . ($nameImageType ? $nameImageType : '') . '.' . $type;
$uriPath = _PS_CAT_IMG_DIR_ . $uriPath_webp;
break;
case "manufacturers":
if (file_exists(_PS_MANU_IMG_DIR_ . $id . (empty($nameImageType) ? '.jpg' : '-' . $nameImageType . '.jpg'))) {
$uriPath = _PS_MANU_IMG_DIR_ . $id . (empty($nameImageType) ? '.' . $type : '-' . $nameImageType . '.' . $type);
} elseif (!empty($nameImageType) && file_exists(_PS_MANU_IMG_DIR_ . $id . '.jpg')) {
$uriPath = _PS_MANU_IMG_DIR_ . $id . '.' . $type;
} elseif (file_exists(_PS_MANU_IMG_DIR_ . Context::getContext()->language->iso_code . (empty($nameImageType) ? '.jpg' : '-default-' . $nameImageType . '.jpg'))) {
$uriPath = _PS_MANU_IMG_DIR_ . Context::getContext()->language->iso_code . (empty($nameImageType) ? '.' . $type : '-default-' . $nameImageType . '.' . $type);
} else {
$uriPath = _PS_MANU_IMG_DIR_ . Context::getContext()->language->iso_code . '.' . $type;
}
break;
case "suppliers":
if (file_exists(_PS_SUPP_IMG_DIR_ . $id . (empty($nameImageType) ? '.jpg' : '-' . $nameImageType . '.jpg'))) {
$uriPath = _PS_SUPP_IMG_DIR_ . $id . (empty($nameImageType) ? '.' . $type : '-' . $nameImageType . '.' . $type);
} elseif (!empty($nameImageType) && file_exists(_PS_SUPP_IMG_DIR_ . $id . '.jpg')) {
$uriPath = _PS_SUPP_IMG_DIR_ . $id . '.' . $type;
} elseif (file_exists(_PS_SUPP_IMG_DIR_ . Context::getContext()->language->iso_code . (empty($nameImageType) ? '.jpg' : '-default-' . $nameImageType . '.jpg'))) {
$uriPath = _PS_SUPP_IMG_DIR_ . Context::getContext()->language->iso_code . (empty($nameImageType) ? '.' . $type : '-default-' . $nameImageType . '.' . $type);
} else {
$uriPath = _PS_SUPP_IMG_DIR_ . Context::getContext()->language->iso_code . '.' . $type;
}
break;
case "stores":
if (file_exists(_PS_STORE_IMG_DIR_ . $id . (empty($nameImageType) ? '.jpg' : '-' . $nameImageType . '.jpg'))) {
$uriPath = _PS_STORE_IMG_DIR_ . $id . (empty($nameImageType) ? '.' . $type : '-' . $nameImageType . '.' . $type);
} elseif (!empty($nameImageType) && file_exists(_PS_STORE_IMG_DIR_ . $id . '.jpg')) {
$uriPath = _PS_STORE_IMG_DIR_ . $id . '.' . $type;
} elseif (file_exists(_PS_STORE_IMG_DIR_ . Context::getContext()->language->iso_code . (empty($nameImageType) ? '.jpg' : $nameImageType . '.jpg'))) {
$uriPath = _PS_STORE_IMG_DIR_ . Context::getContext()->language->iso_code . (empty($nameImageType) ? '.' . $type : $nameImageType . '.' . $type);
} else {
$uriPath = _PS_STORE_IMG_DIR_ . Context::getContext()->language->iso_code . '.' . $type;
}
break;
}
return $uriPath;
}
public function getTotalImages($type)
{
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
switch ($type) {
case 'products':
return count(Image::getAllImages());
break;
case 'categories':
$categories = Category::getSimpleCategories(Context::getContext()->language->id);
return count($this->getTotalCategoryImages($categories));
break;
case 'manufacturers':
$manufacturers = Manufacturer::getManufacturers(false, Context::getContext()->language->id, true, false, false, false, true);
return count($this->getTotalManufacturerImages($manufacturers));
break;
case 'suppliers':
$suppliers = Supplier::getSuppliers(false, Context::getContext()->language->id, false);
return count($this->getTotalSupplierImages($suppliers));
case 'stores':
$stores = $this->getStores();
return count($this->getTotalStoreImages($stores));
break;
case 'cms':
$images = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "' . $type . '"');
$scan = $this->scanAllDirForImages(_PS_IMG_DIR_ . 'cms');
if (!empty($images)) {
foreach ($images as $image) {
if (!in_array($image['image_name'], $scan)) {
Db::getInstance()->delete('x13webp', 'id_x13webp = ' . (int)$image['id_x13webp']);
}
}
}
return count($this->scanAllDirForImages(_PS_IMG_DIR_ . 'cms'));
break;
case 'modules':
$images = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'x13webp` WHERE type = "' . $type . '"');
$scan = $this->scanAllDirForImages(_PS_MODULE_DIR_);
if (!empty($images)) {
foreach ($images as $image) {
if (!in_array($image['image_name'], $scan)) {
Db::getInstance()->delete('x13webp', 'id_x13webp = ' . (int)$image['id_x13webp']);
}
}
}
return count($scan);
break;
case 'theme':
$scan_child = $this->scanAllDirForImages(_PS_THEME_DIR_);
if (defined('_PS_PARENT_THEME_DIR_') && !empty(_PS_PARENT_THEME_DIR_)) {
$scan_parent = $this->scanAllDirForImages(_PS_PARENT_THEME_DIR_);
} else {
$scan_parent = [];
}
$scan = array_merge($scan_child, $scan_parent);
$parent_theme = defined('_PS_PARENT_THEME_DIR_') ? ' OR type = "theme_' . _PARENT_THEME_NAME_ . '"' : '';
$images = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'x13webp` WHERE (type = "theme_' . _THEME_NAME_ . '" ' . $parent_theme . ')');
if (!empty($images)) {
foreach ($images as $image) {
if (!in_array($image['image_name'], $scan)) {
Db::getInstance()->delete('x13webp', 'id_x13webp = ' . (int)$image['id_x13webp']);
}
}
}
return count($scan);
break;
case 'logo':
return $this->getTotalLogo();
break;
case 'others':
return count($this->scanAllDirForImages(_PS_ROOT_DIR_, array_merge($this->getExcludedOthersFiles(), $this->getExcludedOthersDirs())));
break;
default:
return 0;
break;
}
}
public function getStores()
{
if (Tools::version_compare(_PS_VERSION_, '1.7', '>=')) {
return Db::getInstance()->executeS(
'
SELECT s.id_store AS `id`, s.*, sl.*
FROM ' . _DB_PREFIX_ . 'store s
' . Shop::addSqlAssociation('store', 's') . '
LEFT JOIN ' . _DB_PREFIX_ . 'store_lang sl ON (
sl.id_store = s.id_store
AND sl.id_lang = ' . (int) Context::getContext()->language->id . '
)
WHERE s.active = 1 GROUP BY s.`id_store`'
);
} else {
return Db::getInstance()->executeS(
'
SELECT s.id_store AS `id`, s.*
FROM ' . _DB_PREFIX_ . 'store s
' . Shop::addSqlAssociation('store', 's') . '
WHERE s.active = 1 GROUP BY s.`id_store`'
);
}
}
public function checkWebpExistsFromUrl($url)
{
$jpg = str_replace('.webp', '.jpg', $url);
if (strpos($jpg,
'/c/'
) !== false) {
preg_match("/c\/([0-9]+)-?([a-zA-Z_-]+)?\/.+\.jpg$/", $jpg, $matches);
if (!empty($matches)) {
if (file_exists(_PS_ROOT_DIR_ . '/img/c/' . $matches[1] . '-' . $matches[2] . '.webp')) {
return true;
} else if (file_exists(_PS_ROOT_DIR_ . '/img/c/' . $matches[1] . '.webp') && empty($matches[2])) {
return true;
} else {
return false;
}
}
}
if (strpos($jpg, '/m/') !== false) {
preg_match("/m\/([0-9]+)-?([a-zA-Z_-]+)?\/.+\.jpg$/", $jpg,
$matches
);
if (!empty($matches)) {
if (file_exists(_PS_ROOT_DIR_ . '/img/m/' . $matches[1] . '-' . $matches[2] . '.webp')) {
return true;
} elseif (file_exists(_PS_ROOT_DIR_ . '/img/m/' . $matches[1] . '.webp') && empty($matches[2])) {
return true;
} else {
return false;
}
}
}
if (strpos($jpg, '/su/') !== false) {
preg_match("/su\/([0-9]+)-?([a-zA-Z_-]+)?\/.+\.jpg$/", $jpg, $matches);
if (!empty($matches)) {
if (isset($matches[2]) && file_exists(_PS_ROOT_DIR_ . '/img/su/' . $matches[1] . '-' . $matches[2] . '.webp')) {
return true;
} else if (file_exists(_PS_ROOT_DIR_ . '/img/su/' . $matches[1] . '.webp') && empty($matches[2])) {
return true;
} else {
return false;
}
}
}
if (strpos($jpg, '/st/') !== false) {
preg_match("/st\/([0-9]+)-?([a-zA-Z_-]+)?\/.+\.jpg$/", $jpg, $matches);
if (!empty($matches)) {
if (file_exists(_PS_ROOT_DIR_ . '/img/st/' . $matches[1] . '-' . $matches[2] . '.webp')) {
return true;
} else if (file_exists(_PS_ROOT_DIR_ . '/img/st/' . $matches[1] . '.webp') && empty($matches[2])) {
return true;
} else {
return false;
}
}
}
preg_match("/\/([0-9]+)-([a-zA-Z_-]+)?\/.+\.jpg$/", $jpg, $matches);
if (isset($matches[2])) {
$dir = implode('/', str_split($matches[1]));
if (file_exists(_PS_ROOT_DIR_ . '/img/p/' . $dir . '/' . $matches[1] . '-' . $matches[2] . '.webp')) {
return true;
} else if (file_exists(_PS_ROOT_DIR_ . '/img/p/' . $dir . '/' . $matches[1] . '.webp') && empty($matches[2])) {
return true;
} else {
return false;
}
}
$parse_url = parse_url($url);
$path = __PS_BASE_URI__ == '/' ? $parse_url['path'] : str_replace(__PS_BASE_URI__, '', $parse_url['path']);
if (isset($parse_url['path']) && !empty($parse_url['path']) && file_exists(_PS_ROOT_DIR_ . '/' . str_replace(array('.jpg', '.png'), '.webp', $path))) {
return true;
}
return false;
}
public function getTypeName($type)
{
$types = $this->getImageTypes();
if ($type == 'theme_' . _THEME_NAME_ || defined('_PARENT_THEME_NAME_') && !empty(_PARENT_THEME_NAME_) && $type == 'theme_' . _PARENT_THEME_NAME_) {
$type_name = isset($types['theme']['image_name']) ? $types['theme']['image_name'] : $type;
} else {
$type_name = isset($types[$type]['image_name']) ? $types[$type]['image_name'] : $type;
}
return $type_name;
}
public function getDeleteTypeName($type)
{
$types = $this->getImageTypes();
if ($type == 'theme_' . _THEME_NAME_ || defined('_PARENT_THEME_NAME_') && !empty(_PARENT_THEME_NAME_) && $type == 'theme_' . _PARENT_THEME_NAME_) {
$type_name = isset($types['theme']['image_name_del']) ? $types['theme']['image_name_del'] : $type;
} else {
$type_name = isset($types[$type]['image_name_del']) ? $types[$type]['image_name_del'] : $type;
}
return $type_name;
}
public function scanDirForAllFiles($dir)
{
$result = [];
foreach (scandir($dir) as $filename) {
if (in_array($filename, ['.', '..', 'index.php'])) continue;
$filePath = $dir . '/' . $filename;
if (is_dir($filePath)) {
foreach ($this->scanDirForAllFiles($filePath) as $childFilename) {
$result[] = $filename . '/' . $childFilename;
}
} else {
$result[] = $filename;
}
}
return $result;
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace X13Webp\Loggers;
use WebPConvert\Loggers\BaseLogger;
class FileLogger extends BaseLogger
{
private $path = _PS_MODULE_DIR_ . "x13webp/logs/logs.txt";
/**
* Handle log() by echoing the message.
*
* @param string $msg message to log
* @param string $style style (null | bold | italic)
* @return void
*/
public function log($msg, $style = '')
{
if(!file_exists(_PS_MODULE_DIR_ . 'x13webp/logs')){
mkdir(_PS_MODULE_DIR_ . 'x13webp/logs');
}
$file = fopen($this->path, "a");
$msg = htmlspecialchars($msg);
fwrite($file, '[');
fwrite($file, date('Y-m-d H:i:s'));
fwrite($file, '] ');
fwrite($file, $msg);
fclose($file);
}
/**
* Handle ln by echoing a <br> tag.
*
* @return void
*/
public function ln()
{
$file = fopen($this->path, "a");
fwrite($file, PHP_EOL);
fclose($file);
}
}

View File

@@ -0,0 +1,35 @@
<?php
/*
* 2007-2014 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2014 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

View File

@@ -0,0 +1,35 @@
<?php
/*
* 2007-2022 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2014 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,208 @@
<?php
global $_MODULE;
$_MODULE = array();
$_MODULE['<{x13webp}prestashop>x13webp_ea7539e2d6767b6628ed6ed327747944'] = 'Przed odinstalowaniem modułu, upewnij się że wszystkie zdjęcia WebP zostały usunięte';
$_MODULE['<{x13webp}prestashop>x13webp_ef470246fa21232b86a8dfe3acc9d62c'] = 'WebP - konwersja zdjęć do formatu nowej generacji';
$_MODULE['<{x13webp}prestashop>x13webp_f09a520b1814a149eab7b443359352c3'] = 'Zaawansowany moduł umożliwiający szybką konwersję zdjęć do formatu nowej generacji zdjęć. Moduł umożliwia konwersję wszystkich zdjęć ze sklepu do formatu WebP za pomocą AJAXA, zadań CRON oraz generowania zdjęć w locie.';
$_MODULE['<{x13webp}prestashop>x13webp_f4f70727dc34561dfde1a3c529b6205c'] = 'Ustawienia';
$_MODULE['<{x13webp}prestashop>x13webp_00d23a76e43b46dae9ec7aa9dcbebb32'] = 'Włączony';
$_MODULE['<{x13webp}prestashop>x13webp_b9f5c797ebbf55adccdd8539a65a0241'] = 'Wyłączony';
$_MODULE['<{x13webp}prestashop>x13webp_c9cc8cce247e49bae79f15173ce97354'] = 'Zapisz';
$_MODULE['<{x13webp}prestashop>x13webp_79d34572f63cd7e6fdf6908418b1a1f0'] = '%s zdjęć produktów zostało usuniętych';
$_MODULE['<{x13webp}prestashop>x13webp_e3efb202244c119f09038a9fe1e436ab'] = 'Brak zdjęć do usunięcia';
$_MODULE['<{x13webp}prestashop>x13webp_34b80e661d901dda008417391b05c819'] = 'Folder TMP został oczysczony, usunięto %s zdjęć';
$_MODULE['<{x13webp}prestashop>x13webp_8abc9e5b2d92b44ae966dfac1728ceab'] = 'Wystąpił bład';
$_MODULE['<{x13webp}prestashop>x13webp_578f3e2845003263d5081a09dfa3bde8'] = '%s zbędnych zdjęć zostało usuniętych ';
$_MODULE['<{x13webp}prestashop>x13webp_159be9d2b62a25601bc570189de4eded'] = 'Nowa wersja modułu %s jest już dostępna! - pobierz ją z x13.pl';
$_MODULE['<{x13webp}prestashop>x13webp_deb10517653c255364175796ace3553f'] = 'Produkt';
$_MODULE['<{x13webp}prestashop>x13webp_536cf455d663873a6b9d3c42d767f753'] = 'Wystąpił błąd podczas dodawania zdjęcia do bazy danych';
$_MODULE['<{x13webp}prestashop>x13webp_5fb012a3c1cceabd7e0b34015084bc8a'] = 'Wystąpił błąd podczas pobierania następnego zdjęcia';
$_MODULE['<{x13webp}prestashop>x13webp_3adbdb3ac060038aa0e6e6c138ef9873'] = 'Kategoria';
$_MODULE['<{x13webp}prestashop>x13webp_c0bd7654d5b278e65f21cf4e9153fdb4'] = 'Producent';
$_MODULE['<{x13webp}prestashop>x13webp_ec136b444eede3bc85639fac0dd06229'] = 'Dostawca';
$_MODULE['<{x13webp}prestashop>x13webp_fdb0c388de01d545017cdf9ccf00eb72'] = 'Sklep';
$_MODULE['<{x13webp}prestashop>x13webp_8ae43c1d1bd3a09ee0d79af01accaed1'] = 'Zdjęcie ze strony CMS';
$_MODULE['<{x13webp}prestashop>x13webp_a17b1b8e416f7b2c6bb140c1d16de308'] = 'Zdjęcie z modułu';
$_MODULE['<{x13webp}prestashop>x13webp_6e64380b3bef72a0c0db00b26c0e5f06'] = 'Zdjęcie z szablonu';
$_MODULE['<{x13webp}prestashop>x13webp_8c2857a9ad1d8f31659e35e904e20fa6'] = 'Logo';
$_MODULE['<{x13webp}prestashop>x13webp_52ef9633d88a7480b3a938ff9eaa2a25'] = 'Pozostałe';
$_MODULE['<{x13webp}prestashop>x13webp_a65112f5fcdbf65135f35de151b0f167'] = 'Czy na pewno chcesz wygenerować ponownie zdjęcia?';
$_MODULE['<{x13webp}prestashop>x13webp_064c0ca597eb4b7f663b88d94ccb7106'] = 'Nie możesz tego zrobić, dopóki nie zakończy się obecny proces';
$_MODULE['<{x13webp}prestashop>x13webp_4d3d769b812b6faa6b76e1a8abaece2d'] = 'Aktwyne';
$_MODULE['<{x13webp}prestashop>x13webp_b2abc67e4a4bfd250eec8883d27e4c16'] = 'Nieaktywne';
$_MODULE['<{x13webp}prestashop>x13webp_bfbeeee46d14338e2cb15de40dd46048'] = 'Jeśli chcesz wygenerować zdjęcia, musisz najpierw włączyć moduł';
$_MODULE['<{x13webp}prestashop>x13webp_e74f23da6df1be4a267bbeecc0885091'] = 'Brak zdjęć w tym folderze';
$_MODULE['<{x13webp}prestashop>x13webp_642894fbcafca028bdc936bf14fe0ac9'] = 'Wystąpił problem';
$_MODULE['<{x13webp}prestashop>x13webp_068f80c7519d0528fb08e82137a72131'] = 'Produkty';
$_MODULE['<{x13webp}prestashop>x13webp_af1b98adf7f686b84cd0b443e022b7a0'] = 'Kategorie';
$_MODULE['<{x13webp}prestashop>x13webp_2377be3c2ad9b435ba277a73f0f1ca76'] = 'Producenci';
$_MODULE['<{x13webp}prestashop>x13webp_1814d65a76028fdfbadab64a5a8076df'] = 'Dostawcy';
$_MODULE['<{x13webp}prestashop>x13webp_821b8ee6937cec96c30fdafbfe836d68'] = 'Sklepy';
$_MODULE['<{x13webp}prestashop>x13webp_01626b0f006ef81cc7ee50590d5bb7bd'] = 'Zdjęcia CMS';
$_MODULE['<{x13webp}prestashop>x13webp_85625da2fc8dac2b8173ab95d8d259fd'] = 'Wszystkie zdjęcia z folderu /img/cms/';
$_MODULE['<{x13webp}prestashop>x13webp_842d8dbf06bcaadcef614dc6ca7cd3eb'] = 'Zdjęcia z modułów';
$_MODULE['<{x13webp}prestashop>x13webp_74df10ad7ad31874b7ab2507155e3bba'] = 'Wszystkie zdjęcia z folderu /modules/';
$_MODULE['<{x13webp}prestashop>x13webp_ac057490fbcbb2a554afe99fa3aa8c8e'] = 'Zdjęcia z szablonu';
$_MODULE['<{x13webp}prestashop>x13webp_2df8b776e265c3521ac02b40a8f0685e'] = 'Wszystkie zdjęcia z szablonu';
$_MODULE['<{x13webp}prestashop>x13webp_071b267bd8a414d852ffb391f1589539'] = 'Logo sklepu';
$_MODULE['<{x13webp}prestashop>x13webp_f92965e2c8a7afb3c1b9a5c09a263636'] = 'Zrobione';
$_MODULE['<{x13webp}prestashop>x13webp_5b4b548fdfb7782a16c43c3f73c14bac'] = 'Nie możesz tego zrobić, dopóki inne procesy się nie zostaną zakończone';
$_MODULE['<{x13webp}prestashop>x13webp_505a83f220c02df2f85c3810cd9ceb38'] = 'wygenerowano pomyślnie';
$_MODULE['<{x13webp}prestashop>x13webp_a3b9d2cd764b05f4be59cba8f03c01e4'] = 'Produkt zdjęcie';
$_MODULE['<{x13webp}prestashop>x13webp_92d7981ef356bbf4654db23d375ad89f'] = 'Kategoria zdjęcie';
$_MODULE['<{x13webp}prestashop>x13webp_0145d4ffb1d03763884a3f6a3d53f2c1'] = 'Producent zdjęcie';
$_MODULE['<{x13webp}prestashop>x13webp_cde755ebd945203cd259773c08616a61'] = 'Dostawca zdjęcie';
$_MODULE['<{x13webp}prestashop>x13webp_94f036fc59f598687bb4a336efc2b9a2'] = 'Zdjęcie sklepu';
$_MODULE['<{x13webp}prestashop>x13webp_d54f592af02bd4ed669812a1a4451272'] = 'Pozostałe zdjęcie';
$_MODULE['<{x13webp}prestashop>x13webp_2c595b4f6d0c5d25b9c326fcb9738e33'] = 'Zdjęcia produktów';
$_MODULE['<{x13webp}prestashop>x13webp_e454381618da3ec4d3b8384b6358efd3'] = 'Zdjęcia kategorii';
$_MODULE['<{x13webp}prestashop>x13webp_30625afc7fc927cd1c1fd392fc020558'] = 'Zdjęcia producentów';
$_MODULE['<{x13webp}prestashop>x13webp_4ed44aef79248f8f70421b65da089d4c'] = 'Zdjęcia dostawców';
$_MODULE['<{x13webp}prestashop>x13webp_9f2cc353c9382328f87d86fb455ad682'] = 'Zdjęcia sklepów';
$_MODULE['<{x13webp}prestashop>x13webp_6d8cb06c0657f4f992d17d7e1be4e35f'] = 'Pozostałe zdjęcia';
$_MODULE['<{x13webp}prestashop>form_e14d3096743440170ed3a0082e49d441'] = 'Włącz obsługę zdjęć w formacie WebP';
$_MODULE['<{x13webp}prestashop>form_93cba07454f06a4a960172bbd6e2a435'] = 'Tak';
$_MODULE['<{x13webp}prestashop>form_bafd7322c6e97d25b6299b5d6fe8920b'] = 'Nie';
$_MODULE['<{x13webp}prestashop>form_35fbba9f7ad30c2638f45b5d356ee697'] = 'Automatycznie generuj zdjęcia WebP dla nowych produktów, kategorii itd.';
$_MODULE['<{x13webp}prestashop>form_5815bed40447da431f0bb736ade11aca'] = 'Tryb działania modułu';
$_MODULE['<{x13webp}prestashop>form_e17ae6aa8491184eecf8907612eeaf7b'] = 'Wygeneruj wszystkie brakujące zdjęcia WebP podczas pierwszego wczytania strony';
$_MODULE['<{x13webp}prestashop>form_ec2be923ad261849d8aebf40c1a467d0'] = 'Korzystaj tylko z wcześniej wygenerowanych zdjęć WebP';
$_MODULE['<{x13webp}prestashop>form_7771aeb48052063e99cf06a65383abf1'] = 'Generuj zdjęcia dla';
$_MODULE['<{x13webp}prestashop>form_c2f4f97cd5f7f386ff26427c0d4b178a'] = 'Zalecamy wygenerowanie pierwszy raz zdjęć za pomocą wbudowanego rozwiązania';
$_MODULE['<{x13webp}prestashop>form_ffd2d8a44c3db9a005dc0296f32d2f32'] = 'generowania zdjęć za pomocą AJAX';
$_MODULE['<{x13webp}prestashop>form_92bdd4443f877aad13b4997f526924a1'] = 'Ustawienia kompresji zdjęć';
$_MODULE['<{x13webp}prestashop>form_0210b4b2d375efcc09acb15cde8ac347'] = 'Typ konwersji zdjęć';
$_MODULE['<{x13webp}prestashop>form_b43d8ab1087e480ee83c4f7e4ba34f53'] = 'EWW - klucz API';
$_MODULE['<{x13webp}prestashop>form_35c9d340e3eaac6008b00d6df48f6569'] = 'WPC - klucz API';
$_MODULE['<{x13webp}prestashop>form_a508b84dc1683420871549072f42ea7f'] = 'WPC - secret';
$_MODULE['<{x13webp}prestashop>form_1a3069721b50e35eaad9e1e3ffe92737'] = 'WPC - adres URL';
$_MODULE['<{x13webp}prestashop>form_03ef1270a06aed7da15591c385e775e3'] = 'WPC - wersja API';
$_MODULE['<{x13webp}prestashop>form_7d805fc9adc62988f2c89ea7b0fe97ee'] = 'WPC - zamaskuj klucz API podczas transferu';
$_MODULE['<{x13webp}prestashop>form_169a6f6b44766410bffebf76ff3dcf17'] = 'Kodowanie';
$_MODULE['<{x13webp}prestashop>form_06b9281e396db002010bde1de57262eb'] = 'Automatyczne';
$_MODULE['<{x13webp}prestashop>form_b7048ff6b4f97b9230b2365b31d16713'] = 'Bezstratne';
$_MODULE['<{x13webp}prestashop>form_b71142391f68646086edeadddcf020dc'] = 'Stratne';
$_MODULE['<{x13webp}prestashop>form_c92eed4c0fb325645e0b299014fc842e'] = 'Jakość zdjęć (%)';
$_MODULE['<{x13webp}prestashop>form_10aed225e4002f163bdc40c86bf98497'] = 'Auto limit';
$_MODULE['<{x13webp}prestashop>form_a1a758f4cd3aa8ca15fab7f01bd74e40'] = 'Jakość przezroczystości (%)';
$_MODULE['<{x13webp}prestashop>form_71833bb12ff341d1432f18b9cfa7b3e6'] = 'Nie obsługuje obrazów JPEG';
$_MODULE['<{x13webp}prestashop>form_5f86f57c541bb8a7b6652d8c04874a13'] = 'Prawie bezstratne';
$_MODULE['<{x13webp}prestashop>form_df275b4f1a5c609c772bbb43c48b607d'] = 'Ta opcja umożliwia uzyskanie lepszej kompresji dla opcji bezstratnej, z minimalnym wpływem nna jakość zdjęcia';
$_MODULE['<{x13webp}prestashop>form_7034638701c3bbfe812305fe2c901585'] = 'Przenieść metadane do zdjęć WebP';
$_MODULE['<{x13webp}prestashop>form_6adf97f83acf6453d4a6a4b1070f3754'] = 'Żadne';
$_MODULE['<{x13webp}prestashop>form_b1c94ca2fbc3e78fc30069c8d0f01680'] = 'Wszystkie';
$_MODULE['<{x13webp}prestashop>form_ff0306e2bb289f22c8ed170d64f0cf51'] = 'EXIF';
$_MODULE['<{x13webp}prestashop>form_b6b8d73d401b7611fac37ab11898f598'] = 'ICC';
$_MODULE['<{x13webp}prestashop>form_1821c32401ba48c8a1fdb0e5108c45b8'] = 'XMP';
$_MODULE['<{x13webp}prestashop>form_edf35bae89f082e114f4aeb660009be3'] = 'Opcja zależna jest od wyboru typu konwersji zdjęć. Biblioteka cwebp działa z każdą z opcji, GD nie przenosi żadnych danych pozostałe biblioteki mogą przenieść wybrane dane.';
$_MODULE['<{x13webp}prestashop>form_4c3880bb027f159e801041b1021e88e8'] = 'Metoda';
$_MODULE['<{x13webp}prestashop>form_76155a09212b2edfc605b59a6ac27e9c'] = '0 (najlepsza wydajność)';
$_MODULE['<{x13webp}prestashop>form_068208bd10bbaf9c22c7c680b1751df2'] = '1 (dobra wydajność)';
$_MODULE['<{x13webp}prestashop>form_bc9f3e8eefd6fe085d10d5eea4860b37'] = '2 (przyzwoita wydajność z lepszą jakością)';
$_MODULE['<{x13webp}prestashop>form_7c1df6704998962a9d1f43f2770affc0'] = '3 (najlepsza równowaga pomiędzy jakością a wydajnością)';
$_MODULE['<{x13webp}prestashop>form_cc1e545c088d972a77540fb4a1e9413e'] = '4 (przyzwoita jakość z lepszą wydajnością)';
$_MODULE['<{x13webp}prestashop>form_ffcd6fe065eb2d3ddceb184ed04bd5fb'] = '5 (dobra jakość)';
$_MODULE['<{x13webp}prestashop>form_e84206050c899cfb3e4201fbfb31174b'] = '6 (najlepsza jakość)';
$_MODULE['<{x13webp}prestashop>form_c665ff2a0955e059969cb85cffdb9ef3'] = 'Ostrość YUV (Sharp YUV)';
$_MODULE['<{x13webp}prestashop>form_08fc6f2f6fab5cbda6847370fba66891'] = 'Użyj dokładniejszej i ostrzejszejszej konwersji RGB->YUV. Ten proces jest wolniejszy niż domyślna \"szybka\" konwersja RGB->YUV.';
$_MODULE['<{x13webp}prestashop>form_95e123ef148bb2403346d40a186dc3d3'] = 'Auto filt';
$_MODULE['<{x13webp}prestashop>form_d31dadffe75569be5f555b59f23acf5f'] = 'Ten algorytm poświęci dodatkowy czas na optymalizację filtrowania, aby osiągnąć lepszą jakość - ze znacznym obciążeniem serwera.';
$_MODULE['<{x13webp}prestashop>form_70f7c24e3fd9dde1db30f17e3cb1dd12'] = 'Mniejsze zużycie pamięci (Low memory)';
$_MODULE['<{x13webp}prestashop>form_8308e2272d5845d482d1cc9b9e120d0e'] = 'Zmniejsza zużycie pamięci przez kodowanie stratne. Spowoduje, że kodowanie będzie wolniejsze, a wygenerowane zdjęcie będzie nieco inne pod względem rozmiaru i zniekształceń.';
$_MODULE['<{x13webp}prestashop>form_ee97be03cb04119af45014d815621ce1'] = 'Opcje dla konsoli';
$_MODULE['<{x13webp}prestashop>form_f699c6d3f5c3de3e59596d49ccb3f131'] = 'Możesz dodać dodatkowe parametry podczas korzystania z wiersza poleceń biblioteki cwebp.';
$_MODULE['<{x13webp}prestashop>form_ccf7179bd76c5e2df406f48408d985c6'] = 'Dodaj ścieżkę systemową';
$_MODULE['<{x13webp}prestashop>form_1cdfcacf335965ccd65062553b076c88'] = 'Jeśli biblioteka cwebp jest dostępna na serwerze, ale masz błąd podczas generowania zdjęć. Moduł spróbuje podstawić najpopularniejsze ścieżki do biblioteki.';
$_MODULE['<{x13webp}prestashop>form_1e87b222f77862d91006bb9c8d0bd9e9'] = 'Generuj zdjęcia z użyciem Nice (dla zadania CRON)';
$_MODULE['<{x13webp}prestashop>form_6d758425bbff8b47b40900e00bdc0e5c'] = 'Test konwersji';
$_MODULE['<{x13webp}prestashop>form_231cf4c70d866b616c21baddaeed0696'] = 'Rozwiązywanie problemów';
$_MODULE['<{x13webp}prestashop>form_e608cc19cc855342f9617660e2265056'] = 'Wykryj obsługę zdjęć w formacie WebP w przeglądarce';
$_MODULE['<{x13webp}prestashop>form_4dbdea61aec0e36969e041def9d37eee'] = 'Nowe przeglądarki wyświetlą pliki w formacie WebP, a stare takie jak np. Internet Explorer otrzymają zdjęcie w formacie JPG';
$_MODULE['<{x13webp}prestashop>form_5e7cf7d82e70b6ffefed2f3a16c3962f'] = 'Wymuś dodanie zdjęć webP jako';
$_MODULE['<{x13webp}prestashop>form_e4d23e841d8e8804190027bce3180fa5'] = 'tag';
$_MODULE['<{x13webp}prestashop>form_dcfa739705725f36b5bb17ce456f3e62'] = 'Sugerowane rozwiązanie tylko dla części zewnętrznych modułów oraz problemów z CloudFlare';
$_MODULE['<{x13webp}prestashop>form_0ff5cccf7d30ed0671af23840f03c466'] = 'Wymuś rozszerzenie .webp';
$_MODULE['<{x13webp}prestashop>form_c4d0ea57d4a5450de2007f4419693e72'] = 'Wygenerowane zdjęcia zostaną wyświetlone z rozszerzenia pliku jako .webp zamiast .jpg';
$_MODULE['<{x13webp}prestashop>form_e7688b51379d3009efeb9efc9d9bfe2d'] = 'Generowanie zdjęć CRON';
$_MODULE['<{x13webp}prestashop>form_10f7f8c727f928c18ca278983f964f92'] = 'Tryb pracy zadania CRON';
$_MODULE['<{x13webp}prestashop>form_c8648eaf65a475c051546282b410fff8'] = 'Wygeneruj tylko brakujące zdjęcia w formacie WebP';
$_MODULE['<{x13webp}prestashop>form_1b7edac1d5892604b3c84f7eb3790a71'] = 'Wygeneruj ponownie wszystkie zdjęcia WebP';
$_MODULE['<{x13webp}prestashop>form_eaf72a31b2896b06c61f6a6479875c36'] = 'Adres wywołania dla CRON';
$_MODULE['<{x13webp}prestashop>form_fbc2f82af811c282ef1b79e2c4711899'] = 'Data ostatniego poprawnego uruchomienia:';
$_MODULE['<{x13webp}prestashop>form_cc8b8dd7d80dad6572646ef4f6c13e5f'] = 'Pomiń generowanie zdjęć WebP podczas importu porduktów z XML/CSV';
$_MODULE['<{x13webp}prestashop>form_5a09ca2d69b5bf0ae00821f46027ae7a'] = 'Generowanie zdjęć w formacie WebP wydłuży proces importu produktów. Możesz wyłączyć generowanie zdjęć w trakcie importu, oraz pozostawić generowanie zdjęć w trakcie pierwszego wczytania strony.';
$_MODULE['<{x13webp}prestashop>form_bff6c790f0d5f9ab911ecfa8cc21637e'] = 'Włącz wsparcie dla modułu LazyLoad';
$_MODULE['<{x13webp}prestashop>adminx13webpconverter_8abc9e5b2d92b44ae966dfac1728ceab'] = 'Wystąpił bład';
$_MODULE['<{x13webp}prestashop>adminx13webpconverter_3f2d688d254cdff233d70f978173e668'] = 'Zdjęcie nie istnieje';
$_MODULE['<{x13webp}prestashop>adminx13webpconverter_e34282a224d9600e51dc4b2509fe3b28'] = 'Wszystkie zdjęcia zostały usunięte';
$_MODULE['<{x13webp}prestashop>adminx13webpconverter_505a83f220c02df2f85c3810cd9ceb38'] = 'usunięto pomyślnie';
$_MODULE['<{x13webp}prestashop>adminx13webpconverter_6eccfead24e3f92531b1da6c880d7f82'] = 'Wystąpił problem podczas usuwania zdjęcia WebP';
$_MODULE['<{x13webp}prestashop>conversion_form_7110cf64a2a88c6844f7aabec1bfc10b'] = 'Generowanie zdjęć [AJAX]';
$_MODULE['<{x13webp}prestashop>conversion_form_a5c768b5f3c64b006abf664982bbf9f5'] = 'Generuj zdjęcia WebP';
$_MODULE['<{x13webp}prestashop>conversion_form_30b318c14e00eb1b7a4aaf9e8d1c8812'] = 'Generuj zdjęcia JPG';
$_MODULE['<{x13webp}prestashop>conversion_form_dc2854c49b507b256cc831d68e9a83a0'] = 'Generuj zdjęcia WebP i JPG';
$_MODULE['<{x13webp}prestashop>conversion_form_819dd7486184ff4906649500d403846f'] = 'Zakładka została zablokowana do momentu wygenerowania zdjęć';
$_MODULE['<{x13webp}prestashop>conversion_form_72e3dc3cfd29d7a2b7aa2373213d5d11'] = 'Generuj ponownie zdjęcia, które mają błąd';
$_MODULE['<{x13webp}prestashop>conversion_form_4b970413d44fef2acccc2429cb13e01b'] = 'Pokaż wszystkie logi';
$_MODULE['<{x13webp}prestashop>conversion_form_c9f4f4278267e19f397a1f427fd44003'] = 'Pokaż tylko ostrzeżenia';
$_MODULE['<{x13webp}prestashop>file_manager_e74f23da6df1be4a267bbeecc0885091'] = 'Brak zdjęć w tym folderze';
$_MODULE['<{x13webp}prestashop>file_manager_2dd1148046499f9c2422ce1045a4accf'] = 'Typ zdjęcia';
$_MODULE['<{x13webp}prestashop>file_manager_06df33001c1d7187fdd81ea1f5b277aa'] = 'Akcja';
$_MODULE['<{x13webp}prestashop>file_manager_ec53a8c4f07baed5d8825072c89799be'] = 'Status';
$_MODULE['<{x13webp}prestashop>file_manager_46b5f8c58b679b4243cbdb5749642c86'] = 'Postęp';
$_MODULE['<{x13webp}prestashop>file_manager_d85e65e3ff539c88f1c0f0f49c0156c2'] = 'Musisz wybrać zdjęcia, które chcesz wygenerować';
$_MODULE['<{x13webp}prestashop>file_manager_c8fd6128790fc7b05411626fb1df1f4c'] = 'Generuj wszystkie zdjęcia';
$_MODULE['<{x13webp}prestashop>file_manager_59fc33f6ce8128a0b201f817ff3f7c01'] = 'Przerwij generowanie zdjęć';
$_MODULE['<{x13webp}prestashop>file_manager_ec83918f44cf50cc0c58f9a171a4c636'] = 'Przegeneruj wszystkie zdjęcia';
$_MODULE['<{x13webp}prestashop>file_manager_3ca04290662c2e289e9d985991ce6efc'] = 'To zdjęcie nie może być wygenerowany';
$_MODULE['<{x13webp}prestashop>conversion_progress_2dd1148046499f9c2422ce1045a4accf'] = 'Typ zdjęcia';
$_MODULE['<{x13webp}prestashop>conversion_progress_06df33001c1d7187fdd81ea1f5b277aa'] = 'Akcja';
$_MODULE['<{x13webp}prestashop>conversion_progress_ec53a8c4f07baed5d8825072c89799be'] = 'Status';
$_MODULE['<{x13webp}prestashop>conversion_progress_46b5f8c58b679b4243cbdb5749642c86'] = 'Postęp';
$_MODULE['<{x13webp}prestashop>conversion_progress_5d81e434ee797559a52ffc4ba3872b63'] = 'Przyciski zostały wyłączone do końca procesu generowania';
$_MODULE['<{x13webp}prestashop>conversion_progress_6c71260f9c468d92b0db1f3bcedbfaef'] = 'Przycisk został wyłączony, ponieważ wszystkie zdjęcia zostały już wygenerowane';
$_MODULE['<{x13webp}prestashop>conversion_progress_c8fd6128790fc7b05411626fb1df1f4c'] = 'Generuj wszystkie zdjęcia';
$_MODULE['<{x13webp}prestashop>conversion_progress_59fc33f6ce8128a0b201f817ff3f7c01'] = 'Zatrzymaj generowanie zdjęć';
$_MODULE['<{x13webp}prestashop>conversion_progress_ec83918f44cf50cc0c58f9a171a4c636'] = 'Regeneruj wszystkie zdjęcia';
$_MODULE['<{x13webp}prestashop>conversion_progress_3ca04290662c2e289e9d985991ce6efc'] = 'Ten element nie może być generowany';
$_MODULE['<{x13webp}prestashop>cleaner_a17d360a21f1368e4f866dff908739ca'] = 'Usuń zbędne zdjęcia';
$_MODULE['<{x13webp}prestashop>cleaner_c09aad829db895dba6feee6d5f0ae3f0'] = 'Usuń zdjęcia produktów, które nie są poprawnie przypisane w bazie danych';
$_MODULE['<{x13webp}prestashop>cleaner_83fc2a1219e306a46a69d932f3d3cac1'] = 'Czy na pewno chcesz usunąć nieprzypisane zdjęcia?';
$_MODULE['<{x13webp}prestashop>cleaner_f2a6c498fb90ee345d997f888fce3b18'] = 'Usuń';
$_MODULE['<{x13webp}prestashop>cleaner_b312337be480b1e1b463a79efd56369b'] = 'Usuwa nieprawidłowe zdjęcia produktów z folderu img/p/ - które nie są przypisane do produktów w bazie danych';
$_MODULE['<{x13webp}prestashop>cleaner_7b1e7a637798b22a0ddf8ce327dda894'] = 'Usuń zdjęcia z tymczasowego folderu img/tmp/';
$_MODULE['<{x13webp}prestashop>cleaner_99804d100233d8f168bd1687c062e845'] = 'Czy na pewno chcesz usunąć zdjęcia z folderu tymczasowego?';
$_MODULE['<{x13webp}prestashop>cleaner_264f73bee5b76220a20d9495f21fc42a'] = 'Usuwa zdjęcia z folderu tymczasowego, które PrestaShop zregeneruje w razie potrzeby';
$_MODULE['<{x13webp}prestashop>cleaner_48b3ac2d67f588f40564d7c1325234e5'] = 'Usuń zdjęcia, które nie są przypisane do aktualnych typów zdjęć';
$_MODULE['<{x13webp}prestashop>cleaner_068f80c7519d0528fb08e82137a72131'] = 'Produkty';
$_MODULE['<{x13webp}prestashop>cleaner_af1b98adf7f686b84cd0b443e022b7a0'] = 'Kategorie';
$_MODULE['<{x13webp}prestashop>cleaner_2377be3c2ad9b435ba277a73f0f1ca76'] = 'Producenci';
$_MODULE['<{x13webp}prestashop>cleaner_1814d65a76028fdfbadab64a5a8076df'] = 'Dostawcy';
$_MODULE['<{x13webp}prestashop>cleaner_821b8ee6937cec96c30fdafbfe836d68'] = 'Sklepy';
$_MODULE['<{x13webp}prestashop>cleaner_8d85c2df99d7e828ca6e04c4ce1e3a94'] = 'Czy na pewno chcesz usunąć niepotrzebne typy zdjęć?';
$_MODULE['<{x13webp}prestashop>cleaner_0de93ed065b88ef27251dd53bb13f7aa'] = 'Usuń zdjęcia, których typ został usunięty (np. custom_default po zmianie szablonu i generowaniu nowych typów zdjęć)';
$_MODULE['<{x13webp}prestashop>cleaner_101ea21a534486a74d98dc1ea023a7c1'] = 'Usuń wszystkie zdjęcia WebP';
$_MODULE['<{x13webp}prestashop>cleaner_e3efb202244c119f09038a9fe1e436ab'] = 'Brak wygenerowanych zdjęć WebP do usunięcia.';
$_MODULE['<{x13webp}prestashop>cleaner_f4f7e20ea0eb86a01ac8f0950929bb49'] = 'Czy na pewno chcesz usunąć wszystkie zdjęcia WebP?';
$_MODULE['<{x13webp}prestashop>cleaner_eabfd5384f5429e7be8c49b4d35dfea7'] = 'Usuń wszystkie zdjęcia w formacie WebP, które zostały wygenerowane tym modułem';
$_MODULE['<{x13webp}prestashop>progress_item_5d81e434ee797559a52ffc4ba3872b63'] = 'Przyciski zostały wyłączone do końca procesu generowania';
$_MODULE['<{x13webp}prestashop>progress_item_c2dc1837dbdc669e6c80bbf95b951ea5'] = 'Przycisk został wyłączony, ponieważ wszystkie obrazy zostały już wygenerowane';
$_MODULE['<{x13webp}prestashop>conversion_test_190167bdbafb24cc86eab985e438576d'] = 'Test konwersji';
$_MODULE['<{x13webp}prestashop>conversion_test_0834dbec80c240be5b2fda7c96b79b50'] = 'Wyszukaj produkt';
$_MODULE['<{x13webp}prestashop>conversion_test_a740e095948fb54222b006cad3d82542'] = 'Oryginalne zdjęcie (przed)';
$_MODULE['<{x13webp}prestashop>conversion_test_d7a385a37d032776d62164bf150c4385'] = 'jakość zdjęcia';
$_MODULE['<{x13webp}prestashop>conversion_test_a6178f34ffdadfdf556ae90c8f586bb4'] = 'Po kompresji';
$_MODULE['<{x13webp}prestashop>conversion_test_440bde1f6cccab1a05551b30111cd452'] = 'Przekonwertuj zdjęcie';
$_MODULE['<{x13webp}prestashop>conversion_test_aed130f1fd6fe5b7f9d85ec84a1d8c9b'] = 'Wystąpił błąd';
$_MODULE['<{x13webp}prestashop>configuratorbase_c9cc8cce247e49bae79f15173ce97354'] = 'Zapisz';
$_MODULE['<{x13webp}prestashop>configuratorbase_e8a988b75dfac7a9237884c1604159cf'] = 'Pole %s jest nieprawidłowe dla języka %s';
$_MODULE['<{x13webp}prestashop>configuratorbase_305dc4da284fd1ddfea51fde6b5048e8'] = 'Pole %s jest nieprawidłowe';
$_MODULE['<{x13webp}prestashop>configuratorhelpers_882ee81198523d5a26bc7a2d30a93398'] = '--- Wybierz ---';
$_MODULE['<{x13webp}prestashop>x13converter_536cf455d663873a6b9d3c42d767f753'] = 'Wystąpił błąd podczas dodawania zdjęcia do bazy danych';
$_MODULE['<{x13webp}prestashop>x13converter_5fb012a3c1cceabd7e0b34015084bc8a'] = 'Wystąpił błąd podczas pobierania kolejnego zdjęcia';
$_MODULE['<{x13webp}prestashop>x13converter_aed130f1fd6fe5b7f9d85ec84a1d8c9b'] = 'Wystąpił problem';
$_MODULE['<{x13webp}prestashop>x13converter_985b5b995c4574ae5eba2062a13ef168'] = 'Nie udało się zmienić rozmiaru pliku obrazu (%filepath%)';
$_MODULE['<{x13webp}prestashop>x13converter_c5e7d0c13104eed0a195c175f2edfdd2'] = 'Nie udało się zmienić rozmiaru pliku obrazu na wysoką rozdzielczość (%filepath%)';
$_MODULE['<{x13webp}prestashop>x13converter_3f2d688d254cdff233d70f978173e668'] = 'Zdjęcie nie istnieje';
$_MODULE['<{x13webp}prestashop>x13converter_642894fbcafca028bdc936bf14fe0ac9'] = 'Wystąpił problem';

10
modules/x13webp/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>

7
modules/x13webp/vendor/autoload.php vendored Normal file
View File

@@ -0,0 +1,7 @@
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitx13webp::getLoader();

View File

@@ -0,0 +1,445 @@
<?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 http://www.php-fig.org/psr/psr-0/
* @see http://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
// PSR-4
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
// PSR-0
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
private $classMapAuthoritative = false;
private $missingClasses = array();
private $apcuPrefix;
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array $classMap Class to filename map
*/
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 array|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $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 array|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $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] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $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 array|string $paths The PSR-0 base directories
*/
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 array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*/
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
*/
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
*/
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
*/
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
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Unregisters this instance as an autoloader.
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* 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;
}
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;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}

21
modules/x13webp/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,10 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'X13Webp' => $baseDir . '/x13webp.php',
);

View File

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

View File

@@ -0,0 +1,16 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'X13Webp\\' => array($baseDir . '/src'),
'WebPConvert\\' => array($vendorDir . '/rosell-dk/webp-convert/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,55 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitx13webp
{
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;
}
spl_autoload_register(array('ComposerAutoloaderInitx13webp', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitx13webp', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitx13webp::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
return $loader;
}
}

View File

@@ -0,0 +1,81 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitx13webp
{
public static $prefixLengthsPsr4 = array (
'X' =>
array (
'X13Webp\\' => 8,
),
'W' =>
array (
'WebPConvert\\' => 12,
),
'L' =>
array (
'LocateBinaries\\' => 15,
),
'I' =>
array (
'ImageMimeTypeSniffer\\' => 21,
'ImageMimeTypeGuesser\\' => 21,
),
'F' =>
array (
'FileUtil\\' => 9,
),
'E' =>
array (
'ExecWithFallback\\' => 17,
),
);
public static $prefixDirsPsr4 = array (
'X13Webp\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
'WebPConvert\\' =>
array (
0 => __DIR__ . '/..' . '/rosell-dk/webp-convert/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 (
'X13Webp' => __DIR__ . '/../..' . '/x13webp.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitx13webp::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitx13webp::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInitx13webp::$classMap;
}, null, ClassLoader::class);
}
}

View File

@@ -0,0 +1,458 @@
[
{
"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"
}
]
},
{
"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"
}
]
},
{
"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"
}
]
},
{
"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"
}
]
},
{
"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"
}
]
},
{
"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"
}
]
}
]

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,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,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,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,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,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,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`

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