27 Commits

Author SHA1 Message Date
asus
7738ad1863 - added role at registration with xootix
- cleaned folder
2024-03-02 16:14:36 +01:00
asus
8aeef1dca8 added inline code to plugin tools 2024-03-01 17:21:03 +01:00
asus
bd30c97194 - tests on editing author page with acf fields
- some reflexions on registrations
2024-02-29 23:45:02 +01:00
asus
6e88bba879 wip trying to modify html before it is rendered 2024-02-29 01:04:41 +01:00
asus
2ce603e644 now we can add attributes to js files using the tools class 2024-02-27 15:23:07 +01:00
asus
7a8c0750c5 wip adding attributes, works with filter wp-script-attributes 2024-02-27 11:51:46 +01:00
asus
81f3f8a7e7 wip trying to create better options to include scripts with attributes 2024-02-27 01:54:46 +01:00
asus
0177531924 - forget old ajax wp, now use fetch wp
- trying js files without imports
2024-02-26 13:18:19 +01:00
asus
5794e4cafe update private notes 2024-02-25 21:03:58 +01:00
asus
b839bf7f66 payment update acf fields allright 2024-02-25 18:11:33 +01:00
asus
ec18dc60b4 prefixed all paypal related fonctions with fipf 2024-02-25 15:00:21 +01:00
asus
4e094889c7 wip cron job to delete order id, but will deal with that later 2024-02-25 14:43:53 +01:00
asus
3d9b9bac9e wip track payment to user 2024-02-25 11:02:47 +01:00
asus
01187a8450 wip connecting user with payment 2024-02-25 01:46:33 +01:00
asus
1464562379 retrieving user that makes the purchase with nonce ok 2024-02-24 17:40:33 +01:00
asus
61b3f9f2f5 PAYPAL WORKING 2024-02-24 16:57:31 +01:00
asus
745f5ebf91 created routes, but json parse error ate the end of transaction 2024-02-24 01:19:39 +01:00
asus
38260912cd try wordpress rest api instead of ajax 2024-02-23 23:43:23 +01:00
asus
0f15b67e8b wip route api_order 2024-02-23 21:03:34 +01:00
asus
bebb346ff9 better file organisation 2024-02-23 19:49:56 +01:00
asus
b7685cbbc1 - struggled to make ajax works, but now is ok
- starting to make serverside works
2024-02-23 19:36:03 +01:00
asus
7cfa2e6351 - added capacity in plugin tool to take urls
- test front end integration ok
2024-02-23 10:52:02 +01:00
asus
fea195638b sdk call works now, just the begining 2024-02-22 23:44:22 +01:00
asus
45532c497d wip paypal with sdk not working 2024-02-22 20:30:01 +01:00
asus
1046390f59 small improvement in modals with diviengine-form-builder 2024-02-22 11:50:01 +01:00
asus
1262aeb706 wip paypal tests 2024-02-21 23:58:53 +01:00
asus
6158f738a2 submodules ipdates 2024-02-20 23:44:10 +01:00
42 changed files with 1604 additions and 995 deletions

View File

@@ -1,7 +0,0 @@
.first_el_to_change {
border: 1px solid red;
}
#model_plugin_shortcode {
border: 1px solid blue;
padding: 10px;
}

View File

@@ -0,0 +1,6 @@
#mytext {
border: 1px solid blue;
}
#mytext_2 {
border: 1px solid green;
}

View File

