changed plugin name to cipf

This commit is contained in:
asus
2024-03-07 22:35:39 +01:00
parent be79310404
commit 9b5e44dfd3
45 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,82 @@
<?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!');
}
/*
* menu plugin
*/
function cipfcard_plugin_menu()
{
add_menu_page
(
'cipf_card', // webpage title
'cipf_card', // menu title
'manage_options', // capability
'cipfcard-plugin', // menu_slug
'cipfcard_plugin_content' // callback function to display page content
);
}
add_action('admin_menu', 'cipfcard_plugin_menu');
/**
* 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 cipfcard_plugin_content() {
$cipfcard = new PLGNTLS_class();
$my_css = '
#mytext {
background-color: lightblue;
}
#mytext_2 {
background-color: lightgreen;
}
';
echo $cipfcard->add_to_front( array(
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 cipfcard_menu_fetch_handler()
{
return new WP_REST_Response('hello', 200);
}
function cipfcard_menu_endpoint()
{
register_rest_route('plgntls', '/get_data', array(
'methods' => 'POST',
'callback' => 'cipfcard_menu_fetch_handler',
));
};
add_action('rest_api_init', 'cipfcard_menu_endpoint');
?>

View File

@@ -0,0 +1,40 @@
<?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 restrict_author_page_CIPF() {
if (!is_author())
return;
$can_access = false;
if (current_user_can('administrator')) {
$can_access = true;
}
else if (current_user_can('editor')) {
$can_access = true;
}
if ($can_access === true)
return;
$author_id = get_the_author_meta( 'ID' );
$current_user_id = get_current_user_id();
if ($current_user_id != $author_id) {
wp_redirect(home_url(), 301);
exit;
}
}
add_action('template_redirect', 'restrict_author_page_CIPF', 10);
?>

View File

@@ -0,0 +1,135 @@
<?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!');
}
/*
* callback to provide the user info corresponding to the $$key_word$$
*
*/
function replace_words_CIPF($matches, $user_id = null) {
if ($user_id !== null) {
$current_user = get_user_by('id', $user_id);
}
else if (is_user_logged_in()) {
$current_user = wp_get_current_user();
}
else {
return "";
}
if ($current_user === false)
return "";
$query = $matches[1];
$result = $current_user->$query;
/*
* if result is array, take the first element (not ideal)
*
*/
if (is_array($result))
$result = reset($result);
/*
* if is special query __author_page__
* return author page url
*
*/
if ($query === '__author_page__') {
$current_user_id = get_current_user_id();
$result = get_author_posts_url($current_user_id);
}
/*
* if no match, return $$<query>$$
*
*/
if (empty($result))
return $matches[0];
return $result;
}
/*
* filter emails in the form-builder hook, before the wp_mail hook
* it receives the id of the user, no need to have the user still logged-in
*
*/
function filter_email_fb_CIPF($reply_body, $post_array) {
$id = $post_array['ID'];
// pattern : anything surrounded by '$$', ex : $$value$$
$pattern = '/\$\$(.*?)\$\$/';
// inline callback, with 'use' to get the id
$new_body = preg_replace_callback($pattern, function($matches) use ($id) {
return replace_words_CIPF($matches, $id);
}, $reply_body);
return $new_body;
}
add_filter('df_confirmation_body', 'filter_email_fb_CIPF', 10, 2); // the receive an email
add_filter('df_notification_body', 'filter_email_fb_CIPF', 10, 2); // the administrator receive a notification
/*
* filter emails at the final point : the wp_mail hook
* it uses a callback that rely on the logged-in user
* it will works well most of the time, but it's possible
* that a user logged out before the email is sent
* or event that a different user has already logged in
*/
function filter_email_wp_CIPF($args) {
// pattern : anything surrounded by '$$', ex : $$value$$
$pattern = '/\$\$(.*?)\$\$/';
$old_body = $args['message'];
$new_body = preg_replace_callback($pattern, 'replace_words_CIPF', $old_body);
$args['message'] = $new_body;
return $args;
}
add_filter('wp_mail', 'filter_email_wp_CIPF', 10, 1);
/*
all filters in form_builder :
1 $body = apply_filters( 'df_notification_body', $body, $post_array );
2 $email = apply_filters( 'df_notifcation_recipient', $email, $form_id, $post_array );
3 $title = apply_filters( 'wpml_translate_single_string', $title_get, 'divi-form-builder', 'Edit Post Button Title Text' );
4 $body = apply_filters( 'df_contact_body', $body, $post_array );
5 $body = apply_filters( 'df_contact_body', $body, $post_array );
6 $email = apply_filters( 'df_contact_recipient', $email, $form_id, $post_array );
7 $email = apply_filters( 'df_contact_recipient', $email, $form_id, $processed_post_array );
8 $reply_body = apply_filters( 'df_confirmation_body', $reply_body, $post_array );
9 $reply_body = apply_filters( 'df_confirmation_body', $reply_body, $post_array );
10 $reply_body = apply_filters( 'df_confirmation_body', $reply_body, $post_array );
11 $reply_body = apply_filters( 'df_confirmation_body', $reply_body, $post_array );
12 $message_content = apply_filters( 'the_content', get_post_field( 'post_content', $message_array['layout'] ) );
13 $content = apply_filters( 'the_content', get_post_field( 'post_content', $message_array['layout'] ) );
14 $content = apply_filters( 'the_content', get_post_field( 'post_content', $html_content_divi_layout) );
*/
?>

