23 Commits

Author SHA1 Message Date
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
32 changed files with 1823 additions and 474 deletions

View File

@@ -8,111 +8,46 @@ Version: 1.1.0
Author URI: Author URI:
*/ */
/* /**
5.5 . 5.48 * it means someone outside wp is accessing the file, in this case kill it.
59 . 58.99 */
50.6 . 50.58 if (!defined('ABSPATH')) {
38.5 . 38.53 die('You can not access this file!');
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
*/
/* /**
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * plugin dir root
plugin dir root */
*/ include_once( plugin_dir_path(__FILE__) . '/utils/plgntls_class.php');
include_once( plugin_dir_path(__FILE__) . '/utils/plugin_tools.php');
PLGNTLS_class::set_root_dir( plugin_dir_path(__FILE__), plugin_dir_url(__FILE__) ); PLGNTLS_class::set_root_dir( plugin_dir_path(__FILE__), plugin_dir_url(__FILE__) );
/* /**
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * general inclusions
inclusions */
*/
include_once(PLGNTLS_class::get_path() . '/php/utils/globals.php'); 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/utils/console_log.php');
//include_once(PLGNTLS_class::get_path() . '/php/images/image_edit_shortcode.php'); //include_once(PLGNTLS_class::get_path() . '/php/images/image_edit_shortcode.php');
//include_once(PLGNTLS_class::get_path() . '/php/images/image-edit.php'); //include_once(PLGNTLS_class::get_path() . '/php/images/image-edit.php');
//include_once(PLGNTLS_class::get_path() . '/php/test_cache.php');
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
plugin shortcode
*/
function fipfcard_main_shortcode()
{
$fipfcard_tools = new PLGNTLS_class(); /**
* test the class PLGNTLS
*/
add_shortcode('fipfcard_plugin', 'fipfcard_test_class_tools');
$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() { function custom_frontend_posting_form() {
$my_image = the_field('image_ratio'); $my_image = the_field('image_ratio');
error_log("my_image"); error_log("my_image");
@@ -121,13 +56,66 @@ function custom_frontend_posting_form() {
} }
add_shortcode('custom_frontend_posting_form', 'custom_frontend_posting_form'); add_shortcode('custom_frontend_posting_form', 'custom_frontend_posting_form');
// function author_shortode_test($field) {
// // global $authordata;
// // $user_id = $authordata->ID;
//
// $author_username = get_query_var('author_name');
// $author = get_user_by('slug', $author_username);
// $user_id = $author->ID;
//
// $acf_field = $field['field'];
// $acf_post_id = "user_{$user_id}";
//
// $acf_shortcode = "[acf field='" . $acf_field . "' post_id='" . $acf_post_id . "']";
//
// error_log("---");
// error_log("acf_shortcode:");
// error_log($acf_shortcode);
// // error_log("get_userdata:");
// // error_log(json_encode(get_userdata($user_id)->data->user_email));
// error_log("get_fields($acf_post_id):");
// error_log(json_encode(get_fields($acf_post_id)));
// error_log("get_field($acf_field, $acf_post_id):");
// error_log(json_encode(get_field($acf_field, $acf_post_id)));
//
// //$shortcode = "[acf field=" . $field['field'] . "]";
// wp_reset_query();
// $acf_return = do_shortcode($acf_shortcode);
// // error_log("acf_return:");
// // error_log(json_encode($acf_return));
// return $acf_return;
// // regarder option repeter de diviengine
// // peutetre plugin gratuit ?
// // plugin menu avec conditions
// }
// add_shortcode('fipf_acf', 'author_shortode_test', 10, 1);
/**
* call to paypal_shortcode_content()
*/
include_once(PLGNTLS_class::get_path() . '/php/paypal/paypal.php');
add_shortcode('fipf_paypal_shortcode', 'fipf_paypal_shortcode_content');
//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]);
// }
//}
/* /*
@@ -250,22 +238,22 @@ $_POST
"form_id":"modif_profile", "form_id":"modif_profile",
"form_type_confirm":"" "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]);
}
}
*/ */
// 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]);
// }
// }
/** /**
@@ -284,63 +272,63 @@ function my_custom_url_handler($query)
* - https://stackoverflow.com/questions/19802492/check-if-current-user-is-administrator-in-wordpress * - https://stackoverflow.com/questions/19802492/check-if-current-user-is-administrator-in-wordpress
* - https://developer.wordpress.org/reference/functions/current_user_can/ * - 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)
function PLGNTLS_my_custom_df_form_handler($form_id, $post_array, $form_type) // {
{ // error_log("in my_custom_df_form_handler");
error_log("in my_custom_df_form_handler"); // error_log("form_id");
error_log("form_id"); // error_log($form_id);
error_log($form_id); // error_log("post_array");
error_log("post_array"); // error_log(json_encode($post_array));
error_log(json_encode($post_array)); // error_log("form_type");
error_log("form_type"); // error_log($form_type);
error_log($form_type); // }
} // add_action ('df_before_process', 'PLGNTLS_my_custom_df_form_handler', 10, 3);
// Hook into the 'acf/save_post' action /**
/* * 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) // 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("in acf/save_post");
{ // if ($_SERVER['REQUEST_METHOD'] === 'POST' )
error_log("_SERVER['REQUEST_URI']"); // {
error_log(json_encode($_SERVER['REQUEST_URI'])); // error_log("_SERVER['REQUEST_URI']");
error_log("_SERVER['QUERY_STRING']"); // error_log(json_encode($_SERVER['REQUEST_URI']));
error_log(json_encode($_SERVER['QUERY_STRING'])); // error_log("_SERVER['QUERY_STRING']");
error_log("_POST['de_fb_ville']"); // error_log(json_encode($_SERVER['QUERY_STRING']));
error_log(json_encode($_POST['de_fb_ville'])); // 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'] !== '/') { // // Check if the request is coming from the specific URL
return; // Exit if the request is not 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) { // // Check if this is an autosave
return; // if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
} // return;
// }
// Check if this is a revision //
if (wp_is_post_revision($post_id)) { // // Check if this is a revision
return; // 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)) { // // Check if the current user has permission to edit the post
return; // 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 // // Your ACF form submission handling logic goes here
if (isset($_POST['your_acf_field_name'])) { // // For example, you can retrieve form data using $_POST and update ACF fields accordingly
$field_value = sanitize_text_field($_POST['your_acf_field_name']); // if (isset($_POST['your_acf_field_name'])) {
update_field('your_acf_field_name', $field_value, $post_id); // $field_value = sanitize_text_field($_POST['your_acf_field_name']);
} // update_field('your_acf_field_name', $field_value, $post_id);
} // }
*/ // }
@@ -349,6 +337,7 @@ function handle_acf_form_submission($post_id)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
menu plugin menu plugin
*/ */
include_once(PLGNTLS_class::get_path() . '/php/menu/example_menu.php');
function fipfcard_plugin_menu() function fipfcard_plugin_menu()
{ {
add_menu_page add_menu_page
@@ -364,28 +353,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

@@ -55,6 +55,10 @@
} }
?> ?>
</ol> </ol>
<p>get_field('user_email') :</p>
<p>
<?php echo $user_email ?>
</p>
<p>i am a new p</p> <p>i am a new p</p>
<p class="first_el_to_change">to change</p> <p class="first_el_to_change">to change</p>

View File

@@ -1,2 +1,5 @@
<input type='text' id='mytext'> <input type='text' id='mytext'>
<button id='mybutton'>send</button> <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,18 +1,4 @@
const inputElement = document.getElementById('mytext');
const sendButton = document.getElementById('mybutton');
sendButton.addEventListener('click', () => { import { test_fetch } from './example_submenu.js';
const inputValue = inputElement.value;
console.log("inputValue:"); test_fetch();
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);
});
});

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 <?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 * WordPress Image Editor
* *

