Merged in feature/MAW-855-import-code-into-aws (pull request #2)

code import from pantheon

* code import from pantheon
This commit is contained in:
Tony Volpe
2023-12-04 23:08:14 +00:00
parent 8c9b1312bc
commit 8f4b5efda6
4766 changed files with 185592 additions and 239967 deletions
@@ -55,7 +55,7 @@ var $ = jQuery.noConflict(),
default:
if (tag) {
// Queue the requests for an AJAX call at the end of init
dtx.queue.push(raw_value);
dtx.queue.push({ 'value': raw_value, 'multiline': $input.is('textarea') });
}
return; // Don't continue after queuing it for AJAX
}
@@ -1,2 +1,2 @@
/*! Do not edit, this file is generated automatically - 2023-08-07 16:08:32 EDT */
var $=jQuery.noConflict(),dtx={queue:[],init:function(){var $inputs=$("input.dtx-pageload[data-dtx-value]");$inputs.length&&($inputs.each(function(i,el){var el=$(el),raw_value=el.attr("data-dtx-value"),v=decodeURIComponent(raw_value).split(" ");if(v.length){var tag=v[0],atts={};if(1<v.length)for(var x=1;x<v.length;x++){var att=v[x].split("=");2===att.length&&(atts[att[0]]=att[1].split("'").join(""))}var value="";switch(tag){case"CF7_GET":value=dtx.get(atts);break;case"CF7_referrer":value=dtx.referrer(atts);break;case"CF7_URL":value=dtx.current_url(atts);break;case"CF7_get_cookie":value=dtx.get_cookie(atts);break;case"CF7_guid":value=dtx.guid();break;case"CF7_get_current_var":if(!dtx.validKey(atts,"key")||"url"!=atts.key)return;value=dtx.current_url(atts);break;case"CF7_get_post_var":case"CF7_get_custom_field":case"CF7_get_taxonomy":case"CF7_get_attachment":case"CF7_bloginfo":case"CF7_get_theme_option":return;default:return void(tag&&dtx.queue.push(raw_value))}dtx.set(el,value)}}),dtx.queue.length)&&setTimeout(function(){$.ajax({type:"POST",url:dtx_obj.ajax_url,dataType:"json",data:{action:"wpcf7dtx",shortcodes:dtx.queue},cache:!1,error:function(xhr,status,error){console.error("[CF7 DTX AJAX ERROR]",error,status,xhr)},success:function(data,status,xhr){"object"==typeof data&&data.length&&$.each(data,function(i,obj){var $inputs=$('.wpcf7 form input.dtx-pageload[data-dtx-value="'+obj.raw_value+'"]');$inputs.length&&(dtx.set($inputs,obj.value),$inputs.addClass("dtx-ajax-loaded"))})}})},10)},validKey:function(obj,key){return obj.hasOwnProperty(key)&&"string"==typeof obj[key]&&obj[key].trim()},obfuscate:function(value,atts){if(value=value.trim(),dtx.validKey(atts,"obfuscate")&&atts.obfuscate){for(var o="",i=0;i<value.length;i++)o+="&#"+value.codePointAt(i)+";";return o}return value},set:function($input,value){$input.attr("value",value).addClass("dtx-loaded")},get:function(atts){if(dtx.validKey(atts,"key")){var query=window.location.search;if(query)return query=new URLSearchParams(query),dtx.obfuscate(query.get(atts.key).trim(),atts)}return""},referrer:function(atts){return dtx.obfuscate(document.referrer,atts)},current_url:function(atts){if(!atts.hasOwnProperty("part"))return dtx.obfuscate(window.location.href,atts);if(["scheme","host","port","path","query","fragment"].includes(atts.part))switch(atts.part){case"scheme":return dtx.obfuscate(window.location.protocol.replace(":",""),atts);case"host":return dtx.obfuscate(window.location.host,atts);case"port":return dtx.obfuscate(window.location.port,atts);case"path":return dtx.obfuscate(window.location.pathname,atts);case"query":return dtx.obfuscate(window.location.search.replace("?",""),atts);case"fragment":return dtx.obfuscate(window.location.hash.replace("#",""),atts)}return""},get_cookie:function(atts){var keyValue;return atts.hasOwnProperty("key")&&"string"==typeof atts.key&&""!=atts.key.trim()&&(keyValue=document.cookie.match("(^|;) ?"+atts.key.trim()+"=([^;]*)(;|$)"))?dtx.obfuscate(keyValue[2],atts):""},guid:function(){if(void 0!==window.crypto&&void 0!==window.crypto.getRandomValues)return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,c=>(c^crypto.getRandomValues(new Uint8Array(1))[0]&15>>c/4).toString(16)).toUpperCase();console.warn("[CF7 DTX] Cryptographically secure PRNG is not available for generating GUID value");var d=(new Date).getTime(),d2="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=16*Math.random();return 0<d?(r=(d+r)%16|0,d=Math.floor(d/16)):(r=(d2+r)%16|0,d2=Math.floor(d2/16)),("x"===c?r:3&r|8).toString(16).toUpperCase()}).toUpperCase()}};$(document).ready(dtx.init);
/*! Do not edit, this file is generated automatically - 2023-09-18 14:09:50 EDT */
var $=jQuery.noConflict(),dtx={queue:[],init:function(){var e=$("input.dtx-pageload[data-dtx-value]");e.length&&(e.each(function(e,t){var r=$(t),a=r.attr("data-dtx-value"),o=decodeURIComponent(a).split(" ");if(o.length){var n=o[0],c={};if(1<o.length)for(var u=1;u<o.length;u++){var i=o[u].split("="),d;2===i.length&&(c[i[0]]=i[1].split("'").join(""))}var s="";switch(n){case"CF7_GET":s=dtx.get(c);break;case"CF7_referrer":s=dtx.referrer(c);break;case"CF7_URL":s=dtx.current_url(c);break;case"CF7_get_cookie":s=dtx.get_cookie(c);break;case"CF7_guid":s=dtx.guid();break;case"CF7_get_current_var":if(!dtx.validKey(c,"key")||"url"!=c.key)return;s=dtx.current_url(c);break;case"CF7_get_post_var":case"CF7_get_custom_field":case"CF7_get_taxonomy":case"CF7_get_attachment":case"CF7_bloginfo":case"CF7_get_theme_option":return;default:return void(n&&dtx.queue.push({value:a,multiline:r.is("textarea")}))}dtx.set(r,s)}}),dtx.queue.length)&&setTimeout(function(){$.ajax({type:"POST",url:dtx_obj.ajax_url,dataType:"json",data:{action:"wpcf7dtx",shortcodes:dtx.queue},cache:!1,error:function(e,t,r){},success:function(e,t,r){"object"==typeof e&&e.length&&$.each(e,function(e,t){var r=$('.wpcf7 form input.dtx-pageload[data-dtx-value="'+t.raw_value+'"]');r.length&&(dtx.set(r,t.value),r.addClass("dtx-ajax-loaded"))})}})},10)},validKey:function(e,t){return e.hasOwnProperty(t)&&"string"==typeof e[t]&&e[t].trim()},obfuscate:function(e,t){if(e=e.trim(),dtx.validKey(t,"obfuscate")&&t.obfuscate){for(var r="",a=0;a<e.length;a++)r+="&#"+e.codePointAt(a)+";";return r}return e},set:function(e,t){e.attr("value",t).addClass("dtx-loaded")},get:function(e){if(dtx.validKey(e,"key")){var t=window.location.search;if(t)return t=new URLSearchParams(t),dtx.obfuscate(t.get(e.key).trim(),e)}return""},referrer:function(e){return dtx.obfuscate(document.referrer,e)},current_url:function(e){if(!e.hasOwnProperty("part"))return dtx.obfuscate(window.location.href,e);var t;if(["scheme","host","port","path","query","fragment"].includes(e.part))switch(e.part){case"scheme":return dtx.obfuscate(window.location.protocol.replace(":",""),e);case"host":return dtx.obfuscate(window.location.host,e);case"port":return dtx.obfuscate(window.location.port,e);case"path":return dtx.obfuscate(window.location.pathname,e);case"query":return dtx.obfuscate(window.location.search.replace("?",""),e);case"fragment":return dtx.obfuscate(window.location.hash.replace("#",""),e)}return""},get_cookie:function(e){var t;return e.hasOwnProperty("key")&&"string"==typeof e.key&&""!=e.key.trim()&&(t=document.cookie.match("(^|;) ?"+e.key.trim()+"=([^;]*)(;|$)"))?dtx.obfuscate(t[2],e):""},guid:function(){var r,a;return(void 0!==window.crypto&&void 0!==window.crypto.getRandomValues?([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16)):(r=(new Date).getTime(),a="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0,"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random();return 0<r?(t=(r+t)%16|0,r=Math.floor(r/16)):(t=(a+t)%16|0,a=Math.floor(a/16)),("x"===e?t:3&t|8).toString(16).toUpperCase()}))).toUpperCase()}};$(document).ready(dtx.init);
@@ -26,6 +26,14 @@
};
$(function() {
$('form.tag-generator-panel input.dtx-option').on('change keyup', wpcf7dtx.taggen.updateOption);
$('form.tag-generator-panel .dtx-option').on('change keyup click', wpcf7dtx.taggen.updateOption);
$('.contact-form-editor-panel #tag-generator-list a.thickbox.button[href*="inlineId=tag-generator-panel-dynamic_"]').each(function() {
var $btn = $(this),
name = $btn.text();
$btn.addClass('dtx-form-tag');
if (name == 'dynamic drop-down menu' || name == 'dynamic checkboxes' || name == 'dynamic radio buttons') {
$btn.attr('href', $btn.attr('href').replace('height=500', 'height=750'));
}
});
});
})(jQuery);
@@ -1,2 +1,2 @@
/*! Do not edit, this file is generated automatically - 2023-08-07 16:08:32 EDT */
!function($){"use strict";"undefined"!=typeof wpcf7&&null!==wpcf7&&(window.wpcf7dtx=window.wpcf7dtx||{},wpcf7dtx.taggen={},wpcf7dtx.taggen.escapeRegExp=function(str){return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")},wpcf7dtx.taggen.replaceAll=function(input,f,r,no_escape){var rexp;return null!=input&&"string"==typeof input&&""!==input.trim()&&-1<input.indexOf(f)?(rexp=new RegExp(wpcf7dtx.taggen.escapeRegExp(f),"g"),no_escape&&(rexp=new RegExp(f,"g")),input.replace(rexp,r)):input},wpcf7dtx.taggen.updateOption=function(e){var e=$(e.currentTarget),value=encodeURIComponent(wpcf7dtx.taggen.replaceAll(e.val(),"'","&#39;"));e.siblings('input[type="hidden"].option').val(value)},$(function(){$("form.tag-generator-panel input.dtx-option").on("change keyup",wpcf7dtx.taggen.updateOption)}))}(jQuery);
/*! Do not edit, this file is generated automatically - 2023-09-18 14:09:50 EDT */
!function(n){"use strict";"undefined"!=typeof wpcf7&&null!==wpcf7&&(window.wpcf7dtx=window.wpcf7dtx||{},wpcf7dtx.taggen={},wpcf7dtx.taggen.escapeRegExp=function(e){return e.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")},wpcf7dtx.taggen.replaceAll=function(e,t,n,a){var c;return null!=e&&"string"==typeof e&&""!==e.trim()&&-1<e.indexOf(t)?(c=new RegExp(wpcf7dtx.taggen.escapeRegExp(t),"g"),a&&(c=new RegExp(t,"g")),e.replace(c,n)):e},wpcf7dtx.taggen.updateOption=function(e){var e=n(e.currentTarget),t=encodeURIComponent(wpcf7dtx.taggen.replaceAll(e.val(),"'","&#39;"));e.siblings('input[type="hidden"].option').val(t)},n(function(){n("form.tag-generator-panel .dtx-option").on("change keyup click",wpcf7dtx.taggen.updateOption),n('.contact-form-editor-panel #tag-generator-list a.thickbox.button[href*="inlineId=tag-generator-panel-dynamic_"]').each(function(){var e=n(this),t=e.text();e.addClass("dtx-form-tag"),"dynamic drop-down menu"!=t&&"dynamic checkboxes"!=t&&"dynamic radio buttons"!=t||e.attr("href",e.attr("href").replace("height=500","height=750"))})}))}(jQuery);
@@ -1,7 +1,46 @@
.tag-generator-panel[data-id^="dynamic_select"],
.tag-generator-panel[data-id^="dynamic_checkbox"],
.tag-generator-panel[data-id^="dynamic_radio"] {
height: 740px;
}
#tag-generator-list a.button.dtx-form-tag {
border-color: #765cb9;
color: #765cb9;
}
.tag-generator-panel table.form-table th {
width: 130px;
}
.tag-generator-panel .control-box input.oneline {
.tag-generator-panel table.form-table td small {
display: block;
margin-top: 0.25em;
}
.tag-generator-panel .control-box input.oneline,
.tag-generator-panel .control-box input.multiline,
.tag-generator-panel .control-box textarea {
width: 100%;
}
.tag-generator-panel .control-box input[list],
.tag-generator-panel .control-box input.multiline,
.tag-generator-panel .control-box textarea {
height: 30px;
min-height: 30px;
}
.tag-generator-panel .control-box input.multiline {
display: inline-block;
/* -webkit-appearance: none;
-moz-appearance: none;
appearance: none; */
resize: vertical;
overflow-x: hidden;
overflow-y: scroll;
}
.tag-generator-panel .control-box textarea {
height: 3.5em;
}
@@ -0,0 +1 @@
.tag-generator-panel[data-id^=dynamic_checkbox],.tag-generator-panel[data-id^=dynamic_radio],.tag-generator-panel[data-id^=dynamic_select]{height:740px}#tag-generator-list a.button.dtx-form-tag{border-color:#765cb9;color:#765cb9}.tag-generator-panel table.form-table th{width:130px}.tag-generator-panel table.form-table td small{display:block;margin-top:.25em}.tag-generator-panel .control-box input.multiline,.tag-generator-panel .control-box input.oneline,.tag-generator-panel .control-box textarea{width:100%}.tag-generator-panel .control-box input.multiline,.tag-generator-panel .control-box input[list],.tag-generator-panel .control-box textarea{height:30px;min-height:30px}.tag-generator-panel .control-box input.multiline{display:inline-block;resize:vertical;overflow-x:hidden;overflow-y:scroll}.tag-generator-panel .control-box textarea{height:3.5em}
@@ -1,5 +1,48 @@
== Changelog ==
= 4.1.0 =
* Feature: Looks for a `dtx.php` file in the `wp_content` directory to maybe load custom shortcodes, [see support thread](https://wordpress.org/support/topic/how-to-avoid-custom-shortcodes-being-overwritten-on-updates/)
* Feature: Looks for a `dtx.php` file in the current active theme's directory to maybe load custom shortcodes, [see support thread](https://wordpress.org/support/topic/how-to-avoid-custom-shortcodes-being-overwritten-on-updates/)
* Feature: Looks for a `dtx.php` file in the current active theme's parent directory to maybe load custom shortcodes, [see support thread](https://wordpress.org/support/topic/how-to-avoid-custom-shortcodes-being-overwritten-on-updates/)
* Fix: addressed user reported bug, [see support thread](https://wordpress.org/support/topic/fatal-error-v4-0-3/)
= 4.0.3 =
* Feature: Added `exclusive` option to checkbox tag generator
* Fix: addressed bug that put all dynamic checkbox/radio options into one
* Fix: addressed bug in frontend validator for multiple selected values
= 4.0.2 =
* Fix: addressed bug that put all dynamic select options into one, [see support thread](https://wordpress.org/support/topic/dynamic-select-get-option-values-from-shortcode/)
* Update: sanitizing and escaping filters now accept `none` as value for `$type` to bypass. Use with caution.
= 4.0.1 =
* Fix: addressed bug that prevented translation for cache compatibility description
= 4.0.0 =
* Major: modified function names
* Major: deprecated `dynamictext` and `dynamichidden` form tags in favor of `dynamic_text` and `dynamic_hidden`. For more information, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_email` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-email/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_url` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-url/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_tel` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-tel/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_number` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-number/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_range` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-range/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_textarea` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-textarea/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_select` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-select/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_radio` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-radio/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_date` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-date/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_submit` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-submit/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dtx_hide_blank` form tag attribute for `dynamic_select`. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-select/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dtx_disable_blank` form tag attribute for `dynamic_select`. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-select/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: added mail validation for `dynamic_email` and `dynamic_hidden` for backend configuration. For more information, see the [FAQ](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/frequently-asked-questions/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: added the Akismet feature to DTX text, email, and URL form tags.
* Update: adjusted how queued values were sent for cache compatibility mode to allow for multiline values in textareas
* Removed unused utility functions
= 3.5.4 =
* Fix: Updated JavaScript to prevent cacheable fields from making unnecessary AJAX requests
@@ -4,7 +4,7 @@
* Plugin Name: Contact Form 7 - Dynamic Text Extension
* Plugin URI: https://sevenspark.com/goods/contact-form-7-dynamic-text-extension
* Description: This plugin extends Contact Form 7 by adding dynamic form fields that accept any shortcode to generate default values and placeholder text. Requires Contact Form 7.
* Version: 3.5.4
* Version: 4.1.0
* Author: SevenSpark, AuRise Creative
* Author URI: https://sevenspark.com
* License: GPL2
@@ -32,7 +32,7 @@
*/
// Define current version
define('WPCF7DTX_VERSION', '3.5.4');
define('WPCF7DTX_VERSION', '4.1.0');
// Define root directory
defined('WPCF7DTX_DIR') || define('WPCF7DTX_DIR', __DIR__);
@@ -47,31 +47,139 @@ defined('WPCF7DTX_FILE') || define('WPCF7DTX_FILE', __FILE__);
*/
function wpcf7dtx_init()
{
add_action('wpcf7_init', 'wpcf7dtx_add_shortcode_dynamictext'); // Add custom form tags to CF7
add_filter('wpcf7_validate_dynamictext*', 'wpcf7dtx_dynamictext_validation_filter', 20, 2); // Validate custom form tags
add_action('wpcf7_init', 'wpcf7dtx_add_shortcodes'); // Add custom form tags to CF7
}
add_action('plugins_loaded', 'wpcf7dtx_init', 20);
/**
* DTX Formg Tag Configuration
*
* @since 4.0.0
*
* @return array
*/
function wpcf7dtx_config()
{
global $wpcf7_dynamic_fields_config;
if (!isset($wpcf7_dynamic_fields_config)) {
$wpcf7_dynamic_fields_config = array(
'dynamic_text' => array(
'title' => __('dynamic text', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('placeholder', 'readonly', 'dtx_pageload'),
'description' => __('a single-line plain text', 'contact-form-7-dynamic-text-extension')
),
'dynamic_hidden' => array(
'title' => __('dynamic hidden', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('dtx_pageload'),
'description' => __('a single-line plain text hidden input field', 'contact-form-7-dynamic-text-extension'),
'features' => array(
'display-hidden' => true // Generates an HTML element that is not visible
)
),
'dynamic_email' => array(
'title' => __('dynamic email', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('placeholder', 'readonly', 'dtx_pageload'),
'description' => __('a single-line email address input field', 'contact-form-7-dynamic-text-extension')
),
'dynamic_url' => array(
'title' => __('dynamic URL', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('placeholder', 'readonly', 'dtx_pageload'),
'description' => __('a single-line URL input field', 'contact-form-7-dynamic-text-extension')
),
'dynamic_tel' => array(
'title' => __('dynamic tel', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('placeholder', 'readonly', 'pattern'),
'description' => __('a single-line telephone number input field', 'contact-form-7-dynamic-text-extension')
),
'dynamic_number' => array(
'title' => __('dynamic number', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('placeholder', 'readonly', 'min', 'max', 'step', 'pattern'),
'description' => __('a numeric input field displayed as a number spinbox', 'contact-form-7-dynamic-text-extension')
),
'dynamic_range' => array(
'title' => __('dynamic range', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('placeholder', 'readonly', 'min', 'max', 'step', 'pattern'),
'description' => __('a numeric input field displayed as a slider between a minimum and maximum range', 'contact-form-7-dynamic-text-extension')
),
'dynamic_textarea' => array(
'title' => __('dynamic textarea', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('placeholder', 'readonly', 'dtx_pageload'),
'description' => __('a multi-line plain text input field', 'contact-form-7-dynamic-text-extension')
),
'dynamic_select' => array(
'title' => __('dynamic drop-down menu', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('placeholder', 'readonly', 'multiple', 'include_blank'),
'description' => __('a drop-down menu (i.e select input field)', 'contact-form-7-dynamic-text-extension'),
'features' => array(
'selectable-values' => true // Generates an option (or group of options) from which you can select one or more options
)
),
'dynamic_checkbox' => array(
'title' => __('dynamic checkboxes', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('readonly', 'label_first', 'use_label_element', 'exclusive'),
'description' => __('a group of checkboxes', 'contact-form-7-dynamic-text-extension'),
'features' => array(
'multiple-controls-container' => true, // Generates an HTML element that can contain multiple form controls
'selectable-values' => true // Generates an option (or group of options) from which you can select one or more options
)
),
'dynamic_radio' => array(
'title' => __('dynamic radio buttons', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('readonly', 'label_first', 'use_label_element'),
'description' => __('a group of radio buttons', 'contact-form-7-dynamic-text-extension'),
'features' => array(
'multiple-controls-container' => true, // Generates an HTML element that can contain multiple form controls
'selectable-values' => true // Generates an option (or group of options) from which you can select one or more options
)
),
'dynamic_date' => array(
'title' => __('dynamic date', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('placeholder', 'readonly', 'min', 'max'),
'description' => __('a date input field', 'contact-form-7-dynamic-text-extension')
),
'dynamic_submit' => array(
'title' => __('dynamic submit', 'contact-form-7-dynamic-text-extension'), //title
'options' => array('dtx_pageload'),
'description' => __('a submit button', 'contact-form-7-dynamic-text-extension')
)
);
}
return $wpcf7_dynamic_fields_config;
}
/**
* Add Custom Shortcodes to Contact Form 7
*
* @return void
*/
function wpcf7dtx_add_shortcode_dynamictext()
function wpcf7dtx_add_shortcodes()
{
//Add the dynamic text and hidden form fields
wpcf7_add_form_tag(
array(
'dynamictext', 'dynamictext*',
'dynamichidden', 'dynamichidden*' //Required hidden fields do nothing
),
'wpcf7dtx_dynamictext_shortcode_handler', //Callback
array( //Features
'name-attr' => true,
'dtx_pageload' => true
)
);
//Add the dynamic form fields
foreach (wpcf7dtx_config() as $form_tag => $field) {
$input_type = str_replace('dynamic_', '', $form_tag);
$tag_types = array($form_tag, "$form_tag*");
$callback = 'wpcf7dtx_shortcode_handler';
$features = array_merge(array('name-attr' => true), wpcf7dtx_array_has_key('features', $field, array()));
switch ($input_type) {
case 'text':
case 'hidden':
// Add deprecated tags
$dep_tag = str_replace('_', '', $form_tag);
$tag_types[] = $dep_tag;
$tag_types[] = "$dep_tag*";
add_filter("wpcf7_validate_$dep_tag*", 'wpcf7dtx_validation_filter', 20, 2); // Validate required deprecated form tags
break;
case 'submit':
case 'reset':
$callback = 'wpcf7dtx_button_shortcode_handler';
$features['name-attr'] = false;
break;
default:
break;
}
add_filter("wpcf7_validate_$form_tag*", 'wpcf7dtx_validation_filter', 20, 2); // Validate required custom form tags
wpcf7_add_form_tag($tag_types, $callback, $features);
}
}
/**
@@ -112,35 +220,9 @@ add_action('wp_enqueue_scripts', 'wpcf7dtx_enqueue_frontend_assets');
include_once(WPCF7DTX_DIR . '/includes/utilities.php');
/**
* Get Dynamic Value
*
* @since 3.2.2
*
* @param string $value The form tag value.
* @param WPCF7_FormTag|false $tag Optional. Use to look up default value.
*
* @return string The dynamic output or the original value, not escaped or sanitized.
* Include Validation Functions
*/
function wpcf7dtx_get_dynamic($value, $tag = false)
{
if ($tag !== false) {
$default = $tag->get_option('defaultvalue', '', true);
if (!$default) {
$default = $tag->get_default_option(strval(reset($tag->values)));
}
$value = wpcf7_get_hangover($tag->name, $default);
}
$value = apply_filters('wpcf7dtx_sanitize', $value);
if (is_string($value) && !empty($value)) {
// If a shortcode was passed as the options, evaluate it and use the result
$shortcode_tag = '[' . $value . ']';
$shortcode_output = do_shortcode($shortcode_tag); //Shortcode value
if (is_string($shortcode_output) && $shortcode_output != $shortcode_tag) {
return apply_filters('wpcf7dtx_sanitize', $shortcode_output);
}
}
return $value;
}
include_once(WPCF7DTX_DIR . '/includes/validation.php');
/**
* Form Tag Handler
@@ -149,59 +231,54 @@ function wpcf7dtx_get_dynamic($value, $tag = false)
*
* @return string HTML output of the shortcode
*/
function wpcf7dtx_dynamictext_shortcode_handler($tag)
function wpcf7dtx_shortcode_handler($tag)
{
// Name attribute is required for these form tags
if (empty($tag->name)) {
return '';
}
//Validate
// Validate
$validation_error = wpcf7_get_validation_error($tag->name);
//Configure classes
$class = wpcf7_form_controls_class($tag->type, 'wpcf7dtx-dynamictext');
if ($validation_error) {
$class .= ' wpcf7-not-valid';
}
//Configure input attributes
$atts = array();
$atts['type'] = sanitize_key(str_replace(array('dynamic_', 'dynamic'), '', $tag->basetype));
$atts['name'] = $tag->name;
$atts['id'] = $tag->get_id_option();
$atts['id'] = strval($tag->get_id_option());
$atts['tabindex'] = $tag->get_option('tabindex', 'signed_int', true);
$atts['size'] = $tag->get_size_option('40');
$atts['maxlength'] = $tag->get_maxlength_option();
$atts['minlength'] = $tag->get_minlength_option();
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
switch ($tag->basetype) {
case 'dynamichidden':
$atts['type'] = 'hidden'; //Override type as hidden
break;
default: // Includes `dynamictext`
$atts['type'] = 'text'; //Override type as text
break;
}
if ($atts['maxlength'] && $atts['minlength'] && $atts['maxlength'] < $atts['minlength']) {
unset($atts['maxlength'], $atts['minlength']);
$atts['class'] = explode(' ', wpcf7_form_controls_class($atts['type']));
$atts['class'][] = 'wpcf7dtx';
$atts['class'][] = sanitize_html_class('wpcf7dtx-' . $atts['type']);
if ($validation_error) {
$atts['class'][] = 'wpcf7-not-valid';
$atts['aria-invalid'] = 'true';
$atts['aria-describedby'] = wpcf7_get_validation_error_reference($tag->name);
} else {
$atts['aria-invalid'] = 'false';
}
if ($tag->has_option('readonly')) {
$atts['readonly'] = 'readonly';
}
if ($tag->is_required() && $atts['type'] !== 'hidden') {
// Add required attribute to applicable input types
if ($tag->is_required() && !in_array($atts['type'], array('hidden', 'quiz'))) {
$atts['aria-required'] = 'true';
$atts['required'] = 'required';
}
// Evaluate the dynamic value
$value = wpcf7dtx_get_dynamic(false, $tag);
$sanitize_type = $atts['type'] == 'textarea' ? $atts['type'] : 'auto';
$value = wpcf7dtx_get_dynamic(false, $tag, $sanitize_type);
// Identify placeholder
if ($tag->has_option('placeholder') || $tag->has_option('watermark')) {
//Reverse engineer what JS did (converted quotes to HTML entities --> URL encode) then sanitize
$placeholder = html_entity_decode(urldecode(implode('', (array)$tag->get_option('placeholder'))), ENT_QUOTES);
$placeholder = html_entity_decode(urldecode($tag->get_option('placeholder', '', true)), ENT_QUOTES);
if ($placeholder) {
//If a different placeholder text has been specified, set both attributes
$placeholder = wpcf7dtx_get_dynamic($placeholder);
$placeholder = wpcf7dtx_get_dynamic($placeholder, false, $sanitize_type);
$atts['placeholder'] = $placeholder;
$atts['value'] = $value;
} else {
@@ -212,18 +289,186 @@ function wpcf7dtx_dynamictext_shortcode_handler($tag)
$atts['value'] = $value;
}
if ($atts['type'] == 'hidden') {
// Always disable for hidden fields
$atts['autocomplete'] = 'off';
// Page load attribute
if ($tag->has_option('dtx_pageload') && is_array($tag->raw_values) && count($tag->raw_values)) {
$atts['data-dtx-value'] = rawurlencode(sanitize_text_field($tag->raw_values[0]));
$atts['class'][] = 'dtx-pageload';
if (wp_style_is('wpcf7dtx', 'registered') && !wp_script_is('wpcf7dtx', 'queue')) {
// If already registered, just enqueue it
wp_enqueue_script('wpcf7dtx');
} elseif (!wp_style_is('wpcf7dtx', 'registered')) {
// If not registered, do that first, then enqueue it
wpcf7dtx_enqueue_frontend_assets();
wp_enqueue_script('wpcf7dtx');
}
}
// Additional configuration based on form field type
if (in_array($atts['type'], array('select', 'checkbox', 'radio'))) {
/**
* Configuration for selection-based fields
*/
if ($tag->has_option('default')) {
$atts['dtx-default'] = wpcf7dtx_get_dynamic(html_entity_decode(urldecode($tag->get_option('default', '', true)), ENT_QUOTES));
}
// Get options for selection-based fields
$options = array();
$pipes = $tag->pipes->to_array();
if (count($pipes)) {
foreach ($pipes as $pipe) {
$key = trim(strval($pipe[0]));
$value = trim(strval($pipe[1]));
if ($key && $value) {
$options[$key] = $value;
}
}
}
if ($atts['type'] == 'select' && $tag->has_option('include_blank')) {
$atts['placeholder'] = wpcf7dtx_array_has_key('placeholder', $atts, __('&#8212;Please choose an option&#8212;', 'contact-form-7-dynamic-text-extension'));
}
} else {
// Disable autocomplete for this field if a value has been specified
$atts['autocomplete'] = $atts['value'] ? 'off' : $tag->get_option('autocomplete', '[-0-9a-zA-Z]+', true);
/**
* Configuration for text-based fields
*/
// Attributes
$atts['maxlength'] = $tag->get_maxlength_option();
$atts['minlength'] = $tag->get_minlength_option();
if ($atts['maxlength'] && $atts['minlength'] && $atts['maxlength'] < $atts['minlength']) {
unset($atts['maxlength'], $atts['minlength']);
}
// Autocomplete attribute
if ($atts['type'] == 'hidden') {
$atts['autocomplete'] = 'off'; // Always disable for hidden fields
} else {
// Disable autocomplete for this field if a dynamic value has been specified
$atts['autocomplete'] = $atts['value'] ? 'off' : $tag->get_option('autocomplete', '[-0-9a-zA-Z]+', true);
}
switch ($atts['type']) {
case 'email':
case 'url':
case 'tel':
case 'number':
case 'date':
// Client-side validation by type
$atts['class'][] = sanitize_html_class('wpcf7-validates-as-' . $atts['type']);
break;
case 'range':
// Client-side validation by type
$atts['class'][] = 'wpcf7-validates-as-number';
break;
case 'textarea':
// Attributes unique to textareas
$atts['cols'] = $tag->get_cols_option('40');
$atts['rows'] = $tag->get_rows_option('10');
break;
}
}
// Wrap up class attribute
$atts['class'] = $tag->get_class_option($atts['class']);
// Output the form field HTML
$wrapper = '<span class="wpcf7-form-control-wrap %1$s" data-name="%1$s">%2$s%3$s</span>';
$allowed_html = array('br' => array(), 'span' => array('id' => array(), 'class' => array(), 'data-name' => array(), 'aria-hidden' => array()));
switch ($atts['type']) {
case 'checkbox':
case 'radio':
return wp_kses(sprintf(
str_replace('<span class=', '<span%4$s class=', $wrapper), // Insert a 4th parameter for wrapper
esc_attr($tag->name),
wpcf7dtx_checkbox_group_html(
$atts,
$options,
in_array('use_label_element', $tag->options),
in_array('label_first', $tag->options),
in_array('exclusive', $tag->options)
),
$validation_error,
$atts['id'] ? sprintf(' id="%s"', esc_attr($atts['id'])) : ''
), array_merge($allowed_html, array(
'label' => array('for' => array()),
'input' => wpcf7dtx_get_allowed_field_properties($atts['type'])
)));
case 'select':
$allowed_html = array_merge($allowed_html, wpcf7dtx_get_allowed_field_properties('option'), array(
'select' => wpcf7dtx_get_allowed_field_properties($atts['type'])
));
return wp_kses(sprintf(
$wrapper,
esc_attr($tag->name),
wpcf7dtx_select_html(
$atts,
$options,
$tag->has_option('dtx_hide_blank'),
$tag->has_option('dtx_disable_blank')
),
$validation_error
), array_merge($allowed_html, wpcf7dtx_get_allowed_field_properties('option'), array(
'select' => wpcf7dtx_get_allowed_field_properties($atts['type']),
)));
case 'textarea':
return wp_kses(sprintf(
$wrapper,
esc_attr($tag->name),
wpcf7dtx_textarea_html($atts),
$validation_error
), array_merge($allowed_html, array(
'textarea' => wpcf7dtx_get_allowed_field_properties($atts['type'])
)));
default:
return wp_kses(sprintf(
$wrapper,
esc_attr($tag->name),
wpcf7dtx_input_html($atts),
$validation_error
), array_merge($allowed_html, array(
'input' => wpcf7dtx_get_allowed_field_properties($atts['type'])
)));
}
}
/**
* Form Tag Handler for Dynamic Submit
*
* @param WPCF7_FormTag $tag Current Contact Form 7 tag object
*
* @return string HTML output of the shortcode
*/
function wpcf7dtx_button_shortcode_handler($tag)
{
//Configure input attributes
$atts = array();
$atts['type'] = sanitize_key(str_replace('dynamic_', '', $tag->basetype));
$atts['id'] = strval($tag->get_id_option());
$atts['tabindex'] = $tag->get_option('tabindex', 'signed_int', true);
$atts['value'] = wpcf7dtx_get_dynamic(false, $tag); // Evaluate the dynamic value
$atts['class'] = explode(' ', wpcf7_form_controls_class($atts['type']));
$atts['class'][] = 'wpcf7dtx';
$atts['class'][] = sanitize_html_class('wpcf7dtx-' . $atts['type']);
if ($atts['type'] == 'submit') {
$atts['class'][] = 'has-spinner';
}
// Default value if empty
if (empty($atts['value'])) {
switch ($atts['type']) {
case 'reset':
$atts['value'] = __('Clear', 'contact-form-7-dynamic-text-extension');
break;
default:
$atts['value'] = __('Send', 'contact-form-7-dynamic-text-extension');
break;
}
}
// Page load attribute
if ($tag->has_option('dtx_pageload')) {
$atts['data-dtx-value'] = rawurlencode(sanitize_text_field(implode('', (array)$tag->raw_values)));
$class .= ' dtx-pageload';
if ($tag->has_option('dtx_pageload') && is_array($tag->raw_values) && count($tag->raw_values)) {
$atts['data-dtx-value'] = rawurlencode(sanitize_text_field($tag->raw_values[0]));
$atts['class'][] = 'dtx-pageload';
if (wp_style_is('wpcf7dtx', 'registered') && !wp_script_is('wpcf7dtx', 'queue')) {
// If already registered, just enqueue it
wp_enqueue_script('wpcf7dtx');
@@ -235,55 +480,15 @@ function wpcf7dtx_dynamictext_shortcode_handler($tag)
}
// Wrap up class attribute
$atts['class'] = $tag->get_class_option($class);
$atts['class'] = $tag->get_class_option($atts['class']);
//Output the HTML
return sprintf(
'<span class="wpcf7-form-control-wrap %s" data-name="%s"><input %s />%s</span>',
sanitize_html_class($tag->name),
esc_attr($tag->name),
wpcf7_format_atts($atts), //This function already escapes attribute values
$validation_error
// Output the form field HTML
return wp_kses(
wpcf7dtx_input_html($atts),
array('input' => wpcf7dtx_get_allowed_field_properties($atts['type']))
);
}
/**
* Validate Required Dynamic Text Field
*
* @param WPCF7_Validation $result the current validation result object
* @param WPCF7_FormTag $tag the current form tag being filtered for validation
*
* @return WPCF7_Validation a possibly modified validation result object
*/
function wpcf7dtx_dynamictext_validation_filter($result, $tag)
{
//Sanitize value
$value = empty($_POST[$tag->name]) ? '' : sanitize_text_field(strval($_POST[$tag->name]));
//Validate
if ('dynamictext' == $tag->basetype) {
if ($tag->is_required() && '' == $value) {
$result->invalidate($tag, wpcf7_get_message('invalid_required'));
}
}
if (!empty($value)) {
$maxlength = $tag->get_maxlength_option();
$minlength = $tag->get_minlength_option();
if ($maxlength && $minlength && $maxlength < $minlength) {
$maxlength = $minlength = null;
}
$code_units = wpcf7_count_code_units($value);
if (false !== $code_units) {
if ($maxlength && $maxlength < $code_units) {
$result->invalidate($tag, wpcf7_get_message('invalid_too_long'));
} elseif ($minlength && $code_units < $minlength) {
$result->invalidate($tag, wpcf7_get_message('invalid_too_short'));
}
}
}
return $result;
}
/**
* AJAX Request Handler for After Page Loading
*
@@ -296,16 +501,14 @@ function wpcf7dtx_dynamictext_validation_filter($result, $tag)
function wpcf7dtx_js_handler()
{
$return = array();
$shortcodes = wpcf7dtx_array_has_key('shortcodes', $_POST);
if (is_array($shortcodes) && count($shortcodes)) {
foreach ($shortcodes as $raw_value) {
$value = sanitize_text_field(rawurldecode($raw_value));
if (!empty($value)) {
$value = wpcf7dtx_get_dynamic($value);
}
$queue = wpcf7dtx_array_has_key('shortcodes', $_POST);
if (is_array($queue) && count($queue)) {
foreach ($queue as $field) {
$multiline = wpcf7dtx_array_has_key('multiline', $field, false);
$raw_value = sanitize_text_field(rawurldecode(wpcf7dtx_array_has_key('value', $field)));
$return[] = array(
'raw_value' => esc_attr($raw_value),
'value' => esc_attr($value)
'value' => esc_attr(wpcf7dtx_get_dynamic($raw_value, false, $multiline ? 'textarea' : 'auto'))
);
}
}
@@ -322,6 +525,20 @@ if (is_admin()) {
}
/**
* Included Shortcodes
* Built-in Shortcodes
*/
include_once(WPCF7DTX_DIR . '/includes/shortcodes.php');
/**
* Website's custom shortcodes, if they exist
*/
$user_files = array(
constant('WP_CONTENT_DIR') . '/dtx.php', // e.g. C:\path\to\website\wp-content\dtx.php
get_template_directory() . '/dtx.php', // e.g. C:\path\to\website\wp-content/themes/parent-theme/dtx.php
get_stylesheet_directory() . '/dtx.php' // e.g. C:\path\to\website\wp-content/themes/child-theme/dtx.php
);
foreach ($user_files as $user_file) {
if (file_exists($user_file)) {
include_once($user_file);
}
}
@@ -16,13 +16,13 @@ function wpcf7dtx_enqueue_admin_assets($hook)
// Only load on CF7 Form pages (both editing forms and creating new forms)
if ($hook === 'toplevel_page_wpcf7' || $hook === 'contact_page_wpcf7-new') {
$prefix = 'wpcf7dtx-';
$debug = defined('WP_DEBUG') && constant('WP_DEBUG');
$debug = defined('WP_DEBUG_SCRIPTS') && constant('WP_DEBUG_SCRIPTS');
$url = plugin_dir_url(WPCF7DTX_FILE);
$path = plugin_dir_path(WPCF7DTX_FILE);
wp_enqueue_style(
$prefix . 'admin', //Handle
$url . 'assets/styles/tag-generator.css', //Source
$url . 'assets/styles/tag-generator' . ($debug ? '' : '.min') . '.css', //Source
array('contact-form-7-admin'), //Dependencies
$debug ? @filemtime($path . 'assets/styles/tag-generator.css') : WPCF7DTX_VERSION //Version
);
@@ -44,30 +44,22 @@ add_action('admin_enqueue_scripts', 'wpcf7dtx_enqueue_admin_assets'); //Enqueue
*
* @return void
*/
function wpcf7dtx_add_tag_generator_dynamictext()
function wpcf7dtx_add_tag_generators()
{
if (!class_exists('WPCF7_TagGenerator')) {
return;
}
// Custom dynamic fields to add
global $wpcf7_dynamic_fields_config;
// Loop fields to add them
$tag_generator = WPCF7_TagGenerator::get_instance();
//Dynamic Text Field
$tag_generator->add(
'dynamictext', //id
__('dynamic text', 'contact-form-7-dynamic-text-extension'), //title
'wpcf7dtx_tag_generator_dynamictext', //callback
array('placeholder', 'readonly', 'dtx_pageload') //options
);
//Dynamic Hidden Field
$tag_generator->add(
'dynamichidden', //id
__('dynamic hidden', 'contact-form-7-dynamic-text-extension'), //title
'wpcf7dtx_tag_generator_dynamictext', //callback
array('dtx_pageload') // options
);
foreach ($wpcf7_dynamic_fields_config as $id => $field) {
$tag_generator->add($id, $field['title'], 'wpcf7dtx_tag_generator', array_merge(array('name-attr', 'dtx_pageload'), $field['options']));
}
}
add_action('wpcf7_admin_init', 'wpcf7dtx_add_tag_generator_dynamictext', 100);
add_action('wpcf7_admin_init', 'wpcf7dtx_add_tag_generators', 100);
/**
* Echo HTML for Dynamic Tag Generator
@@ -77,36 +69,43 @@ add_action('wpcf7_admin_init', 'wpcf7dtx_add_tag_generator_dynamictext', 100);
*
* @return void
*/
function wpcf7dtx_tag_generator_dynamictext($contact_form, $options = '')
function wpcf7dtx_tag_generator($contact_form, $options = '')
{
$options = wp_parse_args($options);
global $wpcf7_dynamic_fields_config;
$type = $options['id'];
switch ($type) {
case 'dynamichidden': //hiden
$description = __('Generate a form-tag for a hidden input field, with a dynamically generated default value.', 'contact-form-7-dynamic-text-extension');
break;
default:
$description = __('Generate a form-tag for a single-line plain text input field, with a dynamically generated default value.', 'contact-form-7-dynamic-text-extension');
break;
}
$input_type = str_replace('dynamic_', '', $type);
$utm_source = urlencode(home_url());
$description .= sprintf(
' %s <a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" title="%s" target="_blank" rel="noopener">%s</a>.',
esc_html__('For more details, see', 'contact-form-7-dynamic-text-extension'),
esc_attr($utm_source), //UTM source
esc_attr($type), //UTM content
esc_attr__('Go to DTX Documentation website', 'contact-form-7-dynamic-text-extension'),
esc_html__('DTX knowledge base', 'contact-form-7-dynamic-text-extension')
$description = sprintf(
__('Generate a form-tag for %s with a dynamic default value. For more details, see %s fields in the %s.', 'contact-form-7-dynamic-text-extension'),
esc_html($wpcf7_dynamic_fields_config[$type]['description']), // dynamic description
// Link to specific form-tag documentation
sprintf(
'<a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/%s?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" title="%s" target="_blank" rel="noopener">%s</a>',
esc_attr(str_replace('_', '-', $type)), // URL component
esc_attr($utm_source), //UTM source
esc_attr($type), //UTM content
esc_attr__('View this form-tag on the DTX Documentation website', 'contact-form-7-dynamic-text-extension'), // Link title
esc_html(ucwords(str_replace('_', ' ', $type))) // Link label
),
// Link to general DTX documentation
sprintf(
'<a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" title="%s" target="_blank" rel="noopener">%s</a>',
esc_attr($utm_source), //UTM source
esc_attr($type), //UTM content
esc_attr__('Go to DTX Documentation website', 'contact-form-7-dynamic-text-extension'),
esc_html__('DTX knowledge base', 'contact-form-7-dynamic-text-extension')
)
);
//Open Form-Tag Generator
// Open Form-Tag Generator
printf(
'<div class="control-box"><fieldset><legend>%s</legend><table class="form-table"><tbody>',
'<div class="control-box dtx-taggen"><fieldset><legend>%s</legend><table class="form-table"><tbody>',
wp_kses($description, array('a' => array('href' => array(), 'target' => array(), 'rel' => array(), 'title' => array()))) //Tag generator description
);
//Input field - Required checkbox (not available for hidden fields)
if ($type != 'dynamichidden') {
// Input field - Required checkbox (not available for some fields)
if (!in_array($input_type, array('hidden', 'quiz', 'submit', 'reset'))) {
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label></td></tr>',
esc_attr($options['content'] . '-required'), // field id
@@ -120,62 +119,253 @@ function wpcf7dtx_tag_generator_dynamictext($contact_form, $options = '')
);
}
//Input field - Field Name
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><input %s /></td></tr>',
esc_attr($options['content'] . '-name'), // field id
esc_html__('Name', 'contact-form-7-dynamic-text-extension'), // field label
wpcf7_format_atts(array(
'type' => 'text',
'name' => 'name',
'id' => $options['content'] . '-name',
'class' => 'tg-name oneline'
))
);
// Input field - Field Name (not available for some fields)
if (!in_array($input_type, array('submit', 'reset'))) {
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><input %s /></td></tr>',
esc_attr($options['content'] . '-name'), // field id
esc_html__('Name', 'contact-form-7-dynamic-text-extension'), // field label
wpcf7_format_atts(array(
'type' => 'text',
'name' => 'name',
'id' => $options['content'] . '-name',
'class' => 'tg-name oneline',
'autocomplete' => 'off'
))
);
}
//Input field - Dynamic value
// Input field - Dynamic value/options
$value_name = __('Dynamic value', 'contact-form-7-dynamic-text-extension');
$value_description = __('Can be static text or a shortcode.', 'contact-form-7-dynamic-text-extension');
$value_placeholder = "CF7_GET key='foo'";
$value_input_type = '<input %s />';
switch ($input_type) {
case 'textarea':
$value_placeholder = "CF7_get_post_var key='post_excerpt'";
$value_input_type = '<textarea %s></textarea>';
break;
case 'select':
$value_name = __('Dynamic options', 'contact-form-7-dynamic-text-extension');
$value_description .= ' ' . __('If static text, use one option per line. Can define static key/value pairs using pipes.', 'contact-form-7-dynamic-text-extension');
$value_description .= ' ' . __('If shortcode, it must return only option or optgroup HTML and can override the first option and select default settings here.', 'contact-form-7-dynamic-text-extension');
$value_placeholder = "hello-world | Hello World" . PHP_EOL . "Foo";
$value_input_type = '<textarea %s></textarea>';
break;
case 'checkbox':
case 'radio':
$value_name = __('Dynamic options', 'contact-form-7-dynamic-text-extension');
$value_description .= ' ' . __('If static text, use one option per line. Can define static key/value pairs using pipes.', 'contact-form-7-dynamic-text-extension');
$value_description .= ' ' . __('If shortcode, it must return only option or optgroup HTML.', 'contact-form-7-dynamic-text-extension');
$value_placeholder = "hello-world | Hello World" . PHP_EOL . "Foo";
$value_input_type = '<textarea %s></textarea>';
break;
default: // All other text fields
break;
}
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><input %s /><br /><small>%s <a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" target="_blank" rel="noopener">%s</a></small></td></tr>',
'<tr><th scope="row"><label for="%s">%s</label></th><td>' . $value_input_type . '<br /><small>%s <a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" target="_blank" rel="noopener">%s</a></small></td></tr>',
esc_attr($options['content'] . '-values'), // field id
esc_html__('Dynamic value', 'contact-form-7-dynamic-text-extension'), // field label
esc_html($value_name), // field label
wpcf7_format_atts(array(
'type' => 'text',
'name' => 'values',
'id' => $options['content'] . '-values',
'class' => 'oneline',
'placeholder' => "CF7_GET key='foo'"
'class' => 'multiline',
'placeholder' => $value_placeholder,
'list' => 'dtx-shortcodes'
)),
esc_html__('Can be static text or a shortcode.', 'contact-form-7-dynamic-text-extension'),
esc_attr($utm_source), //UTM source
esc_attr($type), //UTM content
esc_html__('View DTX shortcode syntax documentation', 'contact-form-7-dynamic-text-extension') //Link label
esc_html($value_description),
esc_attr($utm_source), // UTM source
esc_attr($type), // UTM content
esc_html__('View DTX shortcode syntax documentation', 'contact-form-7-dynamic-text-extension') // Link label
);
//Input field - Dynamic placeholder (not available for hidden fields)
if ($type != 'dynamichidden') {
if ($input_type == 'select') {
// Input field - Multiple selections checkbox
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><input %s /><input %s /><br /><small>%s <a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/dtx-attribute-placeholder/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" target="_blank" rel="noopener">%s</a></small></td></tr>',
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label></td></tr>',
esc_attr($options['content'] . '-multiple'), // field id
esc_html__('Multiple Options', 'contact-form-7-dynamic-text-extension'), // field Label
wpcf7_format_atts(array(
'type' => 'checkbox',
'name' => 'multiple',
'id' => $options['content'] . '-multiple',
'class' => 'option'
)),
esc_html__('Allow user to select multiple options', 'contact-form-7-dynamic-text-extension') // checkbox label
);
// Input field - Include blank checkbox
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label></td></tr>',
esc_attr($options['content'] . '-include_blank'), // field id
esc_html__('First Option', 'contact-form-7-dynamic-text-extension'), // field Label
wpcf7_format_atts(array(
'type' => 'checkbox',
'name' => 'include_blank',
'id' => $options['content'] . '-include_blank',
'class' => 'include_blankvalue option'
)),
esc_html__('Insert a blank item as the first option', 'contact-form-7-dynamic-text-extension') // checkbox label
);
}
// Input field - Dynamic placeholder (not available for some fields)
if (!in_array($input_type, array('hidden', 'radio', 'checkbox', 'quiz', 'submit', 'reset'))) {
$placeholder_description = '';
if (in_array($input_type, array('select', 'checkbox', 'radio'))) {
$placeholder_label = __('First Option Label', 'contact-form-7-dynamic-text-extension');
$placeholder_description .= __('Optionally define a label for the first option.', 'contact-form-7-dynamic-text-extension') . ' ';
} else {
$placeholder_label = __('Dynamic placeholder', 'contact-form-7-dynamic-text-extension');
}
$placeholder_description .= __('Can be static text or a shortcode.', 'contact-form-7-dynamic-text-extension');
$placeholder_input_type = $input_type == 'textarea' ? $value_input_type : '<input %s />';
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><input %s />' . $placeholder_input_type . '<br /><small>%s <a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/dtx-attribute-placeholder/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" target="_blank" rel="noopener">%s</a></small></td></tr>',
esc_attr($options['content'] . '-placeholder'), // field id
esc_html__('Dynamic placeholder', 'contact-form-7-dynamic-text-extension'), // field label
esc_html($placeholder_label), // field label
wpcf7_format_atts(array(
'type' => 'hidden',
'name' => 'placeholder',
'class' => 'option'
)),
wpcf7_format_atts(array(
'type' => 'text',
'name' => 'dtx-placeholder',
'id' => $options['content'] . '-placeholder', // field id
'class' => 'oneline dtx-option',
'placeholder' => 'CF7_get_post_var key=\'post_title\''
'class' => 'multiline dtx-option',
'placeholder' => "CF7_get_post_var key='post_title'",
'list' => 'dtx-shortcodes'
)),
esc_html__('Can be static text or a shortcode.', 'contact-form-7-dynamic-text-extension'), // Small note below input
esc_html($placeholder_description), // Small note below input
esc_attr($utm_source), //UTM source
esc_attr($type), //UTM content
esc_html__('View DTX placeholder documentation', 'contact-form-7-dynamic-text-extension') //Link label
);
}
// Additional fields for select regarding placeholder options
if ($input_type == 'select') {
// Input field - Hide Blank Option
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label><br /><small>%s <a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-select/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" target="_blank" rel="noopener">%s</a></small></td></tr>',
esc_attr($options['content'] . '-dtx_hide_blank'), // field id
esc_html__('Hide First Option', 'contact-form-7-dynamic-text-extension'), // field Label
wpcf7_format_atts(array(
'type' => 'checkbox',
'name' => 'dtx_hide_blank',
'id' => $options['content'] . '-dtx_hide_blank',
'class' => 'option'
)),
esc_html__('Hide the first blank option from being visible in the drop-down', 'contact-form-7-dynamic-text-extension'), // checkbox label
esc_html__('Optional. Only works if "First Option" is checked.', 'contact-form-7-dynamic-text-extension'), // Small note below input
esc_attr($utm_source), //UTM source
esc_attr($type), //UTM content
esc_html__('View Dynamic Select documentation', 'contact-form-7-dynamic-text-extension') //Link label
);
// Input field - Disable Blank Option
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label><br /><small>%s <a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-select/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" target="_blank" rel="noopener">%s</a></small></td></tr>',
esc_attr($options['content'] . '-dtx_disable_blank'), // field id
esc_html__('Disable First Option', 'contact-form-7-dynamic-text-extension'), // field Label
wpcf7_format_atts(array(
'type' => 'checkbox',
'name' => 'dtx_disable_blank',
'id' => $options['content'] . '-dtx_disable_blank',
'class' => 'option'
)),
esc_html__('Disable the first blank option from being selectable in the drop-down', 'contact-form-7-dynamic-text-extension'), // checkbox label
esc_html__('Optional. Only works if "First Option" is checked.', 'contact-form-7-dynamic-text-extension'), // Small note below input
esc_attr($utm_source), //UTM source
esc_attr($type), //UTM content
esc_html__('View Dynamic Select documentation', 'contact-form-7-dynamic-text-extension') //Link label
);
} elseif (in_array($input_type, array('checkbox', 'radio'))) {
// Additional fields for checkboxes and radio buttons
// Input field - Checkbox Layout Reverse Option
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label></td></tr>',
esc_attr($options['content'] . '-label_first'), // field id
esc_html__('Reverse', 'contact-form-7-dynamic-text-extension'), // field Label
wpcf7_format_atts(array(
'type' => 'checkbox',
'name' => 'label_first',
'id' => $options['content'] . '-label_first',
'class' => 'option'
)),
esc_html__('Put a label first, an input last', 'contact-form-7-dynamic-text-extension') // checkbox label
);
// Input field - Label UI
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label></td></tr>',
esc_attr($options['content'] . '-use_label_element'), // field id
esc_html__('Label', 'contact-form-7-dynamic-text-extension'), // field Label
wpcf7_format_atts(array(
'type' => 'checkbox',
'name' => 'use_label_element',
'id' => $options['content'] . '-use_label_element',
'class' => 'option'
)),
esc_html__('Wrap each item with label element', 'contact-form-7-dynamic-text-extension') // checkbox label
);
// Input field - Exclusive Checkbox
if ($input_type == 'checkbox') {
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label></td></tr>',
esc_attr($options['content'] . '-exclusive'), // field id
esc_html__('Exclusive', 'contact-form-7-dynamic-text-extension'), // field Label
wpcf7_format_atts(array(
'type' => 'checkbox',
'name' => 'exclusive',
'id' => $options['content'] . '-exclusive',
'class' => 'option'
)),
esc_html__('Make checkboxes exclusive', 'contact-form-7-dynamic-text-extension') // checkbox label
);
}
}
// Input field - Dynamic default value (not available for some fields)
if (in_array($input_type, array('select'))) {
$default_input_type = '<input %s />';
$default_placeholder = '';
if ($input_type == 'checkbox') {
$default_input_type = '<textarea %s></textarea>';
$default_description = __('Optionally define the default on/off status of the checkboxes by putting a 1 (checked) or 0 (not checked) on each line that corresponds with the options.', 'contact-form-7-dynamic-text-extension') . ' ';
$default_placeholder = '0' . PHP_EOL . '1';
} else {
$default_description = __('Optionally define the option that is selected by default. This can be different than the first [blank] option. If options use key/value pairs, only define the key here.', 'contact-form-7-dynamic-text-extension') . ' ';
}
$default_description .= __('Can be static text or a shortcode.', 'contact-form-7-dynamic-text-extension');
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><input %s />' . $default_input_type . '<br /><small>%s <a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-select/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" target="_blank" rel="noopener">%s</a></small></td></tr>',
esc_attr($options['content'] . '-default'), // field id
esc_html__('Selected Default'), // field label
wpcf7_format_atts(array(
'type' => 'hidden',
'name' => 'default',
'class' => 'option'
)),
wpcf7_format_atts(array(
'name' => 'dtx-default',
'id' => $options['content'] . '-default', // field id
'class' => 'oneline dtx-option',
'placeholder' => $default_placeholder,
'list' => 'dtx-shortcodes'
)),
esc_html($default_description), // Small note below input
esc_attr($utm_source), //UTM source
esc_attr($type), //UTM content
esc_html__('View Dynamic Select documentation', 'contact-form-7-dynamic-text-extension') //Link label
);
}
//Input field - ID attribute
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><input %s /></td></tr>',
@@ -202,8 +392,8 @@ function wpcf7dtx_tag_generator_dynamictext($contact_form, $options = '')
))
);
//Input field - Readonly attribute (not available for hidden fields)
if ($type != 'dynamichidden') {
//Input field - Readonly attribute (not available for hidden, submit, or quiz fields)
if (!in_array($input_type, array('hidden', 'submit', 'quiz'))) {
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label></td></tr>',
esc_attr($options['content'] . '-readonly'), // field id
@@ -218,25 +408,55 @@ function wpcf7dtx_tag_generator_dynamictext($contact_form, $options = '')
);
}
// Page load data attribute (triggers the loading of a frontend script)
// Input field - Page load data attribute (triggers the loading of a frontend script)
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label><br /><small>%s <a href="https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tag-attribute-after-page-load/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=form-tag-generator-%s" target="_blank" rel="noopener">%s</a></small></td></tr>',
esc_attr($options['content'] . '-frontend'), // field id
esc_attr($options['content'] . '-dtx_pageload'), // field id
esc_html__('Cache Compatible', 'contact-form-7-dynamic-text-extension'), // field Label
wpcf7_format_atts(array(
'type' => 'checkbox',
'name' => 'dtx_pageload',
'id' => $options['content'] . '-dtx_pageload',
'class' => 'dtx_pageloadvalue option'
'class' => 'option'
)),
esc_html__('Get the dynamic value after the page has loaded', 'contact-form-7-dynamic-text-extension'), // checkbox label
esc_html('May impact page performance.', 'contact-form-7-dynamic-text-extension'), // Small note below input
esc_html__('May impact page performance.', 'contact-form-7-dynamic-text-extension'), // Small note below input
esc_attr($utm_source), //UTM source
esc_attr($type), //UTM content
esc_html__('View DTX page load documentation', 'contact-form-7-dynamic-text-extension') //Link label
);
// Input field - Akismet module (only available for text, email, and url fields)
if (in_array($input_type, array('text', 'email', 'url'))) {
switch ($input_type) {
case 'email':
$akismet_name = 'author_email';
$akismet_desc = __("This field requires author's email address", 'contact-form-7-dynamic-text-extension');
break;
case 'url':
$akismet_name = 'author_url';
$akismet_desc = __("This field requires author's URL", 'contact-form-7-dynamic-text-extension');
break;
default:
$akismet_name = 'author';
$akismet_desc = __("This field requires author's name", 'contact-form-7-dynamic-text-extension');
break;
}
printf(
'<tr><th scope="row"><label for="%s">%s</label></th><td><label><input %s />%s</label></td></tr>',
esc_attr($options['content'] . '-readonly'), // field id
esc_html__('Akismet', 'contact-form-7-dynamic-text-extension'), // field Label
wpcf7_format_atts(array(
'type' => 'checkbox',
'name' => 'akismet:' . $akismet_name,
'id' => $options['content'] . '-akismet-' . $akismet_name,
'class' => 'akismetvalue option'
)),
esc_html($akismet_desc) // checkbox label
);
}
//Close Form-Tag Generator
printf(
'</tbody></table></fieldset></div><div class="insert-box"><input type="text" name="%s" class="tag code" readonly="readonly" onfocus="this.select()" /><div class="submitbox"><input type="button" class="button button-primary insert-tag" value="%s" /></div><br class="clear" /></div>',
@@ -50,6 +50,9 @@ add_filter('wpcf7dtx_allow_protocols', 'wpcf7dtx_allow_protocols', 10, 2);
*/
function wpcf7dtx_sanitize($value = '', $type = 'auto', $protocols = false)
{
if ($type == 'none') {
return $value;
}
$value = is_string($value) ? $value : strval($value); // Force string value
if (!empty($value)) {
$type = $type == 'auto' ? wpcf7dtx_detect_value_type($value) : sanitize_text_field($type);
@@ -62,6 +65,8 @@ function wpcf7dtx_sanitize($value = '', $type = 'auto', $protocols = false)
return sanitize_key($value);
case 'slug':
return sanitize_title($value);
case 'textarea':
return sanitize_textarea_field($value);
}
}
return sanitize_text_field($value);
@@ -82,6 +87,9 @@ add_filter('wpcf7dtx_sanitize', 'wpcf7dtx_sanitize', 10, 3);
*/
function wpcf7dtx_escape($value = '', $obfuscate = false, $type = 'auto', $protocols = false)
{
if ($type == 'none') {
return $value;
}
$value = apply_filters('wpcf7dtx_sanitize', $value, $type); // Sanitize value
if (!empty($value)) {
if ($obfuscate) {
@@ -91,6 +99,8 @@ function wpcf7dtx_escape($value = '', $obfuscate = false, $type = 'auto', $proto
switch ($type) {
case 'url':
return esc_url($value, apply_filters('wpcf7dtx_allow_protocols', $protocols));
case 'textarea':
return esc_textarea($value);
}
}
return esc_attr($value); // Return attribute value
@@ -182,51 +192,449 @@ function wpcf7dtx_get_post_id($post_id, $context = 'dtx')
}
/**
* Parse Content for Specified Shortcodes
* Get Dynamic Value
*
* Parse a string of content for a specific shortcode to retrieve its attributes and content
* @since 3.2.2
*
* @since 3.1.0
* @param string $value The form tag value.
* @param WPCF7_FormTag|false $tag Optional. Use to look up default value.
* @param string $sanitize Optional. Specify type of sanitization. Default is `auto`.
*
* @param string $content The content to parse
* @param string $tag The shortcode tag
*
* @return array An associative array with `tag` (string) and `shortcodes` (sequential array). If shortcodes were discovered, each one has keys for `atts` (associative array) and `content` (string)
* @return string The dynamic output or the original value, not escaped or sanitized.
*/
function wpcf7dtx_get_shortcode_atts($content)
function wpcf7dtx_get_dynamic($value, $tag = false, $sanitize = 'auto')
{
$return = array(
'tag' => '',
'atts' => array()
if ($tag !== false) {
$default = $tag->get_option('defaultvalue', '', true);
if (!$default) {
$default = $tag->get_default_option(strval(reset($tag->values)));
}
$value = wpcf7_get_hangover($tag->name, $default);
}
$value = apply_filters('wpcf7dtx_sanitize', $value, $sanitize);
if (is_string($value) && !empty($value)) {
// If a shortcode was passed as the value, evaluate it and use the result
$shortcode_tag = '[' . $value . ']';
$shortcode_output = do_shortcode($shortcode_tag); //Shortcode value
if (is_string($shortcode_output) && $shortcode_output != $shortcode_tag) {
return apply_filters('wpcf7dtx_sanitize', $shortcode_output, $sanitize);
}
}
return $value;
}
/**
* Get Allowed HTML for Form Field Properties
*
* @since 4.0.0
*
* @param string $type Optional. The type of input for unique properties. Default is `text`.
* @param array $extra Optional. A sequential array of properties to additionally include.
*
* @return array An associative array of allowed properties appropriate for use in `wp_kses()`
*/
function wpcf7dtx_get_allowed_field_properties($type = 'text', $extra = array())
{
if (in_array($type, array('option', 'optgroup'))) {
return array(
'optgroup' => array(
'label' => array(),
'disabled' => array(),
'hidden' => array()
),
'option' => array(
'value' => array(),
'selected' => array(),
'disabled' => array(),
'hidden' => array()
)
);
}
$allowed_properties = array(
// Global properties
'type' => array(),
'id' => array(),
'name' => array(),
'value' => array(),
'required' => array(),
'class' => array(),
'disabled' => array(),
'readonly' => array(),
'tabindex' => array(),
'size' => array(),
'title' => array(),
'autofocus' => array(),
// ARIA properties
'aria-invalid' => array(),
'aria-describedby' => array(),
// DTX properties
'data-dtx-value' => array(),
);
//Search for shortcodes with attributes
if (false !== ($start = strpos($content, ' '))) {
$return['tag'] = substr($content, 0, $start); //Opens the start tag, assumes there are attributes because of the space
if (in_array($type, array('checkbox', 'radio', 'acceptance'))) {
// Properties exclusive to checkboxes and radio buttons
$allowed_properties['checked'] = array();
$allowed_properties['dtx-default'] = array();
} elseif (in_array($type, array('number', 'range'))) {
// Properties exclusive to number inputs
$allowed_properties['step'] = array();
} elseif ($type == 'select') {
// Properties exclusive to select fields
$allowed_properties['multiple'] = array();
$allowed_properties['dtx-default'] = array();
unset($allowed_properties['type'], $allowed_properties['value'], $allowed_properties['placeholder'], $allowed_properties['size']); // Remove invalid select attributes
}
if (!in_array($type, array('checkbox', 'radio', 'select', 'acceptance'))) {
// Allowed properties for all text-based inputs
$allowed_properties['placeholder'] = array();
$allowed_properties['autocomplete'] = array();
$allowed_properties['minlength'] = array();
$allowed_properties['maxlength'] = array();
if (in_array($type, array('number', 'range', 'date', 'datetime-local', 'time'))) {
// Additional properties for number and date inputs
$allowed_properties['min'] = array();
$allowed_properties['max'] = array();
}
if ($type == 'textarea') {
// Additional properties exclusive to textarea fields
$allowed_properties['cols'] = array();
$allowed_properties['rows'] = array();
unset($allowed_properties['type'], $allowed_properties['value']); // Remove invalid textarea attributes
} elseif (in_array($type, array('text', 'date', 'url', 'tel', 'email', 'password'))) {
// Additional properties exclusive to specific text fields
$allowed_properties['pattern'] = array();
}
}
if (is_array($extra) && count($extra)) {
foreach ($extra as $property) {
$allowed_properties[sanitize_title($property)] = array();
}
}
return $allowed_properties;
}
//Parse for shortcode attributes: `shortcode att1='foo' att2='bar'`
//Chop only the attributes e.g. `att1="foo" att2="bar"`
$atts_str = trim(str_replace($return['tag'], '', $content));
if (strpos($atts_str, "'") !== false) {
$atts = explode("' ", substr(
$atts_str,
0,
-1 //Clip off the last character, which is a single quote
));
if (is_array($atts) && count($atts)) {
foreach ($atts as $att_str) {
$pair = explode("='", $att_str);
if (is_array($pair) && count($pair) > 1) {
$key = sanitize_key(trim($pair[0])); //Validate & normalize the key
if (!empty($key)) {
$return['atts'][$key] = sanitize_text_field(html_entity_decode($pair[1]));
}
/**
* Returns a formatted string of HTML attributes
*
* @since 4.0.0
*
* @param array $atts Associative array of attribute name and value pairs
*
* @return string Formatted HTML attributes with keys and values both escaped
*/
function wpcf7dtx_format_atts($atts)
{
if (is_array($atts) && count($atts)) {
$sanitized_atts = array();
static $boolean_attributes = array(
'checked', 'disabled', 'multiple', 'readonly', 'required', 'selected'
);
foreach ($atts as $key => $value) {
$key = sanitize_key(strval($key));
if ($key) {
if (in_array($key, $boolean_attributes) || is_bool($value)) {
if ($value) {
$sanitized_atts[$key] = $key;
}
} elseif ($value && (is_string($value) || is_numeric($value))) {
$sanitized_atts[$key] = $value;
}
}
}
if (count($sanitized_atts)) {
$output = array();
foreach ($sanitized_atts as $key => $value) {
$output[] = sprintf('%s="%s"', esc_attr($key), esc_attr($value));
}
return implode(' ', $output);
}
}
return $return;
return '';
}
/**
* Create Input Field HTML
*
* @since 4.0.0
*
* @param array $atts An associative array of input attributes.
*
* @return string HTML output of input field
*/
function wpcf7dtx_input_html($atts)
{
return sprintf('<input %s />', wpcf7dtx_format_atts($atts));
}
/**
* Create Checkbox Field HTML
*
* @since 4.0.0
*
* @param array $atts An associative array of select input attributes.
* @param string $label_text Optional. The text to display next to the checkbox or radio button.
* @param bool $label_ui Optional. If true, will place input and label text inside a `<label>` element. Default is true.
* @param bool $reverse Optional. If true, will reverse the order to display the text label first then the button. Has no effect if label text is empty. Default is false.
*
* @return string HTML output of the checkbox or radio button or empty string on failure.
*/
function wpcf7dtx_checkbox_html($atts, $label_text = '', $label_ui = true, $reverse = false)
{
// Default field attributes
$atts = array_merge(array('value' => '', 'dtx-default' => ''), array_change_key_case((array)$atts, CASE_LOWER));
if ($atts['value'] && $atts['dtx-default'] && $atts['value'] == $atts['dtx-default']) {
$atts['checked'] = 'checked';
}
$input = wpcf7dtx_input_html($atts);
if (!empty(trim($label_text))) {
$label_el = $label_ui ? 'span' : 'label'; // If not wrapping with a label element, display it next to it
$label_text = sprintf(
'<%1$s%2$s class="wpcf7-list-item-label">%3$s</%1$s>',
$label_el,
// If not wrapping with a label element and the element has an ID attribute, add a `for` attribute
$label_ui ? '' : (wpcf7dtx_array_has_key('id', $atts) ? ' for="' . esc_attr($atts['id']) . '"' : ''),
esc_html($label_text)
);
if ($reverse) {
$html = $label_text . $input;
} else {
$html = $input . $label_text;
}
} else {
$html = $input;
}
if ($label_ui) {
$html = '<label>' . $html . '</label>';
}
return $html;
}
/**
* Create Checkbox Group HTML
*
* @since 4.0.3
*
* @param array $atts An associative array of select input attributes.
* @param array|string $options Accepts an associative array of key/value pairs to use as the
* select option's value/label pairs. It also accepts an associative array of associative
* arrays with the keys being used as option group labels and the array values used as that
* group's options. It also accepts a string value of HTML already formatted as options or
* option groups. It also accepts a string value of a self-closing shortcode that is
* evaluated and its output is either options or option groups.
* @param bool $label_ui Optional. If true, will place input and label text inside a `<label>` element. Default is true.
* @param bool $reverse Optional. If true, will reverse the order to display the text label first then the button. Has no effect if label text is empty. Default is false.
*
* @return string HTML output of the checkbox or radio button or empty string on failure.
*/
function wpcf7dtx_checkbox_group_html($atts, $options, $label_ui = false, $reverse = false, $exclusive = false)
{
$group_html = '';
if ($count = count($options)) {
// Attributes specific to HTML creation
$atts = array_merge(array(
'type' => 'checkbox',
'id' => '',
'name' => '',
'value' => '',
'dtx-default' => ''
), array_change_key_case((array)$atts, CASE_LOWER));
// Loop all the options
$group_html = array();
$id_prefix = ($atts['id'] ? $atts['id'] : uniqid($atts['name'] . '_')) . '_'; // Create prefix from passed ID or Name
$i = 1;
foreach ($options as $value => $label) {
$my_atts = array_merge($atts, array(
'id' => sanitize_html_class($id_prefix . $i) // Always have unique IDs for group items
));
$dynamic_value = '';
$dynamic_label = $label;
if ($value && $label && $value === $label) {
// These are identical, just handle it as one, could also be a raw shortcode
$dynamic_option = trim(wpcf7dtx_get_dynamic($value, false, 'none')); // Do not sanitize yet, it may have HTML
if (is_string($dynamic_option) && !empty($dynamic_option) && strpos($dynamic_option, '{') === 0 && strpos($dynamic_option, '}') === strlen($dynamic_option) - 1) {
// If it outputs JSON, try parsing it
try {
$dynamic_option = json_decode($dynamic_option, true);
if (is_array($dynamic_option) && count($dynamic_option)) {
$group_html[] = wpcf7dtx_checkbox_group_html(
$my_atts,
$dynamic_option,
$label_ui,
$reverse,
$exclusive
);
}
} catch (Exception $e) {
// Fail quietly
if (WP_DEBUG && WP_DEBUG_LOG) {
error_log('[Contact Form 7 - Dynamic Text Extension] Error parsing JSON value');
error_log($e->getMessage());
}
}
$i++;
continue; // Continue with next iteration
} elseif (is_string($dynamic_option) && !empty($dynamic_option) && esc_html($dynamic_option) != $dynamic_option) {
$group_html[] = force_balance_tags($dynamic_option); // If it outputs HTML, escape and use them as-is
$i++;
continue; // Continue with next iteration
} else {
$dynamic_value = $dynamic_option;
$dynamic_label = $dynamic_option;
}
} else {
// These are different, could be raw shortcodes
$dynamic_value = wpcf7dtx_get_dynamic($value, false);
$dynamic_label = wpcf7dtx_get_dynamic($label, false);
}
// This could be a single??
$class = array('wpcf7-list-item');
$class[] = sanitize_html_class('wpcf7-list-item-' . $i);
if ($i === 1) {
$class[] = 'first';
}
if ($i === $count) {
$class[] = 'last';
}
if ($exclusive) {
$class[] = 'wpcf7-exclusive-checkbox';
}
if ($dynamic_value && $atts['dtx-default'] && $dynamic_value == $atts['dtx-default']) {
$my_atts['checked'] = 'checked';
}
$group_html[] = sprintf(
'<span class="%s">%s</span>',
esc_attr(implode(' ', $class)),
wpcf7dtx_checkbox_html(
// Overwrite name attribute
array_merge($my_atts, array(
'name' => $atts['type'] == 'radio' || $exclusive || $count === 1 ? $atts['name'] : $atts['name'] . '[]', // if there are multiple checkboxes and they aren't exclusive, names are an array
'value' => $dynamic_value
)),
$dynamic_label,
$label_ui,
$reverse
)
);
$i++;
}
$group_html = implode('', $group_html);
}
return $group_html;
}
/**
* Create Textarea Field HTML
*
* @since 4.0.0
*
* @param array $atts An associative array of textarea field attributes.
*
* @return string HTML output of textarea field
*/
function wpcf7dtx_textarea_html($atts)
{
// Attributes specific to HTML creation
$atts = array_merge(array('value' => ''), array_change_key_case((array)$atts, CASE_LOWER));
return sprintf(
'<textarea %s>%s</textarea>',
wpcf7dtx_format_atts($atts),
apply_filters('wpcf7dtx_escape', $atts['value'], false, 'textarea')
);
}
/**
* Create Select Field HTML
*
* @since 4.0.0
*
* @param array $atts An associative array of select input attributes.
* @param array|string $options Accepts an associative array of key/value pairs to use as the
* select option's value/label pairs. It also accepts an associative array of associative
* arrays with the keys being used as option group labels and the array values used as that
* group's options. It also accepts a string value of HTML already formatted as options or
* option groups. It also accepts a string value of a self-closing shortcode that is
* evaluated and its output is either options or option groups.
* @param bool $hide_blank Optional. If true, the first blank placeholder option will have the `hidden` attribute added to it. Default is false.
* @param bool $disable_blank Optional. If true, the first blank placeholder option will have the `disabled` attribute added to it. Default is false.
*
* @return string HTML output of select field
*/
function wpcf7dtx_select_html($atts, $options, $hide_blank = false, $disable_blank = false)
{
// Attributes specific to HTML creation
$atts = array_merge(array('placeholder' => '', 'dtx-default' => ''), array_change_key_case((array)$atts, CASE_LOWER));
$options_html = ''; // Open options HTML
// If using a placeholder, use it as the text of the first option
if ($atts['placeholder']) {
$options_html .= sprintf(
'<option value=""%s%s%s>%s</option>',
empty($atts['dtx-default']) ? ' selected' : '',
$hide_blank ? ' hidden' : '',
$disable_blank ? ' disabled' : '',
apply_filters('wpcf7dtx_escape', $atts['placeholder'])
);
}
if (is_array($options) && count($options)) {
//Check if using option groups
if (is_array(array_values($options)[0])) {
foreach ($options as $group_name => $opt_group) {
$options_html .= sprintf('<optgroup label="%s">', esc_attr(apply_filters('wpcf7dtx_escape', wpcf7dtx_get_dynamic($group_name)))); // Open option group
foreach ($opt_group as $option_value => $option_label) {
// Check if option values and groups are dynamic
$dynamic_option_value = wpcf7dtx_get_dynamic($option_value);
$options_html .= sprintf(
'<option value="%1$s"%3$s>%2$s</option>',
esc_attr(apply_filters('wpcf7dtx_escape', $dynamic_option_value)),
esc_html(apply_filters('wpcf7dtx_escape', wpcf7dtx_get_dynamic($option_label))),
$atts['dtx-default'] == $dynamic_option_value ? ' selected' : ''
);
}
$options_html .= '</optgroup>'; // Close option group
}
} else {
$allowed_html = wpcf7dtx_get_allowed_field_properties('option');
foreach ($options as $option_value => $option_label) {
if ($option_value === $option_label) {
// These are identical, just handle it as one, could also be a raw shortcode
$dynamic_option = trim(wpcf7dtx_get_dynamic($option_value, false, 'none')); // Do not sanitize yet, it may have HTML
if (is_string($dynamic_option) && !empty($dynamic_option) && (strpos($dynamic_option, '<option') === 0 || stripos($dynamic_option, '<optgroup') === 0)) {
$options_html .= wp_kses($dynamic_option, $allowed_html); // If it outputs HTML, escape and use them as-is
} elseif ($dynamic_option) {
// Just output the option
$dynamic_option = apply_filters('wpcf7dtx_escape', $dynamic_option);
$options_html .= sprintf(
'<option value="%1$s"%3$s>%2$s</option>',
esc_attr($dynamic_option),
esc_html($dynamic_option),
$atts['dtx-default'] == $dynamic_option ? ' selected' : ''
);
}
} else {
$dynamic_option_value = wpcf7dtx_get_dynamic($option_value, false);
$options_html .= sprintf(
'<option value="%1$s"%3$s>%2$s</option>',
esc_attr(apply_filters('wpcf7dtx_escape', $dynamic_option_value)),
esc_html(apply_filters('wpcf7dtx_escape', wpcf7dtx_get_dynamic($option_label))),
$atts['dtx-default'] == $dynamic_option_value ? ' selected' : ''
);
}
}
}
} elseif (is_string($options) && !empty($options = trim($options))) {
$allowed_html = wpcf7dtx_get_allowed_field_properties('option');
// If options were passed as a string, go ahead and use them
if (strpos($options, '<option') === 0 || stripos($options, '<optgroup') === 0) {
$options_html .= wp_kses($options, $allowed_html);
} else {
// If a shortcode was passed as the options, evaluate it and use the result
$shortcode_output = wpcf7dtx_get_dynamic($options);
if (is_string($shortcode_output) && !empty($shortcode_output) && (strpos($shortcode_output, '<option') === 0) || strpos($shortcode_output, '<optgroup') === 0) {
$options_html .= wp_kses($shortcode_output, $allowed_html);
}
}
}
return sprintf('<select %s>%s</select>', wpcf7dtx_format_atts($atts), $options_html);
}
/**
@@ -253,21 +661,3 @@ function wpcf7dtx_array_has_key($key, $array = array(), $default = '')
}
return $default;
}
if (!function_exists('array_key_first')) {
/**
* Gets the first key of an array
*
* Gets the first key of the given array without affecting the internal array pointer.
*
* @param array $array
* @return int|string|null
*/
function array_key_first($array = array())
{
foreach ($array as $key => $value) {
return $key;
}
return null;
}
}
@@ -0,0 +1,233 @@
<?php
/**
* Add Frontend Validation Messages
*
* @since 4.0.0
*
* @param array An associative array of messages
*
* @return array A modified associative array of messages
*/
function wpcf7dtx_messages($messages)
{
return array_merge($messages, array(
'dtx_invalid_email' => array(
'description' => __('There is a field with an invalid email address', 'contact-form-7-dynamic-text-extension'),
'default' => __('Please enter a valid email address.', 'contact-form-7-dynamic-text-extension')
),
'dtx_invalid_tel' => array(
'description' => __('There is a field with an invalid phone number', 'contact-form-7-dynamic-text-extension'),
'default' => __('Please enter a valid phone number.', 'contact-form-7-dynamic-text-extension')
),
'dtx_invalid_number' => array(
'description' => __('There is a field with an invalid number', 'contact-form-7-dynamic-text-extension'),
'default' => __('Please enter a valid number.', 'contact-form-7-dynamic-text-extension')
),
'dtx_invalid_date' => array(
'description' => __('There is a field with an invalid date', 'contact-form-7-dynamic-text-extension'),
'default' => __('Please enter a valid date.', 'contact-form-7-dynamic-text-extension')
),
));
}
add_filter('wpcf7_messages', 'wpcf7dtx_messages');
/**
* Validate DTX Form Fields
*
* Frontend validation for DTX form tags
*
* @param WPCF7_Validation $result the current validation result object
* @param WPCF7_FormTag $tag the current form tag being filtered for validation
*
* @return WPCF7_Validation a possibly modified validation result object
*/
function wpcf7dtx_validation_filter($result, $tag)
{
$type = str_replace(array('dynamic_', 'dynamic'), '', $tag->basetype);
if (empty($tag->name) || in_array($type, array('hidden', 'submit', 'reset'))) {
return $result; // Bail early for tags without names or if a specific type
}
// Get the value
$user_value = wpcf7dtx_array_has_key($tag->name, $_POST);
if (is_array($user_value)) {
$selection_count = count($user_value);
if (!wpcf7_form_tag_supports($tag->type, 'selectable-values')) {
// Field passed selectable values when it's doesn't support them
$result->invalidate($tag, wpcf7_get_message('validation_error'));
return $result;
} elseif ($selection_count > 1) {
if (!wpcf7_form_tag_supports($tag->type, 'multiple-controls-container')) {
// Field passed multiple values when it's doesn't support them
$result->invalidate($tag, wpcf7_get_message('validation_error'));
return $result;
}
foreach ($user_value as $selection) {
// Validate each selected choice
$result = wpcf7dtx_validate_value($result, sanitize_textarea_field(strval($selection)), $tag, $type);
if (!$result->is_valid($tag->name)) {
return $result; // Return early if any are invalid
}
}
return $result;
}
$user_value = sanitize_text_field(strval(implode(' ', $user_value)));
} elseif ($type == 'textarea') {
$user_value = sanitize_textarea_field(strval($user_value));
} else {
$user_value = sanitize_text_field(strval($user_value));
}
// Validate and return
return wpcf7dtx_validate_value($result, $user_value, $tag, $type);
}
/**
* Validate Single Value
*
* @param WPCF7_Validation $result the current validation result object
* @param string $value the current value being validated, sanitized
* @param WPCF7_FormTag $tag the current form tag being filtered for validation
* @param string $type Optional. The type of the current form tag. Default is blank for lookup.
*
* @return WPCF7_Validation a possibly modified validation result object
*/
function wpcf7dtx_validate_value($result, $value, $tag, $type = '')
{
$type = $type ? $type : str_replace(array('dynamic_', 'dynamic'), '', $tag->basetype);
// Validate required fields for value
if ($tag->is_required() && empty($value)) {
$result->invalidate($tag, wpcf7_get_message('invalid_required'));
return $result;
}
// Validate value by type
if (!empty($value)) {
switch ($type) {
case 'email':
if (!wpcf7_is_email($value)) {
$result->invalidate($tag, wpcf7_get_message('dtx_invalid_email'));
return $result;
}
break;
case 'tel':
if (!wpcf7_is_tel($value)) {
$result->invalidate($tag, wpcf7_get_message('dtx_invalid_tel'));
return $result;
}
break;
case 'number':
case 'range':
if (!wpcf7_is_number($value)) {
$result->invalidate($tag, wpcf7_get_message('dtx_invalid_number'));
return $result;
}
break;
case 'date':
if (!wpcf7_is_date($value)) {
$result->invalidate($tag, wpcf7_get_message('dtx_invalid_date'));
return $result;
}
break;
}
// Finish validating text-based inputs
$maxlength = $tag->get_maxlength_option();
$minlength = $tag->get_minlength_option();
if ($maxlength && $minlength && $maxlength < $minlength) {
$maxlength = $minlength = null;
}
$code_units = wpcf7_count_code_units($value);
if (false !== $code_units) {
if ($maxlength && $maxlength < $code_units) {
$result->invalidate($tag, wpcf7_get_message('invalid_too_long'));
return $result;
} elseif ($minlength && $code_units < $minlength) {
$result->invalidate($tag, wpcf7_get_message('invalid_too_short'));
return $result;
}
}
}
return $result;
}
/**
* Backend Mail Configuration Validation
*
* Validate dynamic form tags used in mail configuration.
*
* @since 4.0.0
*
* @param WPCF7_ConfigValidator
*
* @return void
*/
function wpcf7dtx_validate($validator)
{
if (!$validator->is_valid()) {
$contact_form = null;
$form_tags = null;
foreach ($validator->collect_error_messages() as $component => $errors) {
$components = explode('.', $component);
if (count($components) === 2 && strpos($components[0], 'mail') === 0 && in_array($components[1], array('sender', 'recipient', 'additional_headers'))) {
foreach ($errors as $error) {
// Focus on email fields that flag the invalid mailbox syntax warning, have to test link because code isn't sent and message could be in any language
if (strpos(wpcf7dtx_array_has_key('link', $error), 'invalid-mailbox-syntax') !== false) {
if (is_null($contact_form)) {
$contact_form = $validator->contact_form();
}
if (is_null($form_tags)) {
$form_tags = wpcf7_scan_form_tags();
}
$raw_value = $contact_form->prop($components[0])[$components[1]];
foreach ($form_tags as $tag) {
if (!empty($tag->name)) {
// Check if this form tag is in the raw value
$form_tag = '[' . $tag->name . ']';
if (strpos($raw_value, $form_tag) !== false && in_array($tag->basetype, array_keys(wpcf7dtx_config()))) {
$validator->remove_error($component, 'invalid_mailbox_syntax'); // Remove error, this is ours to handle now
$utm_source = urlencode(home_url());
if (!in_array($tag->basetype, array('dynamic_hidden', 'dynamic_email'))) {
$validator->add_error($component, 'invalid_mailbox_syntax', array(
'message' => __('Only email, dynamic email, hidden, or dynamic hidden form tags can be used for email addresses.', 'contact-form-7-dynamic-text-extension'),
'link' => esc_url(sprintf('https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/configuration-errors/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=config-error-invalid_mailbox_syntax#valid-form-tags', $utm_source))
));
} else {
$dynamic_value = wpcf7dtx_get_dynamic(false, $tag); // Get the dynamic value of this tag
if (empty($dynamic_value) && $tag->basetype == 'dynamic_hidden') {
$validator->add_error($component, 'maybe_empty', array(
'message' => __('The dynamic hidden form tag must have a default value.', 'contact-form-7-dynamic-text-extension'),
'link' => esc_url(sprintf('https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/configuration-errors/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=config-error-maybe_empty#maybe-empty', $utm_source))
));
} elseif (empty($dynamic_value) && !$tag->is_required()) {
$validator->add_error($component, 'maybe_empty', array(
'message' => __('The dynamic form tag must be required or have a default value.', 'contact-form-7-dynamic-text-extension'),
'link' => esc_url(sprintf('https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/configuration-errors/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=config-error-maybe_empty#maybe-empty', $utm_source))
));
} elseif (!empty($dynamic_value)) {
if (!wpcf7_is_email($dynamic_value)) {
$validator->add_error($component, 'invalid_mailbox_syntax', array(
'message' => __('The default dynamic value does not result in a valid email address.', 'contact-form-7-dynamic-text-extension'),
'link' => esc_url(sprintf('https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/configuration-errors/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=config-error-invalid_mailbox_syntax#invalid-email-address', $utm_source))
));
} elseif ($component[1] == 'sender' && !wpcf7_is_email_in_site_domain($dynamic_value)) {
$validator->add_error($component, 'email_not_in_site_domain', array(
'message' => __('The dynamic email address for the sender does not belong to the site domain.', 'contact-form-7-dynamic-text-extension'),
'link' => esc_url(sprintf('https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/configuration-errors/?utm_source=%s&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=config-error-email_not_in_site_domain#invalid-site-domain', $utm_source))
));
}
}
}
}
}
}
}
}
}
}
}
}
add_action('wpcf7_config_validator_validate', 'wpcf7dtx_validate');
@@ -0,0 +1 @@
<?php // Silence is golden
@@ -3,9 +3,9 @@ Contributors: sevenspark, tessawatkinsllc
Donate link: https://just1voice.com/donate/
Tags: Contact Form 7, autofill, prepopulate, input, form field, contact form, text, hidden, input, dynamic, GET, POST, title, slug, auto-fill, pre-populate
Tested up to: 6.3
Stable tag: 3.5.4
Stable tag: 4.1.0
This plugin provides additional form tags for the Contact Form 7 plugin. It allows dynamic generation of content for text or hidden input fields using any shortcode.
This plugin provides additional form tags for the Contact Form 7 plugin. It allows dynamic generation of content for text-based input fields like text, hidden, and email, checkboxes, radio buttons, and drop-down selections using any shortcode.
== Description ==
@@ -25,11 +25,25 @@ Contact Form 7 is an excellent WordPress plugin and one of the top choices of fr
* Getting custom theme modifications
* Any value using custom shortcodes
For over 10 years, DTX only handled `<input type="text" />` and `<input type="hidden" />` form fields, but version 4 finally introduces more:
* email
* URL
* tel (for phone numbers)
* number
* range (slider)
* textarea (multiline text)
* drop-down menu (select field)
* checkboxes
* radio buttons
* date
* submit (yes, a submit button where you can have dynamic text!)
The possibilities are endless!
## WHAT DOES IT DO? ##
DTX comes with several built-in shortcodes that will allow the contact form to be populated from HTTPS GET variable or any info from the `get_bloginfo()` function, among others. See below for included shortcodes.
DTX provides flexibility to WordPress users in creating dynamic forms in Contact Form 7. DTX comes with several built-in shortcodes that will allow the contact form to be populated from HTTPS GET variable or any info from the `get_bloginfo()` function, among others. See below for included shortcodes.
Don't see the shortcode you need on the list? You can write a [custom one](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/custom-shortcodes/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)! Any shortcode that returns a string or numeric value can be used here. The included shortcodes just cover the most common scenarios, but DTX provides the flexibility for you to grab any value you have access to programmatically.
@@ -341,9 +355,20 @@ This method is the most involved as it requires you to be familiar with the proc
== Screenshots ==
1. Screenshot of the form tag buttons in the form editor of Contact Form 7. A red square highlights the addition of two new buttons for "dynamic text" and "dynamic hidden"
1. Screenshot of the form tag buttons in the form editor of Contact Form 7. The dynamic buttons appear in purple instead of blue to visually set them apart.
2. The form tag generator screen for the dynamic text form tag
3. The form tag generator screen for the dynamic hidden form tag
4. The form tag generator screen for the dynamic email form tag
5. The form tag generator screen for the dynamic URL form tag
6. The form tag generator screen for the dynamic phone number (tel) form tag
7. The form tag generator screen for the dynamic number spinbox form tag
8. The form tag generator screen for the dynamic sliding range form tag
9. The form tag generator screen for the dynamic textarea form tag
10. The form tag generator screen for the dynamic drop-down menu (select) form tag
11. The form tag generator screen for the dynamic checkboxes form tag
12. The form tag generator screen for the dynamic radio buttons form tag
13. The form tag generator screen for the dynamic date form tag
14. The form tag generator screen for the dynamic submit form tag
== Frequently Asked Questions ==
@@ -351,111 +376,53 @@ Please check out the [FAQ on our website](https://aurisecreative.com/docs/contac
== Upgrade Notice ==
= 3.5.3 =
Optimized JavaScript used in cache compatibility mode.
= 4.1.0 =
Extend functionality without losing your work!
== Changelog ==
= 3.5.4 =
= 4.1.0 =
* Fix: Updated JavaScript to prevent cacheable fields from making unnecessary AJAX requests
* Feature: Looks for a `dtx.php` file in the `wp_content` directory to maybe load custom shortcodes, [see support thread](https://wordpress.org/support/topic/how-to-avoid-custom-shortcodes-being-overwritten-on-updates/)
* Feature: Looks for a `dtx.php` file in the current active theme's directory to maybe load custom shortcodes, [see support thread](https://wordpress.org/support/topic/how-to-avoid-custom-shortcodes-being-overwritten-on-updates/)
* Feature: Looks for a `dtx.php` file in the current active theme's parent directory to maybe load custom shortcodes, [see support thread](https://wordpress.org/support/topic/how-to-avoid-custom-shortcodes-being-overwritten-on-updates/)
* Fix: addressed user reported bug, [see support thread](https://wordpress.org/support/topic/fatal-error-v4-0-3/)
= 3.5.3 =
= 4.0.3 =
* Update: removed the use of sessions, [see support thread](https://wordpress.org/support/topic/add-option-to-disable-session-data/)
* Feature: Added `exclusive` option to checkbox tag generator
* Fix: addressed bug that put all dynamic checkbox/radio options into one
* Fix: addressed bug in frontend validator for multiple selected values
= 3.5.2 =
= 4.0.2 =
* Fix: Updated the `CF7_URL` shortcode to only use `network_home_url()` for multisite installs that do not use subdomains, and use `home_url()` for all others to [maybe address this support thread](https://wordpress.org/support/topic/cf7_url-return-only-domain-and-not-subdomain/)
* Fix: Removed a lingering debug call
* Fix: addressed bug that put all dynamic select options into one, [see support thread](https://wordpress.org/support/topic/dynamic-select-get-option-values-from-shortcode/)
* Update: sanitizing and escaping filters now accept `none` as value for `$type` to bypass. Use with caution.
= 3.5.1 =
= 4.0.1 =
* Fix: fixed bug so tag generator for dynamic fields work on "Add New Contact Form" page of Contact Form 7
* Updated: Updated text in tag generator for cache compatible checkbox and added link to documentation
* Fix: addressed bug that prevented translation for cache compatibility description
= 3.5.0 =
= 4.0.0 =
* Feature: Added the `dtx_pageload` form tag attribute for cache compatibility. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tag-attribute-after-page-load/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Fix: Updated to be compatible with WordPress version 6.3
* Fix: Addressed a bug where `scheme` in `CF7_URL part='scheme'` was incorrectly sanitizing as URL instead of text
* Fix: Fixed `wp_kses()` in tag generator that stripped out link opening in new tab
* Update: `CF7_get_current_var` utilizes PHP session variables where appropriate
* Update: All JavaScript assets will load with the `defer` strategy in the footer in [WordPress 6.3](https://make.wordpress.org/core/2023/07/14/registering-scripts-with-async-and-defer-attributes-in-wordpress-6-3/)
= 3.4.0 =
* Feature: Added the `CF7_get_current_var` shortcode, [see support thread for user request](https://wordpress.org/support/topic/wrong-page-title-7/). For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/dtx-shortcode-current-variables/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Fix: Updated the `CF7_URL` shortcode to no longer check for ports since that's handled in `network_home_url()` function, [see support thread](https://wordpress.org/support/topic/version-3-3-0-breaking/)
= 3.3.0 =
* Feature: Added the `CF7_get_cookie` shortcode. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/dtx-shortcode-cookie/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: Added the `CF7_get_taxonomy` shortcode. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/dtx-shortcode-taxonomy/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: Added the `CF7_get_theme_option` shortcode. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/dtx-shortcode-theme-option/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: Added `wpcf7dtx_sanitize` filter that sanitizes attribute values in built-in shortcodes
* Feature: Added `wpcf7dtx_escape` filter that escapes values in built-in shortcodes
* Feature: Added `wpcf7dtx_allow_protocols` filter to customize allowed protocols in escaping URLs in built-in shortcodes
* Fix: Updated how plugin gets dynamic value in form tags, now uses `wpcf7dtx_get_dynamic()` function
* Fix: Added case-insensitive ID in `CF7_get_post_var`
* Fix: Sanitizes post variable keys as keys in `wpcf7dtx_get_post_var()`
* Fix: Updated `wpcf7dtx_get_post_id()` to pull from "the loop" if `$post` is unavailable and now used consistently across built-in shortcodes
* Fix: Updated tag markup to be compatible with Contact Form 7 version 5.6 Beta for successful form validation, [see support thread](https://wordpress.org/support/topic/required-field-no-error-is-output-when-validating-when-field-is-empty/)
* Fix: Updated the `CF7_URL` shortcode to use `network_home_url()`, [see support thread](https://wordpress.org/support/topic/current-url-not-working/)
* Fix: Updated GUID function to return appropriately escaped values
* Fix: Updated all existing built-in shortcodes to use the the sanitizing, escaping, and obfuscating shortcodes, [see support thread](https://wordpress.org/support/topic/cant-get-obfuscate-to-work/)
* Fix: Marked compatible with WordPress core version 6.2.
= 3.2 =
* Feature: Add optional 'part' parameter to CF7_URL shortcode to retrieve Host, Query, or Path from current URL
* Updated minimum PHP requirement to 7.4 moving forward
* Update branding assets
* Update Tested Up To to 6.1.1
* Plugin will now be jointly maintained by [SevenSpark](https://sevenspark.com/) and [AuRise Creative](https://aurisecreative.com)
= 3.1.3 =
* Fix: Fixed the syntax error that reappeared in 3.1.2.
= 3.1.2 =
**Release Date: January 27, 2023**
* Fix: updated the text domain to match the plugin slug
* Fix: updated all of the translated strings to match
= 3.1.1 =
**Release Date: January 26, 2023**
* Fix: Fixed the syntax error: Parse error: syntax error, unexpected `)` in /wp-content/plugins/contact-form-7-dynamic-text extension/includes/admin.php on line 212
= 3.1.0 =
**Release Date: January 25, 2023**
* Feature: Added the `CF7_get_attachment` shortcode. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/dtx-shortcode-media-attachment/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: Added the `CF7_guid` shortcode. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/dtx-shortcode-guid/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme).
* Feature: Added the dynamic placeholder option to the dynamic form tags that allows you to specify dynamic or static placeholder content while also setting dynamic values. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/shortcodes/dtx-attribute-placeholder/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: Added a "required" dynamic hidden tag (e.g., `[dynamichidden* ...]`). It is identical to the original dynamic hidden tag (as in the field is not actually validated as required because it is hidden); it just doesn't break your website if you use it. This feature was requested by a user.
* Feature: Added the `obfuscate` attribute to all included shortcodes
= 3.0.0 =
**Release Date: January 17, 2023**
* Major: Plugin was adopted by AuRise Creative
* Major: All functions use the `wpcf7dtx_` prefix
* Feature: Added a `post_id` key for the `CF7_get_post_var` shortcode so you can specify a different post
* Feature: Updated the `CF7_get_current_user` shortcode to be able to pull data from user metadata too
* Feature: Added the "obfuscate" option to `CF7_get_custom_field` shortcode
* Feature: Added the "placeholder" checkbox option to the `dynamictext` tag
* Fix: Added additional validation for post ID input
* Fix: Added additional validation for the `key` attribute in the `CF7_GET` and `CF7_POST` shortcodes
* Fix: Shortcode keys are normalized into lowercase before processing
* Security: Sanitizing URLs for the `CF7_URL` and `CF7_referrer` shortcode outputs
* Feature/Security: Added a `allowed_protocols` attribute to the `CF7_URL` and `CF7_referrer` shortcodes that defaults to `http,https`
* Major: modified function names
* Major: deprecated `dynamictext` and `dynamichidden` form tags in favor of `dynamic_text` and `dynamic_hidden`. For more information, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_email` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-email/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_url` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-url/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_tel` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-tel/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_number` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-number/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_range` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-range/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_textarea` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-textarea/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_select` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-select/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_radio` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-radio/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_date` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-date/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dynamic_submit` form tag. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-submit/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dtx_hide_blank` form tag attribute for `dynamic_select`. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-select/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: introduced `dtx_disable_blank` form tag attribute for `dynamic_select`. For usage details, see the [knowledge base](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/form-tags/dynamic-select/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: added mail validation for `dynamic_email` and `dynamic_hidden` for backend configuration. For more information, see the [FAQ](https://aurisecreative.com/docs/contact-form-7-dynamic-text-extension/frequently-asked-questions/?utm_source=wordpress.org&utm_medium=link&utm_campaign=contact-form-7-dynamic-text-extension&utm_content=readme)
* Feature: added the Akismet feature to DTX text, email, and URL form tags.
* Update: adjusted how queued values were sent for cache compatibility mode to allow for multiline values in textareas
* Removed unused utility functions
= Older Releases =
@@ -120,7 +120,7 @@ function wpcf7_editor_box_mail( $post, $args = '' ) {
<?php
if ( ! empty( $args['use'] ) ) :
?>
<label for="<?php echo $id; ?>-active"><input type="checkbox" id="<?php echo $id; ?>-active" name="<?php echo $id; ?>[active]" class="toggle-form-table" value="1"<?php echo ( $mail['active'] ) ? ' checked="checked"' : ''; ?> /> <?php echo esc_html( $args['use'] ); ?></label>
<label for="<?php echo $id; ?>-active"><input type="checkbox" id="<?php echo $id; ?>-active" name="<?php echo $id; ?>[active]" data-config-field="" class="toggle-form-table" value="1"<?php echo ( $mail['active'] ) ? ' checked="checked"' : ''; ?> /> <?php echo esc_html( $args['use'] ); ?></label>
<p class="description"><?php echo esc_html( __( "Mail (2) is an additional mail template often used as an autoresponder.", 'contact-form-7' ) ); ?></p>
<?php
endif;
@@ -2,6 +2,7 @@
return array(
'dependencies' => array(
'react',
'wp-api-fetch',
'wp-block-editor',
'wp-blocks',
File diff suppressed because one or more lines are too long
@@ -0,0 +1,27 @@
<?php
add_action(
'wpcf7_update_option',
'wpcf7_config_validator_update_option',
10, 3
);
/**
* Runs bulk validation after the reCAPTCHA integration option is updated.
*/
function wpcf7_config_validator_update_option( $name, $value, $old_option ) {
if ( 'recaptcha' === $name ) {
$contact_forms = WPCF7_ContactForm::find();
$options = array(
'include' => 'unsafe_email_without_protection',
);
foreach ( $contact_forms as $contact_form ) {
$config_validator = new WPCF7_ConfigValidator( $contact_form, $options );
$config_validator->restore();
$config_validator->validate();
$config_validator->save();
}
}
}
@@ -6,17 +6,22 @@ trait WPCF7_ConfigValidator_AdditionalSettings {
* Runs error detection for the additional settings section.
*/
public function validate_additional_settings() {
$deprecated_settings_used =
$this->contact_form->additional_setting( 'on_sent_ok' ) ||
$this->contact_form->additional_setting( 'on_submit' );
$section = 'additional_settings.body';
if ( $deprecated_settings_used ) {
return $this->add_error( 'additional_settings.body',
'deprecated_settings',
array(
'message' => __( "Deprecated settings are used.", 'contact-form-7' ),
)
);
if ( $this->supports( 'deprecated_settings' ) ) {
$deprecated_settings_used =
$this->contact_form->additional_setting( 'on_sent_ok' ) ||
$this->contact_form->additional_setting( 'on_submit' );
if ( $deprecated_settings_used ) {
$this->add_error( $section, 'deprecated_settings',
array(
'message' => __( "Deprecated settings are used.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'deprecated_settings' );
}
}
}
@@ -8,12 +8,83 @@ trait WPCF7_ConfigValidator_Form {
public function validate_form() {
$section = 'form.body';
$form = $this->contact_form->prop( 'form' );
$this->detect_multiple_controls_in_label( $section, $form );
$this->detect_unavailable_names( $section, $form );
$this->detect_unavailable_html_elements( $section, $form );
$this->detect_dots_in_names( $section, $form );
$this->detect_colons_in_names( $section, $form );
$this->detect_upload_filesize_overlimit( $section, $form );
if ( $this->supports( 'multiple_controls_in_label' ) ) {
if ( $this->detect_multiple_controls_in_label( $section, $form ) ) {
$this->add_error( $section, 'multiple_controls_in_label',
array(
'message' => __( "Multiple form controls are in a single label element.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'multiple_controls_in_label' );
}
}
if ( $this->supports( 'unavailable_names' ) ) {
$ng_names = $this->detect_unavailable_names( $section, $form );
if ( $ng_names ) {
$this->add_error( $section, 'unavailable_names',
array(
'message' =>
/* translators: %names%: a list of form control names */
__( "Unavailable names (%names%) are used for form controls.", 'contact-form-7' ),
'params' => array( 'names' => implode( ', ', $ng_names ) ),
)
);
} else {
$this->remove_error( $section, 'unavailable_names' );
}
}
if ( $this->supports( 'unavailable_html_elements' ) ) {
if ( $this->detect_unavailable_html_elements( $section, $form ) ) {
$this->add_error( $section, 'unavailable_html_elements',
array(
'message' => __( "Unavailable HTML elements are used in the form template.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'unavailable_html_elements' );
}
}
if ( $this->supports( 'dots_in_names' ) ) {
if ( $this->detect_dots_in_names( $section, $form ) ) {
$this->add_error( $section, 'dots_in_names',
array(
'message' => __( "Dots are used in form-tag names.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'dots_in_names' );
}
}
if ( $this->supports( 'colons_in_names' ) ) {
if ( $this->detect_colons_in_names( $section, $form ) ) {
$this->add_error( $section, 'colons_in_names',
array(
'message' => __( "Colons are used in form-tag names.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'colons_in_names' );
}
}
if ( $this->supports( 'upload_filesize_overlimit' ) ) {
if ( $this->detect_upload_filesize_overlimit( $section, $form ) ) {
$this->add_error( $section, 'upload_filesize_overlimit',
array(
'message' => __( "Uploadable file size exceeds PHPs maximum acceptable size.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'upload_filesize_overlimit' );
}
}
}
@@ -54,12 +125,7 @@ trait WPCF7_ConfigValidator_Form {
}
if ( 1 < $fields_count ) {
return $this->add_error( $section,
'multiple_controls_in_label',
array(
'message' => __( "Multiple form controls are in a single label element.", 'contact-form-7' ),
)
);
return true;
}
}
}
@@ -98,17 +164,7 @@ trait WPCF7_ConfigValidator_Form {
}
if ( $ng_names ) {
$ng_names = array_unique( $ng_names );
return $this->add_error( $section,
'unavailable_names',
array(
'message' =>
/* translators: %names%: a list of form control names */
__( "Unavailable names (%names%) are used for form controls.", 'contact-form-7' ),
'params' => array( 'names' => implode( ', ', $ng_names ) ),
)
);
return array_unique( $ng_names );
}
return false;
@@ -124,12 +180,7 @@ trait WPCF7_ConfigValidator_Form {
$pattern = '%(?:<form[\s\t>]|</form>)%i';
if ( preg_match( $pattern, $content ) ) {
return $this->add_error( $section,
'unavailable_html_elements',
array(
'message' => __( "Unavailable HTML elements are used in the form template.", 'contact-form-7' ),
)
);
return true;
}
return false;
@@ -150,12 +201,7 @@ trait WPCF7_ConfigValidator_Form {
foreach ( $tags as $tag ) {
if ( str_contains( $tag->raw_name, '.' ) ) {
return $this->add_error( $section,
'dots_in_names',
array(
'message' => __( "Dots are used in form-tag names.", 'contact-form-7' ),
)
);
return true;
}
}
@@ -177,12 +223,7 @@ trait WPCF7_ConfigValidator_Form {
foreach ( $tags as $tag ) {
if ( str_contains( $tag->raw_name, ':' ) ) {
return $this->add_error( $section,
'colons_in_names',
array(
'message' => __( "Colons are used in form-tag names.", 'contact-form-7' ),
)
);
return true;
}
}
@@ -227,12 +268,7 @@ trait WPCF7_ConfigValidator_Form {
foreach ( $tags as $tag ) {
if ( $upload_max_filesize < $tag->get_limit_option() ) {
return $this->add_error( $section,
'upload_filesize_overlimit',
array(
'message' => __( "Uploadable file size exceeds PHPs maximum acceptable size.", 'contact-form-7' ),
)
);
return true;
}
}
@@ -2,11 +2,27 @@
trait WPCF7_ConfigValidator_Mail {
/**
* Replaces all mail-tags in the given content.
*/
public function replace_mail_tags( $content, $args = '' ) {
$args = wp_parse_args( $args, array(
'html' => false,
'callback' =>
array( $this, 'replace_mail_tags_with_minimum_input_callback' ),
) );
$content = new WPCF7_MailTaggedText( $content, $args );
return $content->replace_tags();
}
/**
* Callback function for WPCF7_MailTaggedText. Replaces mail-tags with
* the most conservative inputs.
*/
public function replace_mail_tags_with_minimum_input( $matches ) {
public function replace_mail_tags_with_minimum_input_callback( $matches ) {
// allow [[foo]] syntax for escaping a tag
if ( $matches[1] === '[' and $matches[4] === ']' ) {
return substr( $matches[0], 1, -1 );
@@ -124,109 +140,253 @@ trait WPCF7_ConfigValidator_Mail {
'attachments' => '',
) );
$callback = array( $this, 'replace_mail_tags_with_minimum_input' );
$subject = new WPCF7_MailTaggedText(
$components['subject'],
array( 'callback' => $callback )
$this->validate_mail_subject(
$template,
$components['subject']
);
$subject = $subject->replace_tags();
$subject = wpcf7_strip_newline( $subject );
$this->detect_maybe_empty( sprintf( '%s.subject', $template ), $subject );
$sender = new WPCF7_MailTaggedText(
$components['sender'],
array( 'callback' => $callback )
$this->validate_mail_sender(
$template,
$components['sender']
);
$sender = $sender->replace_tags();
$sender = wpcf7_strip_newline( $sender );
$invalid_mailbox = $this->detect_invalid_mailbox_syntax(
sprintf( '%s.sender', $template ),
$sender
$this->validate_mail_recipient(
$template,
$components['recipient']
);
if ( ! $invalid_mailbox and ! wpcf7_is_email_in_site_domain( $sender ) ) {
$this->add_error( sprintf( '%s.sender', $template ),
'email_not_in_site_domain',
array(
'message' => __( "Sender email address does not belong to the site domain.", 'contact-form-7' ),
)
);
$this->validate_mail_additional_headers(
$template,
$components['additional_headers']
);
$this->validate_mail_body(
$template,
$components['body']
);
$this->validate_mail_attachments(
$template,
$components['attachments']
);
}
/**
* Runs error detection for the mail subject section.
*/
public function validate_mail_subject( $template, $content ) {
$section = sprintf( '%s.subject', $template );
if ( $this->supports( 'maybe_empty' ) ) {
if ( $this->detect_maybe_empty( $section, $content ) ) {
$this->add_error( $section, 'maybe_empty',
array(
'message' => __( "There is a possible empty field.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'maybe_empty' );
}
}
}
/**
* Runs error detection for the mail sender section.
*/
public function validate_mail_sender( $template, $content ) {
$section = sprintf( '%s.sender', $template );
if ( $this->supports( 'invalid_mailbox_syntax' ) ) {
if ( $this->detect_invalid_mailbox_syntax( $section, $content ) ) {
$this->add_error( $section, 'invalid_mailbox_syntax',
array(
'message' => __( "Invalid mailbox syntax is used.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'invalid_mailbox_syntax' );
}
}
$recipient = new WPCF7_MailTaggedText(
$components['recipient'],
array( 'callback' => $callback )
);
if ( $this->supports( 'email_not_in_site_domain' ) ) {
$this->remove_error( $section, 'email_not_in_site_domain' );
$recipient = $recipient->replace_tags();
$recipient = wpcf7_strip_newline( $recipient );
if ( ! $this->has_error( $section, 'invalid_mailbox_syntax' ) ) {
$sender = $this->replace_mail_tags( $content );
$sender = wpcf7_strip_newline( $sender );
$this->detect_invalid_mailbox_syntax(
sprintf( '%s.recipient', $template ),
$recipient
);
if ( ! wpcf7_is_email_in_site_domain( $sender ) ) {
$this->add_error( $section, 'email_not_in_site_domain',
array(
'message' => __( "Sender email address does not belong to the site domain.", 'contact-form-7' ),
)
);
}
}
}
}
$additional_headers = new WPCF7_MailTaggedText(
$components['additional_headers'],
array( 'callback' => $callback )
);
$additional_headers = $additional_headers->replace_tags();
$additional_headers = explode( "\n", $additional_headers );
$mailbox_header_types = array( 'reply-to', 'cc', 'bcc' );
$invalid_mail_header_exists = false;
/**
* Runs error detection for the mail recipient section.
*/
public function validate_mail_recipient( $template, $content ) {
$section = sprintf( '%s.recipient', $template );
foreach ( $additional_headers as $header ) {
if ( $this->supports( 'invalid_mailbox_syntax' ) ) {
if ( $this->detect_invalid_mailbox_syntax( $section, $content ) ) {
$this->add_error( $section, 'invalid_mailbox_syntax',
array(
'message' => __( "Invalid mailbox syntax is used.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'invalid_mailbox_syntax' );
}
}
if ( $this->supports( 'unsafe_email_without_protection' ) ) {
$this->remove_error( $section, 'unsafe_email_without_protection' );
if ( ! $this->has_error( $section, 'invalid_mailbox_syntax' ) ) {
if (
$this->detect_unsafe_email_without_protection( $section, $content )
) {
$this->add_error( $section, 'unsafe_email_without_protection',
array(
'message' => __( "Unsafe email config is used without sufficient protection.", 'contact-form-7' ),
)
);
}
}
}
}
/**
* Runs error detection for the mail additional headers section.
*/
public function validate_mail_additional_headers( $template, $content ) {
$section = sprintf( '%s.additional_headers', $template );
$invalid_mail_headers = array();
$invalid_mailbox_fields = array();
$unsafe_email_fields = array();
foreach ( explode( "\n", $content ) as $header ) {
$header = trim( $header );
if ( '' === $header ) {
continue;
}
if ( ! preg_match( '/^([0-9A-Za-z-]+):(.*)$/', $header, $matches ) ) {
$invalid_mail_header_exists = true;
} else {
$header_name = $matches[1];
$header_value = trim( $matches[2] );
$is_valid_header = preg_match(
'/^([0-9A-Za-z-]+):(.*)$/',
$header,
$matches
);
if ( in_array( strtolower( $header_name ), $mailbox_header_types )
and '' !== $header_value ) {
$this->detect_invalid_mailbox_syntax(
sprintf( '%s.additional_headers', $template ),
$header_value,
array(
'message' => __( "Invalid mailbox syntax is used in the %name% field.", 'contact-form-7' ),
'params' => array( 'name' => $header_name )
)
);
}
if ( ! $is_valid_header ) {
$invalid_mail_headers[] = $header;
continue;
}
$header_name = $matches[1];
$header_value = trim( $matches[2] );
if (
in_array(
strtolower( $header_name ), array( 'reply-to', 'cc', 'bcc' )
) and
'' !== $header_value and
$this->detect_invalid_mailbox_syntax( $section, $header_value )
) {
$invalid_mailbox_fields[] = $header_name;
continue;
}
if (
in_array( strtolower( $header_name ), array( 'cc', 'bcc' ) ) and
$this->detect_unsafe_email_without_protection( $section, $header_value )
) {
$unsafe_email_fields[] = $header_name;
}
}
if ( $invalid_mail_header_exists ) {
$this->add_error( sprintf( '%s.additional_headers', $template ),
'invalid_mail_header',
array(
'message' => __( "There are invalid mail header fields.", 'contact-form-7' ),
)
);
if ( $this->supports( 'invalid_mail_header' ) ) {
if ( ! empty( $invalid_mail_headers ) ) {
$this->add_error( $section, 'invalid_mail_header',
array(
'message' => __( "There are invalid mail header fields.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'invalid_mail_header' );
}
}
$body = new WPCF7_MailTaggedText(
$components['body'],
array( 'callback' => $callback )
);
if ( $this->supports( 'invalid_mailbox_syntax' ) ) {
if ( ! empty( $invalid_mailbox_fields ) ) {
foreach ( $invalid_mailbox_fields as $header_name ) {
$this->add_error( $section, 'invalid_mailbox_syntax',
array(
'message' => __( "Invalid mailbox syntax is used in the %name% field.", 'contact-form-7' ),
'params' => array( 'name' => $header_name ),
)
);
}
} else {
$this->remove_error( $section, 'invalid_mailbox_syntax' );
}
}
$body = $body->replace_tags();
if ( $this->supports( 'unsafe_email_without_protection' ) ) {
if ( ! empty( $unsafe_email_fields ) ) {
$this->add_error( $section, 'unsafe_email_without_protection',
array(
'message' => __( "Unsafe email config is used without sufficient protection.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'unsafe_email_without_protection' );
}
}
}
$this->detect_maybe_empty( sprintf( '%s.body', $template ), $body );
if ( '' !== $components['attachments'] ) {
/**
* Runs error detection for the mail body section.
*/
public function validate_mail_body( $template, $content ) {
$section = sprintf( '%s.body', $template );
if ( $this->supports( 'maybe_empty' ) ) {
if ( $this->detect_maybe_empty( $section, $content ) ) {
$this->add_error( $section, 'maybe_empty',
array(
'message' => __( "There is a possible empty field.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'maybe_empty' );
}
}
}
/**
* Runs error detection for the mail attachments section.
*/
public function validate_mail_attachments( $template, $content ) {
$section = sprintf( '%s.attachments', $template );
$total_size = 0;
$files_not_found = array();
$files_out_of_content = array();
if ( '' !== $content ) {
$attachables = array();
$tags = $this->contact_form->scan_form_tags(
@@ -236,7 +396,7 @@ trait WPCF7_ConfigValidator_Mail {
foreach ( $tags as $tag ) {
$name = $tag->name;
if ( ! str_contains( $components['attachments'], "[{$name}]" ) ) {
if ( ! str_contains( $content, "[{$name}]" ) ) {
continue;
}
@@ -249,41 +409,61 @@ trait WPCF7_ConfigValidator_Mail {
$total_size = array_sum( $attachables );
$has_file_not_found = false;
$has_file_not_in_content_dir = false;
foreach ( explode( "\n", $components['attachments'] ) as $line ) {
foreach ( explode( "\n", $content ) as $line ) {
$line = trim( $line );
if ( '' === $line or str_starts_with( $line, '[' ) ) {
continue;
}
$has_file_not_found = $this->detect_file_not_found(
sprintf( '%s.attachments', $template ), $line
);
if ( ! $has_file_not_found and ! $has_file_not_in_content_dir ) {
$has_file_not_in_content_dir = $this->detect_file_not_in_content_dir(
sprintf( '%s.attachments', $template ), $line
);
}
if ( ! $has_file_not_found ) {
$path = path_join( WP_CONTENT_DIR, $line );
if ( $this->detect_file_not_found( $section, $line ) ) {
$files_not_found[] = $line;
} elseif ( $this->detect_file_not_in_content_dir( $section, $line ) ) {
$files_out_of_content[] = $line;
} else {
$total_size += (int) @filesize( $path );
}
}
}
if ( $this->supports( 'file_not_found' ) ) {
if ( ! empty( $files_not_found ) ) {
foreach ( $files_not_found as $line ) {
$this->add_error( $section, 'file_not_found',
array(
'message' => __( "Attachment file does not exist at %path%.", 'contact-form-7' ),
'params' => array( 'path' => $line ),
)
);
}
} else {
$this->remove_error( $section, 'file_not_found' );
}
}
if ( $this->supports( 'file_not_in_content_dir' ) ) {
if ( ! empty( $files_out_of_content ) ) {
$this->add_error( $section, 'file_not_in_content_dir',
array(
'message' => __( "It is not allowed to use files outside the wp-content directory.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'file_not_in_content_dir' );
}
}
if ( $this->supports( 'attachments_overweight' ) ) {
$max = 25 * MB_IN_BYTES; // 25 MB
if ( $max < $total_size ) {
$this->add_error( sprintf( '%s.attachments', $template ),
'attachments_overweight',
$this->add_error( $section, 'attachments_overweight',
array(
'message' => __( "The total size of attachment files is too large.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'attachments_overweight' );
}
}
}
@@ -294,17 +474,12 @@ trait WPCF7_ConfigValidator_Mail {
*
* @link https://contactform7.com/configuration-errors/invalid-mailbox-syntax/
*/
public function detect_invalid_mailbox_syntax( $section, $content, $args = '' ) {
$args = wp_parse_args( $args, array(
'message' => __( "Invalid mailbox syntax is used.", 'contact-form-7' ),
'params' => array(),
) );
public function detect_invalid_mailbox_syntax( $section, $content ) {
$content = $this->replace_mail_tags( $content );
$content = wpcf7_strip_newline( $content );
if ( ! wpcf7_is_mailbox_list( $content ) ) {
return $this->add_error( $section,
'invalid_mailbox_syntax',
$args
);
return true;
}
return false;
@@ -317,13 +492,11 @@ trait WPCF7_ConfigValidator_Mail {
* @link https://contactform7.com/configuration-errors/maybe-empty/
*/
public function detect_maybe_empty( $section, $content ) {
$content = $this->replace_mail_tags( $content );
$content = wpcf7_strip_newline( $content );
if ( '' === $content ) {
return $this->add_error( $section,
'maybe_empty',
array(
'message' => __( "There is a possible empty field.", 'contact-form-7' ),
)
);
return true;
}
return false;
@@ -339,13 +512,7 @@ trait WPCF7_ConfigValidator_Mail {
$path = path_join( WP_CONTENT_DIR, $content );
if ( ! is_readable( $path ) or ! is_file( $path ) ) {
return $this->add_error( $section,
'file_not_found',
array(
'message' => __( "Attachment file does not exist at %path%.", 'contact-form-7' ),
'params' => array( 'path' => $content ),
)
);
return true;
}
return false;
@@ -361,12 +528,73 @@ trait WPCF7_ConfigValidator_Mail {
$path = path_join( WP_CONTENT_DIR, $content );
if ( ! wpcf7_is_file_path_in_content_dir( $path ) ) {
return $this->add_error( $section,
'file_not_in_content_dir',
array(
'message' => __( "It is not allowed to use files outside the wp-content directory.", 'contact-form-7' ),
)
);
return true;
}
return false;
}
/**
* Detects errors of that unsafe email config is used without
* sufficient protection.
*
* @link https://contactform7.com/configuration-errors/unsafe-email-without-protection/
*/
public function detect_unsafe_email_without_protection( $section, $content ) {
static $is_recaptcha_active = null;
if ( null === $is_recaptcha_active ) {
$is_recaptcha_active = call_user_func( function () {
$service = WPCF7_RECAPTCHA::get_instance();
return $service->is_active();
} );
}
if ( $is_recaptcha_active ) {
return false;
}
$example_email = 'user-specified@example.com';
// Replace mail-tags connected to an email type form-tag first.
$content = $this->replace_mail_tags( $content, array(
'callback' => function ( $matches ) use ( $example_email ) {
// allow [[foo]] syntax for escaping a tag
if ( $matches[1] === '[' and $matches[4] === ']' ) {
return substr( $matches[0], 1, -1 );
}
$tag = $matches[0];
$tagname = $matches[2];
$values = $matches[3];
$mail_tag = new WPCF7_MailTag( $tag, $tagname, $values );
$field_name = $mail_tag->field_name();
$form_tags = $this->contact_form->scan_form_tags(
array( 'name' => $field_name )
);
if ( $form_tags ) {
$form_tag = new WPCF7_FormTag( $form_tags[0] );
if ( 'email' === $form_tag->basetype ) {
return $example_email;
}
}
return $tag;
},
) );
// Replace remaining mail-tags.
$content = $this->replace_mail_tags( $content );
$content = wpcf7_strip_newline( $content );
if ( str_contains( $content, $example_email ) ) {
return true;
}
return false;
@@ -12,14 +12,27 @@ trait WPCF7_ConfigValidator_Messages {
return;
}
if ( isset( $messages['captcha_not_match'] )
and ! wpcf7_use_really_simple_captcha() ) {
if (
isset( $messages['captcha_not_match'] ) and
! wpcf7_use_really_simple_captcha()
) {
unset( $messages['captcha_not_match'] );
}
foreach ( $messages as $key => $message ) {
$section = sprintf( 'messages.%s', $key );
$this->detect_html_in_message( $section, $message );
if ( $this->supports( 'html_in_message' ) ) {
if ( $this->detect_html_in_message( $section, $message ) ) {
$this->add_error( $section, 'html_in_message',
array(
'message' => __( "HTML tags are used in a message.", 'contact-form-7' ),
)
);
} else {
$this->remove_error( $section, 'html_in_message' );
}
}
}
}
@@ -32,13 +45,8 @@ trait WPCF7_ConfigValidator_Messages {
public function detect_html_in_message( $section, $content ) {
$stripped = wp_strip_all_tags( $content );
if ( $stripped != $content ) {
return $this->add_error( $section,
'html_in_message',
array(
'message' => __( "HTML tags are used in a message.", 'contact-form-7' ),
)
);
if ( $stripped !== $content ) {
return true;
}
return false;
@@ -4,6 +4,7 @@ require_once path_join( __DIR__, 'form.php' );
require_once path_join( __DIR__, 'mail.php' );
require_once path_join( __DIR__, 'messages.php' );
require_once path_join( __DIR__, 'additional-settings.php' );
require_once path_join( __DIR__, 'actions.php' );
/**
@@ -13,15 +14,10 @@ require_once path_join( __DIR__, 'additional-settings.php' );
*/
class WPCF7_ConfigValidator {
use WPCF7_ConfigValidator_Form;
use WPCF7_ConfigValidator_Mail;
use WPCF7_ConfigValidator_Messages;
use WPCF7_ConfigValidator_AdditionalSettings;
/**
* The plugin version in which important updates happened last time.
*/
const last_important_update = '5.6.1';
const last_important_update = '5.8.1';
const error_codes = array(
'maybe_empty',
@@ -39,10 +35,18 @@ class WPCF7_ConfigValidator {
'dots_in_names',
'colons_in_names',
'upload_filesize_overlimit',
'unsafe_email_without_protection',
);
use WPCF7_ConfigValidator_Form;
use WPCF7_ConfigValidator_Mail;
use WPCF7_ConfigValidator_Messages;
use WPCF7_ConfigValidator_AdditionalSettings;
private $contact_form;
private $errors = array();
private $include;
private $exclude;
/**
@@ -66,8 +70,21 @@ class WPCF7_ConfigValidator {
/**
* Constructor.
*/
public function __construct( WPCF7_ContactForm $contact_form ) {
public function __construct( WPCF7_ContactForm $contact_form, $args = '' ) {
$args = wp_parse_args( $args, array(
'include' => null,
'exclude' => null,
) );
$this->contact_form = $contact_form;
if ( isset( $args['include'] ) ) {
$this->include = (array) $args['include'];
}
if ( isset( $args['exclude'] ) ) {
$this->exclude = (array) $args['exclude'];
}
}
@@ -87,6 +104,24 @@ class WPCF7_ConfigValidator {
}
/**
* Returns true if the given error code is supported by this instance.
*/
public function supports( $error_code ) {
if ( isset( $this->include ) ) {
$supported_codes = array_intersect( self::error_codes, $this->include );
} else {
$supported_codes = self::error_codes;
}
if ( isset( $this->exclude ) ) {
$supported_codes = array_diff( $supported_codes, $this->exclude );
}
return in_array( $error_code, $supported_codes, true );
}
/**
* Counts detected errors.
*/
@@ -195,6 +230,27 @@ class WPCF7_ConfigValidator {
}
/**
* Returns true if the specified section has the specified error.
*
* @param string $section The section where the error detected.
* @param string $code The unique code of the error.
*/
public function has_error( $section, $code ) {
if ( empty( $this->errors[$section] ) ) {
return false;
}
foreach ( (array) $this->errors[$section] as $error ) {
if ( isset( $error['code'] ) and $error['code'] === $code ) {
return true;
}
}
return false;
}
/**
* Adds a validation error.
*
@@ -264,8 +320,6 @@ class WPCF7_ConfigValidator {
* @return bool True if there is no error detected.
*/
public function validate() {
$this->errors = array();
$this->validate_form();
$this->validate_mail( 'mail' );
$this->validate_mail( 'mail_2' );
@@ -221,7 +221,7 @@ function wpcf7_contact_form_tag_func( $atts, $content = null, $code = '' ) {
return '[contact-form-7]';
}
if ( 'contact-form-7' == $code ) {
if ( 'contact-form-7' === $code ) {
$atts = shortcode_atts(
array(
'id' => '',
@@ -269,11 +269,15 @@ function wpcf7_contact_form_tag_func( $atts, $content = null, $code = '' ) {
return $contact_form->form_html( $atts );
};
return wpcf7_switch_locale(
$output = wpcf7_switch_locale(
$contact_form->locale(),
$callback,
$contact_form, $atts
);
do_action( 'wpcf7_shortcode_callback', $contact_form, $atts );
return $output;
}
@@ -74,7 +74,7 @@ class WPCF7_ContactFormTemplate {
. '-- ' . "\n"
. sprintf(
/* translators: 1: blog name, 2: blog URL */
__( 'This e-mail was sent from a contact form on %1$s (%2$s)', 'contact-form-7' ),
__( 'This is a notification that a contact form was submitted on your website (%1$s %2$s).', 'contact-form-7' ),
'[_site_title]',
'[_site_url]'
),
@@ -108,7 +108,7 @@ class WPCF7_ContactFormTemplate {
. '-- ' . "\n"
. sprintf(
/* translators: 1: blog name, 2: blog URL */
__( 'This e-mail was sent from a contact form on %1$s (%2$s)', 'contact-form-7' ),
__( 'This email is a receipt for your contact form submission on our website (%1$s %2$s) in which your email address was used. If that was not you, please ignore this message.', 'contact-form-7' ),
'[_site_title]',
'[_site_url]'
),
@@ -140,6 +140,10 @@ form.submitting .wpcf7-spinner {
}
}
.wpcf7 [inert] {
opacity: 0.5;
}
.wpcf7 input[type="file"] {
cursor: pointer;
}
@@ -410,7 +410,7 @@ class WPCF7_FormTag implements ArrayAccess {
if ( $contact_form = WPCF7_ContactForm::get_current() ) {
$val = $contact_form->shortcode_attr( $this->name );
if ( strlen( $val ) ) {
if ( isset( $val ) and strlen( $val ) ) {
if ( $args['multiple'] ) {
$values[] = $val;
} else {
@@ -522,7 +522,13 @@ function wpcf7_format_atts( $atts ) {
}
static $boolean_attributes = array(
'checked', 'disabled', 'multiple', 'readonly', 'required', 'selected',
'checked',
'disabled',
'inert',
'multiple',
'readonly',
'required',
'selected',
);
if ( in_array( $name, $boolean_attributes ) and '' === $value ) {
@@ -210,7 +210,7 @@ function wpcf7_validate_configuration() {
/**
* Returns true if wpcf7_autop() is applied to form content.
* Returns true if wpcf7_autop() is applied.
*/
function wpcf7_autop_or_not() {
return (bool) apply_filters( 'wpcf7_autop_or_not', WPCF7_AUTOP );
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -253,18 +253,46 @@ function wpcf7_is_email_in_site_domain( $email ) {
* false otherwise.
*/
function wpcf7_is_file_path_in_content_dir( $path ) {
if ( $real_path = realpath( $path ) ) {
$path = $real_path;
} else {
if ( ! is_string( $path ) or '' === $path ) {
return false;
}
if ( 0 === strpos( $path, realpath( WP_CONTENT_DIR ) ) ) {
$callback = static function ( $path, $dir ) {
if ( $real_path = realpath( $path ) ) {
$path = $real_path;
} else {
return false;
}
if ( $real_dir = realpath( $dir ) ) {
$dir = trailingslashit( $real_dir );
} else {
return false;
}
return str_starts_with(
wp_normalize_path( $path ),
wp_normalize_path( $dir )
);
};
if (
call_user_func( $callback, $path, WP_CONTENT_DIR )
) {
return true;
}
if ( defined( 'UPLOADS' )
and 0 === strpos( $path, realpath( ABSPATH . UPLOADS ) ) ) {
if (
defined( 'UPLOADS' ) and
call_user_func( $callback, $path, ABSPATH . UPLOADS )
) {
return true;
}
if (
defined( 'WP_TEMP_DIR' ) and
call_user_func( $callback, $path, WP_TEMP_DIR )
) {
return true;
}
@@ -110,10 +110,14 @@ class WPCF7 {
* @param mixed $value Option value.
*/
public static function update_option( $name, $value ) {
$option = get_option( 'wpcf7' );
$option = ( false === $option ) ? array() : (array) $option;
$option = array_merge( $option, array( $name => $value ) );
update_option( 'wpcf7', $option );
$old_option = get_option( 'wpcf7' );
$old_option = ( false === $old_option ) ? array() : (array) $old_option;
update_option( 'wpcf7',
array_merge( $old_option, array( $name => $value ) )
);
do_action( 'wpcf7_update_option', $name, $value, $old_option );
}
}
@@ -1 +1 @@
document.addEventListener("DOMContentLoaded",(t=>{var e;wpcf7_recaptcha={...null!==(e=wpcf7_recaptcha)&&void 0!==e?e:{}};const c=wpcf7_recaptcha.sitekey,{homepage:n,contactform:a}=wpcf7_recaptcha.actions,o=t=>{const{action:e,func:n,params:a}=t;grecaptcha.execute(c,{action:e}).then((t=>{const c=new CustomEvent("wpcf7grecaptchaexecuted",{detail:{action:e,token:t}});document.dispatchEvent(c)})).then((()=>{"function"==typeof n&&n(...a)})).catch((t=>console.error(t)))};if(grecaptcha.ready((()=>{o({action:n})})),document.addEventListener("change",(t=>{o({action:a})})),"undefined"!=typeof wpcf7&&"function"==typeof wpcf7.submit){const t=wpcf7.submit;wpcf7.submit=function(e){o({action:a,func:t,params:[e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}]})}}document.addEventListener("wpcf7grecaptchaexecuted",(t=>{const e=document.querySelectorAll('form.wpcf7-form input[name="_wpcf7_recaptcha_response"]');for(let c=0;c<e.length;c++)e[c].setAttribute("value",t.detail.token)}))}));
document.addEventListener("DOMContentLoaded",(e=>{var t;wpcf7_recaptcha={...null!==(t=wpcf7_recaptcha)&&void 0!==t?t:{}};const c=wpcf7_recaptcha.sitekey,{homepage:n,contactform:a}=wpcf7_recaptcha.actions,o=e=>{const{action:t,func:n,params:a}=e;grecaptcha.execute(c,{action:t}).then((e=>{const c=new CustomEvent("wpcf7grecaptchaexecuted",{detail:{action:t,token:e}});document.dispatchEvent(c)})).then((()=>{"function"==typeof n&&n(...a)})).catch((e=>console.error(e)))};if(grecaptcha.ready((()=>{o({action:n})})),document.addEventListener("change",(e=>{o({action:a})})),"undefined"!=typeof wpcf7&&"function"==typeof wpcf7.submit){const e=wpcf7.submit;wpcf7.submit=(t,c={})=>{o({action:a,func:e,params:[t,c]})}}document.addEventListener("wpcf7grecaptchaexecuted",(e=>{const t=document.querySelectorAll('form.wpcf7-form input[name="_wpcf7_recaptcha_response"]');for(let c=0;c<t.length;c++)t[c].setAttribute("value",e.detail.token)}))}));
@@ -98,7 +98,7 @@ function wpcf7_sendinblue_editor_panels( $panels ) {
),
wpcf7_link(
__( 'https://contactform7.com/sendinblue-integration/', 'contact-form-7' ),
__( 'Brevo (formerly Sendinblue) integration', 'contact-form-7' )
__( 'Brevo integration', 'contact-form-7' )
)
);
@@ -106,7 +106,7 @@ function wpcf7_sendinblue_editor_panels( $panels ) {
$templates = $service->get_templates();
?>
<h2><?php echo esc_html( __( 'Brevo (formerly Sendinblue)', 'contact-form-7' ) ); ?></h2>
<h2><?php echo esc_html( __( 'Brevo', 'contact-form-7' ) ); ?></h2>
<fieldset>
<legend><?php echo $description; ?></legend>
@@ -1,6 +1,6 @@
<?php
/**
* Brevo (formerly Sendinblue) module main file
* Brevo module main file
*
* @link https://contactform7.com/sendinblue-integration/
*/
@@ -27,7 +27,7 @@ class WPCF7_Sendinblue extends WPCF7_Service {
}
public function get_title() {
return __( 'Brevo (formerly Sendinblue)', 'contact-form-7' );
return __( 'Brevo', 'contact-form-7' );
}
public function is_active() {
@@ -47,7 +47,7 @@ class WPCF7_Sendinblue extends WPCF7_Service {
public function link() {
echo wpcf7_link(
'https://www.brevo.com/?tap_a=30591-fb13f0&tap_s=1031580-b1bb1d',
'https://www.brevo.com/',
'brevo.com'
);
}
@@ -153,7 +153,7 @@ class WPCF7_Sendinblue extends WPCF7_Service {
'<p><strong>%s</strong></p>',
wpcf7_link(
__( 'https://contactform7.com/sendinblue-integration/', 'contact-form-7' ),
__( 'Brevo (formerly Sendinblue) integration', 'contact-form-7' )
__( 'Brevo integration', 'contact-form-7' )
)
);
@@ -4,8 +4,8 @@ Donate link: https://contactform7.com/donate/
Tags: contact, form, contact form, feedback, email, ajax, captcha, akismet, multilingual
Requires at least: 6.2
Requires PHP: 7.4
Tested up to: 6.3
Stable tag: 5.8
Tested up to: 6.4
Stable tag: 5.8.3
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
@@ -37,7 +37,7 @@ If you activate certain features in this plugin, the contact form submitter's pe
* reCAPTCHA ([Google](https://policies.google.com/?hl=en))
* Akismet ([Automattic](https://automattic.com/privacy/))
* Constant Contact ([Endurance International Group](https://www.endurance.com/privacy))
* [Brevo (formerly Sendinblue)](https://www.brevo.com/legal/privacypolicy/)
* [Brevo](https://www.brevo.com/legal/privacypolicy/)
* [Stripe](https://stripe.com/privacy)
= Recommended plugins =
@@ -78,6 +78,18 @@ Do you have questions or issues with Contact Form 7? Use these support channels
For more information, see [Releases](https://contactform7.com/category/releases/).
= 5.8.3 =
[https://contactform7.com/contact-form-7-583/](https://contactform7.com/contact-form-7-583/)
= 5.8.2 =
[https://contactform7.com/contact-form-7-582/](https://contactform7.com/contact-form-7-582/)
= 5.8.1 =
[https://contactform7.com/contact-form-7-581/](https://contactform7.com/contact-form-7-581/)
= 5.8 =
[https://contactform7.com/contact-form-7-58/](https://contactform7.com/contact-form-7-58/)
@@ -7,12 +7,12 @@
* Author URI: https://ideasilo.wordpress.com/
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Version: 5.8
* Version: 5.8.3
* Requires at least: 6.2
* Requires PHP: 7.4
*/
define( 'WPCF7_VERSION', '5.8' );
define( 'WPCF7_VERSION', '5.8.3' );
define( 'WPCF7_REQUIRED_WP_VERSION', '6.2' );
@@ -0,0 +1,6 @@
# Security Policy
## Reporting Security Bugs
Please report security bugs found in the site-reviews plugin's source code through the [Patchstack Vulnerability Disclosure Program](https://patchstack.com/database/vdp/imagify). The Patchstack team will assist you with verification, CVE assignment and take care of notifying the developers of this plugin.
---
@@ -0,0 +1,20 @@
/**
* @typedef {import('@roots/bud').Bud} Bud
*
* @param {Bud} bud
*/
module.exports = async bud => {
bud.externals({
jQuery: 'window.jquery',
wp: 'window.wp',
})
bud.runtime('single')
await bud
.setPath('@dist', '../assets/admin')
.entry({
chart: 'chart.js',
bulk: 'bulk.js',
})
//.when( bud.isProduction, () => bud.splitChunks().minimize() )
}
@@ -0,0 +1,15 @@
{
"name": "imagify_dev",
"version": "1.0.0",
"dependencies": {
},
"devDependencies": {
"@roots/bud": "^6.11.0",
"chart.js": "^4.4.0"
},
"scripts": {
"dev": "bud dev",
"build": "bud build",
"bud": "bud"
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,6 @@
import * as chart from 'chart.js/auto'
window.imagify = window.imagify || {};
window.imagify.Color = chart.Colors;
window.imagify.Chart = chart.Chart;
@@ -0,0 +1,14 @@
{
"chart": {
"js": [
"js/runtime.js",
"js/chart.js"
]
},
"bulk": {
"js": [
"js/runtime.js",
"js/bulk.js"
]
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
(()=>{"use strict";var r,e={},o={};function t(r){var n=o[r];if(void 0!==n)return n.exports;var s=o[r]={exports:{}};return e[r](s,s.exports,t),s.exports}t.m=e,r=[],t.O=(e,o,n,s)=>{if(!o){var a=1/0;for(u=0;u<r.length;u++){for(var[o,n,s]=r[u],i=!0,f=0;f<o.length;f++)(!1&s||a>=s)&&Object.keys(t.O).every((r=>t.O[r](o[f])))?o.splice(f--,1):(i=!1,s<a&&(a=s));if(i){r.splice(u--,1);var l=n();void 0!==l&&(e=l)}}return e}s=s||0;for(var u=r.length;u>0&&r[u-1][2]>s;u--)r[u]=r[u-1];r[u]=[o,n,s]},t.o=(r,e)=>Object.prototype.hasOwnProperty.call(r,e),(()=>{var r={666:0};t.O.j=e=>0===r[e];var e=(e,o)=>{var n,s,[a,i,f]=o,l=0;if(a.some((e=>0!==r[e]))){for(n in i)t.o(i,n)&&(t.m[n]=i[n]);if(f)var u=f(t)}for(e&&e(o);l<a.length;l++)s=a[l],t.o(r,s)&&r[s]&&r[s][0](),r[s]=0;return t.O(u)},o=self.webpackChunk_roots_bud=self.webpackChunk_roots_bud||[];o.forEach(e.bind(null,0)),o.push=e.bind(null,o.push.bind(o))})()})();
@@ -0,0 +1,6 @@
{
"chart.js": "js/chart.js",
"bulk.js": "js/bulk.js",
"runtime.js": "js/runtime.js",
"entrypoints.json": "entrypoints.json"
}
@@ -160,3 +160,40 @@
color: #FFF;
text-shadow: 0 0 2px rgba(0, 0, 0, 0.2);
}
#wp-admin-bar-imagify-profile .imagify-upsell-admin-bar {
position:relative ;
background: #c51161;
margin: 10px -13px -10px -13px;
padding: 20px;
}
#wp-admin-bar-imagify-profile .imagify-upsell-admin-bar p {
color: #fff;
}
#wp-admin-bar-imagify-profile a.imagify-upsell-admin-bar-button {
display: block;
height: auto !important;
border: 1px solid #fff;
border-radius: 5px;
color: #fff !important;
padding: 5px 10px !important;
text-align: center;
text-decoration: none;
margin-top: 10px;
}
#wpadminbar #wp-admin-bar-imagify-profile a.imagify-upsell-dismiss {
display: inline !important;
height: auto !important;
}
#wpadminbar #wp-admin-bar-imagify-profile .imagify-upsell-dismiss::before {
position: absolute;
top: 5px;
right: 10px;
content: "\2715";
color: #fff;
}
@@ -1543,3 +1543,45 @@ ul.imagify-datas-details.imagify-datas-details {
padding-right: 0em;
}
}
.imagify-upsell {
position:relative;
background: #c51161;
padding: 20px 40px;
}
.imagify-upsell p {
color: #fff !important;
}
.imagify-upsell-button {
display: block;
background: #fff;
border-radius: 5px;
color: #c51161 !important;
font-weight: bold;
padding: 10px;
text-align: center;
text-decoration: none;
text-transform: uppercase;
}
.imagify-upsell-arrow::after {
content: '\2192';
font-size: large;
margin-left: 5px;
vertical-align: top;
}
.imagify-upsell-dismiss::before {
position: absolute;
top: 5px;
right: 5px;
content: "\2715";
color: #2e3243;
font-size: 2em;
}
.imagify-upsell .imagify-meteo-icon {
filter: invert(100%) sepia(100%) saturate(0%) hue-rotate(104deg) brightness(103%) contrast(103%);
}
@@ -330,7 +330,7 @@ body[class*="_imagify-ngg-bulk-optimization"] .media-item .progress .bar {
.imagify-col-content .imagify-meteo-icon {
height: 64px;
margin: 15px 15px 15px 20px;
margin: 15px 15px 15px 0;
}
.imagify-col-content .imagify-section-title + p {
@@ -936,3 +936,19 @@ input:checked + label .imagify-fake-checkbox:after,
margin-top: 20px;
}
}
.imagify-col-content .imagify-space-left {
margin: 15px 30px 15px 0;
}
.imagify-col-content .imagify-space-left p {
margin: 0 0 10px 0;
font-size: 19px;
font-weight: 500;
color: #343A49;
}
.imagify-col-content .imagify-meteo-icon {
height: 64px;
margin: 15px 15px 15px 0;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -6,7 +6,7 @@
*/
$( '.imagify-notice-dismiss' ).on( 'click.imagify', function( e ) {
var $this = $( this ),
$parent = $this.parents( '.imagify-welcome, .imagify-notice, .imagify-rkt-notice' ),
$parent = $this.parents( '.imagify-welcome, .imagify-notice, .imagify-rkt-notice, .imagify-upsell, .imagify-upsell-admin-bar' ),
href = $this.attr( 'href' );
e.preventDefault();
@@ -0,0 +1,81 @@
<?php
namespace Imagify\Admin;
use Imagify\Traits\InstanceGetterTrait;
use Imagify\User\User;
use Imagify_Views;
/**
* Admin bar handler
*/
class AdminBar {
use InstanceGetterTrait;
/**
* Launch the hooks.
*
* @return void
*/
public function init() {
if ( wp_doing_ajax() ) {
add_action( 'wp_ajax_imagify_get_admin_bar_profile', array( $this, 'get_admin_bar_profile_callback' ) );
}
}
/**
* Get admin bar profile output.
*
* @return void
*/
public function get_admin_bar_profile_callback() {
imagify_check_nonce( 'imagify-get-admin-bar-profile', 'imagifygetadminbarprofilenonce' );
if ( ! imagify_get_context( 'wp' )->current_user_can( 'manage' ) ) {
imagify_die();
}
$user = new User();
$views = Imagify_Views::get_instance();
$unconsumed_quota = $views->get_quota_percent();
$text = '';
$button_text = '';
$upgrade_link = '';
if ( $user->is_free() ) {
$text = esc_html__( 'Upgrade your plan now for more!', 'rocket' ) . '<br>' .
esc_html__( 'From $4.99/month only, keep going with image optimization!', 'rocket' );
$button_text = esc_html__( 'Upgrade My Plan', 'rocket' );
$upgrade_link = IMAGIFY_APP_DOMAIN . '/subscription/?utm_source=plugin&utm_medium=notification';
} elseif ( $user->is_growth() ) {
$text = esc_html__( 'Switch to Infinite plan for unlimited optimization:', 'rocket' ) . '<br>';
if ( $user->is_monthly ) {
$text .= esc_html__( 'For $9.99/month, optimize as many images as you like!', 'rocket' );
$upgrade_link = IMAGIFY_APP_DOMAIN . '/subscription/plan_switch/?label=infinite&payment_plan=1&utm_source=plugin&utm_medium=notification ';
} else {
$text .= esc_html__( 'For $99.9/year, optimize as many images as you like!', 'rocket' );
$upgrade_link = IMAGIFY_APP_DOMAIN . '/subscription/plan_switch/?label=infinite&payment_plan=2&utm_source=plugin&utm_medium=notification ';
}
$button_text = esc_html__( 'Switch To Infinite Plan', 'rocket' );
}
$data = [
'quota_icon' => $views->get_quota_icon(),
'quota_class' => $views->get_quota_class(),
'plan_label' => $user->plan_label,
'plan_with_quota' => $user->is_free() || $user->is_growth(),
'unconsumed_quota' => $unconsumed_quota,
'user_quota' => $user->quota,
'next_update' => $user->next_date_update,
'text' => $text,
'button_text' => $button_text,
'upgrade_link' => $upgrade_link,
];
$template = $views->get_template( 'admin/admin-bar-status', $data );
wp_send_json_success( $template );
}
}
@@ -413,13 +413,14 @@ class Bulk {
*
* @since 1.9
*
* @param string $method The method used: 'GET' (default), or 'POST'.
* @param string $parameter The name of the parameter to look for.
* @param string $method The method used: 'GET' (default), or 'POST'.
* @param string $parameter The name of the parameter to look for.
*
* @return string
*/
public function get_context( $method = 'GET', $parameter = 'context' ) {
$method = 'POST' === $method ? INPUT_POST : INPUT_GET;
$context = filter_input( $method, $parameter, FILTER_SANITIZE_STRING );
$context = 'POST' === $method ? wp_unslash( $_POST[ $parameter ] ) : wp_unslash( $_GET[ $parameter ] ); //phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
$context = htmlspecialchars( $context );
return imagify_sanitize_context( $context );
}
@@ -557,7 +558,7 @@ class Bulk {
public function bulk_get_stats_callback() {
imagify_check_nonce( 'imagify-bulk-optimize' );
$folder_types = filter_input( INPUT_GET, 'types', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );
$folder_types = filter_input( INPUT_GET, 'types', FILTER_REQUIRE_ARRAY );
$folder_types = is_array( $folder_types ) ? array_filter( $folder_types, 'is_string' ) : [];
if ( ! $folder_types ) {
@@ -95,6 +95,7 @@ class CustomFolders extends AbstractBulk {
$files_table = Imagify_Files_DB::get_instance()->get_table_name();
$folders_table = Imagify_Folders_DB::get_instance()->get_table_name();
$mime_types = Imagify_DB::get_mime_types( 'image' );
$mime_types = str_replace( ",'image/webp'", '', $mime_types );
$webp_suffix = constant( imagify_get_optimization_process_class_name( 'custom-folders' ) . '::WEBP_SUFFIX' );
$files = $wpdb->get_results( $wpdb->prepare( // WPCS: unprepared SQL ok.
"
@@ -184,6 +184,7 @@ class WP extends AbstractBulk {
$this->set_no_time_limit();
$mime_types = Imagify_DB::get_mime_types( 'image' );
$mime_types = str_replace( ",'image/webp'", '', $mime_types );
$statuses = Imagify_DB::get_post_statuses();
$nodata_join = Imagify_DB::get_required_wp_metadata_join_clause();
$nodata_where = Imagify_DB::get_required_wp_metadata_where_clause( [
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Imagify\Notices;
use Imagify\Traits\InstanceGetterTrait;
use Imagify\User\User;
/**
* Class that handles the admin notices.
@@ -66,8 +67,6 @@ class Notices {
'http-block-external',
// This warning is displayed when the grid view is active on the library. Dismissible.
'grid-view',
// This warning is displayed to warn the user that the quota is almost consumed for the current month. Dismissible.
'almost-over-quota',
// This warning is displayed if the backup folder is not writable. NOT dismissible.
'backup-folder-not-writable',
// This notice is displayed to rate the plugin after 100 optimizations & 7 days after the first installation. Dismissible.
@@ -76,6 +75,8 @@ class Notices {
'wp-rocket',
'bulk-optimization-complete',
'bulk-optimization-running',
'upsell-banner',
'upsell-admin-bar',
];
/**
@@ -250,7 +251,7 @@ class Notices {
public function renew_almost_over_quota_notice() {
global $wpdb;
$results = $wpdb->get_results( $wpdb->prepare( "SELECT umeta_id, user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value LIKE %s", self::DISMISS_META_NAME, '%almost-over-quota%' ) );
$results = $wpdb->get_results( $wpdb->prepare( "SELECT umeta_id, user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value LIKE %s", self::DISMISS_META_NAME, '%upsell%' ) );
if ( ! $results ) {
return;
@@ -271,7 +272,8 @@ class Notices {
// Renew the notice for all users.
foreach ( $results as $result ) {
self::renew_notice( 'almost-over-quota', $result->user_id );
self::renew_notice( 'upsell-banner', $result->user_id );
self::renew_notice( 'upsell-admin-bar', $result->user_id );
}
}
@@ -439,45 +441,6 @@ class Notices {
return $display;
}
/**
* Tell if the 'almost-over-quota' notice should be displayed.
*
* @since 1.7.0
*
* @return bool|object An Imagify user object. False otherwise.
*/
public function display_almost_over_quota() {
static $display;
if ( isset( $display ) ) {
return $display;
}
$display = false;
if ( ! $this->user_can( 'almost-over-quota' ) ) {
return $display;
}
if ( ! imagify_is_screen( 'imagify-settings' ) && ! imagify_is_screen( 'bulk' ) ) {
return $display;
}
if ( self::notice_is_dismissed( 'almost-over-quota' ) ) {
return $display;
}
$user = new \Imagify_User();
// Don't display the notice if the user's unconsumed quota is superior to 20%.
if ( $user->get_percent_unconsumed_quota() > 20 ) {
return $display;
}
$display = $user;
return $display;
}
/**
* Tell if the 'backup-folder-not-writable' notice should be displayed.
*
@@ -25,6 +25,7 @@ abstract class AbstractData implements DataInterface {
*/
protected $default_optimization_data = [
'status' => '',
'message' => '',
'level' => false,
'sizes' => [],
'stats' => [
@@ -159,6 +159,10 @@ class CustomFolders extends AbstractData {
$old_data['hash'] = md5_file( $file_path );
}
if ( key_exists( 'message', $data ) ) {
$old_data['message'] = $data['message'];
}
if ( ! $data['success'] ) {
/**
* Error.
@@ -93,8 +93,13 @@ class WP extends AbstractData {
'original_size' => 0,
'optimized_size' => 0,
'percent' => 0,
'message' => '',
], $old_data['stats'] );
if ( key_exists( 'message', $data ) ) {
$old_data['message'] = $data['message'];
}
if ( ! $data['success'] ) {
/**
* Error.
@@ -530,6 +530,10 @@ class File {
return new \WP_Error( 'temp_file_not_found', $temp_file->get_error_message() );
}
if ( property_exists( $response, 'message' ) ) {
$args['convert'] = '';
}
if ( 'webp' === $args['convert'] ) {
$destination_path = $this->get_path_to_webp();
$this->path = $destination_path;
@@ -656,6 +656,14 @@ abstract class AbstractProcess implements ProcessInterface {
'non_webp_file_path' => $sizes[ $thumb_size ]['path'], // Don't use $path nor $file->get_path(), it may return the path to a temporary file.
'optimization_level' => $optimization_level,
] );
if ( property_exists( $response, 'message' ) ) {
$path_is_temp = false;
if ( $path !== $sizes[ $thumb_size ]['path'] ) {
$this->filesystem->delete( $path );
}
$path = $sizes[ $thumb_size ]['path'];
}
}
}
}
@@ -731,7 +739,7 @@ abstract class AbstractProcess implements ProcessInterface {
}
// Optimization succeeded.
if ( $args['is_webp'] ) {
if ( ! property_exists( $args['response'], 'message' ) && $args['is_webp'] ) {
/**
* We just created a WebP version:
* Check if it is lighter than the (maybe optimized) non-WebP file.
@@ -776,7 +784,7 @@ abstract class AbstractProcess implements ProcessInterface {
$webp_size = $args['non_webp_thumb_size'] . static::WEBP_SUFFIX;
$webp_file_size = $this->get_data()->get_size_data( $webp_size, 'optimized_size' );
if ( ! $webp_file_size || $webp_file_size < $args['response']->new_size ) {
if ( property_exists( $args['response'], 'message' ) || ! $webp_file_size || $webp_file_size < $args['response']->new_size ) {
// The WebP file is lighter than this one.
return $args['response'];
}
@@ -1531,6 +1539,38 @@ abstract class AbstractProcess implements ProcessInterface {
return is_string( $data ) && strpos( $data, $needle );
}
/**
* Tell if the media has all WebP versions.
*
* @return bool
*/
public function is_full_webp() {
if ( ! $this->is_valid() ) {
return false;
}
if ( ! $this->get_media()->is_image() ) {
return false;
}
$data = $this->get_data()->get_optimization_data();
$sizes = $data['sizes'];
if ( empty( $sizes ) ) {
return false;
}
$keys = array_keys( $sizes );
$non_webp_keys = array_values(array_filter($keys, function ( $key ) {
return strpos( $key, static::WEBP_SUFFIX ) === false;
}));
return array_reduce($non_webp_keys, function ( $is_fully, $key ) use ( $sizes ) {
return key_exists( $key . self::WEBP_SUFFIX, $sizes ) && $is_fully;
}, true);
}
/**
* Tell if a WebP version can be created for the given file.
* Make sure the file is an image before using this method.
@@ -1757,6 +1797,9 @@ abstract class AbstractProcess implements ProcessInterface {
// Size data.
$data['success'] = true;
if ( property_exists( $response, 'message' ) ) {
$data['message'] = imagify_translate_api_message( $response->message );
}
$data['original_size'] = $response->original_size;
$data['optimized_size'] = $response->new_size;
}
@@ -1785,6 +1828,9 @@ abstract class AbstractProcess implements ProcessInterface {
*/
$data = (array) apply_filters( "imagify{$_unauthorized}_file_optimization_data", $data, $response, $size, $level, $this->get_data() );
if ( property_exists( $response, 'message' ) ) {
$size = str_replace( '@imagify-webp', '', $size );
}
// Store.
$this->get_data()->update_size_optimization_data( $size, $data );
@@ -274,6 +274,13 @@ interface ProcessInterface {
*/
public function is_size_webp( $size_name );
/**
* Tell if the media has all WebP versions.
*
* @return bool
*/
public function is_full_webp();
/**
* Tell if the media has WebP versions.
*
@@ -7,6 +7,7 @@ use Imagify\Bulk\Bulk;
use Imagify\CLI\BulkOptimizeCommand;
use Imagify\CLI\GenerateMissingWebpCommand;
use Imagify\Notices\Notices;
use Imagify\Admin\AdminBar;
/**
* Main plugin class.
@@ -56,6 +57,7 @@ class Plugin {
\Imagify\Job\MediaOptimization::get_instance()->init();
\Imagify\Stats\OptimizedMediaWithoutWebp::get_instance()->init();
Bulk::get_instance()->init();
AdminBar::get_instance()->init();
if ( is_admin() ) {
Notices::get_instance()->init();
@@ -0,0 +1,292 @@
<?php
namespace Imagify\User;
use Date;
use Imagify_Data;
use WP_Error;
/**
* Imagify User class.
*
* @since 1.0
*/
class User {
/**
* The Imagify user ID.
*
* @since 1.0
*
* @var string
*/
public $id;
/**
* The user email.
*
* @since 1.0
*
* @var string
*/
public $email;
/**
* The plan ID.
*
* @since 1.0
*
* @var int
*/
public $plan_id;
/**
* The plan label.
*
* @since 1.2
*
* @var string
*/
public $plan_label;
/**
* The total quota.
*
* @since 1.0
*
* @var int
*/
public $quota;
/**
* The total extra quota (Imagify Pack).
*
* @since 1.0
*
* @var int
*/
public $extra_quota;
/**
* The extra quota consumed.
*
* @since 1.0
*
* @var int
*/
public $extra_quota_consumed;
/**
* The current month consumed quota.
*
* @since 1.0
*
* @var int
*/
public $consumed_current_month_quota;
/**
* The next month date to credit the account.
*
* @since 1.1.1
*
* @var Date
*/
public $next_date_update;
/**
* If the account is activate or not.
*
* @since 1.0.1
*
* @var bool
*/
public $is_active;
/**
* If the account is monthly or yearly.
*
* @var bool
*/
public $is_monthly;
/**
* Store a \WP_Error object if the request to fetch the user data failed.
* False overwise.
*
* @var bool|WP_Error
* @since 1.9.9
*/
private $error;
/**
* The constructor.
*
* @since 1.0
*
* @return void
*/
public function __construct() {
$user = get_imagify_user();
if ( is_wp_error( $user ) ) {
$this->error = $user;
return;
}
$this->id = $user->id;
$this->email = $user->email;
$this->plan_id = (int) $user->plan_id;
$this->plan_label = ucfirst( $user->plan_label );
$this->quota = $user->quota;
$this->extra_quota = $user->extra_quota;
$this->extra_quota_consumed = $user->extra_quota_consumed;
$this->consumed_current_month_quota = $user->consumed_current_month_quota;
$this->next_date_update = $user->next_date_update;
$this->is_active = $user->is_active;
$this->is_monthly = $user->is_monthly;
$this->error = false;
}
/**
* Get the possible error returned when fetching user data.
*
* @return bool|WP_Error A \WP_Error object if the request to fetch the user data failed. False overwise.
* @since 1.9.9
*/
public function get_error() {
return $this->error;
}
/**
* Percentage of consumed quota, including extra quota.
*
* @since 1.0
*
* @return float|int
*/
public function get_percent_consumed_quota() {
static $done = false;
if ( $this->get_error() ) {
return 0;
}
$quota = $this->quota;
$consumed_quota = $this->consumed_current_month_quota;
if ( imagify_round_half_five( $this->extra_quota_consumed ) < $this->extra_quota ) {
$quota += $this->extra_quota;
$consumed_quota += $this->extra_quota_consumed;
}
if ( ! $quota || ! $consumed_quota ) {
$percent = 0;
} else {
$percent = 100 * $consumed_quota / $quota;
$percent = round( $percent, 1 );
$percent = min( max( 0, $percent ), 100 );
}
$percent = (float) $percent;
if ( $done ) {
return $percent;
}
$previous_percent = Imagify_Data::get_instance()->get( 'previous_quota_percent' );
// Percent is not 100% anymore.
if ( 100.0 === (float) $previous_percent && $percent < 100 ) {
/**
* Triggered when the consumed quota percent decreases below 100%.
*
* @since 1.7
* @author Grégory Viguier
*
* @param float|int $percent The current percentage of consumed quota.
*/
do_action( 'imagify_not_over_quota_anymore', $percent );
}
// Percent is not >= 80% anymore.
if ( ( (float) $previous_percent >= 80.0 && $percent < 80 ) ) {
/**
* Triggered when the consumed quota percent decreases below 80%.
*
* @since 1.7
* @author Grégory Viguier
*
* @param float|int $percent The current percentage of consumed quota.
* @param float|int $previous_percent The previous percentage of consumed quota.
*/
do_action( 'imagify_not_almost_over_quota_anymore', $percent, $previous_percent );
}
if ( (float) $previous_percent !== (float) $percent ) {
Imagify_Data::get_instance()->set( 'previous_quota_percent', $percent );
}
$done = true;
return $percent;
}
/**
* Count percent of unconsumed quota.
*
* @since 1.0
*
* @return float|int
*/
public function get_percent_unconsumed_quota() {
return 100 - $this->get_percent_consumed_quota();
}
/**
* Check if the user has a free account.
*
* @since 1.1.1
*
* @return bool
*/
public function is_free() {
return 1 === $this->plan_id;
}
/**
* Check if the user is a growth account
*
* @return bool
*/
public function is_growth() {
return ( 16 === $this->plan_id || 18 === $this->plan_id );
}
/**
* Check if the user is an infinite account
*
* @return bool
*/
public function is_infinite() {
return ( 15 === $this->plan_id || 17 === $this->plan_id );
}
/**
* Check if the user has consumed all his/her quota.
*
* @since 1.1.1
* @since 1.9.9 Return false if the request to fetch the user data failed.
*
* @return bool
*/
public function is_over_quota() {
if ( $this->get_error() ) {
return false;
}
return (
$this->is_free()
&&
floatval( 100 ) === round( $this->get_percent_consumed_quota() )
);
}
}
@@ -3,6 +3,7 @@ namespace Imagify\Webp\RewriteRules;
use Imagify\Notices\Notices;
use Imagify\Traits\InstanceGetterTrait;
use Imagify\WriteFile\AbstractWriteDirConfFile;
/**
* Display WebP images on the site with rewrite rules.
@@ -12,6 +13,13 @@ use Imagify\Traits\InstanceGetterTrait;
class Display {
use InstanceGetterTrait;
/**
* Configuration file writer.
*
* @var AbstractWriteDirConfFile
*/
protected $server_conf;
/**
* Option value.
*
+3 -3
View File
@@ -3,7 +3,7 @@
* Plugin Name: Imagify
* Plugin URI: https://wordpress.org/plugins/imagify/
* Description: Dramatically reduce image file sizes without losing quality, make your website load faster, boost your SEO and save money on your bandwidth using Imagify, the new most advanced image optimization tool.
* Version: 2.1.1
* Version: 2.1.3
* Requires at least: 5.3
* Requires PHP: 7.0
* Author: Imagify Optimize Images & Convert WebP
@@ -13,13 +13,13 @@
* Text Domain: imagify
* Domain Path: languages
*
* Copyright 2022 WP Media
* Copyright 2023 WP Media
*/
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
// Imagify defines.
define( 'IMAGIFY_VERSION', '2.1.1' );
define( 'IMAGIFY_VERSION', '2.1.3' );
define( 'IMAGIFY_SLUG', 'imagify' );
define( 'IMAGIFY_FILE', __FILE__ );
define( 'IMAGIFY_PATH', realpath( plugin_dir_path( IMAGIFY_FILE ) ) . '/' );
@@ -123,7 +123,9 @@ function _imagify_sort_attachments_by_status( $vars ) {
),
) );
$vars['post_mime_type'] = imagify_get_mime_types();
if ( ! key_exists( 'post_mime_type', $vars ) ) {
$vars['post_mime_type'] = imagify_get_mime_types();
}
return $vars;
}
@@ -18,6 +18,13 @@ abstract class Imagify_Abstract_Background_Process extends Imagify_WP_Background
*/
protected $prefix = 'imagify';
/**
* URL to query on.
*
* @var string
*/
protected $query_url = '';
/**
* Set to true to automatically displatch at the end of the page.
*
@@ -49,7 +49,6 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
// Account.
'imagify_signup',
'imagify_check_api_key_validity',
'imagify_get_admin_bar_profile',
'imagify_get_prices',
'imagify_check_coupon',
'imagify_get_discount',
@@ -220,13 +219,13 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
$process = imagify_get_optimization_process( $media_id, $context );
if ( ! $process->is_valid() ) {
return new \WP_Error( 'invalid_media', __( 'This media is not valid.', 'imagify' ) );
return new WP_Error( 'invalid_media', __( 'This media is not valid.', 'imagify' ) );
}
$data = $process->get_data();
if ( ! $data->is_already_optimized() ) {
return new \WP_Error( 'not_already_optimized', __( 'This media does not have the right optimization status.', 'imagify' ) );
return new WP_Error( 'not_already_optimized', __( 'This media does not have the right optimization status.', 'imagify' ) );
}
if ( ! $process->has_webp() ) {
@@ -237,7 +236,7 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
$deleted = $process->delete_webp_files();
if ( is_wp_error( $deleted ) ) {
return new \WP_Error( 'webp_not_deleted', __( 'Previous WebP files could not be deleted.', 'imagify' ) );
return new WP_Error( 'webp_not_deleted', __( 'Previous WebP files could not be deleted.', 'imagify' ) );
}
return true;
@@ -829,83 +828,6 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
wp_send_json_success();
}
/**
* Get admin bar profile output.
*
* @since 1.6.11
*/
public function imagify_get_admin_bar_profile_callback() {
imagify_check_nonce( 'imagify-get-admin-bar-profile', 'imagifygetadminbarprofilenonce' );
if ( ! imagify_get_context( 'wp' )->current_user_can( 'manage' ) ) {
imagify_die();
}
$user = new Imagify_User();
$views = Imagify_Views::get_instance();
$unconsumed_quota = $views->get_quota_percent();
$message = '';
if ( $unconsumed_quota <= 20 ) {
$message = '<div class="imagify-error">';
$message .= '<p><i class="dashicons dashicons-warning" aria-hidden="true"></i><strong>' . __( 'Oops, It\'s almost over!', 'imagify' ) . '</strong></p>';
/* translators: %s is a line break. */
$message .= '<p>' . sprintf( __( 'You have almost used all your credit.%sDon\'t forget to upgrade your subscription to continue optimizing your images.', 'imagify' ), '<br/><br/>' ) . '</p>';
$message .= '<p class="center txt-center text-center"><a class="btn imagify-btn-ghost" href="' . esc_url( imagify_get_external_url( 'subscription' ) ) . '" target="_blank">' . __( 'View My Subscription', 'imagify' ) . '</a></p>';
$message .= '</div>';
}
if ( 0 === $unconsumed_quota ) {
$message = '<div class="imagify-error">';
$message .= '<p><i class="dashicons dashicons-warning" aria-hidden="true"></i><strong>' . __( 'Oops, It\'s Over!', 'imagify' ) . '</strong></p>';
$message .= '<p>' . sprintf(
/* translators: 1 is a data quota, 2 is a date. */
__( 'You have consumed all your credit for this month. You will have <strong>%1$s back on %2$s</strong>.', 'imagify' ),
imagify_size_format( $user->quota * pow( 1024, 2 ) ),
date_i18n( get_option( 'date_format' ), strtotime( $user->next_date_update ) )
) . '</p>';
$message .= '<p class="center txt-center text-center"><a class="btn imagify-btn-ghost" href="' . esc_url( imagify_get_external_url( 'subscription' ) ) . '" target="_blank">' . __( 'Upgrade My Subscription', 'imagify' ) . '</a></p>';
$message .= '</div>';
}
// Custom HTML.
$quota_section = '<div class="imagify-admin-bar-quota">';
$quota_section .= '<div class="imagify-abq-row">';
if ( 1 === $user->plan_id ) {
$quota_section .= '<div class="imagify-meteo-icon">' . $views->get_quota_icon() . '</div>';
}
$quota_section .= '<div class="imagify-account">';
$quota_section .= '<p class="imagify-meteo-title">' . __( 'Account status', 'imagify' ) . '</p>';
$quota_section .= '<p class="imagify-meteo-subs">' . __( 'Your subscription:', 'imagify' ) . '&nbsp;<strong class="imagify-user-plan">' . $user->plan_label . '</strong></p>';
$quota_section .= '</div>'; // .imagify-account
$quota_section .= '</div>'; // .imagify-abq-row
if ( 1 === $user->plan_id ) {
$quota_section .= '<div class="imagify-abq-row">';
$quota_section .= '<div class="imagify-space-left">';
/* translators: %s is a data quota. */
$quota_section .= '<p>' . sprintf( __( 'You have %s space credit left', 'imagify' ), '<span class="imagify-unconsumed-percent">' . $unconsumed_quota . '%</span>' ) . '</p>';
$quota_section .= '<div class="' . $views->get_quota_class() . '">';
$quota_section .= '<div style="width: ' . $unconsumed_quota . '%;" class="imagify-unconsumed-bar imagify-progress"></div>';
$quota_section .= '</div>'; // .imagify-bar-{negative|neutral|positive}
$quota_section .= '</div>'; // .imagify-space-left
$quota_section .= '</div>'; // .imagify-abq-row
}
$quota_section .= '<p class="imagify-abq-row">';
$quota_section .= '<a class="imagify-account-link" href="' . esc_url( imagify_get_external_url( 'subscription' ) ) . '" target="_blank">';
$quota_section .= '<span class="dashicons dashicons-admin-users"></span>';
$quota_section .= '<span class="button-text">' . __( 'View my subscription', 'imagify' ) . '</span>';
$quota_section .= '</a>'; // .imagify-account-link
$quota_section .= '</p>'; // .imagify-abq-row
$quota_section .= '</div>'; // .imagify-admin-bar-quota
$quota_section .= $message;
wp_send_json_success( $quota_section );
}
/**
* Get pricings from API for Onetime and Plans at the same time.
*
@@ -1148,7 +1070,7 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
imagify_die();
}
$notice = filter_input( INPUT_GET, 'ad', FILTER_SANITIZE_STRING );
$notice = htmlspecialchars( wp_unslash( $_GET['ad'] ) );
if ( ! $notice ) {
imagify_maybe_redirect();
@@ -1215,8 +1137,8 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
* @return string
*/
public function get_context( $method = 'GET', $parameter = 'context' ) {
$method = 'POST' === $method ? INPUT_POST : INPUT_GET;
$context = filter_input( $method, $parameter, FILTER_SANITIZE_STRING );
$context = 'POST' === $method ? wp_unslash( $_POST[ $parameter ] ) : wp_unslash( $_GET[ $parameter ] ); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
$context = htmlspecialchars( $context );
return imagify_sanitize_context( $context );
}
@@ -1246,14 +1168,15 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
*
* @since 1.9
*
* @param string $method The method used: 'GET' (default), or 'POST'.
* @param string $parameter The name of the parameter to look for.
* @param string $method The method used: 'GET' (default), or 'POST'.
* @param string $parameter The name of the parameter to look for.
*
* @return string
*/
public function get_folder_type( $method = 'GET', $parameter = 'folder_type' ) {
$method = 'POST' === $method ? INPUT_POST : INPUT_GET;
$folder_type = 'POST' === $method ? wp_unslash( $_POST[ $parameter ] ) : wp_unslash( $_GET[ $parameter ] ); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
return filter_input( $method, $parameter, FILTER_SANITIZE_STRING );
return htmlspecialchars( $folder_type );
}
/**
@@ -1261,13 +1184,14 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
*
* @since 1.9
*
* @param string $method The method used: 'GET' (default), or 'POST'.
* @param string $parameter The name of the parameter to look for.
* @param string $method The method used: 'GET' (default), or 'POST'.
* @param string $parameter The name of the parameter to look for.
*
* @return string
*/
public function get_imagify_action( $method = 'GET', $parameter = 'imagify_action' ) {
$method = 'POST' === $method ? INPUT_POST : INPUT_GET;
$action = filter_input( $method, $parameter, FILTER_SANITIZE_STRING );
$action = 'POST' === $method ? wp_unslash( $_POST[ $parameter ] ) : wp_unslash( $_GET[ $parameter ] ); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
$action = htmlspecialchars( $action );
return $action ? $action : 'optimize';
}
@@ -186,7 +186,8 @@ class Imagify_Assets extends Imagify_Assets_Deprecated {
$this->register_script( 'sweetalert', 'sweetalert2', [ 'promise-polyfill' ], '4.6.6' )->localize( 'imagifySwal' );
$this->register_script( 'chart', 'chart', [], '2.7.1.0' );
$this->register_bud_script( 'runtime', 'runtime' );
$this->register_bud_script( 'chart', 'chart', [ 'runtime' ], '4.4.0' );
$this->register_script( 'event-move', 'jquery.event.move', [ 'jquery' ], '2.0.1' );
@@ -211,7 +212,7 @@ class Imagify_Assets extends Imagify_Assets_Deprecated {
$this->register_script( 'async', 'imagify-gulp' );
$this->register_script( 'bulk', 'bulk', [ 'jquery', 'beat', 'underscore', 'chart', 'sweetalert', 'async', 'admin' ] )->defer_localization( 'imagifyBulk' );
$this->register_bud_script( 'bulk', 'bulk', [ 'jquery', 'beat', 'underscore', 'chart', 'sweetalert', 'async', 'admin' ] )->defer_localization( 'imagifyBulk' );
$this->register_script( 'options', 'options', [ 'jquery', 'beat', 'sweetalert', 'underscore', 'admin' ] )->defer_localization( 'imagifyOptions' );
@@ -459,6 +460,42 @@ class Imagify_Assets extends Imagify_Assets_Deprecated {
return $this;
}
/**
* Register a script.
*
* @since 1.6.10
*
* @param string $handle Name of the script. Should be unique.
* @param string|null $file_name The file name, without the extension. If null, $handle is used.
* @param array $dependencies An array of registered script handles this script depends on.
* @param string|null $version String specifying script version number. If set to null, the plugin version is used. If SCRIPT_DEBUG is true, a random string is used.
* @return object This class instance.
*/
public function register_bud_script( $handle, $file_name = null, $dependencies = [], $version = null ) {
// If we register it, it's one of our scripts.
$this->scripts[ $handle ] = 1;
// Set the current handler and handler type.
$this->current_handle = $handle;
$this->current_handle_type = 'js';
$file_name = $file_name ? $file_name : $handle;
$version = $version ? $version : IMAGIFY_VERSION;
$version = $this->is_debug() ? self::$version : $version;
$extension = '.js';
$handle = self::JS_PREFIX . $handle;
$dependencies = $this->prefix_dependencies( $dependencies );
wp_register_script(
$handle,
IMAGIFY_URL . 'assets/admin/js/' . $file_name . $extension,
$dependencies,
$version,
true
);
return $this;
}
/**
* Enqueue a script.
*
@@ -159,18 +159,20 @@ class Imagify_DB {
* It returns an empty string if the database has no attachments without the required metadada.
* It also triggers Imagify_DB::unlimit_joins().
*
* @since 1.7
* @access public
* @author Grégory Viguier
*
* @param string $id_field An ID field to match the metadata ID against in the JOIN clause.
* @param string $id_field An ID field to match the metadata ID against in the JOIN clause.
* Default is the posts table `ID` field, using the `p` alias: `p.ID`.
* In case of "false" value or PEBKAC, fallback to the same field without alias.
* @param bool $matching Set to false to get a query to fetch metas NOT matching the file extensions.
* @param bool $test Test if the site has attachments without required metadata before returning the query. False to bypass the test and get the query anyway.
* @param bool $matching Set to false to get a query to fetch metas NOT matching the file extensions.
* @param bool $test Test if the site has attachments without required metadata before returning the query. False to bypass the test and get the query anyway.
* @param string $special_join_conditions Special conditions to apply on the join.
*
* @return string
* @author Grégory Viguier
*
* @since 1.7
* @access public
*/
public static function get_required_wp_metadata_join_clause( $id_field = 'p.ID', $matching = true, $test = true ) {
public static function get_required_wp_metadata_join_clause( $id_field = 'p.ID', $matching = true, $test = true, $special_join_conditions = '' ) {
global $wpdb;
if ( $test && ! imagify_has_attachments_without_required_metadata() ) {
@@ -186,7 +188,16 @@ class Imagify_DB {
$join = $matching ? 'INNER' : 'LEFT';
$first = true;
foreach ( self::get_required_wp_metadata_aliases() as $meta_name => $alias ) {
if ( $first ) {
$first = false;
$clause .= "
$join JOIN $wpdb->postmeta AS $alias
ON ( $id_field = $alias.post_id AND $alias.meta_key = '$meta_name' $special_join_conditions )";
continue;
}
$clause .= "
$join JOIN $wpdb->postmeta AS $alias
ON ( $id_field = $alias.post_id AND $alias.meta_key = '$meta_name' )";
@@ -299,6 +310,9 @@ class Imagify_DB {
$extensions = array_keys( imagify_get_mime_types() );
$extensions = implode( '|', $extensions );
$extensions = explode( '|', $extensions );
$extensions = array_map(function ( $ex ) {
return strrev( $ex );
}, $extensions);
}
if ( ! $alias ) {
@@ -312,10 +326,12 @@ class Imagify_DB {
return $prepared ? str_replace( '%', '%%', $query[ $key ] ) : $query[ $key ];
}
$regex = '^' . implode( '\..*|^', $extensions ) . '\..*';
if ( $matching ) {
$query[ $key ] = "AND ( LOWER( $alias.meta_value ) LIKE '%." . implode( "' OR LOWER( $alias.meta_value ) LIKE '%.", $extensions ) . "' )";
$query[ $key ] = "AND REVERSE (LOWER( $alias.meta_value )) REGEXP '$regex'";
} else {
$query[ $key ] = "OR ( LOWER( $alias.meta_value ) NOT LIKE '%." . implode( "' AND LOWER( $alias.meta_value ) NOT LIKE '%.", $extensions ) . "' )";
$query[ $key ] = "AND REVERSE (LOWER( $alias.meta_value )) NOT REGEXP '$regex'";
}
return $prepared ? str_replace( '%', '%%', $query[ $key ] ) : $query[ $key ];
@@ -62,7 +62,7 @@ class Imagify_Files_Iterator extends FilterIterator {
*
* @return bool Returns whether the current element of the iterator is acceptable through this filter.
*/
public function accept() {
public function accept(): bool {
static $extensions, $has_extension_method;
$file_path = $this->current()->getPathname();
@@ -4,62 +4,54 @@ defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
/**
* Class that display the "custom folders" files.
*
* @package Imagify
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*/
class Imagify_Files_List_Table extends WP_List_Table {
/**
* Class version.
*
* @var string
* @var string
* @since 1.7
* @author Grégory Viguier
*/
const VERSION = '1.1';
/**
* Class version.
*
* @var string
* @var string
* @since 1.7
* @author Grégory Viguier
*/
const PER_PAGE_OPTION = 'imagify_files_per_page';
/**
* List of the folders containing the listed files.
*
* @var array
* @since 1.7
* @author Grégory Viguier
* @var array
* @since 1.7
*/
protected $folders = array();
/**
* Filesystem object.
*
* @var object Imagify_Filesystem
* @since 1.7.1
* @author Grégory Viguier
* @var Imagify_Filesystem
* @since 1.7.1
*/
protected $filesystem;
/**
* Views object.
*
* @var object Imagify_Views
* @since 1.9
* @author Grégory Viguier
* @var Imagify_Views
* @since 1.9
*/
protected $views;
/**
* Constructor.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param array $args An associative array of arguments.
*/
@@ -80,8 +72,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Prepares the list of items for displaying.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*/
public function prepare_items() {
global $wpdb;
@@ -108,8 +99,8 @@ class Imagify_Files_List_Table extends WP_List_Table {
$file_ids = array();
$where = '';
$sent_orderby = filter_input( INPUT_GET, 'orderby', FILTER_SANITIZE_STRING );
$sent_order = filter_input( INPUT_GET, 'order', FILTER_SANITIZE_STRING );
$sent_orderby = isset( $_GET['orderby'] ) ? htmlspecialchars( wp_unslash( $_GET['orderby'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
$sent_order = isset( $_GET['order'] ) ? htmlspecialchars( wp_unslash( $_GET['order'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
$folder_filter = self::get_folder_filter();
$status_filter = self::get_status_filter();
@@ -227,8 +218,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Message to be displayed when there are no items.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*/
public function no_items() {
if ( self::get_status_filter() ) {
@@ -295,8 +285,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Display views.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*/
public function views() {
global $wpdb;
@@ -412,8 +401,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Get an associative array ( option_name => option_title ) with the list of bulk actions available on this table.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @return array
*/
@@ -427,8 +415,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
* Get a list of columns. The format is:
* 'internal-name' => 'Title'
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @return array
*/
@@ -452,8 +439,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
*
* The second format will make the initial sorting order be descending.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @return array
*/
@@ -469,8 +455,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Get a column contents.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param string $column The column "name": "cb", "title", "optimization_level", etc.
* @param object $item The current item. It must contain at least a $process property.
@@ -489,8 +474,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Handles the checkbox column output.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -505,8 +489,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Handles the title column output.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -555,8 +538,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Handles the parent folder column output.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -590,8 +572,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Handles the optimization data column output.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -642,8 +623,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Handles the status column output.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -677,8 +657,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Handles the optimization level column output.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -693,8 +672,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Handles the actions column output.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -730,8 +708,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Prints a button to optimize the file.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -758,8 +735,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Prints a button to retry to optimize the file.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -789,8 +765,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Prints buttons to re-optimize the file to other levels.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -833,8 +808,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Prints a button to generate WebP versions if they are missing.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -849,8 +823,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Prints a button to delete WebP versions when the status is "already_optimized".
*
* @since 1.9.6
* @author Grégory Viguier
* @since 1.9.6
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -865,8 +838,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Prints a button to restore the file.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -888,8 +860,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Prints a button to check if the file has been modified or not.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -905,8 +876,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Prints a button for the comparison tool (before / after optimization).
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
@@ -952,8 +922,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
* Add the folder_id and folder_path properties to the $item if not set yet.
* It may happen if the $item doesn't come from the prepare() method.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
* @return object The current item.
@@ -988,8 +957,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Get the name of the default primary column.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @return string Name of the default primary column, in this case, 'title'.
*/
@@ -1000,8 +968,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Get a list of CSS classes for the WP_List_Table table tag.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @return array List of CSS classes for the table tag.
*/
@@ -1012,8 +979,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Allow to save the screen options when submitted by the user.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @param bool|int $status Screen option value. Default false to skip.
* @param string $option The option name.
@@ -1031,8 +997,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Get the requested folder filter.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @return string
*/
@@ -1050,8 +1015,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
/**
* Get the requested status filter.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*
* @return string
*/
@@ -1067,7 +1031,7 @@ class Imagify_Files_List_Table extends WP_List_Table {
'unoptimized' => 1,
'errors' => 1,
);
$filter = trim( filter_input( INPUT_GET, 'status-filter', FILTER_SANITIZE_STRING ) );
$filter = isset( $_GET['status-filter'] ) ? trim( htmlspecialchars( wp_unslash( $_GET['status-filter'] ) ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
$filter = isset( $values[ $filter ] ) ? $filter : '';
return $filter;
@@ -52,7 +52,7 @@ class Imagify_Files_Recursive_Iterator extends RecursiveFilterIterator {
*
* @return bool Returns whether the current element of the iterator is acceptable through this filter.
*/
public function accept() {
public function accept(): bool {
static $extensions, $has_extension_method;
$file_path = $this->current()->getPathname();
@@ -1,4 +1,7 @@
<?php
use Imagify\User\User;
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
/**
@@ -303,7 +306,7 @@ class Imagify_Requirements {
return self::$supports['over_quota'];
}
$user = new Imagify_User();
$user = new User();
self::$supports['over_quota'] = $user->get_error() ? false : $user->is_over_quota();
@@ -131,9 +131,12 @@ class Imagify_Settings {
* @return bool
*/
public function is_form_submit() {
return filter_input( INPUT_POST, 'option_page', FILTER_SANITIZE_STRING ) === $this->settings_group && filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING ) === 'update';
}
if ( ! isset( $_POST['option_page'], $_POST['action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
return false;
}
return htmlspecialchars( wp_unslash( $_POST['option_page'] ) ) === $this->settings_group && htmlspecialchars( wp_unslash( $_POST['action'] ) ) === 'update'; // phpcs:ignore WordPress.Security.NonceVerification.Missing
}
/** ----------------------------------------------------------------------------------------- */
/** ON FORM SUBMIT ========================================================================== */
@@ -1,18 +1,20 @@
<?php
use Imagify\User\User;
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
/**
* Class that handles templates and menus.
*
* @since 1.7
* @author Grégory Viguier
* @since 1.7
*/
class Imagify_Views {
/**
* Class version.
*
* @var string
* @var string
* @since 1.7
*/
const VERSION = '1.1';
@@ -20,64 +22,56 @@ class Imagify_Views {
/**
* Slug used for the settings page URL.
*
* @var string
* @since 1.7
* @access protected
* @var string
* @since 1.7
*/
protected $slug_settings;
/**
* Slug used for the bulk optimization page URL.
*
* @var string
* @since 1.7
* @access protected
* @var string
* @since 1.7
*/
protected $slug_bulk;
/**
* Slug used for the "custom folders" page URL.
*
* @var string
* @since 1.7
* @access protected
* @var string
* @since 1.7
*/
protected $slug_files;
/**
* A list of JS templates to print at the end of the page.
*
* @var array
* @since 1.9
* @access protected
* @var array
* @since 1.9
*/
protected $templates_in_footer = [];
/**
* Stores the "custom folders" files list instance.
*
* @var object Imagify_Files_List_Table
* @since 1.7
* @access protected
* @var Imagify_Files_List_Table
* @since 1.7
*/
protected $list_table;
/**
* Filesystem object.
*
* @var object Imagify_Filesystem
* @since 1.7.1
* @access protected
* @author Grégory Viguier
* @var Imagify_Filesystem
* @since 1.7.1
*/
protected $filesystem;
/**
* The single instance of the class.
*
* @var object
* @since 1.7
* @access protected
* @var object
* @since 1.7
*/
protected static $_instance;
@@ -89,9 +83,7 @@ class Imagify_Views {
/**
* The constructor.
*
* @since 1.7
* @author Grégory Viguier
* @access protected
* @since 1.7
*/
protected function __construct() {
$this->slug_settings = IMAGIFY_SLUG;
@@ -103,9 +95,7 @@ class Imagify_Views {
/**
* Get the main Instance.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*
* @return object Main instance.
*/
@@ -120,9 +110,7 @@ class Imagify_Views {
/**
* Launch the hooks.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*/
public function init() {
// Menu items.
@@ -152,9 +140,7 @@ class Imagify_Views {
/**
* Add sub-menus for all sites.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*/
public function add_site_menus() {
$wp_context = imagify_get_context( 'wp' );
@@ -187,9 +173,7 @@ class Imagify_Views {
/**
* Add menu and sub-menus in the network admin when Imagify is network-activated.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*/
public function add_network_menus() {
global $submenu;
@@ -232,9 +216,7 @@ class Imagify_Views {
/**
* Add links to the plugin row in the plugins list.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*
* @param array $actions An array of action links.
* @return array
@@ -254,9 +236,7 @@ class Imagify_Views {
/**
* The main settings page.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*/
public function display_settings_page() {
$this->print_template( 'page-settings' );
@@ -265,9 +245,7 @@ class Imagify_Views {
/**
* The bulk optimization page.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*/
public function display_bulk_page() {
$types = array();
@@ -363,9 +341,7 @@ class Imagify_Views {
/**
* The page displaying the "custom folders" files.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*/
public function display_files_list() {
$this->print_template( 'page-files-list' );
@@ -374,9 +350,7 @@ class Imagify_Views {
/**
* Initiate the "custom folders" list table data.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*/
public function load_files_list() {
// Instantiate the list.
@@ -396,9 +370,7 @@ class Imagify_Views {
/**
* Get the settings page slug.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*
* @return string
*/
@@ -409,9 +381,7 @@ class Imagify_Views {
/**
* Get the bulk optimization page slug.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*
* @return string
*/
@@ -422,9 +392,7 @@ class Imagify_Views {
/**
* Get the "custom folders" files page slug.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*
* @return string
*/
@@ -440,16 +408,14 @@ class Imagify_Views {
/**
* Tell if were displaying the settings page.
*
* @since 1.9
* @author Grégory Viguier
* @access public
* @since 1.9
*
* @return bool
*/
public function is_settings_page() {
global $pagenow;
$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_STRING );
$page = htmlspecialchars( wp_unslash( $_GET['page'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
if ( $this->get_settings_page_slug() !== $page ) {
return false;
@@ -465,16 +431,14 @@ class Imagify_Views {
/**
* Tell if were displaying the bulk optimization page.
*
* @since 1.9
* @author Grégory Viguier
* @access public
* @since 1.9
*
* @return bool
*/
public function is_bulk_page() {
global $pagenow;
$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_STRING );
$page = htmlspecialchars( wp_unslash( $_GET['page'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
return 'upload.php' === $pagenow && $this->get_bulk_page_slug() === $page;
}
@@ -482,16 +446,14 @@ class Imagify_Views {
/**
* Tell if were displaying the custom files list page.
*
* @since 1.9
* @author Grégory Viguier
* @access public
* @since 1.9
*
* @return bool
*/
public function is_files_page() {
global $pagenow;
$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_STRING );
$page = htmlspecialchars( wp_unslash( $_GET['page'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
return 'upload.php' === $pagenow && $this->get_files_page_slug() === $page;
}
@@ -499,26 +461,20 @@ class Imagify_Views {
/**
* Tell if were displaying the WP media library page.
*
* @since 1.9
* @author Grégory Viguier
* @access public
* @since 1.9
*
* @return bool
*/
public function is_wp_library_page() {
global $pagenow;
$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_STRING );
return 'upload.php' === $pagenow && ! $page;
return 'upload.php' === $pagenow && ! isset( $_GET['page'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
}
/**
* Tell if were displaying a media page.
*
* @since 1.9
* @author Grégory Viguier
* @access public
* @since 1.9
*
* @return bool
*/
@@ -536,9 +492,7 @@ class Imagify_Views {
/**
* Get the remaining quota in percent.
*
* @since 1.8.1
* @author Grégory Viguier
* @access public
* @since 1.8.1
*
* @return int
*/
@@ -549,7 +503,7 @@ class Imagify_Views {
return $quota;
}
$user = new Imagify_User();
$user = new User();
$quota = $user->get_percent_unconsumed_quota();
return $quota;
@@ -558,9 +512,7 @@ class Imagify_Views {
/**
* Get the HTML class used for the quota (to change the color when out of quota for example).
*
* @since 1.8.1
* @author Grégory Viguier
* @access public
* @since 1.8.1
*
* @return string
*/
@@ -588,9 +540,7 @@ class Imagify_Views {
/**
* Get the HTML tag used for the quota (the weather-like icon).
*
* @since 1.8.1
* @author Grégory Viguier
* @access public
* @since 1.8.1
*
* @return string
*/
@@ -622,9 +572,7 @@ class Imagify_Views {
/**
* Get a template contents.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*
* @param string $template The template name.
* @param mixed $data Some data to pass to the template.
@@ -648,9 +596,7 @@ class Imagify_Views {
/**
* Print a template.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*
* @param string $template The template name.
* @param mixed $data Some data to pass to the template.
@@ -662,9 +608,7 @@ class Imagify_Views {
/**
* Add a template to the list of JS templates to print at the end of the page.
*
* @since 1.7
* @author Grégory Viguier
* @access public
* @since 1.7
*
* @param string $template The template name.
*/
@@ -691,9 +635,7 @@ class Imagify_Views {
/**
* Print the JS templates that have been added to the "queue".
*
* @since 1.9
* @author Grégory Viguier
* @access public
* @since 1.9
*/
public function print_js_templates() {
if ( ! $this->templates_in_footer ) {
@@ -717,9 +659,7 @@ class Imagify_Views {
/**
* Create HTML attributes from an array.
*
* @since 1.9
* @access public
* @author Grégory Viguier
* @since 1.9
*
* @param array $attributes A list of attribute pairs.
* @return string HTML attributes.
@@ -436,6 +436,19 @@ class Imagify {
return new WP_Error( 'curl', 'cURL isn\'t installed on the server.' );
}
/**
* Allows to mock Imagify calls to the API.
*
* @param stdClass|null $response Response from the call.
* @param string $url URL from the call.
* @param array $args Arguments from the call.
*/
$response = apply_filters( 'pre_imagify_request', null, $url, $args );
if ( $response ) {
return $response;
}
try {
$url = self::API_ENDPOINT . $url;
$ch = curl_init();
@@ -1,4 +1,7 @@
<?php
use Imagify\User\User;
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
if ( class_exists( 'C_NextGEN_Bootstrap' ) && class_exists( 'Mixin' ) && get_site_option( 'ngg_options' ) ) :
@@ -60,7 +63,7 @@ if ( class_exists( 'C_NextGEN_Bootstrap' ) && class_exists( 'Mixin' ) && get_sit
add_filter( 'imagify_count_saving_data', 'imagify_ngg_count_saving_data', 8 );
$saving_data = imagify_count_saving_data();
$user = new Imagify_User();
$user = new User();
$response['imagify_bulk_data'] = array(
// User account.
@@ -1,9 +1,10 @@
<?php
/**
* Imagify User class.
* Deprecated class that handles Imagify User class.
*
* @since 1.0
* @deprecated
*/
class Imagify_User {
/**
@@ -153,7 +154,6 @@ class Imagify_User {
*/
public function get_percent_consumed_quota() {
static $done = false;
if ( $this->get_error() ) {
return 0;
}
@@ -176,12 +176,15 @@ class Imagify_User {
$percent = (float) $percent;
$percent = 100;
if ( $done ) {
return $percent;
}
$previous_percent = Imagify_Data::get_instance()->get( 'previous_quota_percent' );
// Percent is not 100% anymore.
if ( 100.0 === (float) $previous_percent && $percent < 100 ) {
/**
@@ -33,7 +33,10 @@ function imagify_count_attachments() {
$mime_types = Imagify_DB::get_mime_types();
$statuses = Imagify_DB::get_post_statuses();
$nodata_join = Imagify_DB::get_required_wp_metadata_join_clause();
$nodata_join = Imagify_DB::get_required_wp_metadata_join_clause('p.ID', true, true,
"AND p.post_mime_type IN ( $mime_types )
AND p.post_type = 'attachment'
AND p.post_status IN ( $statuses )");
$nodata_where = Imagify_DB::get_required_wp_metadata_where_clause();
$count = (int) $wpdb->get_var( // WPCS: unprepared SQL ok.
"
@@ -42,6 +42,7 @@ function get_imagify_attachment_optimization_text( $process ) {
}
$data = $process->get_data();
$optimized_data = $data->get_optimization_data();
$attachment_id = $media->get_id();
$optimization_level = imagify_get_optimization_level_label( $data->get_optimization_level() );
@@ -49,6 +50,10 @@ function get_imagify_attachment_optimization_text( $process ) {
$output .= $output_before . '<span class="data">' . __( 'New Filesize:', 'imagify' ) . '</span> <strong class="big">' . $data->get_optimized_size() . '</strong>' . $output_after;
}
if ( key_exists( 'message', $optimized_data ) && $optimized_data['message'] ) {
$output .= $output_before . '<span class="data">' . __( 'Convert:', 'imagify' ) . '</span> <strong class="big">' . $optimized_data['message'] . '</strong>' . $output_after;
}
$chart = '';
if ( ! $is_media_page ) {
@@ -90,6 +95,10 @@ function get_imagify_attachment_optimization_text( $process ) {
if ( $media->is_image() ) {
$has_webp = $process->has_webp() ? __( 'Yes', 'imagify' ) : __( 'No', 'imagify' );
if ( $process->has_webp() ) {
$has_webp = $process->is_full_webp() ? __( 'Yes', 'imagify' ) : __( 'Partially', 'imagify' );
}
$output .= $output_before . '<span class="data">' . __( 'WebP generated:', 'imagify' ) . '</span> <strong class="big">' . esc_html( $has_webp ) . '</strong>' . $output_after;
$total_optimized_thumbnails = $data->get_optimized_sizes_count();
@@ -1,5 +1,6 @@
<?php
use Imagify\Notices\Notices;
use Imagify\User\User;
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
@@ -400,7 +401,7 @@ function imagify_cache_user() {
return false;
}
$user = new Imagify_User();
$user = new User();
$data = (object) get_object_vars( $user );
$methods = get_class_methods( $user );
@@ -164,7 +164,7 @@ function get_imagify_max_image_size() {
*/
function imagify_translate_api_message( $message ) {
if ( ! $message ) {
return imagify_translate_api_message( 'Unknown error occurred' );
$message = 'Unknown error occurred';
}
if ( is_wp_error( $message ) ) {
@@ -199,6 +199,7 @@ function imagify_translate_api_message( $message ) {
'</a>'
),
'Your image is too big to be uploaded on our server' => __( 'Your file is too big to be uploaded on our server.', 'imagify' ),
'Webp is less performant than original' => __( 'WebP file is larger than the original image', 'imagify' ),
'Our server returned an invalid response' => __( 'Our server returned an invalid response.', 'imagify' ),
'cURL isn\'t installed on the server' => __( 'cURL is not available on the server.', 'imagify' ),
// API messages.
@@ -115,7 +115,14 @@ function imagify_has_attachments_without_required_metadata() {
$mime_types = Imagify_DB::get_mime_types();
$statuses = Imagify_DB::get_post_statuses();
$nodata_join = Imagify_DB::get_required_wp_metadata_join_clause( 'p.ID', false, false );
$nodata_join = Imagify_DB::get_required_wp_metadata_join_clause(
'p.ID',
false,
false,
"AND p.post_mime_type IN ( $mime_types )
AND p.post_type = 'attachment'
AND p.post_status IN ( $statuses )"
);
$nodata_where = Imagify_DB::get_required_wp_metadata_where_clause( array(
'matching' => false,
'test' => false,
+30 -12
View File
@@ -1,8 +1,8 @@
=== Imagify Optimize Images & Convert WebP | Compress Images Easily ===
Contributors: wp_rocket, imagify
Tags: optimize images, convert webp, webp, image optimization, compress images, image compressor, resize images, reduce image size, performance, image optimizer, core web vitals, best image optimization plugin
Tested up to: 6.1
Stable tag: 2.1.1
Tags: optimize images, convert webp, webp converter, image optimization, compress images, image compressor, resize images, reduce image size, performance, image optimizer, core web vitals, best image optimization plugin
Tested up to: 6.3
Stable tag: 2.1.3
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
@@ -12,7 +12,7 @@ Compress images & convert WebP with the best WordPress image optimization plugin
= The Best Image Optimization Plugin For WordPress =
[Imagify](https://imagify.io/) is the most advanced image optimization plugin to help you resize and compress images. You can now use its power directly in WordPress to optimize images and reduce the weight of the photos you want to add to your site all in just one click and without sacrificing their quality.
[Imagify](https://imagify.io/) is the most advanced image optimization plugin to help you resize and compress images. You can now use its power directly in WordPress to optimise images and reduce the weight of the photos you want to add to your site all in just one click and without sacrificing their quality.
Imagify is the best WordPress image optimizer. The plugin lets you optimize images in one go with its asynchronous bulk optimization option. You can resize your images on the fly they will be automatically optimized at the best compression level. If needed, you can always restore your images to their original versions.
@@ -27,27 +27,27 @@ Our video explains why Imagify is the easiest image optimization plugin and show
= Resize and Compress Images Without Losing Quality =
Imagify is a great image compressor and the ultimate solution to optimize images. You are able to resize and compress images from the most common image formats as well as PDF format. In case you have many images to optimize, you can also resize images in bulk thanks to our async bulk optimization option. In just one click, you will be able to compress multiple images super easily. Imagify compresses all your images in the background, so you can leave the page and not worry about anything.
Imagify is a great image compressor and the ultimate solution to optimise images. You are able to resize and compress images from the most common image formats as well as PDF format. In case you have many images to optimize, you can also resize images in bulk thanks to our async bulk optimization option. In just one click, you will be able to compress multiple images super easily. Imagify compresses all your images in the background, so you can leave the page and not worry about anything.
Many of your high-quality images may be in sizes that are much too large. To reduce image size and compress large images, Imagify has a setting that allows you to choose a maximum width for all of your images, and if you upload images that are larger than that size, it will resize large images for you during optimization. Imagify will resize images proportionally without cropping them.
With such a great image optimizer like Imagify, youll get your images automatically optimized at the best compression level and quality thanks to the Smart Compression Mode.
When using our image compression tool, Imagify, you will enjoy smaller file sizes and faster loading times. But the best part is that you will optimize images and reduce their weight without losing quality: why should you have to choose between beauty and speed? If you want to compress images, its now easier than ever with Imagify!
When using our image compression tool, Imagify, you will enjoy smaller file sizes and faster loading times. But the best part is that you will optimise images and reduce their weight without losing quality: why should you have to choose between beauty and speed? If you want to compress images, its now easier than ever with Imagify!
= Convert WebP for Superior Image Compression =
= Convert Images to the WebP Format =
Thanks to Imagify, you can take a step further in your image optimization process. You can also convert all your images to next-gen image formats such as WebP. WebP format offers superior image compression and quality and is a way to optimize images and speed up their loading times on websites. To convert images to next-gen format, using the Imagify plugin will save you a precious amount of time.
Thanks to Imagify, you can take a step further in your image optimization process. You can also convert all your images to next-gen image formats such as WebP. WebP format offers superior image compression and quality and is a way to optimise images and speed up their loading times on websites. To convert images to next-gen format, using the Imagify plugin will save you a precious amount of time.
With Imagify, WebP compression and conversion are indeed super easy. Wondering how the convert WebP option works? If the "Create WebP versions of images" option is enabled, the WebP versions of optimized images will be created automatically. Simple as that! Thanks to the best WebP plugin for WordPress, youll be able to take advantage of the convert WebP feature in no time.
Imagify can also display these WebP images directly on your front-end. But because some browsers dont support WebP yet, Imagify lets you have both optimized versions of the original format images and the WebP versions ready. Imagify will serve the WebP versions if a visitor's browser supports them and the other optimized format if not.
WebP is definitively an excellent replacement for jpeg, png, and gif images. Imagify offers WebP conversion for all image formats: you can convert gif to webP, jpeg to WebP, and even png to WebP. Whatever your favorite image format, let Imagify optimize your images!
WebP is definitively an excellent replacement for jpeg, png, and gif images. Imagify offers WebP conversion for all image formats: you can convert gif to webP, jpeg to WebP, and even png to WebP. Whatever your favorite image format, let Imagify optimise your images!
= Optimize Images to Make Your Site Faster and Improve Core Web Vitals =
= Optimise Images to Make Your Site Faster and Improve Core Web Vitals =
Did you know that image optimization and web performance go hand in hand? In fact, when it comes to web page speed, one of the first things you should do is optimize your images. Large and heavy image sizes will indeed slow down your website and provide a bad user experience to your visitors and thats why you should compress images. On the contrary, when you optimize images and improve image loading speed, you should see a direct improvement in your website speed and performance. With Imagify, its time to say goodbye to images taking too long to load.
Did you know that image optimization and web performance go hand in hand? In fact, when it comes to web page speed, one of the first things you should do is optimize your images. Large and heavy image sizes will indeed slow down your website and provide a bad user experience to your visitors and thats why you should compress images. On the contrary, when you optimise images and improve image loading speed, you should see a direct improvement in your website speed and performance. With Imagify, its time to say goodbye to images taking too long to load.
Images are one of the largest influencing factors in the Core Web Vitals. Image compression will ensure that your images load faster and improve your overall website performance, including your Core Web Vitals metrics. If youre looking to improve user experience and speed up your WordPress site, images are a good place to start.
@@ -57,7 +57,7 @@ Even Google tells you to take care of your images! If you have ever run a perfor
Heres what our users have to say about us after optimizing their images with Imagify:
>"Images and other media are the largest parts on your web pages (most likely). Therefore don't forget to optimize images for the web before adding to your site. For WordPress there are many optimisation plugins available. My favourite is Imagify" — [Mark Wilkinson](https://twitter.com/wpmark/status/1479128422395830273)
>"Images and other media are the largest parts on your web pages (most likely). Therefore don't forget to optimise images for the web before adding to your site. For WordPress there are many optimisation plugins available. My favourite is Imagify" — [Mark Wilkinson](https://twitter.com/wpmark/status/1479128422395830273)
>
>”To give your images a slimming treatment, without altering them aesthetically, there is a great plugin on WordPress: Imagify. Simple, efficient and functional, its really worth a look.”— [WP Marmite](https://twitter.com/wpmarmite_en/status/1383072818649255937)
@@ -243,6 +243,10 @@ Yes, and no credit card is required.
No. However, you get 20MB of quota per month for free to optimize your images (around 200 images).
= Where do I report security bugs found in this plugin? =
You can report any security bugs found in the source code of the site-reviews plugin through the [Patchstack Vulnerability Disclosure Program](https://patchstack.com/database/vdp/imagify). The Patchstack team will assist you with verification, CVE assignment and take care of notifying the developers of this plugin.
== Screenshots ==
1. Bulk Optimization
@@ -254,6 +258,20 @@ No. However, you get 20MB of quota per month for free to optimize your images (a
4. Other Media Page
== Changelog ==
= 2.1.3 =
- Enhancement: Update chart.js (#742)
- Enhancement: Improve messaging around WebP images when they are larger than the original (#751)
- Enhancement: Update notices when out of quota (#727, #728)
- Bugfix: Prevent PHP deprecated notice on PHP 8.1 (#734)
- Bugfix: Improve database queries on large media libraries (#747)
= 2.1.2 =
- Bugfix: Prevent deprecation notice with PHP 8.1 & 8.2 (#721, #723)
- Bugfix: Escape error message before display (#729)
- Bugfix: Don't count WebP images in the generate missing WebP images versions (#713)
- Bugfix: Improve information related to out of quota on bulk optimization (#714)
- Bugfix: Fix optimization filter type working with file filters on media library (#670)
= 2.1.1 =
- Enhancement: Allow WebP images to be optimized by Imagify from the plugin (#611)
- Enhancement: Improve error message displayed when an unknown error occured (#637)
+1 -1
View File
@@ -22,4 +22,4 @@ if (PHP_VERSION_ID < 50600) {
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit4ba6376c0ffc3020053ab8c93bad1e1e::getLoader();
return ComposerAutoloaderInit49a1cdf8dc57f57539cd34f9d3c0eac1::getLoader();
+53 -55
View File
@@ -45,35 +45,34 @@ class ClassLoader
/** @var \Closure(string):void */
private static $includeFile;
/** @var ?string */
/** @var string|null */
private $vendorDir;
// PSR-4
/**
* @var array[]
* @psalm-var array<string, array<string, int>>
* @var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, array<int, string>>
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, string>
* @var list<string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* @var array[]
* @psalm-var array<string, array<string, string[]>>
* List of PSR-0 prefixes
*
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
*
* @var array<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var array[]
* @psalm-var array<string, string>
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
@@ -81,8 +80,7 @@ class ClassLoader
private $useIncludePath = false;
/**
* @var string[]
* @psalm-var array<string, string>
* @var array<string, string>
*/
private $classMap = array();
@@ -90,21 +88,20 @@ class ClassLoader
private $classMapAuthoritative = false;
/**
* @var bool[]
* @psalm-var array<string, bool>
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var ?string */
/** @var string|null */
private $apcuPrefix;
/**
* @var self[]
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param ?string $vendorDir
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
@@ -113,7 +110,7 @@ class ClassLoader
}
/**
* @return string[]
* @return array<string, list<string>>
*/
public function getPrefixes()
{
@@ -125,8 +122,7 @@ class ClassLoader
}
/**
* @return array[]
* @psalm-return array<string, array<int, string>>
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
@@ -134,8 +130,7 @@ class ClassLoader
}
/**
* @return array[]
* @psalm-return array<string, string>
* @return list<string>
*/
public function getFallbackDirs()
{
@@ -143,8 +138,7 @@ class ClassLoader
}
/**
* @return array[]
* @psalm-return array<string, string>
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
@@ -152,8 +146,7 @@ class ClassLoader
}
/**
* @return string[] Array of classname => path
* @psalm-return array<string, string>
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
@@ -161,8 +154,7 @@ class ClassLoader
}
/**
* @param string[] $classMap Class to filename map
* @psalm-param array<string, string> $classMap
* @param array<string, string> $classMap Class to filename map
*
* @return void
*/
@@ -179,24 +171,25 @@ class ClassLoader
* 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 string[]|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
$paths
);
}
@@ -205,19 +198,19 @@ class ClassLoader
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
$this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
$paths
);
}
}
@@ -226,9 +219,9 @@ class ClassLoader
* 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 string[]|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
@@ -236,17 +229,18 @@ class ClassLoader
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
$paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
@@ -256,18 +250,18 @@ class ClassLoader
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;
$this->prefixDirsPsr4[$prefix] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
$paths
);
}
}
@@ -276,8 +270,8 @@ class ClassLoader
* 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 string[]|string $paths The PSR-0 base directories
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 base directories
*
* @return void
*/
@@ -294,8 +288,8 @@ class ClassLoader
* 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 string[]|string $paths The PSR-4 base directories
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
@@ -429,7 +423,8 @@ class ClassLoader
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
(self::$includeFile)($file);
$includeFile = self::$includeFile;
$includeFile($file);
return true;
}
@@ -480,9 +475,9 @@ class ClassLoader
}
/**
* Returns the currently registered loaders indexed by their corresponding vendor directories.
* Returns the currently registered loaders keyed by their corresponding vendor directories.
*
* @return self[]
* @return array<string, self>
*/
public static function getRegisteredLoaders()
{
@@ -560,7 +555,10 @@ class ClassLoader
return false;
}
private static function initializeIncludeClosure(): void
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
@@ -574,8 +572,8 @@ class ClassLoader
* @param string $file
* @return void
*/
self::$includeFile = static function($file) {
self::$includeFile = \Closure::bind(static function($file) {
include $file;
};
}, null, null);
}
}
@@ -98,7 +98,7 @@ class InstalledVersions
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']);
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
@@ -119,7 +119,7 @@ class InstalledVersions
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints($constraint);
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
@@ -328,7 +328,9 @@ class InstalledVersions
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
$installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
$installed[] = self::$installedByVendor[$vendorDir] = $required;
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
@@ -340,12 +342,17 @@ class InstalledVersions
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = require __DIR__ . '/installed.php';
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
$installed[] = self::$installed;
if (self::$installed !== array()) {
$installed[] = self::$installed;
}
return $installed;
}
@@ -46,7 +46,7 @@ return array(
'Imagify_Regenerate_Thumbnails_Deprecated' => $baseDir . '/inc/deprecated/classes/class-imagify-regenerate-thumbnails-deprecated.php',
'Imagify_Requirements' => $baseDir . '/inc/classes/class-imagify-requirements.php',
'Imagify_Settings' => $baseDir . '/inc/classes/class-imagify-settings.php',
'Imagify_User' => $baseDir . '/inc/classes/class-imagify-user.php',
'Imagify_User' => $baseDir . '/inc/deprecated/classes/class-imagify-user.php',
'Imagify_Views' => $baseDir . '/inc/classes/class-imagify-views.php',
'Imagify_WP_Async_Request' => $baseDir . '/inc/classes/Dependencies/deliciousbrains/wp-background-processing/classes/wp-async-request.php',
'Imagify_WP_Background_Process' => $baseDir . '/inc/classes/Dependencies/deliciousbrains/wp-background-processing/classes/wp-background-process.php',
@@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit4ba6376c0ffc3020053ab8c93bad1e1e
class ComposerAutoloaderInit49a1cdf8dc57f57539cd34f9d3c0eac1
{
private static $loader;
@@ -24,12 +24,12 @@ class ComposerAutoloaderInit4ba6376c0ffc3020053ab8c93bad1e1e
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInit4ba6376c0ffc3020053ab8c93bad1e1e', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInit49a1cdf8dc57f57539cd34f9d3c0eac1', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\AutoloadWPMediaImagifyWordPressPlugin\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInit4ba6376c0ffc3020053ab8c93bad1e1e', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInit49a1cdf8dc57f57539cd34f9d3c0eac1', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit4ba6376c0ffc3020053ab8c93bad1e1e::getInitializer($loader));
call_user_func(\Composer\Autoload\ComposerStaticInit49a1cdf8dc57f57539cd34f9d3c0eac1::getInitializer($loader));
$loader->register(true);
@@ -7,7 +7,7 @@ namespace Composer\Autoload;
use Composer\AutoloadWPMediaImagifyWordPressPlugin\ClassLoader as ClassLoaderWPMediaImagifyWordPressPlugin;
class ComposerStaticInit4ba6376c0ffc3020053ab8c93bad1e1e
class ComposerStaticInit49a1cdf8dc57f57539cd34f9d3c0eac1
{
public static $prefixLengthsPsr4 = array (
'I' =>
@@ -115,7 +115,7 @@ class ComposerStaticInit4ba6376c0ffc3020053ab8c93bad1e1e
'Imagify_Regenerate_Thumbnails_Deprecated' => __DIR__ . '/../..' . '/inc/deprecated/classes/class-imagify-regenerate-thumbnails-deprecated.php',
'Imagify_Requirements' => __DIR__ . '/../..' . '/inc/classes/class-imagify-requirements.php',
'Imagify_Settings' => __DIR__ . '/../..' . '/inc/classes/class-imagify-settings.php',
'Imagify_User' => __DIR__ . '/../..' . '/inc/classes/class-imagify-user.php',
'Imagify_User' => __DIR__ . '/../..' . '/inc/deprecated/classes/class-imagify-user.php',
'Imagify_Views' => __DIR__ . '/../..' . '/inc/classes/class-imagify-views.php',
'Imagify_WP_Async_Request' => __DIR__ . '/../..' . '/inc/classes/Dependencies/deliciousbrains/wp-background-processing/classes/wp-async-request.php',
'Imagify_WP_Background_Process' => __DIR__ . '/../..' . '/inc/classes/Dependencies/deliciousbrains/wp-background-processing/classes/wp-background-process.php',
@@ -124,9 +124,9 @@ class ComposerStaticInit4ba6376c0ffc3020053ab8c93bad1e1e
public static function getInitializer(ClassLoaderWPMediaImagifyWordPressPlugin $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit4ba6376c0ffc3020053ab8c93bad1e1e::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit4ba6376c0ffc3020053ab8c93bad1e1e::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit4ba6376c0ffc3020053ab8c93bad1e1e::$classMap;
$loader->prefixLengthsPsr4 = ComposerStaticInit49a1cdf8dc57f57539cd34f9d3c0eac1::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit49a1cdf8dc57f57539cd34f9d3c0eac1::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit49a1cdf8dc57f57539cd34f9d3c0eac1::$classMap;
}, null, ClassLoaderWPMediaImagifyWordPressPlugin::class);
}
@@ -1,9 +1,9 @@
<?php return array(
'root' => array(
'name' => 'wp-media/imagify-plugin',
'pretty_version' => 'v2.1.1',
'version' => '2.1.1.0',
'reference' => '46f9df25cc18fe7a8609d1a94bec039e169282da',
'pretty_version' => 'v2.1.3',
'version' => '2.1.3.0',
'reference' => '58a54d5f7381cc9884874f51021a0c791965fc05',
'type' => 'wordpress-plugin',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@@ -29,9 +29,9 @@
'dev_requirement' => false,
),
'wp-media/imagify-plugin' => array(
'pretty_version' => 'v2.1.1',
'version' => '2.1.1.0',
'reference' => '46f9df25cc18fe7a8609d1a94bec039e169282da',
'pretty_version' => 'v2.1.3',
'version' => '2.1.3.0',
'reference' => '58a54d5f7381cc9884874f51021a0c791965fc05',
'type' => 'wordpress-plugin',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@@ -0,0 +1,41 @@
<?php
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
?>
<div class="imagify-admin-bar-quota">
<div class="imagify-abq-row">
<?php if ( $data['plan_with_quota'] ) : ?>
<div class="imagify-meteo-icon"><?php echo $data['quota_icon']; ?></div>
<?php endif; ?>
<div class="imagify-account">
<p class="imagify-meteo-title"><?php esc_html_e( 'Account status', 'imagify' ); ?></p>
<p class="imagify-meteo-subs"><?php esc_html_e( 'Your subscription:', 'imagify' ); ?> &nbsp;<strong class="imagify-user-plan"><?php echo $data['plan_label']; ?></strong></p>
</div>
</div>
<?php if ( $data['plan_with_quota'] ) : ?>
<div class="imagify-abq-row">
<div class="imagify-space-left">
<p><?php
printf(
// translators: %s = percentage.
__( 'You have %s space credit left', 'imagify' ), '<span class="imagify-unconsumed-percent">' . $data['unconsumed_quota'] . '%</span>' );
?></p>
<div class="<?php echo esc_attr( $data['quota_class'] ); ?>">
<div style="width: <?php echo esc_attr( $data['unconsumed_quota'] ); ?>%;" class="imagify-unconsumed-bar imagify-progress"></div>
</div>
</div>
</div>
<?php endif; ?>
<?php if ( $data['plan_with_quota'] && $data['unconsumed_quota'] <= 20 ) : ?>
<div class="imagify-upsell-admin-bar">
<?php if ( $data['unconsumed_quota'] <= 20 ) : ?>
<p><i class="dashicons dashicons-warning" aria-hidden="true"></i><strong><?php esc_html_e( 'Oops, It\'s almost over!', 'imagify' ); ?></strong></p>
<?php elseif ( 0 === $data['unconsumed_quota'] ) : ?>
<p><i class="dashicons dashicons-warning" aria-hidden="true"></i><strong><?php esc_html_e( 'Oops, It\'s Over!', 'imagify' ); ?></strong></p>
<?php endif; ?>
<p><?php echo $data['text']; ?></p>
<p class="center txt-center text-center"><a class="imagify-upsell-admin-bar-button" href="<?php echo esc_url( $data['upgrade_link'] ); ?>" target="_blank"><?php echo $data['button_text']; ?></a></p>
<a href="<?php echo esc_url( get_imagify_admin_url( 'dismiss-notice', 'upsell-admin-bar' ) ); ?>" class="imagify-notice-dismiss imagify-upsell-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'imagify' ); ?>"><span class="screen-reader-text"><?php esc_html_e( 'Dismiss this notice', 'imagify' ); ?></span></a>
</div>
<?php endif; ?>
</div>

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