View File

@@ -0,0 +1,23 @@
<?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 test_modal_PLGNTLS() {
$cipf_modal = new PLGNTLS_class();
$cipf_modal->add_to_front(
array(
'js/form_builder_patch/multiple_modals.js',
));
}
add_shortcode('test_modal', 'test_modal_PLGNTLS');
?>

View File

@@ -0,0 +1,31 @@
<?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!');
}
/**
* in `wp-content/plugins/divi-form-builder/includes/DiviFormBuilder.php`
* also :
* - Undefined variable: min_length in /var/www/html/wp-content/plugins/divi-form-builder/includes/modules/FormField/FormField.php on line 5933
* - Undefined variable: use_icon in /var/www/html/wp-content/plugins/divi-form-builder/includes/modules/FormField/FormField.php on line 5984
*/
function add_my_jquery_patch()
{
$handle = 'jquery_validator_url_patch';
$url = PLGNTLS_class::get_url() . 'js/form_builder_patch/url_validation.js';
$dependencies = array('de_fb_validate');
$version = '';
$defer = true;
wp_enqueue_script( $handle, $url, $dependencies, $version, $defer);
}
add_action('wp_enqueue_scripts', 'add_my_jquery_patch');
?>

View File

@@ -0,0 +1,25 @@
<?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!');
}
/*
* hide admin bar if access a front page and is not an admin
*/
function hide_admin_bar_CIPF() {
if (!current_user_can('administrator') && !is_admin()) {
show_admin_bar(false);
}
}
add_action('after_setup_theme', 'hide_admin_bar_CIPF');
?>

View File

@@ -0,0 +1,34 @@
<?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!');
}
?>
<?php acf_form_head(); ?>
<?php get_header(); ?>
<div id="primary">
<div id="content" role="main">
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<p>My custom field: <?php the_field('my_custom_field'); ?></p>
<?php acf_form(); ?>
<?php endwhile; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,89 @@
<?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 cipfcard_image_editor()
{
// ob_start();
// wp_image_editor('33545');
// return ob_get_clean();
$cipfcard_image_editor = new PLGNTLS_class();
return $cipfcard_image_editor->add_to_front(
array(
"js/image_editor.js",
"html/image_editor.html",
)
);
// if ( ! has_action( "wp_ajax_{$action}" ) ) {
// it returns error 400
}
add_shortcode('cipfcard_image_editor', 'cipfcard_image_editor');
*/
/**
* Handles image editing via AJAX.
* from wp-admin/includes/ajax-action.php
*/
/*
function wp_ajax_image_editor() {
$attachment_id = (int) $_POST['postid'];
// $attachment_id = 33555;
// if ( empty( $attachment_id ) || ! current_user_can( 'edit_post', $attachment_id ) ) {
// wp_die( -1 );
// }
// check_ajax_referer( "image_editor-$attachment_id" );
// require_once ABSPATH . 'wp-admin/includes/image-edit.php';
$msg = false;
switch ( $_POST['do'] ) {
case 'save':
$msg = wp_save_image( $attachment_id );
if ( ! empty( $msg->error ) ) {
wp_send_json_error( $msg );
}
wp_send_json_success( $msg );
break;
case 'scale':
$msg = wp_save_image( $attachment_id );
break;
case 'restore':
$msg = wp_restore_image( $attachment_id );
break;
}
ob_start();
wp_image_editor( $attachment_id, $msg );
$html = ob_get_clean();
if ( ! empty( $msg->error ) ) {
wp_send_json_error(
array(
'message' => $msg,
'html' => $html,
)
);
}
wp_send_json_success(
array(
'message' => $msg,
'html' => $html,
)
);
}
add_action( 'wp_ajax_image_editor', 'wp_ajax_image_editor' );
*/
?>

View File

