Compare commits
23 Commits
reset-post
...
8d42eee2c1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d42eee2c1 | ||
|
|
29109c47d1 | ||
|
|
297ba93508 | ||
|
|
d805477f4e | ||
|
|
e5e17cbafc | ||
|
|
ba63181e6a | ||
|
|
e57a7aadb9 | ||
|
|
0ba7c07287 | ||
|
|
558ea24cec | ||
|
|
f0b7c405fa | ||
|
|
a9c7f7c70f | ||
|
|
5345b86a25 | ||
|
|
f458be3293 | ||
|
|
a08d0527b4 | ||
|
|
458c216fea | ||
|
|
5828269a70 | ||
|
|
d4be70eb78 | ||
|
|
f1d0414f58 | ||
|
|
41f44b1200 | ||
|
|
7f32a4bb1b | ||
|
|
492289deb1 | ||
|
|
318eb8f0c5 | ||
|
|
6fd3f4a13c |
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
wp-pppr-salt.php
|
||||||
167
admin.php
Normal file
167
admin.php
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
function init_postode_admin()
|
||||||
|
{
|
||||||
|
add_action("admin_menu", "local_postcodes_admin_menu", 99);
|
||||||
|
add_action("admin_head", "local_postcodes_admin_css");
|
||||||
|
add_action("admin_init", "local_postcodes_register_settings"); // Correct
|
||||||
|
}
|
||||||
|
|
||||||
|
function local_postcodes_admin_menu()
|
||||||
|
{
|
||||||
|
add_submenu_page(
|
||||||
|
"woocommerce", // Parent menu slug
|
||||||
|
"Lokale Postcodes", // Page title
|
||||||
|
"Lokale Postcodes", // Menu title
|
||||||
|
"manage_options", // Capability
|
||||||
|
"local-postcodes", // Menu slug
|
||||||
|
"generate_admin_page", // Callback function
|
||||||
|
"dashicons-buddicons-pm", // Optional icon URL or dashicon
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function local_postcodes_register_settings()
|
||||||
|
{
|
||||||
|
register_setting(
|
||||||
|
"my_plugin_options",
|
||||||
|
"local_postcodes_values",
|
||||||
|
"local_postcodes_input_validate",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function generate_admin_page()
|
||||||
|
{
|
||||||
|
?>
|
||||||
|
<div class="wrap">
|
||||||
|
<h1><span class="dashicons dashicons-admin-home"></span> Lokale Postcodereeksen</h1>
|
||||||
|
<?php settings_errors("local_postcodes_error_messages"); ?>
|
||||||
|
<div class="info">
|
||||||
|
<p class="info">Vul hier de lokale postcodereeksen in.</p>
|
||||||
|
<ul>
|
||||||
|
<li>Het formaat voor een reeks is #### - #### (voorbeeld: 5000 - 5199).</li>
|
||||||
|
<li>Plaats één reeks op één regel.</li>
|
||||||
|
<li>Een reeks van 1 is geldig. (voorbeeld: 5000 - 5000)</li>
|
||||||
|
<li>Om een reeks te verwijderen. Wis de reeks en sla vervolgens de wijzigen op.</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<form id="postcodes_form" method="post" action="options.php">
|
||||||
|
<?php
|
||||||
|
settings_fields("my_plugin_options");
|
||||||
|
do_settings_sections("my_plugin_options");
|
||||||
|
?>
|
||||||
|
<textarea id="local_postcodes_values" name="local_postcodes_values"><?php echo esc_textarea(
|
||||||
|
get_option("local_postcodes_values"),
|
||||||
|
); ?></textarea>
|
||||||
|
<?php submit_button(); ?>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<?php
|
||||||
|
}
|
||||||
|
|
||||||
|
function local_postcodes_admin_css()
|
||||||
|
{
|
||||||
|
?>
|
||||||
|
<style>
|
||||||
|
h1 .dashicons{
|
||||||
|
font-size: 25px;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
.info {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
max-width: 60ch;
|
||||||
|
|
||||||
|
ul {
|
||||||
|
list-style: square inside;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#postcodes_form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
max-width: 60ch;
|
||||||
|
align-items: flex-end;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
|
||||||
|
#local_postcodes_values{
|
||||||
|
width: 100% !important;
|
||||||
|
height: 50vh !important;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-family: "Consolas", "Monaco", "Courier New", monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
.submit{
|
||||||
|
margin-top: .2rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>';
|
||||||
|
<?php
|
||||||
|
}
|
||||||
|
|
||||||
|
function local_postcodes_input_validate($input)
|
||||||
|
{
|
||||||
|
$valid_input = "";
|
||||||
|
$lines = preg_split("/\R/", $input, -1, PREG_SPLIT_NO_EMPTY);
|
||||||
|
$pattern = '/^\d{4}\s*\-\s*\d{4}$/';
|
||||||
|
$pc_arr = [];
|
||||||
|
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
$line = trim($line);
|
||||||
|
if (preg_match($pattern, $line)) {
|
||||||
|
$parts = explode("-", $line);
|
||||||
|
$first = (int) $parts[0];
|
||||||
|
$second = (int) $parts[1];
|
||||||
|
|
||||||
|
if ($first <= $second) {
|
||||||
|
$pc_arr[] = [$first, $second];
|
||||||
|
} else {
|
||||||
|
$pc_arr[] = [$second, $first];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
add_settings_error(
|
||||||
|
"local_postcodes_error_messages",
|
||||||
|
"invalid_postcode_" . md5($line),
|
||||||
|
'❌️ Ongeldige regel: "' .
|
||||||
|
esc_html($line) .
|
||||||
|
'". Gebruik het formaat #### - ####.(bijvoorbeeld: 5000 - 5199)',
|
||||||
|
"error",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
usort($pc_arr, function ($a, $b) {
|
||||||
|
return $a[0] <=> $b[0];
|
||||||
|
});
|
||||||
|
|
||||||
|
$old_pc_arr_len = count($pc_arr);
|
||||||
|
$pc_arr = array_map(
|
||||||
|
"unserialize",
|
||||||
|
array_unique(array_map("serialize", $pc_arr)),
|
||||||
|
);
|
||||||
|
$new_pc_arr_len = count($pc_arr);
|
||||||
|
|
||||||
|
if ($new_pc_arr_len < $old_pc_arr_len) {
|
||||||
|
add_settings_error(
|
||||||
|
"local_postcodes_error_messages",
|
||||||
|
"Duplicaten",
|
||||||
|
// @formatter:off
|
||||||
|
"⚠️ " .
|
||||||
|
$old_pc_arr_len -
|
||||||
|
$new_pc_arr_len .
|
||||||
|
" " .
|
||||||
|
($old_pc_arr_len - $new_pc_arr_len > 1
|
||||||
|
? "duplicaten"
|
||||||
|
: "duplicaat") .
|
||||||
|
" verwijderd.",
|
||||||
|
// @formatter:on
|
||||||
|
"warning",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($pc_arr as $range) {
|
||||||
|
$valid_input .= $range[0] . " - " . $range[1] . "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
return $valid_input;
|
||||||
|
}
|
||||||
@@ -1,70 +1,127 @@
|
|||||||
.postcode_modal {
|
.postcode_modal {
|
||||||
border-radius: 20px;
|
border-radius: 3px;
|
||||||
box-shadow(10px);
|
|
||||||
border: none;
|
border: none;
|
||||||
max-width: 80ch;
|
max-width: 65ch;
|
||||||
box-shadow: 0 0 20pc black;
|
|
||||||
padding: 2rem;
|
padding: 2rem;
|
||||||
|
padding-bottom: 1rem;
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transition: opacity 0.3s ease, display 0.3s allow-discrete;
|
transition:
|
||||||
|
opacity 0.3s ease,
|
||||||
|
display 0.3s allow-discrete;
|
||||||
|
|
||||||
&[open] {
|
&[open] {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
transition-behavior: allow-discrete;
|
transition-behavior: allow-discrete;
|
||||||
transition: opacity 0.3s ease, display 0.3s allow-discrete;
|
transition:
|
||||||
}
|
opacity 0.3s ease,
|
||||||
|
display 0.3s allow-discrete;
|
||||||
&:not([open]) {
|
@starting-style {
|
||||||
display: none;
|
opacity: 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
h2 {
|
h2 {
|
||||||
font-size: 1.5rem;
|
font-size: 1.1rem;
|
||||||
margin: .6rem;
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:not([open]) {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
form {
|
||||||
|
margin-top: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
input[type="text"] {
|
input[type="text"] {
|
||||||
padding: .3rem;
|
padding: 0.3rem;
|
||||||
font-size: 1.4rem;
|
font-size: 1.2rem;
|
||||||
caret-color: hsl(344 98 40);
|
caret-color: var(--wp--preset--color--vivid-red);
|
||||||
|
background: hsl(0 1 80);
|
||||||
|
border: none;
|
||||||
|
text-transform: uppercase;
|
||||||
|
|
||||||
|
&:focus,
|
||||||
|
&:valid,
|
||||||
|
&:invalid,
|
||||||
|
&:autofill,
|
||||||
|
&:autofill:focus {
|
||||||
|
background: hsl(0 1 80) !important;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
button {
|
#postcode_modal_submit {
|
||||||
border: none;
|
display: grid;
|
||||||
font-size: 1.4rem;
|
grid-template-columns: 1fr;
|
||||||
|
grid-template-rows: 1fr;
|
||||||
|
place-items: center;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
font-weight: 700;
|
||||||
color: hsl(233 100 100);
|
color: hsl(233 100 100);
|
||||||
padding: .4rem 1rem;
|
padding: 0.4rem 1rem;
|
||||||
border-radius: 5px;
|
background: var(--wp--preset--color--vivid-red);
|
||||||
background: hsl(344 98 40);
|
border: 1px var(--wp--preset--color--vivid-red) solid;
|
||||||
border: 1px hsl(344 98 40) solid;
|
transition: 0.2s all linear;
|
||||||
margin: 0 0 0 .3rem;
|
padding: 0.2em 2.5em;
|
||||||
transition: .2s all linear;
|
&:hover {
|
||||||
|
color: var(--wp--preset--color--vivid-red);
|
||||||
&:hover{
|
|
||||||
color: hsl(344 98 40 );
|
|
||||||
background: hsl(344 98 100);
|
background: hsl(344 98 100);
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
&:hover > .btn_loader > svg > circle {
|
||||||
|
fill: var(--wp--preset--color--vivid-red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn_loader,
|
||||||
|
.btn_text {
|
||||||
|
transition: 0.2s opacity linear;
|
||||||
|
grid-row: 1 / -1;
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
.form_fields {
|
.form_fields {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
&>{
|
|
||||||
display: flex;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
&::backdrop {
|
&::backdrop {
|
||||||
backdrop-filter: blur(1px);
|
backdrop-filter: blur(2px);
|
||||||
background-color: hsl(40deg 100 0 /0.4);
|
background: hsl(0 1 65 / 0.6);
|
||||||
background: radial-gradient(circle,rgba(33, 33, 33, 0.68) 0%, rgba(15, 15, 15, 0.8) 23%, rgba(0, 0, 0, 0.87) 100%);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.error_message_modal_postcode {
|
.error_message_modal_postcode {
|
||||||
min-height: 1lh;
|
min-height: 1lh;
|
||||||
color: hsl(344 98 40 );
|
color: var(--wp--preset--color--vivid-red);
|
||||||
}/* HTML: <div class="loader"></div> */
|
} /* HTML: <div class="loader"></div> */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* HTML: <div class="loader"></div> */
|
||||||
|
.btn_loader {
|
||||||
|
opacity: 0;
|
||||||
|
svg {
|
||||||
|
height: 0.4rem;
|
||||||
|
}
|
||||||
|
circle {
|
||||||
|
fill: white;
|
||||||
|
transition: 0.2s fill linear;
|
||||||
|
animation: loader-pulse 1.5s ease-in-out infinite;
|
||||||
|
animation-delay: calc((var(--i, 0)) * 0.2s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes loader-pulse {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
opacity: 0.3; /* Dim state */
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 1; /* Bright state */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
139
pppr_cookie.php
Normal file
139
pppr_cookie.php
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
function create_pppr_salt() {
|
||||||
|
// 1. Check permissions first (Optional but recommended)
|
||||||
|
if ( ! wp_is_writable( plugin_dir_path( __FILE__ ) ) ) {
|
||||||
|
// Log error or handle failure
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Define path INSIDE the plugin folder
|
||||||
|
$file_path = plugin_dir_path( __FILE__ ) . 'wp-pppr-salt.php';
|
||||||
|
|
||||||
|
// 3. Get the salt
|
||||||
|
$current_salt = wp_salt( 'auth' );
|
||||||
|
|
||||||
|
if ( empty( $current_salt ) ) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Prepare content
|
||||||
|
$file_content = "<?php\n";
|
||||||
|
$file_content .= "// Auto-generated salt constant\n";
|
||||||
|
$file_content .= "// Exported salt from " . date( 'Y-m-d H:i:s' ) . "\n";
|
||||||
|
$file_content .= "define( 'WP_PPPR_SALT', '{$current_salt}' );\n";
|
||||||
|
|
||||||
|
// 5. Write the file
|
||||||
|
$bytes_written = file_put_contents( $file_path, $file_content, LOCK_EX );
|
||||||
|
|
||||||
|
// 6. Verify success
|
||||||
|
if ( $bytes_written === false ) {
|
||||||
|
// Handle error (e.g., log it)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function set_pppr_cookie($is_local, $street_name, $house_number, $postcode, $city) {
|
||||||
|
$data_string = (int)$is_local . "|" . $street_name . "|" . $house_number . "|" . $postcode . "|" . $city;
|
||||||
|
$signature = hash_hmac('sha256', $data_string, WP_PPPR_SALT);
|
||||||
|
$cookie_value = $data_string . "|" . $signature;
|
||||||
|
|
||||||
|
$is_secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
|
||||||
|
|
||||||
|
setcookie("PPPR", $cookie_value, [
|
||||||
|
'expires' => time() + 7200,
|
||||||
|
'path' => '/',
|
||||||
|
'domain' => $_SERVER['SERVER_NAME'],
|
||||||
|
'secure' => $is_secure, // Only send over HTTPS
|
||||||
|
'httponly' => true, // Prevent JavaScript access
|
||||||
|
'samesite' => 'Lax' // Protect against CSRF
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function unset_pppr_cookie( $path = '/') {
|
||||||
|
unset($_COOKIE["PPPR"]);
|
||||||
|
|
||||||
|
if (empty($domain)) {
|
||||||
|
setcookie("PPPR", '', time() - 3600, '/');
|
||||||
|
} else {
|
||||||
|
setcookie("PPPR", '', time() - 3600, '/' , $_SERVER['SERVER_NAME']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function verify_pppr_cookie_string() {
|
||||||
|
if (!isset($_COOKIE['PPPR'])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$cookie_value = $_COOKIE['PPPR'];
|
||||||
|
|
||||||
|
$last_delimiter = strrpos($cookie_value, '|');
|
||||||
|
if ($last_delimiter === false) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$data_part = substr($cookie_value, 0, $last_delimiter);
|
||||||
|
$hash_part = substr($cookie_value, $last_delimiter + 1);
|
||||||
|
|
||||||
|
// Check if salt is defined
|
||||||
|
if (!defined('WP_PPPR_SALT')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$expected_hash = hash_hmac('sha256', $data_part, WP_PPPR_SALT);
|
||||||
|
|
||||||
|
return hash_equals($expected_hash, $hash_part);
|
||||||
|
}
|
||||||
|
|
||||||
|
function get_PPPR_data() {
|
||||||
|
// 1. Check if cookie exists
|
||||||
|
if (!isset($_COOKIE['PPPR'])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$cookie_value = $_COOKIE['PPPR'];
|
||||||
|
|
||||||
|
// 2. Split safely using the LAST delimiter (handles pipes in street names)
|
||||||
|
$last_delimiter = strrpos($cookie_value, '|');
|
||||||
|
if ($last_delimiter === false) {
|
||||||
|
return false; // Malformed cookie
|
||||||
|
}
|
||||||
|
|
||||||
|
$data_part = substr($cookie_value, 0, $last_delimiter);
|
||||||
|
$provided_hash = substr($cookie_value, $last_delimiter + 1);
|
||||||
|
|
||||||
|
// 3. CRITICAL: Verify the signature before trusting ANY data
|
||||||
|
// Ensure WP_PPPR_SALT is defined and matches the setter exactly
|
||||||
|
if (!defined('WP_PPPR_SALT')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$expected_hash = hash_hmac('sha256', $data_part, WP_PPPR_SALT);
|
||||||
|
|
||||||
|
if (!hash_equals($expected_hash, $provided_hash)) {
|
||||||
|
return false; // Tampered or invalid cookie
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Only now is it safe to explode the verified data
|
||||||
|
$fields = explode('|', $data_part);
|
||||||
|
|
||||||
|
// Ensure we have enough fields
|
||||||
|
if (count($fields) < 5) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'is_local' => (bool)$fields[0],
|
||||||
|
'street' => $fields[1],
|
||||||
|
'house_number' => $fields[2],
|
||||||
|
'postcode' => $fields[3],
|
||||||
|
'city' => $fields[4],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function pppr_is_local() {
|
||||||
|
$first_char = $_COOKIE['PPPR'][0];
|
||||||
|
return $first_char === '1';
|
||||||
|
}
|
||||||
@@ -1,35 +1,50 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
session_start();
|
|
||||||
require_once "session_dialog.php";
|
|
||||||
/*
|
/*
|
||||||
* Plugin Name: prijzen per poscode range
|
* Plugin Name: Prijzen per poscodeereeks.
|
||||||
* Description: posctcodes in de 5000-5800 range krijgen een lokaal tarief aangeboden.
|
* Description: Producten worden gefiltered aan de hand van opgegegeven postcodereeksen.Gebruikers met een postcode die in een opgegegeven postcodereeks valt zal een lokale prijs zien. Waar elke gebruiker met een postcode die buiten eem opgegeven reeks valt zal de reguliere prijs te zien krijgen.
|
||||||
* Author: Remo Zaros
|
* Author: Remo Zaros
|
||||||
* Version: 0.9.1
|
* Version: 0.9.8
|
||||||
* Text Domeain: prijs-per-postcode
|
* Text Domeain: prijs-per-postcode
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
require_once plugin_dir_path(__FILE__) . "session_dialog.php";
|
||||||
|
require_once plugin_dir_path(__FILE__) . "admin.php";
|
||||||
|
require_once plugin_dir_path(__FILE__) . "pppr_cookie.php";
|
||||||
|
|
||||||
if (!defined("ABSPATH")) {
|
if (!defined("ABSPATH")) {
|
||||||
echo "big bag of potatoes";
|
echo "big bag of potatoes";
|
||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
register_activation_hook( __FILE__, 'create_pppr_salt' );
|
||||||
|
if ( ! defined( 'WP_PPPR_SALT' ) ) {
|
||||||
|
$salt_file = __DIR__ . '/wp-pppr-salt.php';
|
||||||
|
if ( file_exists( $salt_file ) ) {
|
||||||
|
require_once $salt_file;
|
||||||
|
}else {
|
||||||
|
define("WP_PPPR_SALT", wp_salt( 'auth' ));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class PrijsPerPostcode
|
class PrijsPerPostcode
|
||||||
{
|
{
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
add_action("init", [$this, "init"]);
|
add_action("init", [$this, "init"], 1);
|
||||||
add_action("rest_api_init", "register_modal_api");
|
add_action("rest_api_init", "register_modal_api");
|
||||||
}
|
}
|
||||||
|
|
||||||
public function init()
|
public function init()
|
||||||
{
|
{
|
||||||
$uri = $_SERVER["REQUEST_URI"];
|
|
||||||
add_filter("woocommerce_sale_flash", "__return_null");
|
|
||||||
init_postcode_handlers($uri);
|
|
||||||
|
|
||||||
//add_action("template_redirect", [$this, "redirect_if_missing_tag"]);
|
$uri = $_SERVER["REQUEST_URI"];
|
||||||
|
init_postcode_handlers($uri);
|
||||||
|
init_postode_admin();
|
||||||
|
|
||||||
|
add_filter("woocommerce_sale_flash", "__return_null");
|
||||||
|
add_filter('woocommerce_show_variation_price', '__return_true');
|
||||||
add_action(
|
add_action(
|
||||||
"woocommerce_variation_options_pricing",
|
"woocommerce_variation_options_pricing",
|
||||||
[$this, "add_local_price_field"],
|
[$this, "add_local_price_field"],
|
||||||
@@ -55,8 +70,21 @@ class PrijsPerPostcode
|
|||||||
);
|
);
|
||||||
add_action("template_redirect", [
|
add_action("template_redirect", [
|
||||||
$this,
|
$this,
|
||||||
"controleer_postcode_op_woocommerce_paginas",
|
"check_postcode_on_every_woocommerce_page",
|
||||||
]);
|
]);
|
||||||
|
add_filter(
|
||||||
|
"woocommerce_variation_is_visible",
|
||||||
|
[$this, "filter_variation_by_local_price"],
|
||||||
|
10,
|
||||||
|
4,
|
||||||
|
);
|
||||||
|
add_filter(
|
||||||
|
"gettext",
|
||||||
|
[$this, "change_variation_regular_price_label"],
|
||||||
|
99,
|
||||||
|
3,
|
||||||
|
);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function add_local_price_field($loop, $variation_data, $variation)
|
public function add_local_price_field($loop, $variation_data, $variation)
|
||||||
@@ -100,8 +128,8 @@ class PrijsPerPostcode
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
$variation_id &&
|
$variation_id &&
|
||||||
isset($_SESSION["postcode_is_local"]) &&
|
isset($_COOKIE["PPPR"]) &&
|
||||||
$_SESSION["postcode_is_local"]
|
pppr_is_local()
|
||||||
) {
|
) {
|
||||||
$local_price = get_post_meta(
|
$local_price = get_post_meta(
|
||||||
$variation_id,
|
$variation_id,
|
||||||
@@ -115,7 +143,7 @@ class PrijsPerPostcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function controleer_postcode_op_woocommerce_paginas()
|
public function check_postcode_on_every_woocommerce_page()
|
||||||
{
|
{
|
||||||
if (is_admin() || defined("DOING_AJAX")) {
|
if (is_admin() || defined("DOING_AJAX")) {
|
||||||
return;
|
return;
|
||||||
@@ -123,14 +151,14 @@ class PrijsPerPostcode
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
(is_product() ||
|
(is_product() ||
|
||||||
is_product_category() ||
|
is_product_category() ||
|
||||||
is_product_tag() ||
|
is_product_tag() ||
|
||||||
is_cart() ||
|
is_cart() ||
|
||||||
is_checkout() ||
|
is_checkout() ||
|
||||||
is_account_page()) &&
|
is_account_page()) &&
|
||||||
!is_shop()
|
!is_shop()
|
||||||
) {
|
) {
|
||||||
if (!isset($_SESSION["postcode_is_local"])) {
|
if (!verify_pppr_cookie_string()) {
|
||||||
wp_redirect(home_url("/winkel/"));
|
wp_redirect(home_url("/winkel/"));
|
||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
@@ -141,8 +169,8 @@ class PrijsPerPostcode
|
|||||||
{
|
{
|
||||||
if (
|
if (
|
||||||
$product->is_type("variation") &&
|
$product->is_type("variation") &&
|
||||||
isset($_SESSION["postcode_is_local"]) &&
|
isset($_COOKIE["PPPR"]) &&
|
||||||
$_SESSION["postcode_is_local"] === true
|
pppr_is_local()
|
||||||
) {
|
) {
|
||||||
$local_price = get_post_meta(
|
$local_price = get_post_meta(
|
||||||
$product->get_id(),
|
$product->get_id(),
|
||||||
@@ -155,6 +183,50 @@ class PrijsPerPostcode
|
|||||||
}
|
}
|
||||||
return $price_html;
|
return $price_html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function filter_variation_by_local_price(
|
||||||
|
$visible,
|
||||||
|
$variation_id,
|
||||||
|
$parent_id,
|
||||||
|
$variation,
|
||||||
|
) {
|
||||||
|
// Ensure $variation is a valid object
|
||||||
|
if (!$variation instanceof WC_Product_Variation) {
|
||||||
|
$variation = wc_get_product($variation_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$variation) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$price = pppr_is_local()
|
||||||
|
? $variation->get_meta("_local_price", true)
|
||||||
|
: $variation->get_regular_price();
|
||||||
|
|
||||||
|
if (empty($price) || floatval($price) == 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function change_variation_regular_price_label(
|
||||||
|
$translated_text,
|
||||||
|
$text,
|
||||||
|
$domain,
|
||||||
|
) {
|
||||||
|
if (
|
||||||
|
"woocommerce" === $domain &&
|
||||||
|
is_admin() &&
|
||||||
|
isset($_REQUEST["action"]) &&
|
||||||
|
"woocommerce_load_variations" === $_REQUEST["action"]
|
||||||
|
) {
|
||||||
|
if ($translated_text === "Reguliere prijs (%s)") {
|
||||||
|
$translated_text = "Prijs overige regios (%s)";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $translated_text;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
new PrijsPerPostcode();
|
new PrijsPerPostcode();
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
session_start();
|
|
||||||
function init_postcode_handlers($uri)
|
function init_postcode_handlers($uri)
|
||||||
{
|
{
|
||||||
if (strpos($uri, "/winkel/") !== false) {
|
if (strpos($uri, "/winkel/") !== false) {
|
||||||
add_action("wp_enqueue_scripts", "modal_styles");
|
add_action("wp_enqueue_scripts", "modal_styles");
|
||||||
add_action("wp_footer", "send_postcode_data");
|
add_action("wp_footer", "send_postcode_data");
|
||||||
if (!has_postcode()) {
|
if (!verify_pppr_cookie_string()) {
|
||||||
if (!is_admin()) {
|
if (!is_admin()) {
|
||||||
WC()->cart->empty_cart();
|
WC()->cart->empty_cart();
|
||||||
}
|
}
|
||||||
add_action("wp_footer", "show_modal");
|
add_action("wp_footer", "show_modal");
|
||||||
render_dialog_html();
|
render_dialog_html();
|
||||||
@@ -22,124 +21,168 @@ function init_postcode_handlers($uri)
|
|||||||
|
|
||||||
function modal_styles()
|
function modal_styles()
|
||||||
{
|
{
|
||||||
wp_enqueue_style(
|
wp_enqueue_style(
|
||||||
"prijs-per-postcode",
|
"prijs-per-postcode",
|
||||||
plugins_url("/assets/postcode_modal.css", __FILE__),
|
plugins_url("/assets/postcode_modal.css", __FILE__),
|
||||||
|
[], // Voeg een lege dependencies array toe (verplicht)
|
||||||
|
filemtime(plugin_dir_path(__FILE__) . "assets/postcode_modal.css"), // Voeg versie toe
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function show_modal()
|
function show_modal()
|
||||||
{
|
{
|
||||||
?>
|
echo <<<'HTML'
|
||||||
<script id="postcode_modal">
|
<script id="postcode_modal_open">
|
||||||
const postcodeModal = document.querySelector("#postcode_modal");
|
const postcodeModal = document.querySelector("#postcode_modal");
|
||||||
postcodeModal.showModal();
|
postcodeModal.showModal();
|
||||||
</script>
|
</script>
|
||||||
<?php
|
HTML;
|
||||||
}
|
}
|
||||||
|
|
||||||
function send_postcode_data()
|
function send_postcode_data()
|
||||||
{
|
{
|
||||||
?>
|
$URL = get_rest_url(null, "postcode-modal/v1/submit");
|
||||||
|
$nonce = wp_create_nonce("wp_rest");
|
||||||
|
|
||||||
|
echo <<<HTML
|
||||||
<script type="module">
|
<script type="module">
|
||||||
const postcodeModal = document.querySelector("#postcode_modal");
|
const postcodeModal = document.querySelector("#postcode_modal");
|
||||||
const modalForm = document.querySelector("#postcode_modal_form");
|
const modalForm = document.querySelector("#postcode_modal_form");
|
||||||
|
const sndBtn = document.querySelector("#postcode_modal_submit");
|
||||||
|
const sndBtnLdr = sndBtn.querySelector(".btn_loader");
|
||||||
|
const sndBtnTxt = sndBtn.querySelector(".btn_text");
|
||||||
|
const errorMsg = document.querySelector("#error_message_modal_postcode");
|
||||||
|
|
||||||
|
// 1. Validatie bij blur (client-side checks)
|
||||||
|
modalForm.querySelectorAll("input").forEach(input => {
|
||||||
|
input.addEventListener("blur", ev => {
|
||||||
|
errorMsg.innerHTML = "";
|
||||||
|
if (!ev.target.validity.valid && ev.target.value !== "") {
|
||||||
|
errorMsg.innerHTML = ev.target.title;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. Submit Handler
|
||||||
modalForm.addEventListener('submit', async (e) => {
|
modalForm.addEventListener('submit', async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
errorMsg.innerHTML = "";
|
||||||
|
|
||||||
|
// UI: Laadstatus
|
||||||
|
sndBtn.disabled = true;
|
||||||
|
sndBtnLdr.style.opacity = "1";
|
||||||
|
sndBtnTxt.style.opacity = "0";
|
||||||
|
|
||||||
const formData = new FormData(e.target);
|
const formData = new FormData(e.target);
|
||||||
const data = Object.fromEntries(formData.entries());
|
const payload = Object.fromEntries(formData.entries());
|
||||||
const json = JSON.stringify(data);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('<?php echo get_rest_url(
|
const resp = await fetch('{$URL}', {
|
||||||
null,
|
method: 'POST',
|
||||||
"postcode-modal/v1/submit",
|
credentials: 'same-origin',
|
||||||
); ?>', {
|
|
||||||
method: 'POST',
|
|
||||||
credentials: 'same-origin',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-WP-Nonce': '<?php echo wp_create_nonce("wp_rest"); ?>'
|
|
||||||
},
|
|
||||||
body: json
|
|
||||||
});
|
|
||||||
|
|
||||||
if(!resp.ok){
|
headers: {
|
||||||
throw new Error(`HTTP Error! status: ${resp.status}` );
|
'Content-Type': 'application/json',
|
||||||
}
|
'X-WP-Nonce': '{$nonce}'
|
||||||
const data = await resp.json();
|
},
|
||||||
console.log("Data returnd", data);
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
if (data.status === "error"){
|
// Parse altijd eerst de JSON, zelfs bij HTTP fouten
|
||||||
const err = data.message;
|
const data = await resp.json();
|
||||||
let errmsg
|
|
||||||
|
|
||||||
switch (err) {
|
// UI: Reset knop
|
||||||
case "Huisnummer not found":
|
sndBtn.disabled = false;
|
||||||
errmsg = "Adres niet gevonden.";
|
sndBtnLdr.style.opacity = "0";
|
||||||
break;
|
sndBtnTxt.style.opacity = "1";
|
||||||
case "Multiple addresses match this huisnummer; add huisletter and/or huisnummertoevoeging":
|
|
||||||
errmsg = "Huisnummertovoeging mist.";
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
errmsg = "Gegevens niet correct.";
|
|
||||||
}
|
|
||||||
document.querySelector("#error_message_modal_postcode").innerHTML = errmsg;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.status === "success"){
|
if (data.status === "error") {
|
||||||
postcodeModal.close();
|
const errorCode = data.code; // Komt nu correct door vanuit PHP
|
||||||
//location.reload();
|
const apiMessage = data.message;
|
||||||
}
|
|
||||||
}catch(err){
|
let userErrorMessage = "Gegevens zijn niet correct.";
|
||||||
console.error("Fetch Failed:", err);
|
|
||||||
throw err;
|
// Specifieke foutafhandeling
|
||||||
|
if (errorCode === "HUISNUMMER_NOT_FOUND" || apiMessage.includes("not found")) {
|
||||||
|
userErrorMessage = "Adres is niet gevonden.";
|
||||||
|
}
|
||||||
|
else if (errorCode === "HUISNUMMER_AMBIGUOUS") {
|
||||||
|
const suggestions = data.suggestions || [];
|
||||||
|
if (suggestions.length > 0) {
|
||||||
|
userErrorMessage = `Meerdere opties: \${suggestions.join(", ")}. Voeg een toevoeging toe.`;
|
||||||
|
} else {
|
||||||
|
userErrorMessage = "Huisnummertoevoeging is verplicht.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (errorCode === "CURL_ERROR" || errorCode === "JSON_ERROR") {
|
||||||
|
userErrorMessage = "Serverfout. Probeer het later opnieuw.";
|
||||||
|
}
|
||||||
|
|
||||||
|
errorMsg.innerHTML = userErrorMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.status === "success") {
|
||||||
|
// Succes: Modal sluiten en eventueel reload of update
|
||||||
|
postcodeModal.close();
|
||||||
|
// Optioneel: location.reload(); of update de pagina content
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
sndBtn.disabled = false;
|
||||||
|
sndBtnLdr.style.opacity = "0";
|
||||||
|
sndBtnTxt.style.opacity = "1";
|
||||||
|
errorMsg.innerHTML = "Er ging iets mis bij het verbinden.";
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
<?php
|
HTML;
|
||||||
}
|
}
|
||||||
|
|
||||||
function render_dialog_html()
|
function render_dialog_html()
|
||||||
{
|
{
|
||||||
?>
|
echo <<<'HTML'
|
||||||
<dialog id="postcode_modal" class="postcode_modal" closedby="none">
|
<dialog id="postcode_modal" class="postcode_modal" closedby="none">
|
||||||
<h2>Vul je postcode en huisnummer in.</h2>
|
<h2>Vul je postcode en huisnummer in.</h2>
|
||||||
<form id="postcode_modal_form" method="post" action="" novalidation>
|
<p>Onze prijzen zijn afhankelijk van de regio. Vul daarom de postcode en het huisnummer in om de exacte prijzen te bekijken.</p>
|
||||||
|
<form id="postcode_modal_form" method="post" action="" novalidate>
|
||||||
<div class="form_fields">
|
<div class="form_fields">
|
||||||
<div>
|
<!-- Dutch Postcode Field -->
|
||||||
<input type="text" name="postcode"
|
<input
|
||||||
title="Voer een geldige Nederlandse postcode in (bijv. 1234AB of 1234 AB)."
|
type="text"
|
||||||
|
name="postcode"
|
||||||
|
title="Voer een geldige postcode in (bijv. 1234AB of 1234 AB)."
|
||||||
pattern="[1-9][0-9]{3} ?(?!sa|sd|ss)[a-zA-Z]{2}"
|
pattern="[1-9][0-9]{3} ?(?!sa|sd|ss)[a-zA-Z]{2}"
|
||||||
placeholder= "1010 AA"
|
placeholder="5010 AA"
|
||||||
size="10"
|
size="8"
|
||||||
required
|
required
|
||||||
|
autocomplete="off"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<input type="text" name="huisnummer"
|
<!-- House Number Field -->
|
||||||
pattern="/\d+([-\\s]?[a-zA-Z]+)?/"
|
<input
|
||||||
title="Voer een geldig huisnummer in (bijv. 1, 1A, 1-A, 1a)."
|
type="text"
|
||||||
placeholder= "12A"
|
name="huisnummer"
|
||||||
size="5"
|
title="Voer een geldig huisnummer in (bijv. 1, 1A, 1-A)."
|
||||||
|
pattern="\d+([\- ]?[a-zA-Z]+)?"
|
||||||
|
placeholder="10"
|
||||||
|
size="3"
|
||||||
required
|
required
|
||||||
|
autocomplete="off"
|
||||||
/>
|
/>
|
||||||
|
<button id="postcode_modal_submit" type="submit"><span class="btn_text">OK</span>
|
||||||
|
<div class="btn_loader">
|
||||||
|
<svg viewBox="0 0 128 30" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<circle style="--i:0" cx="14" cy="15" r="14" />
|
||||||
|
<circle style="--i:1" cx="64" cy="15" r="14" />
|
||||||
|
<circle style="--i:2" cx="114" cy="15" r="14" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<button id="postcode_modal_submit" type="submit">verzend</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
</form>
|
||||||
<div class="error_message_modal_postcode" id="error_message_modal_postcode" aria-live="polite"></div>
|
<div class="error_message_modal_postcode" id="error_message_modal_postcode" aria-live="polite"></div>
|
||||||
<div class="loader_modal"></div>
|
|
||||||
</dialog>
|
</dialog>
|
||||||
<?php
|
HTML;
|
||||||
}
|
|
||||||
|
|
||||||
function has_postcode()
|
|
||||||
{
|
|
||||||
if (isset($_SESSION["postcode"])) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function handle_postcode_modal($data)
|
function handle_postcode_modal($data)
|
||||||
@@ -147,65 +190,95 @@ function handle_postcode_modal($data)
|
|||||||
$params = $data->get_params();
|
$params = $data->get_params();
|
||||||
$nonce = $data->get_header("X-WP-Nonce");
|
$nonce = $data->get_header("X-WP-Nonce");
|
||||||
|
|
||||||
if (wp_verify_nonce($nonce, "wp_rest")) {
|
// 1. Security
|
||||||
if (!verify_postcode($params["postcode"])) {
|
if (!wp_verify_nonce($nonce, "wp_rest")) {
|
||||||
$resp = [
|
echo json_encode(["status" => "error", "message" => "nononce"]);
|
||||||
"status" => "error",
|
exit();
|
||||||
"message" => "postcode",
|
|
||||||
];
|
|
||||||
echo json_encode($resp);
|
|
||||||
exit();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!verify_huisnummer($params["huisnummer"])) {
|
|
||||||
$resp = [
|
|
||||||
"status" => "error",
|
|
||||||
"message" => "huisnummer",
|
|
||||||
];
|
|
||||||
echo json_encode($resp);
|
|
||||||
exit();
|
|
||||||
}
|
|
||||||
|
|
||||||
$result = getStraatnaam($params["postcode"], $params["huisnummer"]);
|
|
||||||
if (isset($result["error"])) {
|
|
||||||
$resp = [
|
|
||||||
"status" => "error",
|
|
||||||
"message" => $result["error"],
|
|
||||||
"apirequest" => "openpostcode.nl",
|
|
||||||
];
|
|
||||||
echo json_encode($resp);
|
|
||||||
exit();
|
|
||||||
}
|
|
||||||
|
|
||||||
$_SESSION["postcode"] = $params["postcode"];
|
|
||||||
$_SESSION["huisnummer"] = $params["huisnummer"];
|
|
||||||
$_SESSION["straatnaam"] = $result["straatnaam"];
|
|
||||||
$_SESSION["woonplaats"] = $result["woonplaats"];
|
|
||||||
|
|
||||||
$_SESSION["postcode_is_local"] = postcode_in_range(
|
|
||||||
$params["postcode"],
|
|
||||||
5000,
|
|
||||||
5800,
|
|
||||||
);
|
|
||||||
|
|
||||||
$resp = [
|
|
||||||
"status" => "success",
|
|
||||||
"message" => "all good",
|
|
||||||
"straatnaam" => $result["straatnaam"],
|
|
||||||
"lokaal_trarief" => postcode_in_range(
|
|
||||||
$params["postcode"],
|
|
||||||
5000,
|
|
||||||
5800,
|
|
||||||
),
|
|
||||||
];
|
|
||||||
} else {
|
|
||||||
$resp = [
|
|
||||||
"status" => "error",
|
|
||||||
"message" => "nononce",
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
echo json_encode($resp);
|
|
||||||
exit();
|
// 2. Basis Validatie
|
||||||
|
if (!verify_postcode($params["postcode"])) {
|
||||||
|
echo json_encode(["status" => "error", "message" => "postcode"]);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
if (!verify_huisnummer($params["huisnummer"])) {
|
||||||
|
echo json_encode(["status" => "error", "message" => "huisnummer"]);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. API Call (Ruwe data)
|
||||||
|
$result = getStraatnaam($params["postcode"], $params["huisnummer"]);
|
||||||
|
|
||||||
|
// 4. Validatie & Logic
|
||||||
|
$hasError = isset($result["error"]);
|
||||||
|
$errorCode = null;
|
||||||
|
$errorMessage = null;
|
||||||
|
$candidates = [];
|
||||||
|
$straatnaam = null;
|
||||||
|
$woonplaats = null;
|
||||||
|
|
||||||
|
if ($hasError) {
|
||||||
|
$errorCode = $result["error"]["code"] ?? "UNKNOWN_ERROR";
|
||||||
|
$errorMessage = $result["error"]["message"] ?? "Onbekende fout";
|
||||||
|
$candidates = $result["error"]["details"]["candidates"] ?? [];
|
||||||
|
|
||||||
|
// SPECIAL CASE: HUISNUMMER_AMBIGUOUS
|
||||||
|
if ($errorCode === "HUISNUMMER_AMBIGUOUS" && !empty($candidates)) {
|
||||||
|
$plainMatch = null;
|
||||||
|
|
||||||
|
// Zoek naar candidate ZONDER toevoeging
|
||||||
|
foreach ($candidates as $candidate) {
|
||||||
|
if (
|
||||||
|
empty($candidate["huisletter"]) &&
|
||||||
|
empty($candidate["huisnummertoevoeging"])
|
||||||
|
) {
|
||||||
|
$plainMatch = $candidate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Als we een 'platte' match hebben (bijv. 15), dan is het SUCCES
|
||||||
|
if ($plainMatch) {
|
||||||
|
$hasError = false; // Negeer de error
|
||||||
|
$straatnaam = $plainMatch["straat"];
|
||||||
|
$woonplaats = $plainMatch["woonplaats"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Normaal succes (geen error in response)
|
||||||
|
if (!empty($result["results"])) {
|
||||||
|
$straatnaam = $result["results"][0]["straat"];
|
||||||
|
$woonplaats = $result["results"][0]["woonplaats"];
|
||||||
|
} else {
|
||||||
|
// Edge case: geen error veld, maar ook geen results
|
||||||
|
$hasError = true;
|
||||||
|
$errorCode = "NO_RESULTS";
|
||||||
|
$errorMessage = "Adres niet gevonden";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Response sturen
|
||||||
|
if ($hasError) {
|
||||||
|
return new WP_REST_Response([
|
||||||
|
"status" => "error",
|
||||||
|
"code" => $errorCode,
|
||||||
|
"message" => $errorMessage,
|
||||||
|
"suggestions" => $result["error"]["details"]["suggestions"] ?? [],
|
||||||
|
"apirequest" => "openpostcode.nl",
|
||||||
|
], 400);
|
||||||
|
}
|
||||||
|
set_pppr_cookie(
|
||||||
|
postcode_in_range($params["postcode"]),
|
||||||
|
$straatnaam,
|
||||||
|
$params["huisnummer"],
|
||||||
|
$params["postcode"],
|
||||||
|
$woonplaats
|
||||||
|
);
|
||||||
|
|
||||||
|
return new WP_REST_Response([
|
||||||
|
"status" => "success",
|
||||||
|
"message" => "all good",
|
||||||
|
], 200);
|
||||||
}
|
}
|
||||||
|
|
||||||
function register_modal_api()
|
function register_modal_api()
|
||||||
@@ -213,6 +286,7 @@ function register_modal_api()
|
|||||||
register_rest_route("postcode-modal/v1", "submit", [
|
register_rest_route("postcode-modal/v1", "submit", [
|
||||||
"methods" => "POST",
|
"methods" => "POST",
|
||||||
"callback" => "handle_postcode_modal",
|
"callback" => "handle_postcode_modal",
|
||||||
|
"permission_callback" => "__return_true",
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,31 +321,45 @@ function getStraatnaam($postcode, $huisnummer)
|
|||||||
curl_setopt($ch, CURLOPT_USERAGENT, "PHP/OpenPostcodeClient");
|
curl_setopt($ch, CURLOPT_USERAGENT, "PHP/OpenPostcodeClient");
|
||||||
|
|
||||||
$response = curl_exec($ch);
|
$response = curl_exec($ch);
|
||||||
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||||
|
|
||||||
if (curl_error($ch)) {
|
if (curl_error($ch)) {
|
||||||
curl_close($ch);
|
curl_close($ch);
|
||||||
return ["error" => "cURL error: " . curl_error($ch)];
|
return [
|
||||||
|
"error" => ["code" => "CURL_ERROR", "message" => curl_error($ch)],
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
curl_close($ch);
|
curl_close($ch);
|
||||||
|
|
||||||
|
// Decodeer als associatieve array (true)
|
||||||
$data = json_decode($response, true);
|
$data = json_decode($response, true);
|
||||||
|
|
||||||
if (isset($data["error"])) {
|
// Als JSON decode faalt
|
||||||
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||||
return [
|
return [
|
||||||
"error" => $data["error"]["message"],
|
"error" => [
|
||||||
"code" => $data["error"]["code"],
|
"code" => "JSON_ERROR",
|
||||||
|
"message" => "Invalid JSON response",
|
||||||
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
// Geef de RUWE response terug (inclusief meta, error, results, etc.)
|
||||||
"straatnaam" => $data["results"][0]["straat"],
|
return $data;
|
||||||
"woonplaats" => $data["results"][0]["woonplaats"],
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function postcode_in_range($postcode, $start, $end)
|
function postcode_in_range($postcode)
|
||||||
{
|
{
|
||||||
|
$vals = get_option("local_postcodes_values", "");
|
||||||
|
$rows = preg_split("/\R/", $vals, -1, PREG_SPLIT_NO_EMPTY);
|
||||||
|
$pc_arr = [];
|
||||||
|
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$row = trim($row);
|
||||||
|
$postcode_range = explode("-", $row);
|
||||||
|
$pc_arr[] = [(int) $postcode_range[0], (int) $postcode_range[1]];
|
||||||
|
}
|
||||||
$cleanPostcode = strtoupper(preg_replace("/\s+/", "", $postcode));
|
$cleanPostcode = strtoupper(preg_replace("/\s+/", "", $postcode));
|
||||||
|
|
||||||
if (!preg_match('/^\d{4}[A-Z]{2}$/', $cleanPostcode)) {
|
if (!preg_match('/^\d{4}[A-Z]{2}$/', $cleanPostcode)) {
|
||||||
@@ -280,7 +368,12 @@ function postcode_in_range($postcode, $start, $end)
|
|||||||
|
|
||||||
$numberPart = (int) substr($cleanPostcode, 0, 4);
|
$numberPart = (int) substr($cleanPostcode, 0, 4);
|
||||||
|
|
||||||
return $numberPart >= $start && $numberPart <= $end;
|
foreach ($pc_arr as $pc_to_check) {
|
||||||
|
if ($numberPart >= $pc_to_check[0] && $numberPart <= $pc_to_check[1]) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function modify_checkout_with_js()
|
function modify_checkout_with_js()
|
||||||
@@ -291,109 +384,157 @@ function modify_checkout_with_js()
|
|||||||
) {
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
$data = get_PPPR_data();
|
||||||
|
|
||||||
$woonplaats = $_SESSION["woonplaats"];
|
$city = $data["city"];
|
||||||
$postcode = $formatted_postcode = preg_replace(
|
$postcode = $formatted_postcode = preg_replace(
|
||||||
"/(\d+)([A-Z]+)/",
|
"/(\d+)([A-Z]+)/",
|
||||||
'$1 $2',
|
'$1 $2',
|
||||||
strtoupper($_SESSION["postcode"]),
|
strtoupper($data["postcode"]),
|
||||||
);
|
);
|
||||||
$address =
|
$address =
|
||||||
$_SESSION["straatnaam"] . " " . strtoupper($_SESSION["huisnummer"]);
|
$data["street"] . " " . strtoupper($data["house_number"]);
|
||||||
// Output the JavaScript
|
|
||||||
?>
|
|
||||||
<script type="text/javascript" id="fill_address_fields">
|
|
||||||
jQuery(document).ready(function($) {
|
|
||||||
fillCheckoutFields();
|
|
||||||
$(document.body).on('updated_checkout', fillCheckoutFields);
|
|
||||||
});
|
|
||||||
|
|
||||||
function fillCheckoutFields() {
|
echo <<<HTML
|
||||||
if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch) {
|
<script type="text/javascript" id="set_pppr_fields">
|
||||||
const store = 'wc/store/cart';
|
jQuery(document).ready(function($) {
|
||||||
|
|
||||||
wp.data.dispatch(store).setShippingAddress({
|
function lockCheckoutFields() {
|
||||||
first_name: '',
|
if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch) {
|
||||||
last_name: '',
|
const store = 'wc/store/cart';
|
||||||
address_1: '<?php echo esc_js($address); ?>',
|
|
||||||
address_2: '',
|
wp.data.dispatch(store).setShippingAddress({
|
||||||
city: '<?php echo esc_js($woonplaats); ?>',
|
first_name: '',
|
||||||
state: '',
|
last_name: '',
|
||||||
postcode: '<?php echo esc_js($postcode); ?>',
|
address_1: 'Tjeuke Timmermansstraat 43',
|
||||||
country: 'NL',
|
address_2: '',
|
||||||
phone: '',
|
city: 'Tilburg',
|
||||||
email: ''
|
state: '',
|
||||||
|
postcode: '5041 EK',
|
||||||
|
country: 'NL',
|
||||||
|
phone: '',
|
||||||
|
email: ''
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
const targets = '#shipping-postcode, #shipping-city, #shipping-address_1';
|
||||||
|
|
||||||
|
$(targets).each(function() {
|
||||||
|
// Voeg readonly attribuut toe (voor toegankelijkheid)
|
||||||
|
$(this).prop('readonly', true);
|
||||||
|
|
||||||
|
$(this).css({
|
||||||
|
'background-color': '#f9f9f9',
|
||||||
|
'cursor': 'not-allowed',
|
||||||
|
'pointer-events': 'none' // Blokkeert alle muisklikken in het veld
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
//make fields READONLY and ppstcode reset.
|
if ($('.postcode-reset').length === 0) {
|
||||||
setTimeout(() => {
|
const div = document.createElement("div");
|
||||||
// make prefilled fiields readonly.
|
div.setAttribute("class", "postcode-reset");
|
||||||
$('#shipping-postcode, #shipping-city, #shipping-address_1')
|
div.innerHTML = `
|
||||||
.prop('readonly', true)
|
<a href="#" class="reset-postcode-show-comfirm" style="font-size:12px; text-decoration:underline;">Reset postcode.</a>
|
||||||
.css('background', '#f9f9f9');
|
<span class="bevestiging" style="display:none; font-size:12px;">
|
||||||
|
Deze handeling leegt ook de winkelwagen. Weet je het zeker?
|
||||||
|
<a href="#" class="accept" style="color:red; font-weight:bold;"> JA </a>/
|
||||||
|
<a href="#" class="decline"> nee </a>
|
||||||
|
</span>`;
|
||||||
|
|
||||||
// create postcode reset button
|
div.style.width = "100%";
|
||||||
const div = document.createElement("div");
|
document.querySelector(".wc-block-components-address-form__city")?.after(div);
|
||||||
const script = document.createElement('script');
|
|
||||||
div.setAttribute("class", "postcode-reset")
|
$('.reset-postcode-show-comfirm').on('click', function(e) {
|
||||||
div.innerHTML = `
|
e.preventDefault();
|
||||||
<a href="#" class="reset-postcode-show-comfirm" >Reset postcode.</a>
|
$(this).hide();
|
||||||
<span class="bevestiging"> Weet je het zeker?
|
$(this).next('.bevestiging').show();
|
||||||
<a href="#" class="accept">ja</a>/<a href="#" class="decline">nee</a>
|
});
|
||||||
(Deze handeling leegt de winkelwagen.)
|
$('.decline').on('click', function(e) {
|
||||||
</span> `;
|
e.preventDefault();
|
||||||
div.style.width = "100%";
|
$(this).closest('.bevestiging').hide();
|
||||||
document.querySelector(".wc-block-components-address-form__city").after(div);
|
$('.reset-postcode-show-comfirm').show();
|
||||||
}, 500);
|
});
|
||||||
|
|
||||||
|
|
||||||
|
$('.accept').on('click', function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
jQuery(document.body).trigger('update_checkout');
|
$.ajax({
|
||||||
|
url: ajax_object.ajax_url,
|
||||||
|
type: 'POST',
|
||||||
|
data: {
|
||||||
|
action: 'unset_my_session', // Matches wp_ajax_ hook
|
||||||
|
nonce: ajax_object.nonce // Matches wp_create_nonce action
|
||||||
|
},
|
||||||
|
success: function(response) {
|
||||||
|
if (response.success) {
|
||||||
|
location.reload();
|
||||||
|
} else {
|
||||||
|
console.error('Server returned error:', response.data);
|
||||||
|
alert('Failed to reset session: ' + (response.data || 'Unknown error'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function(xhr, status, error) {
|
||||||
|
console.error('AJAX request failed:', status, error);
|
||||||
|
console.log('Response Text:', xhr.responseText); // Check for PHP fatal errors
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
jQuery(document.body).trigger('update_checkout');
|
||||||
|
|
||||||
|
}, 800); // Iets langere delay voor React rendering
|
||||||
} else {
|
} else {
|
||||||
console.error('WooCommerce Blocks API is niet beschikbaar');
|
console.error('WooCommerce Blocks API is niet beschikbaar');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
|
||||||
<?php
|
lockCheckoutFields();
|
||||||
|
|
||||||
|
let updateTimeout;
|
||||||
|
$(document.body).on('updated_checkout', function() {
|
||||||
|
clearTimeout(updateTimeout);
|
||||||
|
updateTimeout = setTimeout(lockCheckoutFields, 500);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
HTML;
|
||||||
}
|
}
|
||||||
|
|
||||||
function load_assets_reset_postcode_on_checkout()
|
function load_assets_reset_postcode_on_checkout()
|
||||||
{
|
{
|
||||||
if (is_checkout() && !is_wc_endpoint_url()) {
|
if (is_checkout() && !is_wc_endpoint_url()) {
|
||||||
wp_enqueue_style(
|
wp_enqueue_style(
|
||||||
"reset-postcode-style",
|
"reset-postcode-style",
|
||||||
plugin_dir_url(__FILE__) . "assets/reset-postcode.css",
|
plugin_dir_url(__FILE__) . "assets/reset-postcode.css",
|
||||||
[],
|
[],
|
||||||
"1.0.0",
|
"1.0.0",
|
||||||
);
|
);
|
||||||
|
|
||||||
wp_enqueue_script(
|
wp_enqueue_script(
|
||||||
"reset-postcode-script",
|
"reset-postcode-script",
|
||||||
plugin_dir_url(__FILE__) . "assets/reset-postcode.js",
|
plugin_dir_url(__FILE__) . "assets/reset-postcode.js",
|
||||||
[],
|
[],
|
||||||
"1.0.0",
|
"1.0.0",
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Pass PHP variables to JavaScript
|
// Pass PHP variables to JavaScript
|
||||||
wp_localize_script("reset-postcode-script", "ajax_object", [
|
wp_localize_script("reset-postcode-script", "ajax_object", [
|
||||||
"ajax_url" => admin_url("admin-ajax.php"),
|
"ajax_url" => admin_url("admin-ajax.php"),
|
||||||
"nonce" => wp_create_nonce("reset_postcode_nonce"), // Creates a secure token
|
"nonce" => wp_create_nonce("reset_postcode_nonce"), // Creates a secure token
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function handle_unset_session_fetch()
|
function handle_unset_session_fetch()
|
||||||
{
|
{
|
||||||
// Verify the nonce for security
|
// Verify the nonce for security
|
||||||
if (!wp_verify_nonce($_POST["nonce"], "reset_postcode_nonce")) {
|
if (!wp_verify_nonce($_POST["nonce"], "reset_postcode_nonce")) {
|
||||||
wp_die("Security check failed.");
|
wp_die("Security check failed.");
|
||||||
}
|
|
||||||
|
|
||||||
// Unset the specific session variable
|
|
||||||
if (isset($_SESSION["postcode"])) {
|
|
||||||
$_SESSION = [];
|
|
||||||
}
|
}
|
||||||
|
unset_pppr_cookie();
|
||||||
|
|
||||||
// Send a JSON response
|
// Send a JSON response
|
||||||
wp_send_json_success();
|
wp_send_json_success();
|
||||||
|
|||||||
Reference in New Issue
Block a user