@@ -9,110 +9,43 @@ Author URI:
*/
/*
5.5 . 5.48
59 . 58.99
50.6 . 50.58
38.5 . 38.53
99.8 . 99.84
25.2 . 25.17
131.6 . 135
63.7 . 63.68
85 . 85.05
50.2 . 50.17
41.4 . 41.43
18.8 . 18.82
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
plugin dir root
* plugin dir root
*/
include_once( plugin_dir_path(__FILE__) . '/utils/plugin_tools.php');
include_once( plugin_dir_path(__FILE__) . '/utils/plgntls_class.php');
PLGNTLS_class::set_root_dir( plugin_dir_path(__FILE__), plugin_dir_url(__FILE__) );
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
inclusions
*/
include_once(PLGNTLS_class::get_path() . '/php/utils/globals.php');
include_once(PLGNTLS_class::get_path() . '/php/menu/example_menu.php');
//include_once(PLGNTLS_class::get_path() . '/php/images/image_edit_shortcode.php');
//include_once(PLGNTLS_class::get_path() . '/php/images/image-edit.php');
/*
* general inclusions
*/
include_once(PLGNTLS_class::get_path() . '/utils/globals.php');
include_once(PLGNTLS_class::get_path() . '/utils/console_log.php');
include_once(PLGNTLS_class::get_path() . '/php/paypal/paypal.php');
include_once(PLGNTLS_class::get_path() . '/php/register/partenaires.php');
/*
* test the class PLGNTLS
*/
add_shortcode('fipfcard_plugin', 'fipfcard_test_class_tools');
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
plugin shortcode
*/
function fipfcard_main_shortcode()
{
$fipfcard_tools = new PLGNTLS_class();
$myvar_1 = "I am one";
$myvar_2 = "I am two";
$names = ["hugo", "camille"];
$ages = ["13", "34", "56"];
$data = wp_get_current_user();
$data = $data->data;
$data = $data->user_email;
//error_log("data->data");
//error_log($data);
//delete_post_meta(get_the_ID(), "_data_user_email");
//delete_post_meta(get_the_ID(), "_data");
//add_post_meta(get_the_ID(), "data_user_email", $data);
$post_metadata = get_metadata( 'post', get_the_ID() );
$post_meta = get_post_meta( get_the_ID() );
$user_metadata = get_metadata( 'user', get_current_user_id() );
$user_meta = get_user_meta( get_current_user_id() );
$acf_get_fields = get_fields( get_the_ID() );
$user_data = get_userdata( get_current_user_id() );
$current_user = wp_get_current_user();
return $fipfcard_tools->add_to_front
(
array
(
"css/example_style.css",
"js/example_init.js",
"js/example_script2.js",
"js/example_script3.js",
"html/example_index.html",
"html/example_index2.html",
),
compact
(
"myvar_1",
"myvar_2",
"post_metadata",
"post_meta",
"user_metadata",
"user_meta",
"acf_get_fields",
"user_data",
"current_user",
"names",
"ages",
)
);
}
add_shortcode('fipfcard_plugin', 'fipfcard_main_shortcode');
*
function custom_frontend_posting_form() {
$my_image = the_field('image_ratio');
error_log("my_image");
@@ -120,6 +53,16 @@ function custom_frontend_posting_form() {
return $my_image;
}
add_shortcode('custom_frontend_posting_form', 'custom_frontend_posting_form');
*/
@@ -131,224 +74,9 @@ add_shortcode('custom_frontend_posting_form', 'custom_frontend_posting_form');
/*
add_action('init', 'custom_action_handler');
function custom_action_handler() {
error_log("inside init :)");
if ( isset( $_GET['custom_action'] ) && $_GET['custom_action'] === 'do_something' ) {
error_log("GET :)");
}
if ( isset( $_POST['custom_action'] ) && $_POST['custom_action'] === 'do_something' ) {
error_log("POST :)");
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
error_log("REQUEST_METHOD === GET");
error_log("_GET");
error_log(json_encode($_GET));
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['submit'])) {
error_log("REQUEST_METHOD === GET && GET[SUBMIT]");
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['QUERY_STRING'] === 'custom_action=do_something' ) {
error_log("_POST['de_fb_ville']");
error_log(json_encode($_POST['de_fb_ville']));
}
*/
// custom-form-handler.php
/*
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
error_log("REQUEST_METHOD === POST && POST[SUBMIT]");
error_log("_POST");
error_log(json_encode($_POST));
// Form submitted, handle the submission
$name = sanitize_text_field($_POST['name']);
$email = sanitize_email($_POST['email']);
// Perform validation
$errors = array();
if (empty($name)) {
$errors['name'] = 'Name is required';
}
if (!is_email($email)) {
$errors['email'] = 'Invalid email address';
}
if (empty($errors)) {
// Form data is valid, process the submission
// For example, save data to the database or send an email
// Redirect the user or display a success message
} else {
// Form data is not valid, display errors
// You might re-render the form with error messages here
}
}
}
*/
/*
[17-Feb-2024 17:54:21 UTC]
{
"SERVER_SOFTWARE":"nginx\/1.20.2",
"REQUEST_URI":"\/?custom_action=do_something",
"USER":"www-data",
"HOME":"\/home\/www-data",
"HTTP_SEC_GPC":"1",
"HTTP_SEC_FETCH_USER":"?1",
"HTTP_SEC_FETCH_SITE":"same-origin",
"HTTP_SEC_FETCH_MODE":"navigate",
"HTTP_SEC_FETCH_DEST":"document",
"HTTP_UPGRADE_INSECURE_REQUESTS":"1",
"HTTP_COOKIE":"wordpress_test_cookie=WP%20Cookie%20check; wordpress_logged_in_f31a945e73c53ab9af191e34eb33fa88=hugo%7C1708332197%7CbJvy7kRZ3UWJ2C0ZOaSuhpLCz11vHL8CA68sQv9U1ne%7C927c46e3b46a2716df0fcce98d7ccda0e158be0aad0593b2dc233de4ccad9e27; wp-settings-time-11=1708187741; mjx.menu=renderer%3ANativeMML%26%3Bsemantics%3Atrue%26%3Bcontext%3ABrowser%26%3Bzoom%3ANone",
"HTTP_REFERER":"https:\/\/local_fipfcard_plugin.com\/modif_profile\/",
"HTTP_CONNECTION":"keep-alive",
"HTTP_DNT":"1",
"HTTP_ORIGIN":"https:\/\/local_fipfcard_plugin.com",
"HTTP_CONTENT_LENGTH":"2310",
"HTTP_CONTENT_TYPE":"multipart\/form-data; boundary=---------------------------92033335430820533424009149678",
"HTTP_ACCEPT_ENCODING":"gzip, deflate, br",
"HTTP_ACCEPT_LANGUAGE":"en-US,en;q=0.5",
"HTTP_ACCEPT":"text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/avif,image\/webp,*\/*;q=0.8",
"HTTP_USER_AGENT":"Mozilla\/5.0 (X11; Ubuntu; Linux x86_64; rv:122.0) Gecko\/20100101 Firefox\/122.0",
"HTTP_HOST":"local_fipfcard_plugin.com",
"REDIRECT_STATUS":"200",
"SERVER_NAME":"local_fipfcard_plugin.com",
"SERVER_PORT":"443",
"SERVER_ADDR":"172.18.0.4",
"REMOTE_PORT":"47220",
"REMOTE_ADDR":"172.18.0.1",
"GATEWAY_INTERFACE":"CGI\/1.1",
"HTTPS":"on",
"REQUEST_SCHEME":"https",
"SERVER_PROTOCOL":"HTTP\/1.1",
"DOCUMENT_ROOT":"\/var\/www\/html",
"DOCUMENT_URI":"\/index.php",
"SCRIPT_NAME":"\/index.php",
"CONTENT_LENGTH":"2310",
"CONTENT_TYPE":"multipart\/form-data; boundary=---------------------------92033335430820533424009149678",
"REQUEST_METHOD":"POST",
"QUERY_STRING":"custom_action=do_something",
"SCRIPT_FILENAME":"\/var\/www\/html\/index.php",
"FCGI_ROLE":"RESPONDER",
"PHP_SELF":"\/index.php",
"REQUEST_TIME_FLOAT":1708192460.934234,
"REQUEST_TIME":1708192460
}
$_POST
{
"field_title":["ville_title","nom","pedagogie"],
"field_name":["de_fb_ville","de_fb_nom","de_fb_pedagogie"],
"field_id":["de_fb_ville_id","de_fb_nom","de_fb_pedagogie"],
"de_fb_ville":"gut",
"de_fb_nom":"gut",
"de_fb_pedagogie":"gut",
"form_key":"33420-0",
"unique_id":"d2564b14-290e-4865-b740-7932ae770d43",
"form_type":"custom",
"divi-form-submit":"yes",
"form_id":"modif_profile",
"form_type_confirm":""
}
add_action('parse_request', 'my_custom_url_handler');
function my_custom_url_handler($query)
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST' )
return ;
if ($_SERVER['QUERY_STRING'] !== 'update_profile_acf' )
return ;
// ! add verification that user can do this edit !
foreach($_POST['field_name'] as $field)
{
error_log("_POST[$field]");
error_log($_POST[$field]);
}
}
*/
/**
* do_action( 'df_before_process', string $form_id, Array $post_array, String $form_type )
* Description: Fires after form is submitted and captcha checking is ok.
* Parameters:
* - $form_id: (String) Form ID from Form setting.
* - $post_array: (Array) Submitted fields from the form. Keys are mapped field names or custom field names (in case of Field Mapping Type is Custom).
* - $form_type : (String) Form Type
*
* wordpress_docker/volumes/wp_volume/wp-content/plugins/divi-form-builder/includes/DiviFormBuilder.php|298 col 18-35| do_action( 'df_before_process', $form_id, $post_array, $form_type );
* wordpress_docker/volumes/wp_volume/wp-content/plugins/divi-form-builder/includes/ajaxcalls/post_ajax.php|254 col 16-33| do_action( 'df_before_process', $form_id, $post_array, $form_type );
*
* check user rights :
* - https://developer.wordpress.org/reference/functions/is_user_logged_in/
* - https://stackoverflow.com/questions/19802492/check-if-current-user-is-administrator-in-wordpress
* - https://developer.wordpress.org/reference/functions/current_user_can/
*/
add_action ('df_before_process', 'PLGNTLS_my_custom_df_form_handler', 10, 3);
function PLGNTLS_my_custom_df_form_handler($form_id, $post_array, $form_type)
{
error_log("in my_custom_df_form_handler");
error_log("form_id");
error_log($form_id);
error_log("post_array");
error_log(json_encode($post_array));
error_log("form_type");
error_log($form_type);
}
// Hook into the 'acf/save_post' action
/*
add_action('acf/save_post', 'handle_acf_form_submission', 5); // 20 is the priority, you can adjust it as needed
function handle_acf_form_submission($post_id)
{
error_log("in acf/save_post");
if ($_SERVER['REQUEST_METHOD'] === 'POST' )
{
error_log("_SERVER['REQUEST_URI']");
error_log(json_encode($_SERVER['REQUEST_URI']));
error_log("_SERVER['QUERY_STRING']");
error_log(json_encode($_SERVER['QUERY_STRING']));
error_log("_POST['de_fb_ville']");
error_log(json_encode($_POST['de_fb_ville']));
}
// Check if the request is coming from the specific URL
if ($_SERVER['QUERY_STRING'] !== '/') {
return; // Exit if the request is not from the specific URL
}
// Check if this is an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check if this is a revision
if (wp_is_post_revision($post_id)) {
return;
}
// Check if the current user has permission to edit the post
if (!current_user_can('edit_post', $post_id)) {
return;
}
// Your ACF form submission handling logic goes here
// For example, you can retrieve form data using $_POST and update ACF fields accordingly
if (isset($_POST['your_acf_field_name'])) {
$field_value = sanitize_text_field($_POST['your_acf_field_name']);
update_field('your_acf_field_name', $field_value, $post_id);
}
}
*/
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
menu plugin
* menu plugin
*/
include_once(PLGNTLS_class::get_path() . '/php/menu/example_menu.php');
function fipfcard_plugin_menu()
{
add_menu_page
@@ -364,28 +92,4 @@ add_action('admin_menu', 'fipfcard_plugin_menu');
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
ajax
- https://stackoverflow.com/questions/43557755/how-to-call-ajax-in-wordpress
- in `add_action( 'wp_ajax_get_data', 'my_ajax_handler' );`
the 'wp_ajax_get_data' is a hooks formated as 'wp_ajax_{$action}'
the `$action` param is passed in the data object of the ajax call
- to access the content of the data object properties of the ajax call :
use $_POST['property_name']
*/
function fipfcard_ajax_handler()
{
wp_send_json_success( array
(
'It works',
"data_received" => $_POST['postid'],
),
200
);
}
add_action( 'wp_ajax_get_data', 'fipfcard_ajax_handler' );
?>

View File

@@ -1,66 +0,0 @@
<div id="model_plugin_shortcode">
<ol>
<p>list get_metadata('post') :</p>
<?php
foreach($post_metadata as $meta_key => $meta_value) {
include($plgn_dir."html/templates/print_meta.html");
}
?>
</ol>
<ol>
<p>list get_post_meta() :</p>
<?php
foreach($post_meta as $meta_key => $meta_value) {
include($plgn_dir."html/templates/print_meta.html");
}
?>
</ol>
<ol>
<p>list get_metadata('user') :</p>
<?php
foreach($user_metadata as $meta_key => $meta_value) {
include($plgn_dir."html/templates/print_meta.html");
}
?>
</ol>
<ol>
<p>list get_user_meta() :</p>
<?php
foreach($user_meta as $meta_key => $meta_value) {
include($plgn_dir."html/templates/print_meta.html");
}
?>
</ol>
<ol>
<p>list get_userdata() :</p>
<?php
foreach($user_data as $meta_key => $meta_value) {
include($plgn_dir."html/templates/print_meta.html");
}
?>
</ol>
<ol>
<p>list wp_get_current_user() :</p>
<?php
foreach($current_user as $meta_key => $meta_value) {
include($plgn_dir."html/templates/print_meta.html");
}
?>
</ol>
<ol>
<p>list wp_get_current_user()->data :</p>
<?php
foreach($current_user->data as $meta_key => $meta_value) {
include($plgn_dir."html/templates/print_meta.html");
}
?>
</ol>
<p>i am a new p</p>
<p class="first_el_to_change">to change</p>
<button id='test_ajax_1' name="ajax_button_1" value="2024">2024</button>
<?php
foreach($names as $name) {
include($plgn_dir."html/templates/example_presentation.html");
}
?>

View File

@@ -1,22 +0,0 @@
<?php
foreach($ages as $age) {
?>
<p>age <?php echo esc_html($age); ?></p>
<?php
}
?>
<p class="third_el_to_change">to change</p>
<p>aaaaaand this is the end</p>
<form method="post" action="<?php echo esc_url( wp_registration_url() ); ?>">
<input type="text" name="user_login" placeholder="username">
<input type="email" name="user_email" placeholder="email">
<input type="password" name="user_pass" placeholder="password">
<button type="submit">register</button>
</form>
<form method="post" action="<?php echo esc_url( wp_lostpassword_url() ); ?>">
<input type="hidden" id="user_login" value="rexe">
<input type="text" name="pass1" data-reveal="1" data-pw="i0#chBo*S1Br5iDY" placeholder="new password">
<input type="hidden" name="rp_key" value="WO8qGALMbbKKsEEhXsOQ">
<button type="submit">generate</button>
</form>
</div>

View File

@@ -1,3 +0,0 @@
<input type='text' id='image_id' placeholder="image_id" value="33555">
<button id='edit_image'>edit image</button>
<div id="media_editor"></div>

View File

@@ -1,2 +1,5 @@
<input type='text' id='mytext'>
<button id='mybutton'>send</button>
<input type='text' id='mytext_2'>
<button id='mybutton_2'>send</button>

View File

@@ -0,0 +1,24 @@
<h1>old button :</h1>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick" />
<input type="hidden" name="hosted_button_id" value="H876N9DGSCLKS" />
<input type="hidden" name="currency_code" value="EUR" />
<input type="image" src="https://www.paypalobjects.com/fr_XC/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" title="PayPal, votre réflexe sécurité pour payer en ligne." alt="Acheter" />
</form>
<h1>new button :</h1>
<div id="paypal-button-container"></div>
<!--
custom card fields
@see https://developer.paypal.com/docs/checkout/advanced/integrate#link-addpaypalbuttonsandcardfields
<div id="card-name-field-container"></div>
<div id="checkout-form">
<div id="card-number-field-container"></div>
<div id="card-expiry-field-container"></div>
<div id="card-cvv-field-container"></div>
<button id="card-field-submit-button" type="button">
Pay now with Card
</button>
</div>
-->
<p id="result-message"></p>

View File

@@ -1,2 +0,0 @@
<p>hello <?php echo esc_html($name); ?></p>
<p class="second_el_to_change">to change</p>

View File

@@ -1,4 +0,0 @@
<li>
"<?php echo esc_html($meta_key); ?>" :
<?php echo esc_html(json_encode($meta_value)); ?>
</li>

View File

@@ -1,20 +0,0 @@
console.log("PLGNTLS_data:");
console.log(PLGNTLS_data);
const title = document.querySelector(".first_el_to_change");
title.innerHTML = "--- coucou ;) " + PLGNTLS_data.myvar_1;
const ajax_button_1 = document.querySelector("#test_ajax_1");
ajax_button_1.addEventListener('click', () => {
PLGNTLS_data.ajax(ajax_button_1, 'get_data')
.then((response) => response.json())
.then((data) => {
console.log("datou: ");
console.log(data);
})
.catch((error) => {
console.log("error: ");
console.log(error);
})
;
});

View File

@@ -1,3 +0,0 @@
const title2 = document.querySelector(".second_el_to_change");
title2.innerHTML = "--- ho boy !";

View File

@@ -1,3 +0,0 @@
const title3 = document.querySelector(".third_el_to_change");
title3.innerHTML = "--- bye bye, " + PLGNTLS_data.myvar_2;

View File

@@ -1,18 +1,4 @@
const inputElement = document.getElementById('mytext');
const sendButton = document.getElementById('mybutton');
sendButton.addEventListener('click', () => {
const inputValue = inputElement.value;
console.log("inputValue:");
console.log(inputValue);
PLGNTLS_ajax(inputValue, 'get_data')
.then((response) => response.json())
.then((data) => {
console.log("dataaa: ");
console.log(data);
})
.catch((error) => {
console.log("error: ");
console.log(error);
});
});
import { test_fetch } from './example_submenu.js';
test_fetch();

View File

@@ -0,0 +1,29 @@
const inputElement2 = document.getElementById('mytext_2');
const sendButton2 = document.getElementById('mybutton_2');
sendButton2.addEventListener('click', () => {
let inputValue = inputElement2.value;
inputValue = {
key1: 'value1',
key2: 'value2'
};
inputValue = JSON.stringify(inputValue);
console.log("inputValue:");
console.log(inputValue);
PLGNTLS_fetch('/plgntls/get_data', {
method: "POST",
})
//PLGNTLS_fetch('get_data', {body: {inputValue}})
.then((response) => response.json())
.then((data) => {
console.log("dataaa: ");
console.log(data);
})
.catch((error) => {
console.log("error: ");
console.log(error);
});
});

View File

@@ -0,0 +1,33 @@
import { PLGNTLS_fetch } from '../../utils/plgntls_fetch.js';
export function test_fetch() {
const inputElement = document.getElementById('mytext');
const sendButton = document.getElementById('mybutton');
sendButton.addEventListener('click', () => {
let inputValue = inputElement.value;
inputValue = {
key1: 'value1',
key2: 'value2'
};
inputValue = JSON.stringify(inputValue);
console.log("inputValue:");
console.log(inputValue);
PLGNTLS_fetch('/plgntls/get_data', {
method: "POST",
})
//PLGNTLS_fetch('get_data', {body: {inputValue}})
.then((response) => response.json())
.then((data) => {
console.log("dataaa: ");
console.log(data);
})
.catch((error) => {
console.log("error: ");
console.log(error);
});
});
}

View File

@@ -0,0 +1,66 @@
import { resultMessage } from './result_message.js';
import { PLGNTLS_fetch } from '../../utils/plgntls_fetch.js';
/**
* @see https://developer.paypal.com/docs/checkout/standard/integrate/#link-integratebackend
*/
//async function createOrder() {
export async function createOrder() {
try {
//const fetch_create_url = PLGNTLS_data.fetch_url + "/fipf_plugin/api/v1/orders";
//console.log("fetch_create_url:", fetch_create_url);
//const response = await fetch(fetch_create_url, {
const response = await PLGNTLS_fetch('/fipf_plugin/api/v1/orders', {
method: "POST",
headers: {
"Content-Type": "application/json",
//"X-WP-Nonce": PLGNTLS_data.rest_nonce,
},
// use the "body" param to optionally pass additional order information
// like product ids and quantities
body: JSON.stringify({
cart: [
{
id: "1234",
quantity: "1",
},
],
}),
});
const orderData = await response.json();
if (orderData.id) {
return orderData.id;
} else {
const errorDetail = orderData?.details?.[0];
const errorMessage = errorDetail
? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})`
: JSON.stringify(orderData);
throw new Error(errorMessage);
}
} catch (error) {
console.error(error);
resultMessage(`Could not initiate PayPal Checkout...<br><br>${error}`);
}
}
/**
* @see https://developer.paypal.com/demo/checkout/#/pattern/server
*
// Call your server to set up the transaction
function createOrder(data, actions) {
const fetch_create_url = PLGNTLS_data.fetch_url + "/fipf_plugin/api/v1/orders";
console.log("fetch_create_url:", fetch_create_url);
return fetch(fetch_create_url, {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
*/

View File

@@ -0,0 +1,107 @@
import { resultMessage } from './result_message.js';
import { PLGNTLS_fetch } from '../../utils/plgntls_fetch.js';
/**
* @see https://developer.paypal.com/docs/checkout/standard/integrate/#link-integratebackend
*/
//async function onApprove(data, actions) {
export async function onApprove(data, actions) {
try {
const fetch_approve_url = PLGNTLS_data.fetch_url + "/fipf_plugin/api/v1/orders/" + data.orderID + "/capture";
console.log("fetch_approve_url:", fetch_approve_url);
//const response = await fetch(fetch_approve_url, {
const response = await PLGNTLS_fetch('/fipf_plugin/api/v1/orders/' + data.orderID + '/capture', {
method: "POST",
headers: {
"Content-Type": "application/json",
//"X-WP-Nonce": PLGNTLS_data.rest_nonce,
},
});
const orderData = await response.json();
// Three cases to handle:
// (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
// (2) Other non-recoverable errors -> Show a failure message
// (3) Successful transaction -> Show confirmation or thank you message
const errorDetail = orderData?.details?.[0];
if (errorDetail?.issue === "INSTRUMENT_DECLINED") {
// (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
// recoverable state, per https://developer.paypal.com/docs/checkout/standard/customize/handle-funding-failures/
return actions.restart();
} else if (errorDetail) {
// (2) Other non-recoverable errors -> Show a failure message
throw new Error(`${errorDetail.description} (${orderData.debug_id})`);
} else if (!orderData.purchase_units) {
throw new Error(JSON.stringify(orderData));
} else {
// (3) Successful transaction -> Show confirmation or thank you message
// Or go to another URL: actions.redirect('thank_you.html');
const transaction =
orderData?.purchase_units?.[0]?.payments?.captures?.[0] ||
orderData?.purchase_units?.[0]?.payments?.authorizations?.[0];
// to show a message on page
//resultMessage(`Transaction ${transaction.status}: ${transaction.id}<br><br>See console for all available details`,);
console.log(
"Capture result",
orderData,
JSON.stringify(orderData, null, 2),
);
actions.redirect('https://local_fipfcard_plugin.com/');
}
} catch (error) {
console.error(error);
resultMessage(
`Sorry, your transaction could not be processed...<br><br>${error}`,
);
}
}
/**
* @see https://developer.paypal.com/demo/checkout/#/pattern/server
*
// Call your server to finalize the transaction
function onApprove (data, actions) {
const fetch_approve_url = PLGNTLS_data.fetch_url + "/fipf_plugin/api/v1/orders/" + data.orderID + "/capture";
console.log("fetch_approve_url:", fetch_approve_url);
return fetch(fetch_approve_url, {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(orderData) {
// Three cases to handle:
// (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
// (2) Other non-recoverable errors -> Show a failure message
// (3) Successful transaction -> Show confirmation or thank you
// This example reads a v2/checkout/orders capture response, propagated from the server
// You could use a different API or structure for your 'orderData'
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart(); // Recoverable state, per:
// https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
if (errorDetail.description) msg += '\n\n' + errorDetail.description;
if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
return alert(msg); // Show a failure message (try to avoid alerts in production environments)
}
// Successful capture! For demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
var transaction = orderData.purchase_units[0].payments.captures[0];
alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
// Replace the above to show a success message within this page, e.g.
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
*/

View File

@@ -0,0 +1,56 @@
import { createOrder } from './create_order.js';
import { onApprove } from './on_approve.js';
window.paypal.Buttons({
/*
style: {
layout: 'vertical',
color: 'blue',
shape: 'rect',
label: 'paypal',
},
*/
createOrder: createOrder,
onApprove: onApprove,
})
.render("#paypal-button-container");
/**
* customize card fields
* from : https://developer.paypal.com/docs/checkout/advanced/integrate#link-addpaypalbuttonsandcardfields
*
// Create the Card Fields Component and define callbacks
const cardField = paypal.CardFields({
createOrder: createOrder,
onApprove: onApprove,
});
// Render each field after checking for eligibility
if (cardField.isEligible()) {
const nameField = cardField.NameField();
nameField.render("#card-name-field-container");
const numberField = cardField.NumberField();
numberField.render("#card-number-field-container");
const cvvField = cardField.CVVField();
cvvField.render("#card-cvv-field-container");
const expiryField = cardField.ExpiryField();
expiryField.render("#card-expiry-field-container");
// Add click listener to submit button and call the submit function on the CardField component
document
.getElementById("card-field-submit-button")
.addEventListener("click", () => {
cardField.submit().then(() => {
// submit successful
});
});
}
*/

View File

@@ -0,0 +1,13 @@
//function PLGNTLS_fetch(url, options = {}) {
export function PLGNTLS_fetch(url, options = {}) {
console.log("inside PLGNTLS_fetch");
url = PLGNTLS_data.fetch_url + url;
options.headers = options.headers || {};
options.headers['X-WP-Nonce'] = PLGNTLS_data.fetch_nonce,
console.log("options:", options);
return fetch(url, options);
}

View File

@@ -0,0 +1,7 @@
// Example function to show a result to the user. Your site's UI library can be used instead.
//function resultMessage(message) {
export function resultMessage(message) {
const container = document.querySelector("#result-message");
container.innerHTML = message;
}

View File

@@ -1,4 +1,13 @@
<?php
/**
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
/**
* WordPress Image Editor
*

View File

@@ -1,5 +1,12 @@
<?php
/**
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
/*
function fipfcard_image_editor()
{

View File

@@ -1,12 +1,54 @@
<?php
/**
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
function fipfcard_plugin_content() {
$fipfcard = new PLGNTLS_class();
$my_css = '
#mytext {
background-color: lightblue;
}
#mytext_2 {
background-color: lightgreen;
}
';
echo $fipfcard->add_to_front( array(
"js/menu/example_menu.js",
array("js/menu/example_menu.js", 'type'=>'module'),
"css/menu/menu.css",
"PLGNTLS_menu_css" => array('css'=>$my_css),
"js/menu/example_menu_2.js",
"html/menu/example_menu.html",
));
}
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
ajax
- https://stackoverflow.com/questions/43557755/how-to-call-ajax-in-wordpress
- in `add_action( 'wp_ajax_get_data', 'my_ajax_handler' );`
the 'wp_ajax_get_data' is a hooks formated as 'wp_ajax_{$action}'
the `$action` param is passed in the data object of the ajax call
- to access the content of the data object properties of the ajax call :
use $_POST['property_name']
*/
function fipfcard_menu_fetch_handler()
{
return new WP_REST_Response('hello', 200);
}
function fipfcard_menu_endpoint()
{
register_rest_route('plgntls', '/get_data', array(
'methods' => 'POST',
'callback' => 'fipfcard_menu_fetch_handler',
));
};
add_action('rest_api_init', 'fipfcard_menu_endpoint');
?>

View File

@@ -0,0 +1,110 @@
<?php
/**
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
include_once(PLGNTLS_class::get_path() . '/php/paypal/route_api_orders.php');
include_once(PLGNTLS_class::get_path() . '/php/paypal/route_api_orders_capture.php');
/*
function check_paypal_request()
{
error_log("----");
if (is_page('test_paypal_payment'))
error_log("on test_paypal_payment");
else if (is_page('test_paypal_ok'))
error_log("on test_paypal_ok");
else if (is_page('test_paypal_infos'))
error_log("on test_paypal_infos");
else
return;
error_log("_GET");
error_log(json_encode($_GET));
error_log("_POST");
error_log(json_encode($_POST));
// error_log("_COOKIE");
// error_log(json_encode($_COOKIE));
}
add_action('template_redirect', 'check_paypal_request');
*/
/**
* call to paypal_shortcode_content()
*/
function fipf_paypal_shortcode_content()
{
$fipfcard_paypal = new PLGNTLS_class();
$pp_sdk_currency = "EUR";
$pp_sdk_debug = "true";
$pp_sdk_base_url="https://sandbox.paypal.com";
$pp_sdk_base_url="https://www.paypal.com";
// $pp_sdk_client_token="abc123xyz==";
$pp_sdk_src="$pp_sdk_base_url/sdk/js?client-id=" . PAYPAL_CLIENT_ID . "&currency=$pp_sdk_currency&debug=$pp_sdk_debug";
$pp_sdk_src="$pp_sdk_base_url/sdk/js?client-id=" . PAYPAL_CLIENT_ID ;
// $pp_sdk_attributes="src='$pp_sdk_src' data-client-token='$pp_sdk_client_token'";
// $pp_sdk_attributes="src='$pp_sdk_src'";
// $pp_sdk_html_script="<script $pp_sdk_attributes></script>";
$added_to_front = $fipfcard_paypal->add_to_front(
array(
$pp_sdk_src,
// 'js/paypal/result_message.js',
// 'js/paypal/create_order.js',
// 'js/paypal/on_approve.js',
//"js/paypal/paypal.js",
array("js/paypal/paypal.js", 'type'=>'module'),
"html/paypal/paypal.html",
),
);
return $added_to_front;
}
add_shortcode('fipf_paypal_shortcode', 'fipf_paypal_shortcode_content');
/**
* the js file paypal.js needs to be imported as a module to use import
* @see https://developer.wordpress.org/reference/hooks/script_loader_tag/
function fipf_add_id_to_script( $tag, $handle, $src ) {
if ( $handle === 'PLGNTLS_paypal_js' ) {
$tag = '<script type="module" src="' . esc_url( $src ) . '" ></script>';
}
return $tag;
}
add_filter( 'script_loader_tag', 'fipf_add_id_to_script', 10, 3 );
*/
// handling routes and endpoints
// diff routes and endpoints : https://stackoverflow.com/q/56075017/9497573
function fipf_routes_endpoints()
{
$base_rest_route = "fipf_plugin/api/v1";
register_rest_route($base_rest_route, '/orders', array(
'methods' => 'POST',
'callback' => 'fipf_handle_orders_request',
));
// https://local_fipfcard_plugin.com/wp-json/fipf_plugin/api/v1/orders/21T129305J264761D/capture
register_rest_route($base_rest_route, '/orders/(?P<orderID>[a-zA-Z0-9]+)/capture', array(
'methods' => 'POST',
'callback' => 'fipf_handle_orders_capture_request',
));
};
add_action('rest_api_init', 'fipf_routes_endpoints');
?>

View File

@@ -0,0 +1,97 @@
<?php
include_once(PLGNTLS_class::get_path() . '/php/paypal/route_api_utils.php');
include_once(PLGNTLS_class::get_path() . '/php/paypal/update_user_payment.php');
/**
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
/**
* @see https://developer.paypal.com/docs/checkout/standard/integrate/#link-integratebackend
*/
function fipf_handle_orders_request($request_data) {
try {
// Extract cart information from request body
$cart = $request_data['cart'];
// Process the order and get the response
$order_response = fipf_create_order($cart);
$json_response = $order_response['json_response'];
$http_status_code = $order_response['http_status_code'];
fipf_update_user_payment($json_response, 'start');
// Return response
return new WP_REST_Response($json_response, $http_status_code);
} catch (Exception $e) {
// Handle errors
error_log('Failed to create order: ' . $e->getMessage());
return new WP_Error('500', 'Failed to create order.', array('status' => 500));
}
}
/**
* Create an order to start the transaction.
* @see https://developer.paypal.com/docs/api/orders/v2/#orders_create
*/
function fipf_create_order( $cart )
{
// use the cart information passed from the front-end to calculate the purchase unit details
$access_token = fipf_generate_access_token();
$url = PAYPAL_API_BASE_URL . '/v2/checkout/orders';
$payload = array(
'intent' => "CAPTURE",
'purchase_units' => array(
array(
'amount' => array(
'currency_code' => "USD",
'value' => "100.00",
),
),
),
);
$headers = array(
"Content-Type: application/json",
"Authorization: Bearer " . $access_token
// Uncomment one of these to force an error for negative testing (in sandbox mode only). Documentation:
// https://developer.paypal.com/tools/sandbox/negative-testing/request-headers/
// "PayPal-Mock-Response": '{"mock_application_codes": "MISSING_REQUIRED_PARAMETER"}'
// "PayPal-Mock-Response": '{"mock_application_codes": "PERMISSION_DENIED"}'
// "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}'
);
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute cURL session and get the response
$response = curl_exec($ch);
if ($response === false)
throw new Exception('cURL error: ' . curl_error($ch));
// Close cURL session
curl_close($ch);
// in utils
return fipf_handle_response($response);
};
?>

View File

@@ -0,0 +1,74 @@
<?php
include_once(PLGNTLS_class::get_path() . '/php/paypal/route_api_utils.php');
include_once(PLGNTLS_class::get_path() . '/php/paypal/update_user_payment.php');
/**
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
function fipf_handle_orders_capture_request($request) {
$order_id = $request['orderID'];
try {
// Implement captureOrder function logic here
// Make sure you implement captureOrder function similar to the Node.js code
$response_data = fipf_capture_order($order_id);
$http_status_code = $response_data['http_status_code'];
$json_response = $response_data['json_response'];
fipf_update_user_payment($json_response, 'end');
return new WP_REST_Response($json_response, $http_status_code);
}
catch (Exception $e) {
error_log('Failed to capture order: ' . $e->getMessage());
return new WP_REST_Response(array('error' => 'Failed to capture order.'), 500);
}
}
/**
* Capture payment for the created order to complete the transaction.
* @see https://developer.paypal.com/docs/api/orders/v2/#orders_capture
*/
function fipf_capture_order($orderID) {
$access_token = fipf_generate_access_token();
$url = PAYPAL_API_BASE_URL . '/v2/checkout/orders/' . $orderID . '/capture';
$headers = array(
"Content-Type: application/json",
"Authorization: Bearer " . $access_token
// Uncomment one of these to force an error for negative testing (in sandbox mode only). Documentation:
// https://developer.paypal.com/tools/sandbox/negative-testing/request-headers/
// 'PayPal-Mock-Response: {"mock_application_codes": "INSTRUMENT_DECLINED"}',
// 'PayPal-Mock-Response: {"mock_application_codes": "TRANSACTION_REFUSED"}',
// 'PayPal-Mock-Response: {"mock_application_codes": "INTERNAL_SERVER_ERROR"}'
);
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute cURL session and get the response
$response = curl_exec($ch);
if ($response === false)
throw new Exception('cURL error: ' . curl_error($ch));
// Close cURL session
curl_close($ch);
// in utils
return fipf_handle_response($response);
};
?>

View File

@@ -0,0 +1,98 @@
<?php
/**
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
/**
* @see https://developer.paypal.com/docs/checkout/standard/integrate/#link-integratebackend
*/
function fipf_handle_response($response) {
try
{
// Decode JSON response
$json_response = json_decode($response);
return array(
'json_response' => $json_response,
'http_status_code' => http_response_code()
);
}
catch (Exception $err)
{
// Get error message from response
$error_message = $response->text();
throw new Exception($error_message);
}
}
/*
async function handleResponse(response) {
try {
const jsonResponse = await response.json();
return {
jsonResponse,
httpStatusCode: response.status,
};
} catch (err) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
}
*/
/**
* Generate an OAuth 2.0 access token for authenticating with PayPal REST APIs.
* @see https://developer.paypal.com/docs/checkout/standard/integrate/#link-integratebackend
* @see https://developer.paypal.com/api/rest/authentication/
*/
function fipf_generate_access_token()
{
try
{
if ( !PAYPAL_CLIENT_ID || !PAYPAL_CLIENT_SECRET ) {
throw new Exception( "MISSING_API_CREDENTIALS" );
}
$credentials = PAYPAL_CLIENT_ID . ":" . PAYPAL_CLIENT_SECRET;
$auth = base64_encode($credentials);
$url = PAYPAL_API_BASE_URL . '/v1/oauth2/token';
$body = http_build_query(array('grant_type' => 'client_credentials'));
// Initialize curl
$ch = curl_init();
// Set curl options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Basic ' . $auth,
));
// Execute curl and get the response
$data_json = curl_exec($ch);
if ( $data_json === false)
throw new Exception('cURL error: ' . curl_error($ch));
// Close curl
curl_close($ch);
$data = json_decode($data_json);
return $data->access_token;
}
catch (Exception $error)
{
error_log("Failed to generate Access Token:");
error_log($error->getMessage());
}
};
?>

View File

@@ -0,0 +1,209 @@
<?php
/**
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
/**
* see documentation in private 'paypal.md'
* basically it check if the user who initiate the transaction
* is the same that finish it
*
* add_user_meta('user_id', 'fipf_order_id', 'aaaaaa');
* ['aaaaaa']
* add_user_meta('user_id', 'fipf_order_id', 'bbbbbb');
* ['aaaaaa', 'bbbbbb']
* add_user_meta('user_id', 'fipf_order_id', 'bbbbbb');
* ['aaaaaa', 'bbbbbb', 'bbbbbb']
* get_user_meta('user_id', 'fipf_order_id');
* ['aaaaaa', 'bbbbbb', 'bbbbbb']
* $del_ret = delete_user_meta('user_id', 'fipf_order_id', 'bbbbbb');
* ['aaaaaa'] - $del_ret === true
* $del_ret = delete_user_meta('user_id', 'fipf_order_id', 'bbbbbb');
* ['aaaaaa'] - $del_ret === false
*
*/
function fipf_update_user_payment($message, $step)
{
$order_id = $message->id;
$user_id = get_current_user_id();
/*
order status : https://developer.paypal.com/docs/api/orders/v2/#orders_capture!c=201&path=status&t=response
CREATED
SAVED
APPROVED ?
VOIDED
- COMPLETED
PAYER_ACTION_REQUIRED
*/
$status = $message->status;
//error_log("--- in update_user_payment, step :");
//error_log($step);
////error_log("message :");
////error_log(json_encode($message));
//error_log("order_id :");
//error_log($order_id);
//error_log("status :");
//error_log($status);
//$user_meta_order_id = get_user_meta($user_id, 'fipf_order_id');
//error_log("user_meta->fipf_order_id :");
//error_log(json_encode($user_meta_order_id));
//error_log("... update user");
// addind order_id to fipf_order_id meta field
// it can duplicate, it's not a problem : delete_user_meta will delete all
add_user_meta($user_id, 'fipf_order_id', $order_id);
// add a schedule event to delete this order_id
fipf_schedule_delete_orderid($user_id, $order_id);
fipf_validate_payment_for_user($user_id, $order_id);
// if transaction is COMPLETED, then delete order_id and update user
if ($status === 'COMPLETED')
{
// find the user containing the order_id and delete this order_id
$user_id_to_update = fipf_delete_order_id_on_success($user_id, $order_id);
// proceed to validate payment for user
fipf_validate_payment_for_user($user_id_to_update, $order_id);
}
//$user_meta_order_id = get_user_meta($user_id, 'fipf_order_id');
//error_log("user_meta->fipf_order_id :");
//error_log(json_encode($user_meta_order_id));
//error_log("--- out update_user_payment");
}
/**
*
* change acf field [carte_est_valide](validite) to true
* change acf field [date_d_achat](achat) to new current date
* change acf field [date_fin_validite](echance) to previous date + 1 year
*
* create scheduled emails to inform of end of validity
*
* acf uses 'Y-m-d H:i:s' format :
* -> https://www.advancedcustomfields.com/resources/date-time-picker/
*/
function fipf_validate_payment_for_user($user_id, $order_id)
{
$acf_date_format = 'Y-m-d H:i:s';
/**
* update card validity to true
*/
$post_id = 'user_'.$user_id;
update_field('carte_est_valide', true, $post_id);
/**
* update purchase date to now
*/
$date_now = date($acf_date_format);
update_field('date_d_achat', $date_now, $post_id);
/**
* update date limit validity to add 1 year
*/
$current_date_limit = get_field('date_fin_validite', $post_id);
// output is in format 'dd/mm/yyyy' which is not understood by php dates functions
// so i clean it
// -> not a reliable solution, someone can change the ouput format in dashboard
$current_date_limit = str_replace('/', '-', $current_date_limit);
// id current date limit is not in the futur, use now date
if ($current_date_limit === null)
$current_date_limit = $date_now;
else
{
// compare 2 dates : https://stackoverflow.com/q/8722806/9497573
// also I dont use strtotime to compare 2 ints,
// because i don't know if it will fail one day (2000 bug like)
$comp_current_date_limit = date_create($current_date_limit);
$comp_date_now = date_create($date_now);
$date_is_in_past = date_diff($comp_date_now, $comp_current_date_limit)->format("%R%a") < 0;
if ($date_is_in_past)
$current_date_limit = $date_now;
}
// add one year to current date limit
$time_plus_one_year = strtotime('+1 year', strtotime($current_date_limit));
$new_date_limit = date('Y-m-d H:i:s', $time_plus_one_year);
update_field('date_fin_validite', $new_date_limit, $post_id);
}
/**
* add a schedule event to delete this order_id
* after 3 days ?
* time() + 60 = one minute from now
* time() + MINUTE_IN_SECONDS = one minute from now
* -> https://codex.wordpress.org/Easier_Expression_of_Time_Constants
* -> also strtotime : https://www.php.net/manual/en/function.strtotime.php
*/
function fipf_schedule_delete_orderid($user_id, $order_id)
{
$delay = time() + MINUTE_IN_SECONDS;
wp_schedule_single_event($delay, 'fipf_orderid_deletion_event', array($user_id, $order_id));
}
/**
* action hook for the scheduled event
* TODO: ne marche pas je ne sais pas pourquoi, pas urgent a resoudre
*/
function fipf_delete_order_id_later($user_id, $order_id)
{
error_log("delete order_id[$order_id] from user_id[$user_id]");
delete_user_meta($user_id, 'fipf_order_id', $order_id);
}
add_action('fipf_orderid_deletion_event', 'fipf_delete_order_id_later', 5, 2);
/**
* @return mixed num - user_id
* bool false - if no match found
*/
function fipf_delete_order_id_on_success($current_user_id, $order_id)
{
$del_ret = delete_user_meta($current_user_id, 'fipf_order_id', $order_id);
if ($del_ret === true)
return $current_user_id;
// it means the current user didn't have this order_id
// so we look for another user
$users = get_users();
foreach ($users as $user)
{
$user_id = $user->ID;
$del_ret = delete_user_meta($user_id, 'fipf_order_id', $order_id);
if ($del_ret === true)
return $user_id;
}
return false;
}
?>

View File

@@ -0,0 +1,15 @@
<?php
function add_partenaires_PLGNTLS($customer_data){
$current_url = $_SERVER['HTTP_REFERER'];
$path_brut = parse_url($current_url, PHP_URL_PATH);
$path = trim($path_brut, '/');
if ($path === 'creation-du-compte-partenaire')
$customer_data['role'] = 'partenaire';
return $customer_data;
}
add_filter( 'xoo_el_register_new_customer_data', 'add_partenaires_PLGNTLS', 10, 1 );
?>

View File

@@ -1,156 +0,0 @@
<?php
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
function that add the ajax script to front
no real needs to check if already included :
- $handle is uniq so it will not be re-enqueued
the first enqueued version would be kept
- if we used add_var_to_front() (which use wp_add_inline_script())
the vars would be added twice
leading to js syntaxe error (redeclaraiton of 'let' or 'const')
- but we use wp_localize_script() so the object will be overwritten
it's not a real pbm
(what is more efficient, check for double or overwritte object ?)
*/
function fipfcard_add_ajax_post() {
global $fipfcard_first_script;
global $fipfcard_ajax_file;
$file = fipfcard_init_file($fipfcard_ajax_file);
// // check if ajax script was already enqueued
// global $wp_scripts;
// $already_enqueued = array_search($file->handle, $wp_scripts->queue);
// if ($already_enqueued !== false)
// return ;
$fipfcard_first_script = $file->handle;
wp_enqueue_script( $file->handle, $file->url, '', $file->version, true);
$_url = admin_url( 'admin-ajax.php' );
$_nonce = wp_create_nonce( 'wp-pageviews-nonce' );
$vars = compact("_url","_nonce",);
// add_var_to_front($vars);
$object_name = "fipfcard_ajax";
wp_localize_script($file->handle, $object_name, $vars);
}
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
@param string : name of the file, with its path from its extension directory
- from js/ root for .js files
- from css/ root for .css files
@return object / null :
- null if file is not js or css
- or an object with all the necessary infos :
- ext : name.js -> "js"
- basename : name.js -> "name"
- handle : name.js -> "name_js"
- url : url to file in wordpress
- path : path to file in server
- version : used to avoid browser caching
*/
function fipfcard_init_file($file_name) {
$file = (object)[];
$file->ext = pathinfo($file_name, PATHINFO_EXTENSION);
if ($file->ext === "js")
$dir_path = 'js/';
else if ($file->ext === "css")
$dir_path = 'css/';
else
return null;
$file->basename = pathinfo($file_name, PATHINFO_FILENAME);
$file->handle = str_replace(".", "_", $file_name);
$file->url = FIPFCARD_PLUGIN_URL.$dir_path.$file_name;
$file->path = FIPFCARD_PLUGIN_DIR.$dir_path.$file_name;
$file->version = date("ymd-Gis", filemtime($file->path));
return $file;
}
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
@param array : list of files :
- with their path from root of their type of file (ex: from js/ to .js files)
- and with their extension
@param boolean
- to add ajax script and variables
- default to true
*/
function fipfcard_add_files_to_front($files_arr, $add_ajax = true) {
//wp_enqueue_script(<give_it_a_name>, /url/to/file, [depends on], version, defer? );
//wp_enqueue_style( <give_it_a_name>, /url/to/file, [depends on], version, media );
global $fipfcard_first_script;
if ($add_ajax === true)
fipfcard_add_ajax_post();
$previous_css_basename = '';
$previous_js_basename = '';
foreach ($files_arr as $file_name) {
$file = fipfcard_init_file($file_name);
if ($file->ext === "js") {
if (is_null($fipfcard_first_script))
$fipfcard_first_script = $file->handle;
wp_enqueue_script( $file->handle, $file->url, $previous_js_basename, $file->version, true);
$previous_js_basename = $file->basename;
}
else if ($file->ext === "css") {
wp_enqueue_style( $file->handle, $file->url, $previous_css_basename, $file->version, '');
$previous_css_basename = $file->basename;
}
}
}
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
pass variables to js front as global variables
@param array : list of key => value
with the key being name of the variable, like this :
'my_var' => 'value',
simpler way to do it is to use compact when calling the function :
add_var_to_front(compact("var1", "var2", "var3"));
@param string (optionnal) : name of first embended script that need these variables
(it will be available to this script and all followings)
this name is the filename + "_" + extension :
init.js -> init_js
*/
function fipfcard_add_var_to_front($vars, $handle = null) {
if (is_null($handle)) {
global $fipfcard_first_script;
$handle = $fipfcard_first_script;
}
extract($vars);
foreach ($vars as $key => $var)
{
$js_var = 'let '.$key.' = '.json_encode($var).';';
wp_add_inline_script($handle, $js_var, 'before');
}
// the other way with localize has multiple incidences :
// - it creates an object from wich you can access the variables
// - so if you call it again wiht the same name, it will overwrite the previous
// {
// $handle = pathinfo($handle, PATHINFO_FILENAME);
// $object_name = "php_data";
//
// wp_localize_script($handle, $object_name, $vars);
// }
}
?>

View File

@@ -1,16 +0,0 @@
<?php
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
https://stackify.com/how-to-log-to-console-in-php/
*/
function console_log($output) {
if (CONSOLE_OFF)
return;
$json_output = json_encode($output, JSON_HEX_TAG);
$js_code = '<script>console.log(' . $json_output . ');</script>';
echo $js_code;
}
?>

View File

@@ -1,39 +0,0 @@
<?php
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
@param two arguments :
1. html files to include in front
- can be a string of 1 filename
- or an array of strings of filenames
( https://stackoverflow.com/q/4747876/9497573 )
- it's probably better to only add 1 file, and let it include other files
2. list of variables to make available to this files
- in the form of key => val
- recommanded to do it with compact()
ex: create_html( "file.html", compact("var1","var2",) );
ex: create_html( array("file1.html", "file2.html"), array("var1"=>"value") );
@return a string of html code
using ob_start() and ob_get_clean()
allows to have php expansion inside the html loaded
in opposition to the methode file_get_contents()
https://stackoverflow.com/a/4402045/9497573
*/
function fipfcard_create_html($files, $vars = null) {
$files = (array)$files;
$html_dir = FIPFCARD_PLUGIN_DIR.'html/';
if (!is_null($vars))
extract($vars);
ob_start();
foreach($files as $file) {
include($html_dir.$file);
}
$html = ob_get_clean();
return $html;
}
?>

View File

@@ -1,22 +0,0 @@
<?php
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
globals variables
const vs define : https://stackoverflow.com/questions/2447791/php-define-vs-const
*/
/* switch console_log
const CONSOLE_OFF = true;
*/
const FIPFCARD_CONSOLE_OFF = false;
/* a variable that will contain the name of the first script enqueued
*/
$fipfcard_first_script = null;
/* path to ajax.js file, from root of js dir
*/
$fipfcard_ajax_file = "utils/ajax.js";
?>

View File

@@ -0,0 +1,26 @@
<?php
/**
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
https://stackify.com/how-to-log-to-console-in-php/
*/
function console_log(...$outputs) {
if (FIPFCARD_CONSOLE_OFF)
return;
foreach($outputs as $output)
{
$json_output = json_encode($output, JSON_HEX_TAG);
$js_code = '<script>console.log(' . $json_output . ');</script>';
echo $js_code;
}
}
?>

View File

@@ -0,0 +1,55 @@
<?php
/**
* it means someone outside wp is accessing the file, in this case kill it.
*/
if (!defined('ABSPATH')) {
die('You can not access this file!');
}
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
globals variables
const vs define : https://stackoverflow.com/questions/2447791/php-define-vs-const
*/
/* switch console_log
const CONSOLE_OFF = true;
*/
const FIPFCARD_CONSOLE_OFF = false;
/**
* a variable that will contain the name of the first script enqueued
*/
$fipfcard_first_script = null;
/**
* path to ajax.js file, from root of js dir
*/
$fipfcard_ajax_file = "utils/ajax.js";
/**
* paypal credentials
*
* LIVE :
*
* const PAYPAL_CLIENT_ID = "Aedn5e8z__hPBvKirqw5bwlhI9ChG8_N6c1xbgybYyBr4B4oP8uVzmVdH1QVKdPQKf6bWg7orPV4PDrO";
* const PAYPAL_CLIENT_SECRET = "EGeGwfHGxHxsjnC-tH8W0IL4nN3_xlc3sXFRPCQOw5uUoWae3eOgghuDKMnZc5DVGTbP6yIjVJ1BaAra";
*
* SANBOX :
*
* const PAYPAL_CLIENT_ID = "AfcmwxIXlG2ZxaMdjazX57I70BXz__aEqNWaTnqfSCI34a0V7nMbytswx7EViUjlpHs7opyrRwaH9YLl";
* const PAYPAL_CLIENT_SECRET = "EGunIhGRjPvn0Z8wXO0JsdhET30OStTAH_IyRsmhimEN23_qiRSFD-ql4tvnulKJw6TitZ-vU-ytc4A-";
*
*/
const PAYPAL_CLIENT_ID = "AfcmwxIXlG2ZxaMdjazX57I70BXz__aEqNWaTnqfSCI34a0V7nMbytswx7EViUjlpHs7opyrRwaH9YLl";
const PAYPAL_CLIENT_SECRET = "EGunIhGRjPvn0Z8wXO0JsdhET30OStTAH_IyRsmhimEN23_qiRSFD-ql4tvnulKJw6TitZ-vU-ytc4A-";
/**
* paypal api base url
*/
const PAYPAL_API_BASE_URL = "https://api-m.sandbox.paypal.com";
?>

View File

@@ -0,0 +1,455 @@
<?php
/**
* include those two lines at the top of the main plugin file
*
* include_once( plugin_dir_path(__FILE__) . '/php/utils/plugin_tools.php');
* PLGNTLS_class::set_root_dir( plugin_dir_path(__FILE__), plugin_dir_url(__FILE__) );
*
* PLGNTLS means PLUGIN TOOLS
*
* .add_to_front() : this method is made to add files and codes all at once
* otherwise use the wp functions (wp_enqueue_*, wp_add_inline_*, etc)
*
*
* ex:
*
* $my_plugin_class = new PLGNTLS_class();
* $var_1 = 'value_1';
* $var_2 = 'value_2';
* $var_3 = 'value_3';
* return $my_plugin_class->add_to_front(
* array( // files added in order by types
* 'path/to/style1.css', //
* 'path/to/script1.js', //
* 'path/to/style2.css', // -> depends on style1.css
* 'http://my_url1.com', //
* 'path/to/script2.js', // -> depends on script1.js
* 'path/to/file1.html', // | will be returned
* 'path/to/file2.html', // -> | as expanded html
* 'path/to/file3.html', // | in the order included
* 'handle_name' => 'path/to/script3.js', // -> depends on the script with handle 'handle_name'
* array( //
* 'path/to/script4.js', // | add a script with attributes
* 'attribute_1' => 'value_1', // -> | first element of array must be
* 'attribute_2' => 'value_2', // | the script, without explicit key
* ), //
* array( 'js' => 'var_js' ), // -> add inline js, only first element will be used
* array( 'css' => 'var_css' ), // -> add inline css, only first element will be used
* ),
* compact( // these variables are added to html and js files
* 'var_1', // - in html files you can access them directly
* 'var_2', // - in js files they are properties of object PLGNTLS_data
* 'var_3', // like PLGNTLS_data.var_1;
* )
* );
*
*/
class PLGNTLS_class
{
private static $_root_path;
private static $_root_url;
private $_first_script;
private $_first_style;
private $_prefix;
private $_js_dependencies;
private $_css_dependencies;
private $_scripts_attributes;
/**
*/
public function __construct() {
$this->_prefix = "PLGNTLS";
$this->_first_script = null;
$this->_first_style = null;
$this->_js_dependencies = array();
$this->_css_dependencies = array();
$this->_scripts_attributes = array();
}
/**
* can be used before class is instanciated :
* PLGNTLS_class::set_root_dir( plugin_dir_path(__FILE__), plugin_dir_url(__FILE__) );
*/
public static function set_root_dir($path, $url) {
if (isset( self::$_root_path ))
return ;
if (isset( self::$_root_url ))
return ;
self::$_root_path = $path;
self::$_root_url = $url;
}
public static function get_path() {
return(self::$_root_path);
}
public static function get_url() {
return(self::$_root_url);
}
public function add_to_front($srcs_arr = null, $vars = null) {
if (!is_array($vars))
$vars = array();
if (!is_null($srcs_arr))
$this->add_fetch($srcs_arr, $vars);
$srcs = array();
foreach($srcs_arr as $src_key => $src_value) {
$init = $this->init_src($src_key, $src_value);
if ($init !== null)
$srcs[] = $init;
}
if (!is_null($srcs_arr))
$this->add_srcs_to_front($srcs);
if (!is_null($vars))
$this->add_vars_to_front($vars);
return $this->create_html($srcs, $vars);
}
/**
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* PRIVATES FUNCTIONS
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
/**
* for fetch, we add the file script that contains the fetch function
* it is an es6 module with the export keyword
* that way, it can also be used by modules scripts
* to achieve that, we wouldn't need to include it here though
* but we need that the fetch function is also available for inline scripts
* so we could attach a copy of the script file without the export keyword
* but instead, inside the file, we add the fetch function to the global scope
*/
private function add_fetch(&$srcs_arr, &$vars) {
// add fetch script at beginning of scripts list
array_unshift($srcs_arr, array("utils/plgntls_fetch.js", 'type'=>'module'));
// for the custom endpoints in rest api to work
// they need to have a nonce named 'wp_rest'
// see : https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
$fetch_nonce = array("fetch_nonce" => wp_create_nonce('wp_rest'));
$fetch_url = array("fetch_url" => get_site_url() . "/wp-json");
$vars = array_merge($vars, $fetch_nonce);
$vars = array_merge($vars, $fetch_url);
}
/**
* @param two arguments :
* 1. html files to include in front
* - can be a string of 1 filename
* - or an array of strings of filenames
* ( https://stackoverflow.com/q/4747876/9497573 )
* - it's probably better to only add 1 file, and let it include other files
* 2. list of variables to make available to this files
* - in the form of key => val
* - recommanded to do it with compact()
* ex: create_html( "file.html", compact("var1","var2",) );
* ex: create_html( array("file1.html", "file2.html"), array("var1"=>"value") );
* @return a string of html code
*
* using ob_start() and ob_get_clean()
* allows to have php expansion inside the html loaded
* in opposition to the methode file_get_contents()
*
* https://stackoverflow.com/a/4402045/9497573
*/
private function create_html($files = null, $vars = null) {
if (is_null($files))
return null;
$plgn_dir = $this->get_path();
if (!is_null($vars))
extract($vars);
ob_start();
foreach($files as $file) {
if ($file->ext === 'html')
include($file->path);
}
$html = ob_get_clean();
return $html;
}
/**
* pass variables to js front as global variables
* @param array : list of key => value
* with the key being name of the variable, like this :
* 'my_var' => 'value',
* simpler way to do it is to use compact when calling the function :
* add_var_to_front(compact("var1", "var2", "var3"));
* @param string (optionnal) : name of first embended script that need these variables
* (it will be available to this script and all followings)
* this name is the filename + "_" + extension :
* init.js -> init_js
*/
private function add_vars_to_front($vars_arr)
{
if (is_null($this->_first_script))
return ;
if (is_null($vars_arr))
return ;
$handle = $this->_first_script;
$object_name = $this->_prefix . "_data";
$vars_json = json_encode($vars_arr);
$front = "let $object_name = $vars_json;";
wp_add_inline_script($handle, $front, 'before');
}
/**
* @param array : list of files :
* - with their path from root of their type of file (ex: from js/ to .js files)
* - and with their extension
* @param boolean
* - to add ajax script and variables
* - default to true
*/
private function add_srcs_to_front($srcs_arr) {
//wp_enqueue_script(<give_it_a_name>, /url/to/script, [depends on], version, defer? );
//wp_enqueue_style( <give_it_a_name>, /url/to/script, [depends on], version, media );
$previous_css_basename = '';
$previous_js_basename = '';
foreach ($srcs_arr as $src) {
if ($src->inline !== null) {
if ($src->inline === "js")
$this->add_inline_script($src);
else if ($src->inline === "css")
$this->add_inline_style($src);
}
else if (in_array($src->ext, array("js", "url"))) {
$this->add_script($src, $previous_js_basename);
$previous_js_basename = $src->handle;
}
else if ($src->ext === "css") {
$this->add_style($src, $previous_css_basename);
$previous_css_basename = $src->handle;
}
}
// https://developer.wordpress.org/reference/hooks/wp_script_attributes/
// https://wordpress.stackexchange.com/questions/66843/attach-a-private-function-at-a-hook
add_filter( 'wp_script_attributes', fn($attr)=>$this->add_attributes_to_script($attr), 10, 1 );
/*
* uncomment to print all enqueued files, can be usefull
global $wp_scripts;
error_log("wp_scripts->queue:");
error_log(json_encode($wp_scripts->queue));
global $wp_styles;
error_log("wp_styles->queue:");
error_log(json_encode($wp_styles->queue));
*/
}
private function add_script($script, $previous_js_basename) {
if (is_null($this->_first_script))
$this->_first_script = $script->handle;
$depends_on = $this->check_dependencies($script, $previous_js_basename);
if ($depends_on !== null)
wp_enqueue_script( $script->handle, $script->url, $depends_on, $script->version, true);
}
private function add_style($style, $previous_css_basename) {
if (is_null($this->_first_style))
$this->_first_style = $style->handle;
$depends_on = $this->check_dependencies($style, $previous_css_basename);
if ($depends_on !== null)
wp_enqueue_style( $style->handle, $style->url, $depends_on, $style->version, '');
}
private function add_inline_script($src) {
$handle = $src->depends;
if ($handle === null)
$handle = $this->_first_script;
wp_add_inline_script($src->depends, $src->src, 'before');
}
private function add_inline_style($src) {
error_log("inside add_inline_style");
$handle = $src->depends;
if ($handle === null)
$handle = $this->_first_style;
wp_add_inline_style($src->depends, $src->src);
}
private function add_attributes_to_script($attr) {
if (empty($attr['id']))
return $attr;
$handle = $attr['id'];
if (isset($this->_scripts_attributes[$handle]))
$script = $this->_scripts_attributes[$handle];
else
return $attr;
foreach($script as $key => $value){
$attr[$key] = $value;
}
unset($this->_scripts_attributes[$handle]);
return $attr;
}
private function check_dependencies(&$src, $previous_basename)
{
if (in_array($src->ext, array("js", "url")))
{
global $wp_scripts;
$already_enqueued = array_search($src->handle, $wp_scripts->queue);
if ($already_enqueued !== false)
return null;
}
else if ($src->ext === "css")
{
global $wp_styles;
$already_enqueued = array_search($src->handle, $wp_styles->queue);
if ($already_enqueued !== false)
return null;
}
$depends_on = array();
if (isset($src->depends) && $src->depends !== '')
$depends_on[] = $src->depends;
if (isset($previous_basename) && $previous_basename !== '')
$depends_on[] = $previous_basename;
return $depends_on;
}
/**
* @param string : name of the file, with its path from its extension directory
* - from js/ root for .js files
* - from css/ root for .css files
* @return object / null :
* - null if file is not valid
* - or an object with all the necessary infos :
* 0. src : array("name.js", ...) -> "name.js"
* "name.js" -> "name.js"
* 1. ext : name.js -> "js"
* 2. basename : name.js -> "name"
* 3. handle : name.js -> "name_js"
* 4. url : url to file in wordpress
* 5. path : path to file in server
* 6. version : used to avoid browser caching
* 7. depends : string if depends on a handle, or ''
* 8. attr : associative array of html attribute like 'type'=>'module'
* 9. inline : array("js" => "name.js") -> js
* array("css" => "name.css") -> css
*/
private function init_src($key, $value) {
if (empty($value))
return null;
$src = (object)[
'src' => null,
'ext' => null,
'basename' => null,
'handle' => null,
'url' => null,
'path' => null,
'version' => null,
'depends' => null,
'attr' => null,
'inline' => null,
];
// 7. depends
$src->depends = '';
if (is_string($key))
$src->depends = $key;
// 0. src
// 8. attr
// 9. inline
// first element of array is used, so must not be empty
// value => ['path/to/file', 'key1'=>'value1', 'key2'=>'value2']
// src => 'path/to/file'
// attr => ['key1'=>'value1', 'key2'=>'value2']
if (is_array($value)){
$first_key = array_keys($value)[0];
if (empty($value[$first_key]))
return null;
if ($first_key === 0) { // is a script file or url with attributes
$src->src = array_shift($value);
$src->attr = $value;
}
else if ($first_key === "js" || $first_key === "css") { // is an inline code
$src->src = $value[$first_key];
$src->inline = $first_key;
return $src; // inline only needs 'depends', 'src' and 'inline'
}
}
else {
$src->src = $value;
$src->attr = null;
}
// 1. ext
if(filter_var($src->src, FILTER_VALIDATE_URL))
$src->ext = "url";
else
$src->ext = pathinfo($src->src, PATHINFO_EXTENSION);
if (! in_array($src->ext, array("js", "css", "html", "url")))
return null;
// 2. basename
// 3. handle
// basename handle
// https://www.url.com/route -> www.url.com/route -> www_url_com_route
// path/to/script.js -> script.js -> script_js
if ($src->ext === "url")
{
$url = parse_url($src->src);
$src->basename = $url['host'] . $url['path'];
}
else
$src->basename = pathinfo($src->src, PATHINFO_BASENAME);
$src->handle = "PLGNTLS_" . str_replace(array('.', '/'), "_", $src->basename);
// 4. url
// 5. path
// 6. version
if ($src->ext === "url") {
$src->url = $src->src;
$src->path = null;
$src->version = null;
}
else {
$src->url = $this->get_url().$src->src;
$src->path = $this->get_path().$src->src;
$src->version = date("ymd-Gis", filemtime($src->path));
}
// if ext is 'js' or 'url' and attr is not empty
// also add to global variable to access in 'wp_script_attributes' filter
if ($src->ext === 'js' || $src->ext === 'url') {
if ($src->attr !== null) {
$this->_scripts_attributes[$src->handle.'-js'] = $src->attr;
}
}
return $src;
}
}
?>

View File

@@ -0,0 +1,22 @@
/**
* this file is there for scripts that uses modules import
*/
export function PLGNTLS_fetch(url, options = {}) {
console.log("inside PLGNTLS_fetch");
url = PLGNTLS_data.fetch_url + url;
options.headers = options.headers || {};
options.headers['X-WP-Nonce'] = PLGNTLS_data.fetch_nonce,
console.log("options:", options);
return fetch(url, options);
}
/**
* For non-module scripts, attach to the global scope
*/
if (typeof window !== 'undefined') {
window.PLGNTLS_fetch = PLGNTLS_fetch;
}

View File

@@ -1,20 +0,0 @@
/**
* function that create an ajax post action
* - PLGNTLS_data.ajax_nonce and PLGNTLS_data.ajax_url
* are passed from the class PLGNTLS_class
*/
console.log("PLGNTLS_data");
console.log(PLGNTLS_data);
function PLGNTLS_ajax(data_obj, action) {
const data = new FormData();
data.append("action", action);
data.append("_ajax_nonce", PLGNTLS_data.ajax_nonce);
for (const key in data_obj)
data.append(key, data_obj[key]);
return fetch(PLGNTLS_data.ajax_url, {
method: "POST",
credentials: "same-origin",
body: data
});
}

View File

@@ -1,261 +0,0 @@
<?php
/**
* include those two lines at the top of the main plugin file
*
* include_once( plugin_dir_path(__FILE__) . '/php/utils/plugin_tools.php');
* PLGNTLS_class::set_root_dir( plugin_dir_path(__FILE__), plugin_dir_url(__FILE__) );
*
* PLGNTLS means PLUGIN TOOLS
*/
class PLGNTLS_class
{
private static $_root_path;
private static $_root_url;
private static $_ajax_already_there;
private $_first_script;
private $_prefix;
private $_js_dependencies;
private $_css_dependencies;
/**
*/
public function __construct() {
if (! isset( self::$_ajax_already_there ))
self::$_ajax_already_there = false;
$this->_prefix = "PLGNTLS";
$this->_first_script = null;
$this->_js_dependencies = array();
$this->_css_dependencies = array();
}
/**
* can be used before class is instanciated :
* PLGNTLS_class::set_root_dir( plugin_dir_path(__FILE__), plugin_dir_url(__FILE__) );
*/
public static function set_root_dir($path, $url) {
if (isset( self::$_root_path ))
return ;
if (isset( self::$_root_url ))
return ;
self::$_root_path = $path;
self::$_root_url = $url;
}
public static function get_path() {
return(self::$_root_path);
}
public static function get_url() {
return(self::$_root_url);
}
public function add_to_front($files_arr = null, $vars = null) {
if (!is_null($files_arr))
{
// add ajax file at beginning of files list
array_unshift($files_arr, "utils/plugin_ajax.js");
$nonce = array("ajax_nonce" => wp_create_nonce('wp-pageviews-nonce'));
$url = array("ajax_url" => admin_url('admin-ajax.php'));
$vars = array_merge($vars, $nonce);
$vars = array_merge($vars, $url);
}
$files = array();
foreach($files_arr as $key => $file_name) {
$files[] = $this->init_file($key, $file_name);
}
if (!is_null($files_arr))
$this->add_files_to_front($files);
if (!is_null($vars))
$this->add_vars_to_front($vars);
return $this->create_html($files, $vars);
}
/**
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* PRIVATES FUNCTIONS
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
/**
* @param two arguments :
* 1. html files to include in front
* - can be a string of 1 filename
* - or an array of strings of filenames
* ( https://stackoverflow.com/q/4747876/9497573 )
* - it's probably better to only add 1 file, and let it include other files
* 2. list of variables to make available to this files
* - in the form of key => val
* - recommanded to do it with compact()
* ex: create_html( "file.html", compact("var1","var2",) );
* ex: create_html( array("file1.html", "file2.html"), array("var1"=>"value") );
* @return a string of html code
*
* using ob_start() and ob_get_clean()
* allows to have php expansion inside the html loaded
* in opposition to the methode file_get_contents()
*
* https://stackoverflow.com/a/4402045/9497573
*/
private function create_html($files = null, $vars = null) {
if (is_null($files))
return null;
$plgn_dir = $this->get_path();
if (!is_null($vars))
extract($vars);
ob_start();
foreach($files as $file) {
if ($file->ext === 'html')
include($file->path);
}
$html = ob_get_clean();
return $html;
}
/**
* pass variables to js front as global variables
* @param array : list of key => value
* with the key being name of the variable, like this :
* 'my_var' => 'value',
* simpler way to do it is to use compact when calling the function :
* add_var_to_front(compact("var1", "var2", "var3"));
* @param string (optionnal) : name of first embended script that need these variables
* (it will be available to this script and all followings)
* this name is the filename + "_" + extension :
* init.js -> init_js
*/
private function add_vars_to_front($vars_arr)
{
if (is_null($this->_first_script))
return ;
if (is_null($vars_arr))
return ;
$handle = $this->_first_script;
$object_name = $this->_prefix . "_data";
$vars_json = json_encode($vars_arr);
$front = "let $object_name = $vars_json;";
wp_add_inline_script($handle, $front, 'before');
}
/**
* @param array : list of files :
* - with their path from root of their type of file (ex: from js/ to .js files)
* - and with their extension
* @param boolean
* - to add ajax script and variables
* - default to true
*/
private function add_files_to_front($files_arr) {
//wp_enqueue_script(<give_it_a_name>, /url/to/file, [depends on], version, defer? );
//wp_enqueue_style( <give_it_a_name>, /url/to/file, [depends on], version, media );
$previous_css_basename = '';
$previous_js_basename = '';
foreach ($files_arr as $file) {
if ($file->ext === "js") {
if (is_null($this->_first_script))
$this->_first_script = $file->handle;
$depends_on = $this->check_dependencies($file, $previous_js_basename);
if ($depends_on !== null)
wp_enqueue_script( $file->handle, $file->url, $depends_on, $file->version, true);
$previous_js_basename = $file->handle;
}
else if ($file->ext === "css") {
$depends_on = $this->check_dependencies($file, $previous_css_basename);
if ($depends_on !== null)
wp_enqueue_style( $file->handle, $file->url, $depends_on, $file->version, '');
$previous_css_basename = $file->handle;
}
}
}
private function check_dependencies(&$file, $previous_basename)
{
if ($file->ext === "js")
{
global $wp_scripts;
$already_enqueued = array_search($file->handle, $wp_scripts->queue);
if ($already_enqueued !== false)
return null;
}
else if ($file->ext === "css")
{
global $wp_styles;
$already_enqueued = array_search($file->handle, $wp_styles->queue);
if ($already_enqueued !== false)
return null;
}
$depends_on = array();
if (isset($file->depends) && $file->depends !== '')
$depends_on[] = $file->depends;
if (isset($previous_basename) && $previous_basename !== '')
$depends_on[] = $previous_basename;
return $depends_on;
}
/**
* @param string : name of the file, with its path from its extension directory
* - from js/ root for .js files
* - from css/ root for .css files
* @return object / null :
* - null if file is not js or css
* - or an object with all the necessary infos :
* - ext : name.js -> "js"
* - basename : name.js -> "name"
* - handle : name.js -> "name_js"
* - url : url to file in wordpress
* - path : path to file in server
* - version : used to avoid browser caching
* - depends : string if depends on a handle, or ''
*/
private function init_file($key, $file_name) {
$file = (object)[];
$file->ext = pathinfo($file_name, PATHINFO_EXTENSION);
if (! in_array($file->ext, array("js", "css", "html")))
return null;
$file->basename = pathinfo($file_name, PATHINFO_BASENAME);
$file->handle = "PLGNTLS_" . str_replace(".", "_", $file->basename);
$file->url = $this->get_url().$file_name;
$file->path = $this->get_path().$file_name;
$file->version = date("ymd-Gis", filemtime($file->path));
$file->depends = '';
if (is_string($key))
$file->depends = $key;
return $file;
}
}
?>

Submodule private updated: 64c9462106...8b8c17b979