View File

@@ -1,5 +1,12 @@
<?php <?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() function fipfcard_image_editor()
{ {

View File

@@ -1,12 +1,44 @@
<?php <?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() { function fipfcard_plugin_content() {
$fipfcard = new PLGNTLS_class(); $fipfcard = new PLGNTLS_class();
echo $fipfcard->add_to_front( array( echo $fipfcard->add_to_front( array(
"js/menu/example_menu.js", array("js/menu/example_menu.js", 'type'=>'module'),
"js/menu/example_menu_2.js",
"html/menu/example_menu.html", "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,104 @@
<?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');
*/
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;
}
/**
* 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,33 @@
<?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 prevent_page_caching( $headers ) {
error_log("in prevent_page_caching");
if (is_page('test-form-modals')) {
error_log("in test-form-modals");
$headers['Cache-Control'] = 'no-cache, no-store, must-revalidate';
$headers['Pragma'] = 'no-cache';
$headers['Expires'] = '0';
}
return $headers;
}
add_filter( 'nocache_headers', 'prevent_page_caching' );
function add_custom_meta_tags() {
error_log("add_custom_meta_tags");
echo '<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">';
echo '<meta http-equiv="Pragma" content="no-cache">';
echo '<meta http-equiv="Expires" content="0">';
}
add_action('wp_head', 'add_custom_meta_tags');
?>

View File

@@ -0,0 +1,74 @@
<?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_test_class_tools()
{
$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();
$user_email = get_field('user_email', 'MarieM');
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",
"user_email",
"names",
"ages",
)
);
}
?>

View File

@@ -1,5 +1,12 @@
<?php <?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!');
}
/* /*

View File

@@ -1,15 +1,25 @@
<?php <?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/ https://stackify.com/how-to-log-to-console-in-php/
*/ */
function console_log($output) { function console_log(...$outputs) {
if (CONSOLE_OFF) if (FIPFCARD_CONSOLE_OFF)
return; return;
$json_output = json_encode($output, JSON_HEX_TAG); foreach($outputs as $output)
$js_code = '<script>console.log(' . $json_output . ');</script>'; {
echo $js_code; $json_output = json_encode($output, JSON_HEX_TAG);
$js_code = '<script>console.log(' . $json_output . ');</script>';
echo $js_code;
}
} }

View File

@@ -1,5 +1,12 @@
<?php <?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!');
}
/* /*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
@param two arguments : @param two arguments :

View File

@@ -1,5 +1,12 @@
<?php <?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 globals variables
@@ -11,12 +18,38 @@ const CONSOLE_OFF = true;
*/ */
const FIPFCARD_CONSOLE_OFF = false; const FIPFCARD_CONSOLE_OFF = false;
/* a variable that will contain the name of the first script enqueued /**
*/ * a variable that will contain the name of the first script enqueued
*/
$fipfcard_first_script = null; $fipfcard_first_script = null;
/* path to ajax.js file, from root of js dir
*/ /**
* path to ajax.js file, from root of js dir
*/
$fipfcard_ajax_file = "utils/ajax.js"; $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,404 @@
<?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
*
*
* 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(
* 'path/to/style.css' // those files are added to front
* 'path/to/script.js' // in the order you put them
* 'http://my_url.com' // it can be urls
* 'path/to/file.html' // html are just rendered then returned
* ),
* 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;
* )
* );
*
* complete syntax to include js scripts :
*
* key => value
* 1: 'src'
* 2: 'dependence' => 'src'
* 3: array( 'src', 'attr_1' => 'value_1', ... )
* 4: 'dependence' => array( 'src', 'attr_1' => 'value_1', ... )
*
* -> 'src' is required
* -> 'dependence' is optional
* explicit key is always a dependence
* -> value can be a string 'src', or an array('srcs', ...)
* if value is array, first element is 'src' and following
* are attributes for <script> html elements
*
*/
class PLGNTLS_class
{
private static $_root_path;
private static $_root_url;
private $_first_script;
private $_prefix;
private $_js_dependencies;
private $_css_dependencies;
private $_scripts_modules;
private $_scripts_attributes;
/**
*/
public function __construct() {
$this->_prefix = "PLGNTLS";
$this->_first_script = null;
$this->_js_dependencies = array();
$this->_css_dependencies = array();
$this->_scripts_modules = 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);
array_push($this->_scripts_modules, 'PLGNTLS_example_menu_js', 'PLGNTLS_plgntls_fetch_js');
$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 (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_type_module($attr), 10, 1 );
/*
* uncomment to print all enqueued scripts, can be usefull
global $wp_scripts;
error_log("wp_scripts->queue:");
error_log(json_encode($wp_scripts->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) {
$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_type_module($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 ($script->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'
*/
private function init_src($key, $value) {
if (empty($value))
return null;
$src = (object)[];
// 0. src
// 8. attr
if (is_array($value)){
$src->src = array_shift($value);
$src->attr = $value;
}
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));
}
// 7. depends
$src->depends = '';
if (is_string($key))
$src->depends = $key;
// also add to global variable to access in 'wp_script_attributes' filter
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

@@ -3,18 +3,115 @@
* - PLGNTLS_data.ajax_nonce and PLGNTLS_data.ajax_url * - PLGNTLS_data.ajax_nonce and PLGNTLS_data.ajax_url
* are passed from the class PLGNTLS_class * are passed from the class PLGNTLS_class
*/ */
/*
// OLD VERSION
console.log("PLGNTLS_data"); console.log("PLGNTLS_data");
console.log(PLGNTLS_data); console.log(PLGNTLS_data);
function PLGNTLS_ajax(data_obj, action) { */
function PLGNTLS_ajax(action, data_obj) {
const data = new FormData(); const data = new FormData();
data.append("action", action); data.append("action", action);
data.append("_ajax_nonce", PLGNTLS_data.ajax_nonce); data.append("_ajax_nonce", PLGNTLS_data.ajax_nonce);
for (const key in data_obj) // for (const key in data_obj)
data.append(key, data_obj[key]); // {
// data.append(key, data_obj[key]);
// }
// console.log("data:", data);
data.append(data_obj);
return fetch(PLGNTLS_data.ajax_url, { return fetch(PLGNTLS_data.ajax_url, {
method: "POST", method: "POST",
credentials: "same-origin", credentials: "same-origin",
body: data hedears: {"Content-Type": "application/json"},
body: JSON.stringify(data),
}); });
} }
// https://stackoverflow.com/q/52657814/9497573
function is_plain_object(obj)
{
if (!obj)
return false;
if (obj.constructor !== Object)
return false;
if (Object.getPrototypeOf(obj) !== Object.prototype)
return false;
return true;
}
/*
function PLGNTLS_fetch(src = null, options = null)
{
if (src === null)
return null;
if (options === null)
{
const data = new FormData();
data.append('action', src);
data.append('_ajax_nonce', PLGNTLS_data.ajax_nonce);
options = {
method: 'POST',
credentials: 'same-origin',
body: data,
};
}
else if (is_plain_object(options))
{
// check for method, default POST
if (!Object.hasOwn(options, 'method'))
options.method = 'POST';
// check for credentials, default same-origin
if (!Object.hasOwn(options, 'credentials'))
options.credentials = 'same-origin';
// check for body, default contains action and nonce
if (!Object.hasOwn(options, 'body'))
options.body = new FormData();
// add action and nonce in options.body
if (options.body instanceof FormData)
{
// dont check if action and nonce already exist, need new anyway
options.body.set('action', src);
options.body.set('_ajax_nonce', PLGNTLS_data.ajax_nonce);
}
else
{
// should think a better strategy : https://stackoverflow.com/q/20295080/9497573
// const data = {};
// if (is_plain_object(options.body))
// {
// for (const key in options.body)
// data[key] = options.body[key];
// }
// else
// data.data = options.body;
// data.action = src;
// data._ajax_nonce = PLGNTLS_data.ajax_nonce;
// options.body = JSON.stringify(data);
// cannot work if fetch use :
// headers: {"Content-Type": "application/json"},
const data = new FormData( );
data.append( 'action', src );
data.append( '_ajax_nonce', PLGNTLS_data.ajax_nonce );
if ( is_plain_object( options.body ) )
{
for ( const key in options.body )
data.append( key, JSON.stringify(options.body[key]) );
}
// is string : https://stackoverflow.com/q/4059147/9497573
else if ( typeof options.body === 'string' || options.body instanceof String )
data.append( 'data', options.body );
else
data.append('data', JSON.stringify(options.body));
options.body = data;
}
}
else
throw new Error('options not plain object or formData');
return fetch(PLGNTLS_data.ajax_url, options);
}
*/

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...987b3a522f