@@ -0,0 +1,43 @@
<?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!');
}
/*
* menu deconnexion
* 1. il faut creer un menu personalisé dans Apparence > Menus
* 2. dans le code ci-dessous, changer la valeur de $menu_title pour correspondre au titre du menu
* 3. et si besoin changer la valeur de $menu_redirect pour choisir la page de redirection :
* - si laissée vide, la redirection se fera sur la page de connexion de wordpress
* - avec $current_url la redirection se fera sur la page actuelle
* - avec $base_url on redirige vers la page d'accueil du site (l'url sans chemin supplementaire)
* cette variable $base_url peut etre utilisee pour construire une autre url :
* - $menu_redirect = $base_url -> https://le_site_actuel.com/
* - $menu_redirect = $base_url . 'contact' -> https://le_site_actuel.com/contact
* - $menu_redirect = $current_url -> https://le_site_actuel.com/la_meme_page
* - $menu_redirect = 'www.un_autre_site.net/contact' -> https://www.un_autre_site.net/contact
*/
function change_menu_logout($items){
$menu_title = 'special logout';
// quelques urls utiles :
$base_url = home_url();
$current_url = home_url( $_SERVER['REQUEST_URI'] );
$menu_redirect = '';
foreach($items as $item){
if( $item->title === $menu_title){
$item->url = wp_nonce_url( wp_logout_url( $menu_redirect ), 'log-out' );
}
}
return $items;
}
add_filter('wp_nav_menu_objects', 'change_menu_logout');
?>

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!');
}
include_once(PLGNTLS_class::get_path() . '/php/utils/http_errors.php');
include_once(PLGNTLS_class::get_path() . '/php/paypal/route_api_utils.php');
include_once(PLGNTLS_class::get_path() . '/php/paypal/user_can_pay.php');
include_once(PLGNTLS_class::get_path() . '/php/paypal/update_user_payment.php');
include_once(PLGNTLS_class::get_path() . '/php/paypal/shortcode.php');
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');
include_once(PLGNTLS_class::get_path() . '/php/paypal/routes.php');
?>

View File

@@ -0,0 +1,108 @@
<?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 handle_orders_request_CIPF($request_data) {
try {
// Extract cart information from request body
//$cart = $request_data['cart'];
$can_pay = can_pay_now_CIPF();
if ($can_pay['success'] === false)
throw new HttpErrorException($can_pay['message'], 403);
// Process the order and get the response
//$order_response = create_order_CIPF($cart);
$order_response = create_order_CIPF();
$json_response = $order_response['json_response'];
$http_status_code = $order_response['http_status_code'];
update_user_payment_CIPF($json_response, 'start');
// Return response
return new WP_REST_Response($json_response, $http_status_code);
}
catch (HttpErrorException $error) {
$status_code = $error->getStatusCode();
return new WP_Error($status_code, 'Failed to create order in server :' . $error->getMessage(), array('status' => $status_code));
}
catch (Exception $error) {
return new WP_Error('500', 'Failed to create order in server :' . $error->getMessage(), array('status' => 500));
}
}
/**
* Create an order to start the transaction.
* @see https://developer.paypal.com/docs/api/orders/v2/#orders_create
*/
//function create_order_CIPF($cart)
function create_order_CIPF()
{
// use the cart information passed from the front-end to calculate the purchase unit details
$access_token = generate_access_token_CIPF();
$user_id = get_current_user_id();
$acf_id = 'user_' . $user_id;
$price = get_field('somme_a_regler', $acf_id);
$url = PAYPAL_API_BASE_URL . '/v2/checkout/orders';
$payload = array(
'intent' => "CAPTURE",
'note' => 'ERRPYO005',
'purchase_units' => array(
array(
'amount' => array(
'currency_code' => "EUR",
'value' => $price,
),
),
),
);
$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 handle_response_CIPF($response);
};
?>

View File

@@ -0,0 +1,73 @@
<?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 handle_orders_capture_request_CIPF($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 = capture_order_CIPF($order_id);
$http_status_code = $response_data['http_status_code'];
$json_response = $response_data['json_response'];
update_user_payment_CIPF($json_response, 'end');
return new WP_REST_Response($json_response, $http_status_code);
}
catch (Exception $e) {
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 capture_order_CIPF($orderID) {
$access_token = generate_access_token_CIPF();
$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 handle_response_CIPF($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 handle_response_CIPF($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 generate_access_token_CIPF()
{
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,31 @@
<?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!');
}
// handling routes and endpoints
// diff routes and endpoints : https://stackoverflow.com/q/56075017/9497573
function routes_endpoints_CIPF()
{
$base_rest_route = "cipf_plugin/api/v1";
register_rest_route($base_rest_route, '/orders', array(
'methods' => 'POST',
'callback' => 'handle_orders_request_CIPF',
));
register_rest_route($base_rest_route, '/orders/(?P<orderID>[a-zA-Z0-9]+)/capture', array(
'methods' => 'POST',
'callback' => 'handle_orders_capture_request_CIPF',
));
};
add_action('rest_api_init', 'routes_endpoints_CIPF');
?>

View File

@@ -0,0 +1,59 @@
<?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!');
}
/**
* call to paypal_shortcode_content()
*/
function paypal_shortcode_content_CIPF()
{
// if (!can_pay_now_CIPF())
// return no_payment_CIPF();
$cipfcard_paypal = new PLGNTLS_class();
$pp_client_id = PAYPAL_CLIENT_ID;
$pp_sdk_currency = "EUR";
$pp_sdk_base_url = "https://www.paypal.com";
$pp_sdk_url = "{$pp_sdk_base_url}/sdk/js?client-id={$pp_client_id}&currency={$pp_sdk_currency}";
$paypal_redirection_success = PAYPAL_REDIRECTION_SUCCESS;
$paypal_redirection_failure = PAYPAL_REDIRECTION_FAILURE;
$paypal_message_success = PAYPAL_MESSAGE_SUCCESS;
$paypal_message_failure = PAYPAL_MESSAGE_FAILURE;
$added_to_front = $cipfcard_paypal->add_to_front(
array(
$pp_sdk_url,
array("js/paypal/paypal.js", 'type'=>'module'),
"html/paypal/paypal.html",
),
compact (
'paypal_redirection_success',
'paypal_redirection_failure',
'paypal_message_success',
'paypal_message_failure',
),
);
return $added_to_front;
}
add_shortcode('cipf_paypal_shortcode', 'paypal_shortcode_content_CIPF');
function no_payment_CIPF() {
return;
}
?>

View File

@@ -0,0 +1,221 @@
<?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', 'cipf_order_id', 'aaaaaa');
* ['aaaaaa']
* add_user_meta('user_id', 'cipf_order_id', 'bbbbbb');
* ['aaaaaa', 'bbbbbb']
* add_user_meta('user_id', 'cipf_order_id', 'bbbbbb');
* ['aaaaaa', 'bbbbbb', 'bbbbbb']
* get_user_meta('user_id', 'cipf_order_id');
* ['aaaaaa', 'bbbbbb', 'bbbbbb']
* $del_ret = delete_user_meta('user_id', 'cipf_order_id', 'bbbbbb');
* ['aaaaaa'] - $del_ret === true
* $del_ret = delete_user_meta('user_id', 'cipf_order_id', 'bbbbbb');
* ['aaaaaa'] - $del_ret === false
*
* 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
*
*/
function update_user_payment_CIPF($message, $step) {
$order_id = $message->id;
$user_id = get_current_user_id();
$status = $message->status;
// addind order_id to cipf_order_id meta field
// it can duplicate, it's not a problem : delete_user_meta will delete all
add_user_meta($user_id, 'cipf_order_id', $order_id);
// add a schedule event to delete this order_id
schedule_delete_orderid_CIPF($user_id, $order_id);
/*
* create a meta field to check states of payements on prof author page :
* - 'started' -> payement started | at order creation (if seen on author page, it means failure)
* - 'success' -> success payement | at order success (on author page, it means success, then empty it)
* - '' -> no message to output | on author page (after set to empty on author page)
*
*/
delete_user_meta($user_id, 'cipf_payement_status');
add_user_meta($user_id, 'cipf_payement_status', 'started');
// 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 = delete_order_id_on_success_CIPF($user_id, $order_id);
// change payement status to success
update_user_meta($user_id_to_update, 'cipf_payement_status', 'success');
// proceed to validate payment for user
validate_payment_for_user_CIPF($user_id_to_update, $order_id);
}
}
/*
* const CARD_IS_VALID : acf field 'true false' [carte_est_valide](validite)
* const CARD_DATE_PURCHASE : acf field 'date picker' [date_d_achat](achat)
* const CARD_DATE_VALIDITY : acf field 'date picker' [date_fin_validite](echance)
*
* - change CARD_IS_VALID to true
* - change CARD_DATE_PURCHASE to now
* - change CARD_DATE_VALIDITY to previous value + 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 validate_payment_for_user_CIPF($user_id, $order_id) {
$acf_card_state = PLGNTLS_class::ACF_CARD_STATE;
$acf_card_expiration = PLGNTLS_class::ACF_CARD_EXPIRATION;
$card_duration = PLGNTLS_class::CARD_VALIDITY_TIME;
$prof_is_activ = PLGNTLS_class::ACF_PROF_IS_ACTIV;
$acf_date_format = 'Y-m-d H:i:s';
$acf_id = 'user_'.$user_id;
/*
* update card validity to true
*
*/
update_field($acf_card_state, 'Renouvellement', $acf_id);
$date_now = date_create('today');
/*
* update purchase date to now
*
update_field(CARD_DATE_PURCHASE, $date_now, $acf_id);
*/
/*
* get current date limit
* if no date, use now
* if paste date, use now
*
*/
$current_date_limit_object = get_field_object($acf_card_expiration, $acf_id);
if ($current_date_limit_object === false) {
$current_date_limit = $date_now;
}
else if (empty($current_date_limit_object['value'])) {
$current_date_limit = $date_now;
}
else
{
$current_date_limit_string = $current_date_limit_object['value'];
$current_format_field = $current_date_limit_object['return_format'];
// 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 alike)
$current_date_limit = date_create_from_format($current_format_field, $current_date_limit_string);
$date_diff = date_diff($date_now, $current_date_limit);
$date_is_in_past = $date_diff->format('%R%a') < 0;
if ($date_is_in_past)
$current_date_limit = $date_now;
}
/*
* update date limit validity to add 1 year
*
*/
$date_plus_one_year = $current_date_limit->add(date_interval_create_from_date_string('+'.$card_duration));
update_field($acf_card_expiration, $date_plus_one_year->format($acf_date_format), $acf_id);
/*
* change user profil to active
*
*/
update_field($prof_is_activ, 'Actif', $acf_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 schedule_delete_orderid_CIPF($user_id, $order_id)
{
$delay = time() + MINUTE_IN_SECONDS;
wp_schedule_single_event($delay, 'orderid_deletion_event_CIPF', 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 delete_order_id_later_CIPF($user_id, $order_id)
{
delete_user_meta($user_id, 'cipf_order_id', $order_id);
}
add_action('orderid_deletion_event_CIPF', 'delete_order_id_later_CIPF', 5, 2);
/*
* @return mixed num - user_id
* bool false - if no match found
*
*/
function delete_order_id_on_success_CIPF($current_user_id, $order_id)
{
$del_ret = delete_user_meta($current_user_id, 'cipf_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, 'cipf_order_id', $order_id);
if ($del_ret === true)
return $user_id;
}
return false;
}
?>

View File

@@ -0,0 +1,95 @@
<?php
/*
* can pay in certain conditions
* default true
*/
function can_pay_now_CIPF() {
$acf_card_state = PLGNTLS_class::ACF_CARD_STATE;
$acf_card_payment_method = PLGNTLS_class::ACF_CARD_PAYMENT_METHOD;
$acf_card_price_choice = PLGNTLS_class::ACF_CARD_PRICE_CHOICE;
$acf_card_price_delivery = PLGNTLS_class::ACF_CARD_PRICE_DELIVERY;
$acf_card_price_total = PLGNTLS_class::ACF_CARD_PRICE_TOTAL;
$acf_card_expiration = PLGNTLS_class::ACF_CARD_EXPIRATION;
$card_renew_period = PLGNTLS_class::CARD_RENEW_PERIOD;
$current_user = wp_get_current_user();
$user_id = get_current_user_id();
$acf_id = 'user_' . $user_id;
/*
* check if payment is virement or immediat
*
$payement = get_field($acf_card_payment_method, $acf_id);
if (strtolower($payement) === 'virement') {
return false;
}
*/
/*
* calculate price
* update the price even if form builder already did it
* in case it was changed from admin pannel
*
*/
$tarif = (int)get_field($acf_card_price_choice, $acf_id);
$livraison = (int)get_field($acf_card_price_delivery, $acf_id);
$price = $tarif + $livraison;
update_field($acf_card_price_total, $price, $acf_id);
/*
* price is not empty or 0
*
*/
$price = get_field($acf_card_price_total, $acf_id);
if (empty($price)) {
return array('success' => false, 'message' => "error: no price selected");
}
if ($price === 0) {
return array('success' => false, 'message' => "error: price is 0, nothing to purchase");
}
/*
* date validity is empty
* or is paste
* or is less than 1 month
*
*/
$validity_field = get_field_object($acf_card_expiration, $acf_id);
if ($validity_field === false)
return array('success' => true);
$validity = $validity_field['value'];
$format_field = $validity_field['return_format'];
if (empty($validity))
return array('success' => true);
$date_validity = date_create_from_format($format_field, $validity);
$date_now = date_create('today');
$diff = date_diff($date_now, $date_validity)->format('%R%a');
if ((int)$diff <= 0) {
// date end of validity in the past
return array('success' => true);
}
else if ((int)$diff <= $card_renew_period) {
// date expiration is in less that renew period time (ex: 30 days)
return array('success' => true);
}
else {
// date end of validity is in more than renew perdio (ex: 3 month)
return array('success' => false, 'message' => "error: it's too soon to renew your card");
}
return array('success' => true);
}
?>

View File

@@ -0,0 +1,123 @@
<?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 handle_prof_is_activ_CIPF($author_id) {
$acf_prof_is_activ = PLGNTLS_class::ACF_PROF_IS_ACTIV;
$slug_wait_activation = PLGNTLS_class::SLUG_PROF_INACTIV;
$acf_id = 'user_' . $author_id;
/*
* if prof is activ, do nothing more
*
*/
$is_activ = get_field($acf_prof_is_activ, $acf_id);
if ($is_activ === 'Actif')
return;
/*
* else if prof inactiv
* if is admin or other allowed roles, see the page anyway
* no need to handle allowed roles, it's already
* taken care by author_restriction.php
*
*/
$user_id = get_current_user_id();
if ($user_id !== $author_id)
return;
/*
* if prof is activ
* redirect to waiting page
*
*/
$redirection_prof_inactiv = home_url() . '/' . $slug_wait_activation;
wp_redirect($redirection_prof_inactiv, 301);
exit;
}
/*
* check meta field 'cipf_payement_status'
* if field value is 'success'
* - hide block 'failure'
* - and update field to '', so it will not show next time
* if field value is 'started'
* - hide bloc success
* (we assume it means the order didn't go well)
* (it does not really makes sens, but ok for the moment)
* if field value is ''
* - hide both 'success' and 'failure' blocs
*
* .cipf_prof_paiement_message -> on row, added display none in page css
* #cipf_prof_paiement_reussi -> on row
* #cipf_prof_paiement_echoue -> on row
*
*/
function show_prof_paiement_messages_CIPF($user_id) {
/*
* if prof is inactive, do nothing more
*
*/
$acf_prof_is_activ = PLGNTLS_class::ACF_PROF_IS_ACTIV;
$acf_id = 'user_' . $user_id;
$is_activ = get_field($acf_prof_is_activ, $acf_id);
if (is_null($is_activ) || empty($is_activ))
return;
if ($is_activ === 'Inactif')
return;
$cipf_prof_payement = new PLGNTLS_class();
$payement_status2 = get_user_meta($user_id, 'cipf_payement_status');
$payement_status = get_user_meta($user_id, 'cipf_payement_status', true);
if ($payement_status === 'success') {
$cipf_prof_payement->add_to_front(array(
array( 'css' => '#cipf_prof_paiement_reussi {display: block;}' )
));
}
else if ($payement_status === 'started') {
$cipf_prof_payement->add_to_front(array(
array( 'css' => '#cipf_prof_paiement_echoue {display: block;}' )
));
}
update_user_meta($user_id, 'cipf_payement_status', '');
}
/*
* series of check to do before printing a prof author page
*
*/
function check_prof_page_CIPF() {
// is an author page
if (!is_author())
return;
// the way to find the id of the author of an author_page
$author_id = get_queried_object_id();
handle_prof_is_activ_CIPF($author_id);
show_prof_paiement_messages_CIPF($author_id);
}
add_action('template_redirect', 'check_prof_page_CIPF', 11);
?>

View File

@@ -0,0 +1,52 @@
<?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!');
}
/*
* redirect users to profil
* if prof -> author page
* if partenaire -> post page || home page
*/
function redirection_page_CIPF(){
if (!is_page(PROF_PARTENAIRE_REDIRECTION_PAGE))
return;
$base_url = home_url();
$current_user_id = get_current_user_id();
if (!is_user_logged_in()) {
wp_redirect($base_url, 301);
}
if (current_user_can('professeur__professeure')) {
$user_page = get_author_posts_url($current_user_id);
wp_redirect($user_page, 301);
}
else if (current_user_can('partenaire')) {
$args = array(
'post_type' => 'post',
'author' => $current_user_id,
'posts_per_page' => 1,
);
$posts = get_posts($args);
if (empty($posts))
$redirect_url = $base_url;
else {
$query = reset($posts);
$post_id = $query->ID;
$redirect_url = get_permalink($query->ID);
}
wp_redirect($redirect_url, 301);
}
exit;
}
add_action('template_redirect', 'redirection_page_CIPF');
?>

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!');
}
/*
* at registration, add role 'partenaire' when page url has path 'creation-du-compte-partenaire'
*/
function add_partenaires_PLGNTLS($customer_data){
$current_url = $_SERVER['HTTP_REFERER']; // not reliable to use referer, TODO: find another solution
$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

@@ -0,0 +1,78 @@
<?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!');
}
/*
* prevent users to fill the renew form if
* they are not prof and logged in,
* and if there card is not in renewable state
* except admins and editor
*
*/
function renew_page_restrictions_CIPF(){
$slug_renew_card = PLGNTLS_class::SLUG_RENEW_CARD;
if (!is_page($slug_renew_card))
return;
if (!is_user_logged_in()) {
wp_redirect($base_url, 301);
}
$base_url = home_url();
$current_user_id = get_current_user_id();
/*
if (current_user_can('professeur__professeure')) {
$user_page = get_author_posts_url($current_user_id);
wp_redirect($user_page, 301);
}
else if (current_user_can('partenaire')) {
$args = array(
'post_type' => 'post',
'author' => $current_user_id,
'posts_per_page' => 1,
);
$posts = get_posts($args);
if (empty($posts))
$redirect_url = $base_url;
else {
$query = reset($posts);
$post_id = $query->ID;
$redirect_url = get_permalink($query->ID);
}
wp_redirect($redirect_url, 301);
}
exit;
*/
}
add_action('template_redirect', 'renew_page_restrictions_CIPF');
function renew_page_filter_message_CIPF(){
$slug_renew_card = PLGNTLS_class::SLUG_RENEW_CARD;
if (!is_page($slug_renew_card))
return;
$cipf_renew = new PLGNTLS_class();
$cipf_prof_payement->add_to_front(array(
array( 'css' => '#cipf_prof_paiement_reussi {display: block;}' )
));
}
add_action('wp_enqueue_scripts', 'renew_page_filter_message_CIPF');
?>

View File

@@ -0,0 +1,24 @@
<?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 reset_some_fields_CIPF($form_id, $user_id, $post_array) {
*/
function reset_some_fields_CIPF() {
$user_id = get_current_user_id();
update_field('cgv', array(""), 'user_'.$user_id);
update_field('paiement', array(""), 'user_'.$user_id);
update_field('livraison', array(""), 'user_'.$user_id);
}
add_action('df_after_insert_user', 'reset_some_fields_CIPF');
?>

View File

@@ -0,0 +1,221 @@
<?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 extract_if_array_size_one_CIPF($value) {
if (is_array($value) && count($value) === 1)
return reset($value);
return $value;
}
function merge_two_arrays_CIPF($array1, $array2) {
$new_array = $array1;
foreach ($array2 as $key2 => $value2) {
$value = extract_if_array_size_one_CIPF($value2);
// if key was not in first array, add the new element to it
if (!isset($new_array[$key2])) {
$new_array[$key2] = $value2;
continue;
}
// if key was in first array, add both in an array
$value1 = extract_if_array_size_one_CIPF($new_array[$key2]);
if (empty($value1))
$new_array[$key2] = $value2;
else if (empty($value2))
$new_array[$key2] = $value1;
else {
$new_value = array($value1, $value2);
$new_array[$key] = $new_value;
}
}
return $new_array;
}
function output_list_front_CIPF($array) {
$output = '<ul>';
foreach ($array as $key => $value) {
if (str_starts_with($key, '_'))
continue ;
$output .= '<li>';
$output .= '<span>';
$output .= $key;
$output .= ' : ';
if (is_array($value) && count($value) === 1)
$output .= json_encode($value[0]);
else
$output .= json_encode($value);
$output .= '</span>';
$output .= '</li>';
}
$output .= '</ul>';
return $output;
}
function format_user_info_CIPF($output, $query, &$current_user, $user_id) {
$output_date_format = PLGNTLS_class::USER_INFO_DATE_FORMAT;
$is_acf = false;
$is_date = false;
/*
* check if it's an acf field
* first method : check if _field exist
*
$_acf_field = '_'.$query;
$acf_field = $current_user->$_acf_field;
if (!empty($acf_field))
$is_acf = true;
*/
/*
* check if it's an acf field, and a date
* second method : check what get_field_object() returns
*
*/
$acf_id = 'user_'.$user_id;
$acf_object = get_field_object($query, $acf_id);
if ($acf_object !== false)
$is_acf = true;
/*
* check if is date
*
*/
if ($is_acf) {
$acf_type = $acf_object['type'];
if ($acf_type && $acf_type === "date_picker")
$is_date = true;
}
/*
* if is date, transform format
*
*/
if ($is_date) {
$acf_date_string = $acf_object['value'];
$acf_date_format = $acf_object['return_format'];
$date = date_create_from_format($acf_date_format, $acf_date_string);
$output = $date->format($output_date_format);
}
/*
* return the result
*
*/
if (is_string($output))
return $output;
else
return json_encode($output);
}
/*
* shortcode to write user info of post author
* 0 or 1 argument, usage :
* - [cipf_user_info] -> list of all availables infos
* - [cipf_user_info user_email] -> display the email
* - [cipf_user_info user_email user_login] -> display the email
* - [cipf_user_info user_email author='logged_in'] -> display the email of the connected user
* - [cipf_user_info user_email author='post_creator'] -> display the email of the creator of the page/post
*
*/
function current_user_infos_CIPF($atts) {
if (!is_user_logged_in())
return ;
/*
* choose the default id target : logged in user, or post creator ?
*
$author_is = 'logged_in'; // logged in user
*/
$author_is = 'post_creator'; // creator of post (also for author pages)
/*
* has parameter 'author' ?
* if yes, removes it from $atts
*
*/
if (is_array($atts)) {
if (isset($atts['author'])) {
$author_is = $atts['author'];
unset($atts['author']);
}
}
/*
* should output all or a specific parameter ?
*
*/
$output_all = false;
if (empty($atts))
$output_all = true;
else if (count($atts) === 0)
$output_all = true;
/*
* get author id outside loop and outside singular page : https://wordpress.stackexchange.com/q/65548
*
*/
if ($author_is === 'logged_in') {
$current_user = wp_get_current_user();
$user_id = get_current_user_id();
}
else {
if (is_author()) {
$user_id = get_queried_object_id();
}
else if (in_the_loop()) {
$user_id = get_the_author_meta('ID');
}
else if (is_singular()) {
$user_id = get_queried_object()->post_author;
}
else {
global $wp_query;
if (!empty($wp_query->posts))
$user_id = $wp_query->posts[0]->post_author;
}
//$current_user = new WP_User($user_id);
$current_user = get_user_by('id', $user_id);
}
/*
* output all the available parameters (for help)
*
*/
if ($output_all) {
$user_properties = (array) get_userdata($user_id)->data;
$user_metas = get_user_meta($user_id);
$user_infos = merge_two_arrays_CIPF($user_metas, $user_properties);
return output_list_front_CIPF($user_infos);
}
/*
* real purpose of this shortcode :
* only return the first argument (that is not 'author')
*
*/
if (is_array($atts))
$query = reset($atts);
else if (is_string($atts))
$query = $atts;
else
return '';
$output = $current_user->$query;
return format_user_info_CIPF($output, $query, $current_user, $user_id);
}
add_shortcode('cipf_user_info', 'current_user_infos_CIPF');
?>

View File

@@ -0,0 +1,80 @@
<?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 CIPF_CONSOLE_OFF = false;
/*
* redirections users
*/
const PROF_PARTENAIRE_REDIRECTION_PAGE = 'redirection_cipf';
define('PROF_PARTENAIRE_REDIRECTION_URL', home_url() . '/' . PROF_PARTENAIRE_REDIRECTION_PAGE);
/*
* 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";
/*
* paypal redirections
*/
const PAYPAL_REDIRECTION_SUCCESS = PROF_PARTENAIRE_REDIRECTION_URL;
const PAYPAL_REDIRECTION_FAILURE = PROF_PARTENAIRE_REDIRECTION_URL;
/*
* paypal messages
* put the message betweeen backticks `message` and then between single quotes '`message`'
* because it will be evaluated in front by js, so it need something to evaluate, in ``
* you can then use variables available in the context of execution : '`Transaction ${transaction.status}`'
* is it good strategy ? idk
const PAYPAL_MESSAGE_SUCCESS = '`Transaction ${transaction.status}: ${transaction.id}<br><br>See console for all available details`';
const PAYPAL_MESSAGE_FAILURE = '`Sorry, your transaction could not be processed...<br><br>${error}`';
*/
const PAYPAL_MESSAGE_SUCCESS = '`paiement reussi`';
const PAYPAL_MESSAGE_FAILURE = '`paiement raté`';
/*
* acf fields for card :
* - card_is_valid : has valid card
* - card_date_purchase : date of purchase
* - card_date_validity : date end of validity
*/
const CARD_IS_VALID = 'carte_est_valide';
const CARD_DATE_PURCHASE = 'date_d_achat';
const CARD_DATE_VALIDITY = 'date_fin_validite';
?>

View File

@@ -0,0 +1,30 @@
<?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!');
}
// Define a custom exception class for HTTP errors
class HttpErrorException extends Exception {
// HTTP status code
private $statusCode;
public function __construct($message, $statusCode) {
parent::__construct($message);
$this->statusCode = $statusCode;
}
public function getStatusCode() {
return $this->statusCode;
}
}
?>