Hotel Raxa - Advanced Booking System Implementation

🏨 Hotel Booking Enhancements:
- Implemented Eagle Booking Advanced Pricing add-on
- Added Booking.com-style rate management system
- Created professional calendar interface for pricing
- Integrated deals and discounts functionality

💰 Advanced Pricing Features:
- Dynamic pricing models (per room, per person, per adult)
- Base rates, adult rates, and child rates management
- Length of stay discounts and early bird deals
- Mobile rates and secret deals implementation
- Seasonal promotions and flash sales

📅 Availability Management:
- Real-time availability tracking
- Stop sell and restriction controls
- Closed to arrival/departure functionality
- Minimum/maximum stay requirements
- Automatic sold-out management

💳 Payment Integration:
- Maintained Redsys payment gateway integration
- Seamless integration with existing Eagle Booking
- No modifications to core Eagle Booking plugin

🛠️ Technical Implementation:
- Custom database tables for advanced pricing
- WordPress hooks and filters integration
- AJAX-powered admin interface
- Data migration from existing Eagle Booking
- Professional calendar view for revenue management

📊 Admin Interface:
- Booking.com-style management dashboard
- Visual rate and availability calendar
- Bulk operations for date ranges
- Statistics and analytics dashboard
- Modal dialogs for quick editing

🔧 Code Quality:
- WordPress coding standards compliance
- Secure database operations with prepared statements
- Proper input validation and sanitization
- Error handling and logging
- Responsive admin interface

🤖 Generated with Claude Code (https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Hotel Raxa Dev
2025-07-11 07:43:22 +02:00
commit 5b1e2453c7
9816 changed files with 2784509 additions and 0 deletions

View File

@@ -0,0 +1,75 @@
<?php
/*
* 2Checkout Payment Gateway
* Author Eagle Themes (Jomin Muskaj)
* Package Eagle Booking
* Version 1.0.0
*/
defined('ABSPATH') || exit;
if ( isset($_GET['sid']) ) :
// Data
$eagle_booking_form_date_from = $_GET['eagle_booking_checkout_form_date_from'];
$eagle_booking_form_date_to = $_GET['eagle_booking_checkout_form_date_to'];
$eagle_booking_form_guests = $_GET['eagle_booking_checkout_form_guests'];
$eagle_booking_form_adults = $_GET['eagle_booking_checkout_form_adults'];
$eagle_booking_form_children = $_GET['eagle_booking_checkout_form_children'];
$eb_room_price = $_GET['eb_room_price'];
$eagle_booking_form_final_price = $_GET['eagle_booking_checkout_form_final_price'];
$eagle_booking_deposit_amount = $_GET['eagle_booking_deposit_amount'];
$eagle_booking_room_id = $_GET['eagle_booking_room_id'];
$eagle_booking_room_title = $_GET['eagle_booking_room_title'];
$eagle_booking_form_name = $_GET['eagle_booking_checkout_form_name'];
$eagle_booking_form_surname = $_GET['eagle_booking_checkout_form_surname'];
$eagle_booking_form_email = $_GET['eagle_booking_checkout_form_email'];
$eagle_booking_form_phone = $_GET['eagle_booking_checkout_form_phone'];
$eagle_booking_form_address = $_GET['eagle_booking_checkout_form_address'];
$eagle_booking_form_city = $_GET['eagle_booking_checkout_form_city'];
$eagle_booking_form_country = $_GET['eagle_booking_checkout_form_country'];
$eagle_booking_form_zip = $_GET['eagle_booking_checkout_form_zip'];
$eagle_booking_form_requests = $_GET['eagle_booking_checkout_form_requets'];
$eagle_booking_form_arrival = $_GET['eagle_booking_checkout_form_arrival'];
$eagle_booking_form_coupon = $_GET['eagle_booking_form_coupon'];
$eagle_booking_form_services = $_GET['eagle_booking_form_services'];
$eagle_booking_form_action_type = $_GET['eagle_booking_form_action_type'];
$eagle_booking_form_payment_status = $_GET['eagle_booking_form_payment_status'];
// Defaults
$eagle_booking_form_currency = eb_currency();
$eagle_booking_date = date('H:m:s F j Y');
$hashSecretWord = eb_get_option('eagle_booking_2checkout_secret_word'); // 2Checkout Secret Word
$hashSid = eb_get_option('eagle_booking_2checkout_account_number'); // 2Checkout account number
// 2Ceckout Mode
if ($_REQUEST['demo'] == 'Y') {
$order_number = 1;
} else {
$order_number = $_REQUEST['order_number'];
}
// Transaction ID
$eagle_booking_transaction_id = $order_number;
// Status
$compare_string = $hashSecretWord . $hashSid . $order_number . $_REQUEST['total'];
$compare_hash1 = strtoupper(md5($compare_string));
$compare_hash2 = $_REQUEST['key'];
if ($compare_hash1 == $compare_hash2) {
$eagle_booking_form_payment_status = 'Completed';
$eagle_booking_payment_completed = true;
} else {
$eagle_booking_payment_completed = false;
}
endif;

View File

@@ -0,0 +1,59 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['2checkout'] ) : ?>
<div id="eagle_booking_checkout_payment_2checkout_tab">
<p class="checkout-mssg"><?php echo do_shortcode(eb_get_option('eagle_booking_2checkout_mssg')) ?></p>
<?php eb_get_option('eagle_booking_2checkout_sandbox_mode') == true ? $eb_demo_mode = 'Y' : $eb_demo_mode = ''; ?>
<form accept-charset="UTF-8" action="https://www.2checkout.com/checkout/purchase" id="2checkout" method="post">
<!-- Booking Details -->
<input type="hidden" name="eagle_booking_payment_method" value="2checkout">
<input type="hidden" name="eagle_booking_checkout_form_date_from" value="<?php echo $eagle_booking_form_date_from ?>">
<input type="hidden" name="eagle_booking_checkout_form_date_to" value="<?php echo $eagle_booking_form_date_to ?>">
<input type="hidden" name="eagle_booking_checkout_form_guests" value="<?php echo $eagle_booking_form_guests ?>">
<input type="hidden" name="eagle_booking_checkout_form_adults" value="<?php echo $eagle_booking_form_adults ?>">
<input type="hidden" name="eagle_booking_checkout_form_children" value="<?php echo $eagle_booking_form_children ?>">
<input type="hidden" name="eb_room_price" value="<?php echo $eb_room_price ?>">
<input type="hidden" name="eagle_booking_checkout_form_final_price" value="<?php echo $eagle_booking_form_final_price ?>">
<input type="hidden" name="eagle_booking_deposit_amount" value="<?php echo $eagle_booking_deposit_amount ?>">
<input type="hidden" name="eagle_booking_room_id" value="<?php echo $eagle_booking_room_id ?>">
<input type="hidden" name="eagle_booking_room_title" value="<?php echo $eagle_booking_room_title ?>">
<input type="hidden" name="eagle_booking_checkout_form_name" value="<?php echo $eagle_booking_form_name ?>">
<input type="hidden" name="eagle_booking_checkout_form_surname" value="<?php echo $eagle_booking_form_surname ?>">
<input type="hidden" name="eagle_booking_checkout_form_email" value="<?php echo $eagle_booking_form_email ?>">
<input type="hidden" name="eagle_booking_checkout_form_phone" value="<?php echo $eagle_booking_form_phone ?>">
<input type="hidden" name="eagle_booking_checkout_form_address" value="<?php echo $eagle_booking_form_address ?>">
<input type="hidden" name="eagle_booking_checkout_form_city" value="<?php echo $eagle_booking_form_city ?>">
<input type="hidden" name="eagle_booking_checkout_form_country" value="<?php echo $eagle_booking_form_country ?>">
<input type="hidden" name="eagle_booking_checkout_form_zip" value="<?php echo $eagle_booking_form_zip ?>">
<input type="hidden" name="eagle_booking_checkout_form_requets" value="<?php echo $eagle_booking_form_requests ?>">
<input type="hidden" name="eagle_booking_checkout_form_arrival" value="<?php echo $eagle_booking_form_arrival ?>">
<input type="hidden" name="eagle_booking_form_services" value="<?php echo $eagle_booking_form_services ?>">
<input type="hidden" name="eagle_booking_form_coupon" value="<?php echo $eagle_booking_form_coupon ?>">
<input type="hidden" name="eagle_booking_form_action_type" value="2checkout">
<input type="hidden" name="eagle_booking_form_payment_status" value="Pending Payment">
<!-- 2Checkout Parameters -->
<input id="sid" name="sid" type="hidden" value="<?php echo esc_html(eb_get_option('eagle_booking_2checkout_account_number')) ?>" />
<input type='hidden' name='demo' value='<?php echo $eb_demo_mode ?>' />
<input id="mode" name="mode" type="hidden" value="2CO" />
<input id="merchant_order_id" name="merchant_order_id" type="hidden" value="<?php echo $eagle_booking_room_id ?>" />
<input id="li_0_product_id" name="li_0_product_id" type="hidden" value="<?php echo $eagle_booking_room_id ?>" />
<input id="li_0_name" name="li_0_name" type="hidden" value="<?php echo $eagle_booking_room_title ?>" />
<input id="li_0_price" name="li_0_price" type="hidden" value="<?php echo $eagle_booking_deposit_amount ?>" />
<input type='hidden' name='currency_code' value='<?php echo esc_html( eb_get_option('eagle_booking_2checkout_currency') ) ?>' >
<input id="card_holder_name" name="card_holder_name" type="hidden" value="<?php echo $eagle_booking_form_name .' '.$eagle_booking_form_surname ?>" />
<input id="street_address" name="street_address" type="hidden" value="<?php echo $eagle_booking_form_address ?>" />
<input id="city" name="city" type="hidden" value="<?php echo $eagle_booking_form_city ?>" />
<input id="zip" name="zip" type="hidden" value="<?php echo $eagle_booking_form_zip ?>" />
<input id="country" name="country" type="hidden" value="<?php echo $eagle_booking_form_country ?>" />
<input id="email" name="email" type="hidden" value="<?php echo $eagle_booking_form_email ?>" />
<input id="phone" name="phone" type="hidden" value="<?php echo $eagle_booking_form_phone ?>" />
<input type='hidden' name='x_receipt_link_url' value='<?php echo esc_url( eb_checkout_page() ) ?>' />
<button type="submit" class="btn eb-btn btn-2checkout"><?php echo esc_html__('Checkout Now','eagle-booking') ?></button>
</form>
<script src="https://www.2checkout.com/static/checkout/javascript/direct.min.js"></script>
</div>
<?php endif ?>

View File

@@ -0,0 +1,7 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['2checkout'] ) : ?>
<li class="payment-tab-item">
<a href="#eagle_booking_checkout_payment_2checkout_tab">
<i class="fa fa-credit-card" aria-hidden="true"></i><?php echo esc_html__('Credit Card','eagle-booking') ?>
</a>
</li>
<?php endif ?>

View File

@@ -0,0 +1,51 @@
<?php
/*
* Payment On Arrival
* author Eagle Themes (Jomin Muskaj)
* package Eagle Booking
* version 1.0.0
*/
defined('ABSPATH') || exit;
if ( $eagle_booking_payment_method == 'payment_on_arrive') :
// PAYPAL VALUES
$eagle_booking_transaction_id = rand(100000000,999999999);
// FORM VALUES
$eagle_booking_form_date_from = $_POST['eagle_booking_checkout_form_date_from'];
$eagle_booking_form_date_to = $_POST['eagle_booking_checkout_form_date_to'];
$eagle_booking_form_guests = $_POST['eagle_booking_checkout_form_guests'];
$eagle_booking_form_adults = $_POST['eagle_booking_checkout_form_adults'];
$eagle_booking_form_children = $_POST['eagle_booking_checkout_form_children'];
$eb_room_price = $_POST['eb_room_price'];
$eagle_booking_form_final_price = $_POST['eagle_booking_checkout_form_final_price'];
$eagle_booking_deposit_amount = $_POST['eagle_booking_deposit_amount'];
$eagle_booking_room_id = $_POST['eagle_booking_checkout_room_id'];
$eagle_booking_room_title = $_POST['eagle_booking_checkout_form_post_title'];
$eagle_booking_form_name = $_POST['eagle_booking_checkout_form_name'];
$eagle_booking_form_surname = $_POST['eagle_booking_checkout_form_surname'];
$eagle_booking_form_email = $_POST['eagle_booking_checkout_form_email'];
$eagle_booking_form_phone = $_POST['eagle_booking_checkout_form_phone'];
$eagle_booking_form_address = $_POST['eagle_booking_checkout_form_address'];
$eagle_booking_form_city = $_POST['eagle_booking_checkout_form_city'];
$eagle_booking_form_country = $_POST['eagle_booking_checkout_form_country'];
$eagle_booking_form_zip = $_POST['eagle_booking_checkout_form_zip'];
$eagle_booking_form_requests = $_POST['eagle_booking_checkout_form_requets'];
$eagle_booking_form_arrival = $_POST['eagle_booking_checkout_form_arrival'];
$eagle_booking_form_coupon = $_POST['eagle_booking_form_coupon'];
$eagle_booking_form_services = $_POST['eagle_booking_form_services'];
$eagle_booking_form_action_type = $_POST['eagle_booking_form_action_type'];
$eagle_booking_form_payment_status = $_POST['eagle_booking_form_payment_status'];
// DEFAULTS
$eagle_booking_form_currency = eb_currency();
$eagle_booking_date = date('H:m:s F j Y');
// PAYMENT COMPLETED
$eagle_booking_payment_completed = true;
endif;

View File

@@ -0,0 +1,35 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['arrive'] ) : ?>
<div id="eagle_booking_checkout_payment_arrive_tab">
<p class="checkout-mssg"><?php echo do_shortcode(eb_get_option('eagle_booking_arrive_mssg')) ?></p>
<form action="<?php echo eb_checkout_page() ?>" method="post">
<input type="hidden" name="eagle_booking_payment_method" value="payment_on_arrive">
<input type="hidden" name="eagle_booking_checkout_form_date_from" value="<?php echo $eagle_booking_form_date_from ?>">
<input type="hidden" name="eagle_booking_checkout_form_date_to" value="<?php echo $eagle_booking_form_date_to ?>">
<input type="hidden" name="eagle_booking_checkout_form_guests" value="<?php echo $eagle_booking_form_guests ?>">
<input type="hidden" name="eagle_booking_checkout_form_adults" value="<?php echo $eagle_booking_form_adults ?>">
<input type="hidden" name="eagle_booking_checkout_form_children" value="<?php echo $eagle_booking_form_children ?>">
<input type="hidden" name="eb_room_price" value="<?php echo $eb_room_price ?>">
<input type="hidden" name="eagle_booking_checkout_form_final_price" value="<?php echo $eagle_booking_form_final_price ?>">
<input type="hidden" name="eagle_booking_deposit_amount" value="<?php echo $eagle_booking_deposit_amount ?>">
<input type="hidden" name="eagle_booking_checkout_room_id" value="<?php echo $eagle_booking_room_id ?>">
<input type="hidden" name="eagle_booking_checkout_form_post_title" value="<?php echo $eagle_booking_room_title ?>">
<input type="hidden" name="eagle_booking_checkout_form_name" value="<?php echo $eagle_booking_form_name ?>">
<input type="hidden" name="eagle_booking_checkout_form_surname" value="<?php echo $eagle_booking_form_surname ?>">
<input type="hidden" name="eagle_booking_checkout_form_email" value="<?php echo $eagle_booking_form_email ?>">
<input type="hidden" name="eagle_booking_checkout_form_phone" value="<?php echo $eagle_booking_form_phone ?>">
<input type="hidden" name="eagle_booking_checkout_form_address" value="<?php echo $eagle_booking_form_address ?>">
<input type="hidden" name="eagle_booking_checkout_form_city" value="<?php echo $eagle_booking_form_city ?>">
<input type="hidden" name="eagle_booking_checkout_form_country" value="<?php echo $eagle_booking_form_country ?>">
<input type="hidden" name="eagle_booking_checkout_form_zip" value="<?php echo $eagle_booking_form_zip ?>">
<input type="hidden" name="eagle_booking_checkout_form_requets" value="<?php echo $eagle_booking_form_requests ?>">
<input type="hidden" name="eagle_booking_checkout_form_arrival" value="<?php echo $eagle_booking_form_arrival ?>">
<input type="hidden" name="eagle_booking_form_services" value="<?php echo $eagle_booking_form_services ?>">
<input type="hidden" name="eagle_booking_form_coupon" value="<?php echo $eagle_booking_form_coupon ?>">
<input type="hidden" name="eagle_booking_form_action_type" value="payment_on_arrive">
<input type="hidden" name="eagle_booking_form_payment_status" value="Pending Payment">
<button type="submit" class="btn eb-btn btn-arrive"> <?php echo esc_html__('Book Now', 'eagle-booking') ?></button>
</form>
</div>
<?php endif ?>

View File

@@ -0,0 +1,7 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['arrive'] ) : ?>
<li class="payment-tab-item">
<a href="#eagle_booking_checkout_payment_arrive_tab">
<i class="ion-cash" aria-hidden="true"></i><?php echo esc_html__('Payment On Arrival','eagle-booking') ?>
</a>
</li>
<?php endif ?>

View File

@@ -0,0 +1,51 @@
<?php
/*
* Bank Transfer
* author Eagle Themes (Jomin Muskaj)
* package Eagle Booking
* version 1.0.0
*/
defined('ABSPATH') || exit;
if ( $eagle_booking_payment_method == 'bank') :
// PAYPAL VALUES
$eagle_booking_transaction_id = rand(100000000,999999999);
// FORM VALUES
$eagle_booking_form_date_from = $_POST['eagle_booking_checkout_form_date_from'];
$eagle_booking_form_date_to = $_POST['eagle_booking_checkout_form_date_to'];
$eagle_booking_form_guests = $_POST['eagle_booking_checkout_form_guests'];
$eagle_booking_form_adults = $_POST['eagle_booking_checkout_form_adults'];
$eagle_booking_form_children = $_POST['eagle_booking_checkout_form_children'];
$eb_room_price = $_POST['eb_room_price'];
$eagle_booking_form_final_price = $_POST['eagle_booking_checkout_form_final_price'];
$eagle_booking_deposit_amount = $_POST['eagle_booking_deposit_amount'];
$eagle_booking_room_id = $_POST['eagle_booking_room_id'];
$eagle_booking_room_title = $_POST['eagle_booking_room_title'];
$eagle_booking_form_name = $_POST['eagle_booking_checkout_form_name'];
$eagle_booking_form_surname = $_POST['eagle_booking_checkout_form_surname'];
$eagle_booking_form_email = $_POST['eagle_booking_checkout_form_email'];
$eagle_booking_form_phone = $_POST['eagle_booking_checkout_form_phone'];
$eagle_booking_form_address = $_POST['eagle_booking_checkout_form_address'];
$eagle_booking_form_city = $_POST['eagle_booking_checkout_form_city'];
$eagle_booking_form_country = $_POST['eagle_booking_checkout_form_country'];
$eagle_booking_form_zip = $_POST['eagle_booking_checkout_form_zip'];
$eagle_booking_form_requests = $_POST['eagle_booking_checkout_form_requets'];
$eagle_booking_form_arrival = $_POST['eagle_booking_checkout_form_arrival'];
$eagle_booking_form_coupon = $_POST['eagle_booking_form_coupon'];
$eagle_booking_form_services = $_POST['eagle_booking_form_services'];
$eagle_booking_form_action_type = $_POST['eagle_booking_form_action_type'];
$eagle_booking_form_payment_status = $_POST['eagle_booking_form_payment_status'];
// DEFAULTS
$eagle_booking_form_currency = eb_currency();
$eagle_booking_date = date('H:m:s F j Y');
// PAYMENT COMPLETED
$eagle_booking_payment_completed = true;
endif;

View File

@@ -0,0 +1,35 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['bank'] ) : ?>
<div id="eagle_booking_checkout_payment_bank_tab">
<p class="checkout-mssg"><?php echo do_shortcode(eb_get_option('eagle_booking_bank_mssg')) ?></p>
<form action="<?php echo eb_checkout_page() ?>" method="post">
<input type="hidden" name="eagle_booking_payment_method" value="bank">
<input type="hidden" name="eagle_booking_checkout_form_date_from" value="<?php echo $eagle_booking_form_date_from ?>">
<input type="hidden" name="eagle_booking_checkout_form_date_to" value="<?php echo $eagle_booking_form_date_to ?>">
<input type="hidden" name="eagle_booking_checkout_form_guests" value="<?php echo $eagle_booking_form_guests ?>">
<input type="hidden" name="eagle_booking_checkout_form_adults" value="<?php echo $eagle_booking_form_adults ?>">
<input type="hidden" name="eagle_booking_checkout_form_children" value="<?php echo $eagle_booking_form_children ?>">
<input type="hidden" name="eb_room_price" value="<?php echo $eb_room_price ?>">
<input type="hidden" name="eagle_booking_checkout_form_final_price" value="<?php echo $eagle_booking_form_final_price ?>">
<input type="hidden" name="eagle_booking_deposit_amount" value="<?php echo $eagle_booking_deposit_amount ?>">
<input type="hidden" name="eagle_booking_room_id" value="<?php echo $eagle_booking_room_id ?>">
<input type="hidden" name="eagle_booking_room_title" value="<?php echo $eagle_booking_room_title ?>">
<input type="hidden" name="eagle_booking_checkout_form_name" value="<?php echo $eagle_booking_form_name ?>">
<input type="hidden" name="eagle_booking_checkout_form_surname" value="<?php echo $eagle_booking_form_surname ?>">
<input type="hidden" name="eagle_booking_checkout_form_email" value="<?php echo $eagle_booking_form_email ?>">
<input type="hidden" name="eagle_booking_checkout_form_phone" value="<?php echo $eagle_booking_form_phone ?>">
<input type="hidden" name="eagle_booking_checkout_form_address" value="<?php echo $eagle_booking_form_address ?>">
<input type="hidden" name="eagle_booking_checkout_form_city" value="<?php echo $eagle_booking_form_city ?>">
<input type="hidden" name="eagle_booking_checkout_form_country" value="<?php echo $eagle_booking_form_country ?>">
<input type="hidden" name="eagle_booking_checkout_form_zip" value="<?php echo $eagle_booking_form_zip ?>">
<input type="hidden" name="eagle_booking_checkout_form_requets" value="<?php echo $eagle_booking_form_requests ?>">
<input type="hidden" name="eagle_booking_checkout_form_arrival" value="<?php echo $eagle_booking_form_arrival ?>">
<input type="hidden" name="eagle_booking_form_services" value="<?php echo $eagle_booking_form_services ?>">
<input type="hidden" name="eagle_booking_form_coupon" value="<?php echo $eagle_booking_form_coupon ?>">
<input type="hidden" name="eagle_booking_form_action_type" value="bank_transfer">
<input type="hidden" name="eagle_booking_form_payment_status" value="Pending Payment">
<button type="submit" class="btn eb-btn btn-bank"><?php echo esc_html__('Book Now','eagle-booking') ?></button>
</form>
</div>
<?php endif ?>

View File

@@ -0,0 +1,7 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['bank'] ) : ?>
<li class="payment-tab-item">
<a href="#eagle_booking_checkout_payment_bank_tab">
<i class="fa fa-university" aria-hidden="true"></i><?php echo esc_html__('Bank Transfer','eagle-booking') ?>
</a>
</li>
<?php endif ?>

View File

@@ -0,0 +1,96 @@
<?php
/*
* Flutterwave Payment Gateway
* Author Eagle Themes (Jomin Muskaj)
* Package Eagle Booking
* Version 1.0.0
*/
defined('ABSPATH') || exit;
if ( isset($_POST['tx_ref']) ):
// Data
$eagle_booking_form_date_from = $_POST['eagle_booking_checkout_form_date_from'];
$eagle_booking_form_date_to = $_POST['eagle_booking_checkout_form_date_to'];
$eagle_booking_form_guests = $_POST['eagle_booking_checkout_form_guests'];
$eagle_booking_form_adults = $_POST['eagle_booking_checkout_form_adults'];
$eagle_booking_form_children = $_POST['eagle_booking_checkout_form_children'];
$eb_room_price = $_POST['eb_room_price'];
$eagle_booking_form_final_price = $_POST['eagle_booking_checkout_form_final_price'];
$eagle_booking_deposit_amount = $_POST['eagle_booking_deposit_amount'];
$eagle_booking_room_id = $_POST['eagle_booking_room_id'];
$eagle_booking_room_title = $_POST['eagle_booking_room_title'];
$eagle_booking_form_name = $_POST['eagle_booking_checkout_form_name'];
$eagle_booking_form_surname = $_POST['eagle_booking_checkout_form_surname'];
$eagle_booking_form_email = $_POST['eagle_booking_checkout_form_email'];
$eagle_booking_form_phone = $_POST['eagle_booking_checkout_form_phone'];
$eagle_booking_form_address = $_POST['eagle_booking_checkout_form_address'];
$eagle_booking_form_city = $_POST['eagle_booking_checkout_form_city'];
$eagle_booking_form_country = $_POST['eagle_booking_checkout_form_country'];
$eagle_booking_form_zip = $_POST['eagle_booking_checkout_form_zip'];
$eagle_booking_form_requests = $_POST['eagle_booking_checkout_form_requets'];
$eagle_booking_form_arrival = $_POST['eagle_booking_checkout_form_arrival'];
$eagle_booking_form_coupon = $_POST['eagle_booking_form_coupon'];
$eagle_booking_form_services = $_POST['eagle_booking_form_services'];
$eagle_booking_form_action_type = $_POST['eagle_booking_form_action_type'];
$eagle_booking_form_payment_status = $_POST['eagle_booking_form_payment_status'];
// Retrive Flutterwave Token
$flutterwave_secret_key = eb_get_option('flutterwave_secret_key');
$transaction_id = $_POST['transaction_id'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.flutterwave.com/v3/transactions/$transaction_id/verify",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json",
"Authorization: Bearer $flutterwave_secret_key"
),
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
if ($error) {
echo "cURL Error #:" . $error;
}
$response = json_decode($response, true);
if( !empty( $transaction_id ) || $error ){
if( $response['status'] == 'success' ){
$eagle_booking_payment_completed = true;
$eagle_booking_form_currency = eb_currency();
$eagle_booking_date = date('H:m:s F j Y');
$eagle_booking_form_payment_status = 'Completed';
$eagle_booking_transaction_id = $transaction_id;
} else {
$eagle_booking_payment_completed = false;
}
} else {
$eagle_booking_payment_completed = false;
}
endif;

View File

@@ -0,0 +1,86 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['flutterwave'] ) : ?>
<div id="eagle_booking_checkout_payment_flutterwave_tab">
<p class="checkout-mssg"><?php echo do_shortcode(eb_get_option('flutterwave_mssg')) ?></p>
<form accept-charset="UTF-8" action="<?php echo eb_checkout_page() ?>" id="flutterwave" method="POST">
<!-- Booking Details -->
<input type="hidden" name="eagle_booking_payment_method" value="flutterwave">
<input type="hidden" name="eagle_booking_checkout_form_date_from" value="<?php echo $eagle_booking_form_date_from ?>">
<input type="hidden" name="eagle_booking_checkout_form_date_to" value="<?php echo $eagle_booking_form_date_to ?>">
<input type="hidden" name="eagle_booking_checkout_form_guests" value="<?php echo $eagle_booking_form_guests ?>">
<input type="hidden" name="eagle_booking_checkout_form_adults" value="<?php echo $eagle_booking_form_adults ?>">
<input type="hidden" name="eagle_booking_checkout_form_children" value="<?php echo $eagle_booking_form_children ?>">
<input type="hidden" name="eb_room_price" value="<?php echo $eb_room_price ?>">
<input type="hidden" name="eagle_booking_checkout_form_final_price" value="<?php echo $eagle_booking_form_final_price ?>">
<input type="hidden" name="eagle_booking_deposit_amount" value="<?php echo $eagle_booking_deposit_amount ?>">
<input type="hidden" name="eagle_booking_room_id" value="<?php echo $eagle_booking_room_id ?>">
<input type="hidden" name="eagle_booking_room_title" value="<?php echo $eagle_booking_room_title ?>">
<input type="hidden" name="eagle_booking_checkout_form_name" value="<?php echo $eagle_booking_form_name ?>">
<input type="hidden" name="eagle_booking_checkout_form_surname" value="<?php echo $eagle_booking_form_surname ?>">
<input type="hidden" name="eagle_booking_checkout_form_email" value="<?php echo $eagle_booking_form_email ?>">
<input type="hidden" name="eagle_booking_checkout_form_phone" value="<?php echo $eagle_booking_form_phone ?>">
<input type="hidden" name="eagle_booking_checkout_form_address" value="<?php echo $eagle_booking_form_address ?>">
<input type="hidden" name="eagle_booking_checkout_form_city" value="<?php echo $eagle_booking_form_city ?>">
<input type="hidden" name="eagle_booking_checkout_form_country" value="<?php echo $eagle_booking_form_country ?>">
<input type="hidden" name="eagle_booking_checkout_form_zip" value="<?php echo $eagle_booking_form_zip ?>">
<input type="hidden" name="eagle_booking_checkout_form_requets" value="<?php echo $eagle_booking_form_requests ?>">
<input type="hidden" name="eagle_booking_checkout_form_arrival" value="<?php echo $eagle_booking_form_arrival ?>">
<input type="hidden" name="eagle_booking_form_services" value="<?php echo $eagle_booking_form_services ?>">
<input type="hidden" name="eagle_booking_form_coupon" value="<?php echo $eagle_booking_form_coupon ?>">
<input type="hidden" name="eagle_booking_form_action_type" value="flutterwave">
<input type="hidden" name="eagle_booking_form_payment_status" value="Completed">
<input type="hidden" id="tx_ref" name="tx_ref">
<input type="hidden" id="transaction_id" name="transaction_id">
<!-- Flutterwave Parameters -->
<button class="btn eb-btn" type="button" onClick="makePayment()"><?php echo __('Checkout Now','eagle-booking') ?></button>
</form>
<script src="https://checkout.flutterwave.com/v3.js"></script>
<script>
function makePayment() {
FlutterwaveCheckout({
public_key: "<?php echo eb_get_option('flutterwave_public_key') ?>",
tx_ref: "eb-<?php echo rand( )?>",
amount: "<?php echo $eagle_booking_deposit_amount ?>",
currency: "<?php echo eb_get_option('flutterwave_currency')?>",
customer: {
email: "<?php echo $eagle_booking_form_email ?>",
phone_number: "<?php echo $eagle_booking_form_phone ?>",
name: "<?php echo $eagle_booking_form_name.' '.$eagle_booking_form_surname ?>",
},
callback: function (data) {
jQuery('#tx_ref').val(data.tx_ref);
jQuery('#transaction_id').val(data.transaction_id);
// Form Submit
jQuery('#flutterwave').submit();
},
// close modal
onclose: function() {
},
customizations: {
title: "<?php echo get_bloginfo( 'name' ); ?>",
description: "<?php __('Payment for Booking', 'eagle-booking') ?>",
logo: "<?php echo eb_get_option( 'hotel_logo' ); ?>",
},
});
}
</script>
</div>
<?php endif ?>

View File

@@ -0,0 +1,7 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['flutterwave'] ) : ?>
<li class="payment-tab-item">
<a href="#eagle_booking_checkout_payment_flutterwave_tab">
<i class="fa fa-credit-card" aria-hidden="true"></i><?php echo do_shortcode( eb_get_option('flutterwave_title') ) ?>
</a>
</li>
<?php endif ?>

View File

@@ -0,0 +1,38 @@
<?php
defined('ABSPATH') || exit;
/**
* Include payment content - Sorting
*/
$eb_payment_methods = eb_get_option('eagle_booking_payment_method');
foreach ($eb_payment_methods as $eb_payment_method=>$value) {
switch($eb_payment_method) {
case 'paypal': include_once 'paypal/tab-content.php';
break;
case 'stripe': include_once 'stripe/tab-content.php';
break;
case '2checkout': include_once '2checkout/tab-content.php';
break;
case 'payu': include_once 'payu/tab-content.php';
break;
case 'paystack': include_once 'paystack/tab-content.php';
break;
case 'flutterwave': include_once 'flutterwave/tab-content.php';
break;
case 'razorpay': include_once 'razorpay/tab-content.php';
break;
case 'vivawallet': include_once 'vivawallet/tab-content.php';
break;
case 'bank': include_once 'bank/tab-content.php';
break;
case 'arrive': include_once 'arrive/tab-content.php';
break;
case 'request': include_once 'request/tab-content.php';
break;
}
}

View File

@@ -0,0 +1,38 @@
<?php
defined('ABSPATH') || exit;
/**
* Include payment tabs - Sorting
*/
$eb_payment_methods = eb_get_option('eagle_booking_payment_method');
foreach ($eb_payment_methods as $eb_payment_method=>$value) {
switch($eb_payment_method) {
case 'paypal': include_once 'paypal/tab.php';
break;
case 'stripe': include_once 'stripe/tab.php';
break;
case '2checkout': include_once '2checkout/tab.php';
break;
case 'payu': include_once 'payu/tab.php';
break;
case 'paystack': include_once 'paystack/tab.php';
break;
case 'flutterwave': include_once 'flutterwave/tab.php';
break;
case 'razorpay': include_once 'razorpay/tab.php';
break;
case 'vivawallet': include_once 'vivawallet/tab.php';
break;
case 'bank': include_once 'bank/tab.php';
break;
case 'arrive': include_once 'arrive/tab.php';
break;
case 'request': include_once 'request/tab.php';
break;
}
}

View File

@@ -0,0 +1,112 @@
<?php
/*
* PayPal Payment Gateway
* author Eagle Themes (Jomin Muskaj)
* package Eagle Booking
* version 1.0.0
*/
defined('ABSPATH') || exit;
if ( isset($_GET['tx']) ) :
// PLUGIN OPTIONS
$eagle_booking_paypal_email = eb_get_option('eagle_booking_paypal_id');
$eagle_booking_paypal_currency = eb_currency();
$eagle_booking_paypal_token = eb_get_option('eagle_booking_paypal_token');
$eagle_booking_paypal_developer = eb_get_option('eagle_booking_paypal_developer_mode');
if ( $eagle_booking_paypal_developer == true) {
$eagle_booking_paypal_action_1 = 'https://www.sandbox.paypal.com/cgi-bin';
$eagle_booking_paypal_action_2 = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
} else {
$eagle_booking_paypal_action_1 = 'https://www.paypal.com/cgi-bin';
$eagle_booking_paypal_action_2 = 'https://www.paypal.com/cgi-bin/webscr';
}
// PAYPAL DEFAULTS
$eagle_booking_transaction_id = $_GET['tx'];
$eagle_booking_request = curl_init();
// PAYPAL REQUEST OPTIONS
curl_setopt_array($eagle_booking_request, array
(
CURLOPT_URL => $eagle_booking_paypal_action_2,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => http_build_query(array
(
'cmd' => '_notify-synch',
'tx' => $eagle_booking_transaction_id,
'at' => $eagle_booking_paypal_token,
)),
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HEADER => FALSE,
));
$eagle_booking_response = curl_exec($eagle_booking_request);
$eagle_booking_status = curl_getinfo($eagle_booking_request, CURLINFO_HTTP_CODE);
// CLOSE CONNECTION
curl_close($eagle_booking_request);
// PAYPAL PAYMENT STATUS
if($eagle_booking_status == 200 AND strpos($eagle_booking_response, 'SUCCESS') === 0){
// DECODE RESPONSE
$eagle_booking_response = substr($eagle_booking_response, 7);
$eagle_booking_response = urldecode($eagle_booking_response);
preg_match_all('/^([^=\s]++)=(.*+)/m', $eagle_booking_response, $m, PREG_PATTERN_ORDER);
$eagle_booking_response = array_combine($m[1], $m[2]);
$eagle_booking_room_id = $eagle_booking_response['item_number'];
$eagle_booking_room_title = $eagle_booking_response['item_name'];
// PAYPAL USER INFO
$eagle_booking_paypal_name = $eagle_booking_response['first_name'];
$eagle_booking_paypal_surname = $eagle_booking_response['last_name'];
$eagle_booking_paypal_email = $eagle_booking_response['payer_email'];
$eagle_booking_paypal_address = $eagle_booking_response['address_street'];
$eagle_booking_paypal_city = $eagle_booking_response['address_city'];
$eagle_booking_paypal_country = $eagle_booking_response['address_country'];
$eagle_booking_paypal_zip = $eagle_booking_response['address_zip'];
// PAYPAL PAYMENT DETAILS
$eagle_booking_date = $eagle_booking_response['payment_date'];
$eagle_booking_deposit_amount = $eagle_booking_response['mc_gross'];
$eagle_booking_form_currency = $eagle_booking_response['mc_currency'];
$eagle_booking_form_action_type = 'paypal';
$eagle_booking_form_payment_status = $eagle_booking_response['payment_status'];
// EXTRACT CUSTOM FIELD FROM 'CUSTOM'
$eagle_booking_custom_field_array = explode('[eb]', $eagle_booking_response['custom']);
$eagle_booking_form_date_from = $eagle_booking_custom_field_array[0];
$eagle_booking_form_date_to = $eagle_booking_custom_field_array[1];
$eagle_booking_form_guests = $eagle_booking_custom_field_array[2];
$eagle_booking_form_adults = $eagle_booking_custom_field_array[3];
$eagle_booking_form_children = $eagle_booking_custom_field_array[4];
$eagle_booking_form_name = $eagle_booking_custom_field_array[5];
$eagle_booking_form_surname = $eagle_booking_custom_field_array[6];
$eagle_booking_form_email = $eagle_booking_custom_field_array[7];
$eagle_booking_form_phone = $eagle_booking_custom_field_array[8];
$eagle_booking_form_address = $eagle_booking_custom_field_array[9];
$eagle_booking_form_zip = $eagle_booking_custom_field_array[10];
$eagle_booking_form_city = $eagle_booking_custom_field_array[11];
$eagle_booking_form_country = $eagle_booking_custom_field_array[12];
$eagle_booking_form_services = $eagle_booking_custom_field_array[13];
$eagle_booking_form_requests = $eagle_booking_custom_field_array[14];
$eagle_booking_form_arrival = $eagle_booking_custom_field_array[15];
$eagle_booking_form_coupon = $eagle_booking_custom_field_array[16];
$eagle_booking_form_final_price = $eagle_booking_custom_field_array[17];
$eb_room_price = $eagle_booking_custom_field_array[18];
// PAYMENT COMPLETED
$eagle_booking_payment_completed = true;
} else {
$eagle_booking_payment_completed = false;
}
endif;

View File

@@ -0,0 +1,38 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['paypal'] ) : ?>
<div id="eagle_booking_checkout_payment_paypal_tab">
<?php
// PLUGIN OPTIONS
$eagle_booking_paypal_email = eb_get_option('eagle_booking_paypal_id');
$eagle_booking_paypal_currency = eb_get_option('eagle_booking_paypal_currency');
$eagle_booking_paypal_token = eb_get_option('eagle_booking_paypal_token');
$eagle_booking_paypal_developer = eb_get_option('eagle_booking_paypal_developer_mode');
if ( $eagle_booking_paypal_developer == true ) {
$eagle_booking_paypal_action_1 = 'https://www.sandbox.paypal.com/cgi-bin';
$eagle_booking_paypal_action_2 = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
} else {
$eagle_booking_paypal_action_1 = 'https://www.paypal.com/cgi-bin';
$eagle_booking_paypal_action_2 = 'https://www.paypal.com/cgi-bin/webscr';
}
?>
<p class="checkout-mssg"><?php echo do_shortcode(eb_get_option('eagle_booking_paypal_mssg')) ?></p>
<form target="paypal" action="<?php echo $eagle_booking_paypal_action_1 ?>" method="post" >
<input type="hidden" name="eagle_booking_payment_method" value="paypal">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="<?php echo $eagle_booking_paypal_email ?>">
<input type="hidden" name="lc" value="">
<input type="hidden" name="item_name" value="<?php echo $eagle_booking_room_title ?>">
<input type="hidden" name="item_number" value="<?php echo $eagle_booking_room_id ?>">
<input type="hidden" name="custom" value="<?php echo $eagle_booking_form_date_from.'[eb]'.$eagle_booking_form_date_to.'[eb]'.$eagle_booking_form_guests.'[eb]'.$eagle_booking_form_adults.'[eb]'.$eagle_booking_form_adults.'[eb]'.$eagle_booking_form_name.'[eb]'.$eagle_booking_form_surname.'[eb]'.$eagle_booking_form_email.'[eb]'.$eagle_booking_form_phone.'[eb]'.$eagle_booking_form_address.'[eb]'.$eagle_booking_form_zip.'[eb]'.$eagle_booking_form_city.'[eb]'.$eagle_booking_form_country.'[eb]'.$eagle_booking_form_services.'[eb]'.$eagle_booking_form_requests.'[eb]'.$eagle_booking_form_arrival.'[eb]'.$eagle_booking_form_coupon.'[eb]'.$eagle_booking_form_final_price.'[eb]'.$eb_room_price ?>">
<input type="hidden" name="amount" value="<?php echo $eagle_booking_deposit_amount ?>">
<input type="hidden" name="currency_code" value="<?php echo $eagle_booking_paypal_currency ?>">
<input type="hidden" name="rm" value="2" />
<input type="hidden" name="return" value="<?php echo esc_url( eb_checkout_page() ) ?>" />
<input type="hidden" name="cancel_return" value="" />
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHostedGuest">
<button class="btn eb-btn btn-paypal" type="submit"><?php echo esc_html__('Checkout with PayPal','eagle-booking') ?></button>
</form>
</div>
<?php endif ?>

View File

@@ -0,0 +1,7 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['paypal'] ) : ?>
<li class="payment-tab-item">
<a href="#eagle_booking_checkout_payment_paypal_tab">
<i class="icon-paypal" aria-hidden="true"></i><?php echo esc_html__('PayPal','eagle-booking')?>
</a>
</li>
<?php endif ?>

View File

@@ -0,0 +1,95 @@
<?php
/*
* 2Checkout Payment Gateway
* Author Eagle Themes (Jomin Muskaj)
* Package Eagle Booking
* Version 1.0.0
*/
defined('ABSPATH') || exit;
if ( isset($_POST['paystack_reference']) ) :
// Data
$eagle_booking_form_date_from = $_POST['eagle_booking_checkout_form_date_from'];
$eagle_booking_form_date_to = $_POST['eagle_booking_checkout_form_date_to'];
$eagle_booking_form_guests = $_POST['eagle_booking_checkout_form_guests'];
$eagle_booking_form_adults = $_POST['eagle_booking_checkout_form_adults'];
$eagle_booking_form_children = $_POST['eagle_booking_checkout_form_children'];
$eb_room_price = $_POST['eb_room_price'];
$eagle_booking_form_final_price = $_POST['eagle_booking_checkout_form_final_price'];
$eagle_booking_deposit_amount = $_POST['eagle_booking_deposit_amount'];
$eagle_booking_room_id = $_POST['eagle_booking_room_id'];
$eagle_booking_room_title = $_POST['eagle_booking_room_title'];
$eagle_booking_form_name = $_POST['eagle_booking_checkout_form_name'];
$eagle_booking_form_surname = $_POST['eagle_booking_checkout_form_surname'];
$eagle_booking_form_email = $_POST['eagle_booking_checkout_form_email'];
$eagle_booking_form_phone = $_POST['eagle_booking_checkout_form_phone'];
$eagle_booking_form_address = $_POST['eagle_booking_checkout_form_address'];
$eagle_booking_form_city = $_POST['eagle_booking_checkout_form_city'];
$eagle_booking_form_country = $_POST['eagle_booking_checkout_form_country'];
$eagle_booking_form_zip = $_POST['eagle_booking_checkout_form_zip'];
$eagle_booking_form_requests = $_POST['eagle_booking_checkout_form_requets'];
$eagle_booking_form_arrival = $_POST['eagle_booking_checkout_form_arrival'];
$eagle_booking_form_coupon = $_POST['eagle_booking_form_coupon'];
$eagle_booking_form_services = $_POST['eagle_booking_form_services'];
$eagle_booking_form_action_type = $_POST['eagle_booking_form_action_type'];
$eagle_booking_form_payment_status = $_POST['eagle_booking_form_payment_status'];
// Retrive Paystack Token
$paystack_secret_key = eb_get_option('paystack_secret_key');
$eb_paystack_token = $_POST['paystack_reference'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.paystack.co/transaction/verify/$eb_paystack_token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $paystack_secret_key",
"Cache-Control: no-cache",
),
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
if ($error) {
echo "cURL Error #:" . $error;
}
$response = json_decode($response, true);
if( !empty( $eb_paystack_token ) || $error ){
if( $response['data']['status'] == 'success' ){
$eagle_booking_payment_completed = true;
$eagle_booking_form_currency = eb_currency();
$eagle_booking_date = date('H:m:s F j Y');
$eagle_booking_form_payment_status = 'Completed';
$eagle_booking_transaction_id = $response['data']['id'];
} else {
$eagle_booking_payment_completed = false;
}
} else {
$eagle_booking_payment_completed = false;
}
endif;

View File

@@ -0,0 +1,81 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['paystack'] ) : ?>
<div id="eagle_booking_checkout_payment_paystack_tab">
<p class="checkout-mssg"><?php echo do_shortcode(eb_get_option('paystack_mssg')) ?></p>
<form accept-charset="UTF-8" action="<?php echo eb_checkout_page() ?>" id="paystack" method="POST">
<!-- Booking Details -->
<input type="hidden" name="eagle_booking_payment_method" value="paystack">
<input type="hidden" name="eagle_booking_checkout_form_date_from" value="<?php echo $eagle_booking_form_date_from ?>">
<input type="hidden" name="eagle_booking_checkout_form_date_to" value="<?php echo $eagle_booking_form_date_to ?>">
<input type="hidden" name="eagle_booking_checkout_form_guests" value="<?php echo $eagle_booking_form_guests ?>">
<input type="hidden" name="eagle_booking_checkout_form_adults" value="<?php echo $eagle_booking_form_adults ?>">
<input type="hidden" name="eagle_booking_checkout_form_children" value="<?php echo $eagle_booking_form_children ?>">
<input type="hidden" name="eb_room_price" value="<?php echo $eb_room_price ?>">
<input type="hidden" name="eagle_booking_checkout_form_final_price" value="<?php echo $eagle_booking_form_final_price ?>">
<input type="hidden" name="eagle_booking_deposit_amount" value="<?php echo $eagle_booking_deposit_amount ?>">
<input type="hidden" name="eagle_booking_room_id" value="<?php echo $eagle_booking_room_id ?>">
<input type="hidden" name="eagle_booking_room_title" value="<?php echo $eagle_booking_room_title ?>">
<input type="hidden" name="eagle_booking_checkout_form_name" value="<?php echo $eagle_booking_form_name ?>">
<input type="hidden" name="eagle_booking_checkout_form_surname" value="<?php echo $eagle_booking_form_surname ?>">
<input type="hidden" name="eagle_booking_checkout_form_email" value="<?php echo $eagle_booking_form_email ?>">
<input type="hidden" name="eagle_booking_checkout_form_phone" value="<?php echo $eagle_booking_form_phone ?>">
<input type="hidden" name="eagle_booking_checkout_form_address" value="<?php echo $eagle_booking_form_address ?>">
<input type="hidden" name="eagle_booking_checkout_form_city" value="<?php echo $eagle_booking_form_city ?>">
<input type="hidden" name="eagle_booking_checkout_form_country" value="<?php echo $eagle_booking_form_country ?>">
<input type="hidden" name="eagle_booking_checkout_form_zip" value="<?php echo $eagle_booking_form_zip ?>">
<input type="hidden" name="eagle_booking_checkout_form_requets" value="<?php echo $eagle_booking_form_requests ?>">
<input type="hidden" name="eagle_booking_checkout_form_arrival" value="<?php echo $eagle_booking_form_arrival ?>">
<input type="hidden" name="eagle_booking_form_services" value="<?php echo $eagle_booking_form_services ?>">
<input type="hidden" name="eagle_booking_form_coupon" value="<?php echo $eagle_booking_form_coupon ?>">
<input type="hidden" name="eagle_booking_form_action_type" value="paystack">
<input type="hidden" name="eagle_booking_form_payment_status" value="Completed">
<!-- Paystack Parameters -->
<input type="hidden" id="email-address" value="<?php echo $eagle_booking_form_email ?>" />
<input type="hidden" id="amount" value="<?php echo $eagle_booking_deposit_amount ?>" />
<button id="card-button" class="btn eb-btn" type="submit" onclick="payWithPaystack(event)"><?php echo __('Checkout Now','eagle-booking') ?></button>
</form>
<script src="https://js.paystack.co/v1/inline.js"></script>
<script>
var Form = document.getElementById('paystack');
Form.addEventListener('submit', payWithPaystack, false);
function payWithPaystack(event) {
event.preventDefault();
let handler = PaystackPop.setup({
key: '<?php echo eb_get_option('paystack_public_key') ?>',
email: document.getElementById("email-address").value,
amount: document.getElementById("amount").value * 100,
currency: '<?php echo eb_get_option('paystack_currency') ?>',
onClose: function(){
},
callback: function(response){
//Create Token
var hiddenInput = document.createElement("input");
hiddenInput.setAttribute("type", "hidden");
hiddenInput.setAttribute("name", "paystack_reference");
hiddenInput.setAttribute("value", response.reference);
Form.appendChild(hiddenInput);
// Submit Form
Form.submit();
}
});
handler.openIframe();
}
</script>
</div>
<?php endif ?>

View File

@@ -0,0 +1,7 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['paystack'] ) : ?>
<li class="payment-tab-item">
<a href="#eagle_booking_checkout_payment_paystack_tab">
<i class="fa fa-credit-card" aria-hidden="true"></i><?php echo __('Paystack','eagle-booking') ?>
</a>
</li>
<?php endif ?>

View File

@@ -0,0 +1,75 @@
<?php
/*
* Package: Core / PayU Payment Gateway
* Author: Eagle Themes (Jomin Muskaj)
* Version 1.0.0
*/
defined('ABSPATH') || exit;
if (isset($_POST ['key'])) :
// PayU
$eb_payu_merchant_key = eb_get_option('eb_payu_merchant_key');
$eb_payu_merchant_salt = eb_get_option('eb_payu_merchant_salt');
$eb_payu_transaction_id = $_POST['txnid'];
$eagle_booking_deposit_amount = $_POST['amount'];
$eagle_booking_room_title = $_POST['productinfo'];
$eagle_booking_form_name = $_POST['firstname'];
$eagle_booking_form_email = $_POST['email'];
$mihpayid = $_POST['mihpayid'];
$status = $_POST['status'];
$resphash = $_POST['hash'];
// Get custom parameters
$eb_payu_udf5 = $_POST['udf5'];
// Explode parameters
$eb_custom_field_array = explode('[eb]', $eb_payu_udf5);
$eagle_booking_room_id = $eb_custom_field_array[0];
$eagle_booking_form_date_from = $eb_custom_field_array[1];
$eagle_booking_form_date_to = $eb_custom_field_array[2];
$eagle_booking_form_guests = $eb_custom_field_array[3];
$eagle_booking_form_adults = $eb_custom_field_array[4];
$eagle_booking_form_children = $eb_custom_field_array[5];
$eagle_booking_form_name = $eb_custom_field_array[6];
$eagle_booking_form_surname = $eb_custom_field_array[7];
$eagle_booking_form_email = $eb_custom_field_array[8];
$eagle_booking_form_phone = $eb_custom_field_array[9];
$eagle_booking_form_address = $eb_custom_field_array[10];
$eagle_booking_form_zip = $eb_custom_field_array[11];
$eagle_booking_form_city = $eb_custom_field_array[12];
$eagle_booking_form_country = $eb_custom_field_array[13];
$eagle_booking_form_services = $eb_custom_field_array[14];
$eagle_booking_form_requests = $eb_custom_field_array[15];
$eagle_booking_form_arrival = $eb_custom_field_array[16];
$eagle_booking_form_coupon = $eb_custom_field_array[17];
$eagle_booking_form_final_price = $eb_custom_field_array[18];
// Defaults
$eagle_booking_form_currency = eb_currency();
$eagle_booking_date = date('H:m:s F j Y');
$eagle_booking_form_payment_status = 'Completed';
$eagle_booking_transaction_id = $eb_payu_transaction_id;
$eagle_booking_form_action_type = 'PayU';
// Calculate response hash to verify
$keyString = $eb_payu_merchant_key.'|'.$eb_payu_transaction_id.'|'.$eagle_booking_deposit_amount.'|'.$eagle_booking_room_title.'|'.$eagle_booking_form_name.'|'.$eagle_booking_form_email.'|||||'.$eb_payu_udf5.'|||||';
$keyArray = explode("|",$keyString);
$reverseKeyArray = array_reverse($keyArray);
$reverseKeyString = implode("|",$reverseKeyArray);
$CalcHashString = strtolower(hash('sha512', $eb_payu_merchant_salt.'|'.$status.'|'.$reverseKeyString));
if ($status == 'success' && $resphash == $CalcHashString) {
$eagle_booking_payment_completed = true;
}
else {
$eagle_booking_payment_completed = false;
}
endif;

View File

@@ -0,0 +1,98 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['payu'] ) : ?>
<div id="eagle_booking_checkout_payment_payu_tab">
<p class="checkout-mssg"><?php echo do_shortcode(eb_get_option('eb_payu_checkout_mssg')) ?></p>
<?php
$eb_payu_merchant_key = eb_get_option('eb_payu_merchant_key');
$eb_payu_merchant_salt = eb_get_option('eb_payu_merchant_salt');
$eb_payu_transaction_id = 'Txn'.rand(10000, 99999999);
// Pass parameters as array
$eb_payu_udf5 = $eagle_booking_room_id .'[eb]'.$eagle_booking_form_date_from.'[eb]'.$eagle_booking_form_date_to.'[eb]'.$eagle_booking_form_guests.'[eb]'.$eagle_booking_form_adults.'[eb]'.$eagle_booking_form_adults.'[eb]'.$eagle_booking_form_name.'[eb]'.$eagle_booking_form_surname.'[eb]'.$eagle_booking_form_email.'[eb]'.$eagle_booking_form_phone.'[eb]'.$eagle_booking_form_address.'[eb]'.$eagle_booking_form_zip.'[eb]'.$eagle_booking_form_city.'[eb]'.$eagle_booking_form_country.'[eb]'.$eagle_booking_form_services.'[eb]'.$eagle_booking_form_requests.'[eb]'.$eagle_booking_form_arrival.'[eb]'.$eagle_booking_form_coupon.'[eb]'.$eagle_booking_form_final_price;
$eb_payu_hash = hash('sha512', $eb_payu_merchant_key.'|'.$eb_payu_transaction_id.'|'.$eagle_booking_deposit_amount.'|'.$eagle_booking_room_title.'|'.$eagle_booking_form_name.'|'.$eagle_booking_form_email.'|||||'.$eb_payu_udf5.'||||||'.$eb_payu_merchant_salt);
?>
<form action="#" id="payu_form">
<input type="hidden" id="surl" name="surl" value="<?php echo eb_checkout_page() ?>" />
<input type="hidden" id="key" name="key" value="<?php echo $eb_payu_merchant_key ?>" />
<input type="hidden" id="salt" name="salt" value="<?php echo $eb_payu_merchant_salt ?>" />
<input type="hidden" id="txnid" name="txnid" value="<?php echo $eb_payu_transaction_id ?>" />
<input type="hidden" id="amount" name="amount" value="<?php echo $eagle_booking_deposit_amount ?>">
<input type="hidden" id="pinfo" name="pinfo" value="<?php echo $eagle_booking_room_title ?>">
<input type="hidden" id="email" name="email" value="<?php echo $eagle_booking_form_email ?>">
<input type="hidden" id="mobile" name="mobile" value="<?php echo $eagle_booking_form_phone ?>">
<input type="hidden" id="fname" name="fname" value="<?php echo $eagle_booking_form_name ?>">
<input type="hidden" id="udf5" name="udf5" value="<?php echo $eb_payu_udf5 ?>">
<input type="hidden" id="hash" name="hash" value="<?php echo $eb_payu_hash ?>" />
<button id="payu-button" class="btn eb-btn btn-payu" type="submit"><?php echo __('Checkout Now','eagle-booking') ?></button>
</form>
<?php if ( eb_get_option('eb_payu_sandbox') == true ) : ?>
<script id="bolt" src="https://sboxcheckout-static.citruspay.com/bolt/run/bolt.min.js" bolt-color="19a1f7" bolt-logo="https://boltiswatching.com/wp-content/uploads/2015/09/Bolt-Logo-e14421724859591.png"></script>
<?php else : ?>
<script id="bolt" src="https://checkout-static.citruspay.com/bolt/run/bolt.min.js" bolt-color="19a1f7" bolt-logo="http://boltiswatching.com/wp-content/uploads/2015/09/Bolt-Logo-e14421724859591.png"></script>
<?php endif ?>
<script type="text/javascript">
jQuery(function($) {
$(document).on('submit','#payu_form',function(e){
launchBOLT();
e.preventDefault();
});
function launchBOLT() {
bolt.launch({
key: $('#key').val(),
salt: $('#salt').val(),
txnid: $('#txnid').val(),
hash: $('#hash').val(),
amount: $('#amount').val(),
firstname: $('#fname').val(),
email: $('#email').val(),
phone: $('#mobile').val(),
productinfo: $('#pinfo').val(),
udf5: $('#udf5').val(),
surl : $('#surl').val(),
furl: $('#surl').val(),
mode: 'dropout'
},
{
responseHandler: function(BOLT){
console.log( BOLT.response.txnStatus );
if(BOLT.response.txnStatus != 'CANCEL') {
var fr = '<form action=\"'+$('#surl').val()+'\" method=\"post\">' +
'<input type=\"hidden\" name=\"key\" value=\"'+BOLT.response.key+'\" />' +
'<input type=\"hidden\" name=\"txnid\" value=\"'+BOLT.response.txnid+'\" />' +
'<input type=\"hidden\" name=\"amount\" value=\"'+BOLT.response.amount+'\" />' +
'<input type=\"hidden\" name=\"productinfo\" value=\"'+BOLT.response.productinfo+'\" />' +
'<input type=\"hidden\" name=\"firstname\" value=\"'+BOLT.response.firstname+'\" />' +
'<input type=\"hidden\" name=\"email\" value=\"'+BOLT.response.email+'\" />' +
'<input type=\"hidden\" name=\"udf5\" value=\"'+BOLT.response.udf5+'\" />' +
'<input type=\"hidden\" name=\"mihpayid\" value=\"'+BOLT.response.mihpayid+'\" />' +
'<input type=\"hidden\" name=\"status\" value=\"'+BOLT.response.status+'\" />' +
'<input type=\"hidden\" name=\"hash\" value=\"'+BOLT.response.hash+'\" />' +
'</form>';
var form = jQuery(fr);
jQuery('body').append(form);
form.submit();
}
},
catchException: function(BOLT){
alert( BOLT.message );
}
});
}
});
</script>
</div>
<?php endif ?>

View File

@@ -0,0 +1,7 @@
<?php if ( eb_get_option('eagle_booking_payment_method')['payu'] ) : ?>
<li class="payment-tab-item">
<a href="#eagle_booking_checkout_payment_payu_tab">
<i class="fa fa-credit-card" aria-hidden="true"></i><?php echo esc_html__('Credit Card','eagle-booking') ?>
</a>
</li>
<?php endif ?>

View File

@@ -0,0 +1,14 @@
# This file is for unifying the coding style for different editors and IDEs
# editorconfig.org
root = true
[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[**.php]
indent_style = space
indent_size = 4

View File

@@ -0,0 +1,39 @@
name: feature.md
description: Submit a proposal for a new feature
title: '[Feature]: '
labels: [':rocket: Feature Request']
body:
- type: markdown
attributes:
value: |
### Thank you for taking the time to suggest a new feature!
We kindly ask that you search to see if an issue [already exists](https://github.com/razorpay/razorpay-php/issues?q=is%3Aissue+sort%3Acreated-desc+) for your feature.
We are also happy to accept contributions from our users.
- type: textarea
id: description
attributes:
label: '🚀 Feature Proposal'
description:
validations:
required: true
- type: textarea
id: solution
attributes:
label: Suggested Solution
description:
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives
description:
validations:
required: false
- type: textarea
id: extra
attributes:
label: Additional Information
description:
validations:
required: true

View File

@@ -0,0 +1,62 @@
name: issue.md
description: Create a report to help us improve
labels: ["issue"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this issue report!
- type: textarea
id: repro-steps
attributes:
label: Steps to reproduce the behavior
description:
placeholder: |
1. Fetch a '...'
2. Update the '....'
3. See error
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: Expected behavior
description: A clear and concise description of what you expected to happen.
validations:
required: true
- type: textarea
id: actual-behavior
attributes:
label: Actual behavior
description: A clear and concise description of what actually happen.
validations:
required: true
- type: textarea
id: code-snippets
attributes:
label: Code snippets
description: If applicable, add code snippets to help explain your problem.
render: Php
validations:
required: false
- type: input
id: language-version
attributes:
label: Php version
placeholder: Php v7.4
validations:
required: true
- type: input
id: lib-version
attributes:
label: Library version
placeholder: razorpay-php v2.8.4
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: Additional Information
description: Add any other information about the problem here.
validations:
required: false

View File

@@ -0,0 +1,8 @@
version: 2
updates:
- package-ecosystem: composer
directory: "/"
schedule:
interval: daily
time: "04:00"
timezone: Asia/Calcutta

View File

@@ -0,0 +1,8 @@
## Note :- Please follow the below points while attaching test cases document link below:
### - If label `Tested` is added then test cases document URL is mandatory.
### - Link added should be a valid URL and accessible throughout the org.
### - If the branch name contains hotfix / revert by default the BVT workflow check will pass.
| Test Case Document URL |
|-----------------------------------------------|
| Please paste test case document link here.... |

View File

@@ -0,0 +1,37 @@
name: CI
on:
push:
branches:
- master
tags:
- v[0-9]+.[0-9]+.[0-9]+*
pull_request:
branches:
- master
jobs:
run:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Set up php 8.0
uses: shivammathur/setup-php@v2
with:
php-version: '8.0'
- name: 'Create env file'
run: |
touch ${{ github.workspace }}/tests/.env
echo RAZORPAY_API_KEY=${{ secrets.RAZORPAY_API_KEY }} >> ${{ github.workspace }}/tests/.env
echo RAZORPAY_API_SECRET=${{ secrets.RAZORPAY_API_SECRET }} >> ${{ github.workspace }}/tests/.env
cat ${{ github.workspace }}/tests/.env
- name: Install dependencies
run: composer self-update && composer install && composer require vlucas/phpdotenv && composer dump-autoload
- name: Run tests and collect coverage
run: vendor/bin/phpunit ./tests/CoverageTest.php --coverage-clover coverage.xml .
env:
RAZORPAY_API_KEY: ${{ secrets.RAZORPAY_API_KEY }}
RAZORPAY_API_SECRET: ${{ secrets.RAZORPAY_API_SECRET }}
RAZORPAY_PARTNER_API_KEY: ${{ secrets.RAZORPAY_PARTNER_API_KEY }}
RAZORPAY_PARTNER_API_SECRET: ${{ secrets.RAZORPAY_PARTNER_API_SECRET }}
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3

View File

@@ -0,0 +1,51 @@
name: SecurityChecks
on:
pull_request: {}
push:
branches: ["master"]
schedule:
- cron: '30 20 * * *'
jobs:
semgrep:
name: Semgrep
runs-on: [ubuntu-latest]
container:
image: returntocorp/semgrep
steps:
- uses: actions/checkout@v4.0.0
- name: Run semgrep
run: semgrep ci
env:
SEMGREP_APP_TOKEN: ${{ secrets.SEMGREP_APP_TOKEN }}
workflow_status:
runs-on: [ ubuntu-latest ] # nosemgrep : semgrep.dev/s/swati31196:github_provided_runner
name: Update Status Check
needs: [ semgrep ]
if: always()
env:
githubCommit: ${{ github.event.pull_request.head.sha }}
steps:
- name: Set github commit id
run: |
if [ "${{ github.event_name }}" = "push" ] || [ "${{ github.event_name }}" = "schedule" ]; then
echo "githubCommit=${{ github.sha }}" >> $GITHUB_ENV
fi
exit 0
- name: Failed
id: failed
if: (contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) && github.ref != 'refs/heads/master'
run: |
echo 'Failing the workflow for github security status check.'
curl -X POST -H "Content-Type: application/json" -H "Authorization: token ${{ github.token }}" \
-d '{ "state" : "failure" , "context" : "github/security-status-check" , "description" : "github/security-status-check", "target_url" : "https://github.com/${{ github.repository }}" }' \
https://api.github.com/repos/${{ github.repository }}/statuses/${{ env.githubCommit }}
exit 1
- name: Success
if: steps.failed.conclusion == 'skipped' || github.ref != 'refs/heads/master'
run: |
echo 'Status check has passed!'
curl -X POST -H "Content-Type: application/json" -H "Authorization: token ${{ github.token }}" \
-d '{ "state" : "success" , "context" : "github/security-status-check" , "description" : "github/security-status-check", "target_url" : "https://github.com/${{ github.repository }}" }' \
https://api.github.com/repos/${{ github.repository }}/statuses/${{ env.githubCommit }}
exit 0

View File

@@ -0,0 +1,5 @@
composer.lock
phpunit.xml
vendor/
reports/
**/.DS_Store

View File

@@ -0,0 +1,45 @@
dist: precise
language: php
php:
- 7.3
- 7.4
- 8.0
- 8.1
install: composer install
before_script:
- cp phpunit.xml.dist phpunit.xml
# These two are required in the build step for non-composer-tests
- mkdir -p libs
- cd libs && wget https://github.com/rmccue/Requests/archive/v2.0.4.zip -O requests.zip && unzip requests.zip && rm requests.zip && cd ..
- rm -rf libs/Requests-2.0.4/examples libs/Requests-2.0.4/docs libs/Requests-2.0.4/bin libs/Requests-2.0.4/tests
script:
# Run a syntax validation check on all PHP files
- find . -path ./vendor -prune -o -iname '*.php' |xargs -n1 php -l
- ./vendor/bin/phpunit
notifications:
slack:
secure: fLT1x7BCXi8+sP1Qk1lP74+60JIBCw2clUTSOmB0OuoQGWYIJ4qelKcGH5FFsADGuC1GX2pf0fKRiLdavVrGpBkD4MGFPpyYKPYb0S/FyArN3PjdaNvAqE1VgQCtKkbugP5bHH9bp631+lo2EGQVLWTjlwiijWbCEyDu3L0YVMY=
# We are doing the releases for non-composer folks
# So this includes the vendor directory
before_deploy:
- echo $TRAVIS_TAG > version.txt
- cat release.txt |zip -r@ "razorpay-php.zip"
deploy:
provider: releases
# Otherwise, we lose the vendor/ directory
skip_cleanup: true
api_key:
secure: bHcu1jUASH6aVSD1LmzXdjQC4hc0o8EBbVs9X8e5j+/OC7+UuBBRu+jh6gQje/XWu9Nj1W2LkWhv0IKX1tJbcs0uRstggx+xC0ZayRzkscsqErqeM4WeyJjxe5ewb2eeGujtl9+WWFB3wpUQJtxXaaPuGYtroYGGYuI23wzKN4A=
# travis doesn't support multi file deployes yet, not that we need them
file: razorpay-php.zip
on:
# Only do the release for one build every tag
php: 7.3
# GitHub refuses to accept releases that are not tagged
tags: true
# Allow builds for non-master branches as well
all_branches: true
# Only do the releases if the repo is not a fork
repo: razorpay/razorpay-php

View File

@@ -0,0 +1,260 @@
# Change Log
Changelog for Razorpay-PHP SDK. Follows [keepachangelog.com](https://keepachangelog.com/en/1.0.0/) for formatting.
## Unreleased
## [2.9.0] - 2023-12-18
feat: Added new API endpoints
* Added support for `addBankAccount`, `deleteBankAccount`, `requestEligibilityCheck` & `fetchEligibility` on customer
* Added support for `uploadAccountDoc` & `fetchAccountDoc` on account
* Added support for [Dispute](https://razorpay.com/docs/api/disputes/)
* Added support for [Document](https://razorpay.com/docs/api/documents/)
* Added support for fetch all IINs Supporting native otps & fetch all IINs with business sub-type using `all`
* Added support for `viewRtoReview` & `editFulfillment` on order
* Added support for fetch a payment (emi/ offer/ card/ upi) using `expandedDetails` on payments
* Added support for `uploadStakeholderDoc` & `fetchStakeholderDoc` on stakeholder
## [2.8.7] - 2023-09-11
[#357](https://github.com/razorpay/razorpay-php/pull/357) [`b29754f`](https://github.com/razorpay/razorpay-php/commit/b29754f8892e0c2035055cf73fd7ab132de18e52) Chore: Changed Content-Type `application/json` for `order create` API from default `application/x-www-form-urlencoded`
## [2.8.6] - 2023-06-16
[#348](https://github.com/razorpay/razorpay-php/pull/348) [`68b2028`](https://github.com/razorpay/razorpay-php/commit/68b2028bafda49af970a098d6d11aa8e5a575d40) feat: Added new API endpoints
* Added account onboarding API (create, fetch, edit, delete)
* Added stakeholders API (create, fetch, fetchAll, edit)
* Added product configuration API (requestProductConfiguration, fetch, edit, fetchTnc)
* Added webhooks API (create, fetch, fetchAll, edit, delete)
* Added token sharing API (create, fetch, delete, processPaymentOnAlternatePAorPG)
## [2.8.5] - 2022-10-19
### Added
- Update [Request](https://github.com/WordPress/Requests/tree/v2.0.4) library to v2.0.4
## [2.8.4] - 2022-06-28
- New APIs for Third party validation (createUpi, validateVpa, fetchPaymentMethods)
- Update documentation
## [2.8.3] - 2022-04-29
- PHP v8.1 is officially supported
- Update [Request](https://github.com/WordPress/Requests/tree/v2.0.0) library to v2.0
- Improve documentation
- Add PHPUnit v9
## [2.8.2] - 2022-03-08
- Change name convention to standard in Unit test
- Removed test api key due to security concern from test cases
## [2.8.1] - 2021-11-08
### Added
- Added Item Api
- Added Unit Tests
## [2.8.0][2.8.0] - 2021-10-07
### Added
- QR code end point API [[#235](https://github.com/razorpay/razorpay-php/pull/235)]
- Update, cancel, create subscription link,fetch details of a Pending Update,cancel, pause and resume subscription API[[#236](https://github.com/razorpay/razorpay-php/pull/236)]
- Smart Collect(Virtual Account) TPV API's [[#238](https://github.com/razorpay/razorpay-php/pull/238)]
- Add/Delete TPV Bank Account [[#239](https://github.com/razorpay/razorpay-php/pull/239)]
- Card end point api [[#240](https://github.com/razorpay/razorpay-php/pull/240)]
- Route end point api [[#241](https://github.com/razorpay/razorpay-php/pull/241)]
- Register emandate and charge first payment together [[#245](https://github.com/razorpay/razorpay-php/pull/245)]
- PaperNACH/Register NACH and charge first payment together [[#246](https://github.com/razorpay/razorpay-php/pull/246)]
- Added payment and Settlements methods [[#247](https://github.com/razorpay/razorpay-php/pull/247)]
- Added edit and notify API's for payment links [[#248](https://github.com/razorpay/razorpay-php/pull/248)]
- Added fetch, fetch multiple refund,edit and notify API's for refunds [[#250](https://github.com/razorpay/razorpay-php/pull/250)]
- Added edit order API [[#251](https://github.com/razorpay/razorpay-php/pull/251)]
- Fund API's end point [[#252](https://github.com/razorpay/razorpay-php/pull/252)]
- UPI [[#253](https://github.com/razorpay/razorpay-php/pull/253)]
- Added payment link paymentverification [[#255](https://github.com/razorpay/razorpay-php/pull/255)]
- Update readme file [[#254](https://github.com/razorpay/razorpay-php/pull/254)]
## [2.7.1][2.7.1] - 2021-09-16
### Added
- Added Payment Link end point API [[#233](https://github.com/razorpay/razorpay-php/pull/233)]
## [2.7.0][2.7.0] - 2021-05-07
### Added
- Adds support for payment page enity API [[#224](https://github.com/razorpay/razorpay-php/pull/224)]
## [2.6.1][2.6.1] - 2021-04-30
### Changed
- Upgrades [requests](https://github.com/rmccue/Requests/) to v1.8. [[#221](https://github.com/razorpay/razorpay-php/pull/221)]
## [2.6.0][2.6.0] - 2021-04-05
### Added
- Adds support for webhook enity API [[#212](https://github.com/razorpay/razorpay-php/pull/212)]
## [2.4.0-beta][2.4.0-beta] - 2018-11-28
### Changed
- Upgrades [requests](https://github.com/rmccue/Requests/) to v1.7. [[#89](https://github.com/razorpay/razorpay-php/pull/89)]
- Enforces TLS1.1+ for all requests. Workaround for a bug in RHEL 6. [[#76](https://github.com/razorpay/razorpay-php/pull/76)]
## [2.3.0][2.3.0] - 2018-09-15
### Added
- Add parameters to Subscription Cancel API
- Support for fetching Settlements
## [2.2.1][2.2.1] - 2018-05-28
### Added
- Support for fetching all customer entities
## [2.2.0][2.2.0] - 2017-10-23
### Added
- Support for VirtualAccount entity
- Support for Subscriptions
## [2.1.0][2.1.0] - 2017-10-10
### Added
- Support for new actions(cancel, notifyBy, edit, issue, delete) on invoices
- Removes PHP 5.3 from list of versions to test build against
## [2.0.2][2.0.2] - 2017-08-03
### Added
- Support for creating and fetching Transfers
- Support for creating Reversals on transfers
## [2.0.1][2.0.1] - 2017-07-31
### Fixed
- Webhook signature verification
- Conditional require of Request class
## [2.0.0][2.0.0] - 2017-03-07
### Added
- Support for custom Application header
- Support for card entity
- Support for Webhook and Order Signature verification
- Support for direct refund creation via Razorpay\Api\Refund::create()
- Support for Utility functions via Razorpay\Api\Utility::verifyPaymentSignature and Razorpay\Api\Utility::verifyWebhookSignature
- Support for case insensitive error codes
- Support for 2xx HTTP status codes
### Changed
- Razorpay\Api\Payment::refunds() now returns a Razorpay\Api\Collection object instead of Razorpay\Api\Refund object
- Razorpay\Api\Api::$baseUrl, Razorpay\Api\Api::$key and Razorpay\Api\Api::$secret are now `protected` instead of `public`
## [1.2.9][1.2.9] - 2017-01-03
### Added
- Support for creating and fetching Invoices
## [1.2.8][1.2.8] - 2016-10-12
### Added
- Support for Customer and Token entities
## [1.2.7][1.2.7] - 2016-09-21
### Added
- Increases the request timeout to 30 seconds for all requests.
## [1.2.6][1.2.6] - 2016-03-28
### Added
- Adds better tracing when client is not able to recognize server response.
## [1.2.5][1.2.5] - 2016-03-28
### Added
- Add support for overriding request headers via setHeader
## [1.2.3][1.2.3] - 2016-02-24
### Added
- Add support for Orders
## [1.2.2][1.2.2] - 2016-02-17
### Changed
- Razorpay\Api\Request::checkErrors is now `protected` instead of `private`
- The final build is now leaner and includes just requests, instead of entire vendor directory
## [1.2.1][1.2.1] - 2016-01-21
### Added
- Add version.txt in release with current git tag
- This changelog file
- `Api\Request::getHeaders()` method
## [1.2.0][1.2.0] - 2015-10-23
### Added
- Add version string to User Agent
### Changed
- New release process that pushes pre-packaged zip files to GitHub
## 1.0.0 - 2015-01-18
### Added
- Initial Release
[unreleased]: https://github.com/razorpay/razorpay-php/compare/2.5.0...HEAD
[1.2.1]: https://github.com/razorpay/razorpay-php/compare/1.2.0...1.2.1
[1.2.0]: https://github.com/razorpay/razorpay-php/compare/1.1.0...1.2.0
[1.2.2]: https://github.com/razorpay/razorpay-php/compare/1.2.1...1.2.2
[1.2.3]: https://github.com/razorpay/razorpay-php/compare/1.2.2...1.2.3
[1.2.4]: https://github.com/razorpay/razorpay-php/compare/1.2.3...1.2.4
[1.2.5]: https://github.com/razorpay/razorpay-php/compare/1.2.4...1.2.5
[1.2.6]: https://github.com/razorpay/razorpay-php/compare/1.2.5...1.2.6
[1.2.7]: https://github.com/razorpay/razorpay-php/compare/1.2.6...1.2.7
[1.2.8]: https://github.com/razorpay/razorpay-php/compare/1.2.7...1.2.8
[1.2.9]: https://github.com/razorpay/razorpay-php/compare/1.2.8...1.2.9
[2.0.0]: https://github.com/razorpay/razorpay-php/compare/1.2.9...2.0.0
[2.0.1]: https://github.com/razorpay/razorpay-php/compare/2.0.0...2.0.1
[2.0.2]: https://github.com/razorpay/razorpay-php/compare/2.0.1...2.0.2
[2.1.0]: https://github.com/razorpay/razorpay-php/compare/2.0.2...2.1.0
[2.2.0]: https://github.com/razorpay/razorpay-php/compare/2.1.0...2.2.0
[2.2.1]: https://github.com/razorpay/razorpay-php/compare/2.2.0...2.2.1
[2.3.0]: https://github.com/razorpay/razorpay-php/compare/2.2.1...2.3.0
[2.4.0-beta]: https://github.com/razorpay/razorpay-php/compare/2.3.0...2.4.0-beta
[2.5.0]: https://github.com/razorpay/razorpay-php/compare/2.4.0-beta...2.5.0
[2.8.0]: https://github.com/razorpay/razorpay-php/compare/2.7.1...2.8.0
[2.8.1]: https://github.com/razorpay/razorpay-php/compare/2.8.0...2.8.1
[2.8.2]: https://github.com/razorpay/razorpay-php/compare/2.8.0...2.8.2

View File

@@ -0,0 +1,20 @@
<?php
/**
* Backwards compatibility layer for Requests.
*
* Allows for Composer to autoload the old PSR-0 classes via the custom autoloader.
* This prevents issues with _extending final classes_ (which was the previous solution).
*
* Please see the Changelog for the 2.0.4 release for upgrade notes.
*
* @package Requests
*
* @deprecated 2.0.4 Use the PSR-4 class names instead.
*/
define("REQUESTS_SILENCE_PSR0_DEPRECATIONS",true);
if (class_exists('WpOrg\Requests\Autoload') === false) {
require_once __DIR__. 'libs/Requests-2.0.4/src/Autoload.php';
}
WpOrg\Requests\Autoload::register();

View File

@@ -0,0 +1,7 @@
Copyright 2019 Razorpay
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,106 @@
# razorpay-php
[![Build Status](https://travis-ci.org/razorpay/razorpay-php.svg?branch=master)](https://travis-ci.org/razorpay/razorpay-php) [![Stable](https://img.shields.io/badge/stable-v2.8.0-blue.svg)](https://packagist.org/packages/razorpay/razorpay#2.8.0) [![License](https://poser.pugx.org/razorpay/razorpay/license.svg)](https://packagist.org/packages/razorpay/razorpay)
Official PHP library for [Razorpay API](https://docs.razorpay.com/docs/payments).
Read up here for getting started and understanding the payment flow with Razorpay: <https://docs.razorpay.com/docs/getting-started>
### Prerequisites
- A minimum of PHP 7.3 upto 8.1
## Installation
- If your project using composer, run the below command
```
composer require razorpay/razorpay:2.*
```
- If you are not using composer, download the latest release from [the releases section](https://github.com/razorpay/razorpay-php/releases).
**You should download the `razorpay-php.zip` file**.
After that, include `Razorpay.php` in your application and you can use the API as usual.
##Note:
This PHP library follows the following practices:
- Namespaced under `Razorpay\Api`
- API throws exceptions instead of returning errors
- Options are passed as an array instead of multiple arguments wherever possible
- All requests and responses are communicated over JSON
## Documentation
Documentation of Razorpay's API and their usage is available at <https://docs.razorpay.com>
## Basic Usage
Instantiate the razorpay php instance with `key_id` & `key_secret`. You can obtain the keys from the dashboard app ([https://dashboard.razorpay.com/#/app/keys](https://dashboard.razorpay.com/#/app/keys))
```php
use Razorpay\Api\Api;
$api = new Api($api_key, $api_secret);
```
The resources can be accessed via the `$api` object. All the methods invocations follows the following pattern
```php
// $api->class->function() to access the API
//Example
$api->payment->fetch($paymentId);
```
## Supported Resources
- [Account](documents/account.md)
- [Customer](documents/customer.md)
- [Dispute](documents/dispute.md)
- [Document](documents/document.md)
- [Token](documents/token.md)
- [Order](documents/order.md)
- [Payments](documents/payment.md)
- [Settlements](documents/settlement.md)
- [Refunds](documents/refund.md)
- [Fund](documents/fund.md)
- [Invoice](documents/invoice.md)
- [Iin](documents/Iin.md)
- [Plan](documents/plan.md)
- [Item](documents/item.md)
- [Subscriptions](documents/subscription.md)
- [Add-on](documents/addon.md)
- [Payment Links](documents/paymentLink.md)
- [Product Configuration](documents/productConfiguration.md)
- [Smart Collect](documents/virtualaccount.md)
- [Stakeholder](documents/stakeholder.md)
- [Transfer](documents/transfer.md)
- [QR Code](documents/qrcode.md)
- [Emandate](documents/emandate.md)
- [Cards](documents/card.md)
- [Paper NACH](documents/papernach.md)
- [UPI](documents/upi.md)
- [Register Emandate and Charge First Payment Together](documents/registeremandate.md)
- [Register NACH and Charge First Payment Together](documents/registernach.md)
- [Payment Verification](documents/paymentVerfication.md)
- [Webhook](documents/webhook.md)
## Development
See the [doc.md](doc.md) file for getting started with development.
## Release
Steps to follow for a release:
0. Merge the branch with the new code to master.
1. Bump the Version in `src/Api.php`.
2. Rename Unreleased to the new tag in `CHANGELOG.md`
3. Add a new empty "Unreleased" section at the top of `CHANGELOG.md`
4. Fix links at bottom in `CHANGELOG.md`
5. Commit
6. Tag the release and push to GitHub
7. A release should automatically be created once the travis build passes. Edit the release to add some description.
## License
The Razorpay PHP SDK is released under the MIT License. See [LICENSE](LICENSE) file for more details.

View File

@@ -0,0 +1,60 @@
<?php
// Include Requests only if not already defined
if (!defined('REQUESTS_SILENCE_PSR0_DEPRECATIONS'))
{
define('REQUESTS_SILENCE_PSR0_DEPRECATIONS', true);
}
if (class_exists('WpOrg\Requests\Autoload') === false)
{
require_once __DIR__.'/libs/Requests-2.0.4/src/Autoload.php';
}
try
{
WpOrg\Requests\Autoload::register();
if (version_compare(Requests::VERSION, '1.6.0') === -1)
{
throw new Exception('Requests class found but did not match');
}
}
catch (\Exception $e)
{
throw new Exception('Requests class found but did not match');
}
spl_autoload_register(function ($class)
{
// project-specific namespace prefix
$prefix = 'Razorpay\Api';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/src/';
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0)
{
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
//
// replace the namespace prefix with the base directory,
// replace namespace separators with directory separators
// in the relative class name, append with .php
//
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file))
{
require $file;
}
});

View File

@@ -0,0 +1,41 @@
{
"name": "razorpay/razorpay",
"description": "Razorpay PHP Client Library",
"keywords": ["razorpay", "api", "php", "client"],
"authors": [
{
"name": "Abhay Rana",
"email": "nemo@razorpay.com",
"homepage": "https://captnemo.in",
"role": "Developer"
},
{
"name": "Shashank Kumar",
"email": "shashank@razorpay.com",
"role": "Developer"
}
],
"support": {
"email": "contact@razorpay.com",
"issues": "https://github.com/Razorpay/razorpay-php/issues",
"source": "https://github.com/Razorpay/razorpay-php"
},
"homepage": "https://docs.razorpay.com",
"license": "MIT",
"require": {
"php": ">=7.3",
"rmccue/requests": "^2.0",
"ext-json": "*"
},
"require-dev": {
"raveren/kint": "1.*",
"phpunit/phpunit": "^9"
},
"autoload": {
"psr-4": {
"Razorpay\\Api\\": "src/",
"Razorpay\\Tests\\": "tests/"
},
"files" : ["Deprecated.php"]
}
}

View File

@@ -0,0 +1,48 @@
This document talks about the implementation of the code for the Api.
Everything comes under namespace Razorpay\Api\.
Namespaces put a requirement of PHP 5.3 minimum
```php
namespace Razorpay\
class Api
{
// Contains a __get function that returns the appropriate
// class object when one tries to access them.
}
namespace Razorpay\
class Client
{
// Handles request and response
// Uses Composer:Requests internally
}
class Payment
{
public function get($id)
{
}
public function fetch($options)
{
}
public function capture($id)
{
}
public function refund($id)
{
}
}
```

View File

@@ -0,0 +1,15 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = tab
[{*.json,*.yml}]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false

View File

@@ -0,0 +1,49 @@
Requests
========
Copyright (c) 2010-2012 Ryan McCue and contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ComplexPie IRI Parser
=====================
Copyright (c) 2007-2010, Geoffrey Sneddon and Steve Minutillo.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the SimplePie Team nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,168 @@
Requests for PHP
================
[![CS](https://github.com/WordPress/Requests/actions/workflows/cs.yml/badge.svg)](https://github.com/WordPress/Requests/actions/workflows/cs.yml)
[![Lint](https://github.com/WordPress/Requests/actions/workflows/lint.yml/badge.svg)](https://github.com/WordPress/Requests/actions/workflows/lint.yml)
[![Test](https://github.com/WordPress/Requests/actions/workflows/test.yml/badge.svg)](https://github.com/WordPress/Requests/actions/workflows/test.yml)
[![codecov.io](https://codecov.io/gh/WordPress/Requests/branch/stable/graph/badge.svg?token=AfpxK7WMxj&branch=stable)](https://codecov.io/gh/WordPress/Requests?branch=stable)
Requests is a HTTP library written in PHP, for human beings. It is roughly
based on the API from the excellent [Requests Python
library](http://python-requests.org/). Requests is [ISC
Licensed](https://github.com/WordPress/Requests/blob/stable/LICENSE) (similar to
the new BSD license) and has no dependencies, except for PHP 5.6+.
Despite PHP's use as a language for the web, its tools for sending HTTP requests
are severely lacking. cURL has an
[interesting API](https://www.php.net/curl-setopt), to say the
least, and you can't always rely on it being available. Sockets provide only low
level access, and require you to build most of the HTTP response parsing
yourself.
We all have better things to do. That's why Requests was born.
```php
$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = WpOrg\Requests\Requests::get('https://api.github.com/gists', $headers, $options);
var_dump($request->status_code);
// int(200)
var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"
var_dump($request->body);
// string(26891) "[...]"
```
Requests allows you to send **HEAD**, **GET**, **POST**, **PUT**, **DELETE**,
and **PATCH** HTTP requests. You can add headers, form data, multipart files,
and parameters with basic arrays, and access the response data in the same way.
Requests uses cURL and fsockopen, depending on what your system has available,
but abstracts all the nasty stuff out of your way, providing a consistent API.
Features
--------
- International Domains and URLs
- Browser-style SSL Verification
- Basic/Digest Authentication
- Automatic Decompression
- Connection Timeouts
Installation
------------
### Install with Composer
If you're using [Composer](https://getcomposer.org/) to manage
dependencies, you can add Requests with it.
```sh
composer require rmccue/requests
```
or
```json
{
"require": {
"rmccue/requests": "^2.0"
}
}
```
### Install source from GitHub
To install the source code:
```bash
$ git clone git://github.com/WordPress/Requests.git
```
Next, include the autoloader in your scripts:
```php
require_once '/path/to/Requests/src/Autoload.php';
```
You'll probably also want to register the autoloader:
```php
WpOrg\Requests\Autoload::register();
```
### Install source from zip/tarball
Alternatively, you can fetch a [tarball][] or [zipball][]:
```bash
$ curl -L https://github.com/WordPress/Requests/tarball/stable | tar xzv
(or)
$ wget https://github.com/WordPress/Requests/tarball/stable -O - | tar xzv
```
[tarball]: https://github.com/WordPress/Requests/tarball/stable
[zipball]: https://github.com/WordPress/Requests/zipball/stable
### Using a Class Loader
If you're using a class loader (e.g., [Symfony Class Loader][]) for
[PSR-4][]-style class loading:
```php
$loader = new Psr4ClassLoader();
$loader->addPrefix('WpOrg\\Requests\\', 'path/to/vendor/Requests/src');
$loader->register();
```
[Symfony Class Loader]: https://github.com/symfony/ClassLoader
[PSR-4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4.md
Documentation
-------------
The best place to start is our [prose-based documentation][], which will guide
you through using Requests.
After that, take a look at [the documentation for
`\WpOrg\Requests\Requests::request()`][request_method], where all the parameters are fully
documented.
Requests is [100% documented with PHPDoc](https://requests.ryanmccue.info/api-2.x/).
If you find any problems with it, [create a new
issue](https://github.com/WordPress/Requests/issues/new)!
[prose-based documentation]: https://github.com/WordPress/Requests/blob/stable/docs/README.md
[request_method]: https://requests.ryanmccue.info/api-2.x/classes/WpOrg-Requests-Requests.html#method_request
Testing
-------
Requests strives to have 100% code-coverage of the library with an extensive
set of tests. We're not quite there yet, but [we're getting close][codecov].
[codecov]: https://codecov.io/github/WordPress/Requests/
To run the test suite, first check that you have the [PHP
JSON extension ](https://www.php.net/book.json) enabled. Then
simply:
```bash
$ phpunit
```
If you'd like to run a single set of tests, specify just the name:
```bash
$ phpunit Transport/cURL
```
Contribute
----------
1. Check for open issues or open a new issue for a feature request or a bug.
2. Fork [the repository][] on Github to start making your changes to the
`develop` branch (or branch off of it).
3. Write one or more tests which show that the bug was fixed or that the feature works as expected.
4. Send in a pull request.
If you have questions while working on your contribution and you use Slack, there is
a [#core-http-api] channel available in the [WordPress Slack] in which contributions can be discussed.
[the repository]: https://github.com/WordPress/Requests
[#core-http-api]: https://wordpress.slack.com/archives/C02BBE29V42
[WordPress Slack]: https://make.wordpress.org/chat/

View File

@@ -0,0 +1 @@
6ed95025fba2aef0ce7b647607225745624497f876d74ef6ec22b26e73e9de77 cacert.pem

View File

@@ -0,0 +1,88 @@
{
"name": "rmccue/requests",
"description": "A HTTP library written in PHP, for human beings.",
"homepage": "https://requests.ryanmccue.info/",
"license": "ISC",
"type": "library",
"keywords": [
"http",
"idna",
"iri",
"ipv6",
"curl",
"sockets",
"fsockopen"
],
"authors": [
{
"name": "Ryan McCue",
"homepage": "https://rmccue.io/"
},
{
"name": "Alain Schlesser",
"homepage": "https://github.com/schlessera"
},
{
"name": "Juliette Reinders Folmer",
"homepage": "https://github.com/jrfnl"
},
{
"name": "Contributors",
"homepage": "https://github.com/WordPress/Requests/graphs/contributors"
}
],
"support": {
"issues": "https://github.com/WordPress/Requests/issues",
"source": "https://github.com/WordPress/Requests",
"docs": "https://requests.ryanmccue.info/"
},
"require": {
"php": ">=5.6",
"ext-json": "*"
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
},
"require-dev": {
"requests/test-server": "dev-main",
"squizlabs/php_codesniffer": "^3.6",
"phpcompatibility/php-compatibility": "^9.0",
"wp-coding-standards/wpcs": "^2.0",
"dealerdirect/phpcodesniffer-composer-installer": "^0.7",
"php-parallel-lint/php-parallel-lint": "^1.3.1",
"php-parallel-lint/php-console-highlighter": "^0.5.0",
"yoast/phpunit-polyfills": "^1.0.0",
"roave/security-advisories": "dev-latest"
},
"autoload": {
"psr-4": {
"WpOrg\\Requests\\": "src/"
},
"classmap": ["library/Requests.php"],
"files": ["library/Deprecated.php"]
},
"autoload-dev": {
"psr-4": {
"WpOrg\\Requests\\Tests\\": "tests/"
}
},
"scripts": {
"lint": [
"@php ./vendor/php-parallel-lint/php-parallel-lint/parallel-lint . -e php --exclude vendor --exclude .git"
],
"checkcs": [
"@php ./vendor/squizlabs/php_codesniffer/bin/phpcs"
],
"fixcs": [
"@php ./vendor/squizlabs/php_codesniffer/bin/phpcbf"
],
"test": [
"@php ./vendor/phpunit/phpunit/phpunit --no-coverage"
],
"coverage": [
"@php ./vendor/phpunit/phpunit/phpunit"
]
}
}

View File

@@ -0,0 +1,19 @@
<?php
/**
* Backwards compatibility layer for Requests.
*
* Allows for Composer to autoload the old PSR-0 classes via the custom autoloader.
* This prevents issues with _extending final classes_ (which was the previous solution).
*
* Please see the Changelog for the 2.0.0 release for upgrade notes.
*
* @package Requests
*
* @deprecated 2.0.0 Use the PSR-4 class names instead.
*/
if (class_exists('WpOrg\Requests\Autoload') === false) {
require_once dirname(__DIR__) . '/src/Autoload.php'; // nosemgrep : https://semgrep.dev/s/e5El
}
WpOrg\Requests\Autoload::register();

View File

@@ -0,0 +1,6 @@
## The Library directory is deprecated.
The files in this directory are only still in place to provide backward compatibility with Requests 1.x.
Please see the release notes of Requests 2.0.0 on how to upgrade.
This directory will be removed in Requests v 4.0.0.

View File

@@ -0,0 +1,78 @@
<?php
/**
* Requests for PHP
*
* Inspired by Requests for Python.
*
* Based on concepts from SimplePie_File, RequestCore and WP_Http.
*
* @package Requests
*
* @deprecated 2.0.0
*/
/*
* Integrators who cannot yet upgrade to the PSR-4 class names can silence deprecations
* by defining a `REQUESTS_SILENCE_PSR0_DEPRECATIONS` constant and setting it to `true`.
* The constant needs to be defined before this class is required.
*/
if (!defined('REQUESTS_SILENCE_PSR0_DEPRECATIONS') || REQUESTS_SILENCE_PSR0_DEPRECATIONS !== true) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
trigger_error(
'The PSR-0 `Requests_...` class names in the Request library are deprecated.'
. ' Switch to the PSR-4 `WpOrg\Requests\...` class names at your earliest convenience.',
E_USER_DEPRECATED
);
// Prevent the deprecation notice from being thrown twice.
if (!defined('REQUESTS_SILENCE_PSR0_DEPRECATIONS')) {
define('REQUESTS_SILENCE_PSR0_DEPRECATIONS', true);
}
}
require_once dirname(__DIR__) . '/src/Requests.php'; // nosemgrep : https://semgrep.dev/s/e5El
/**
* Requests for PHP
*
* Inspired by Requests for Python.
*
* Based on concepts from SimplePie_File, RequestCore and WP_Http.
*
* @package Requests
*
* @deprecated 2.0.0 Use `WpOrg\Requests\Requests` instead for the actual functionality and
* use `WpOrg\Requests\Autoload` for the autoloading.
*/
class Requests extends WpOrg\Requests\Requests {
/**
* Deprecated autoloader for Requests.
*
* @deprecated 2.0.0 Use the `WpOrg\Requests\Autoload::load()` method instead.
*
* @codeCoverageIgnore
*
* @param string $class Class name to load
*/
public static function autoloader($class) {
if (class_exists('WpOrg\Requests\Autoload') === false) {
require_once dirname(__DIR__) . '/src/Autoload.php'; // nosemgrep : https://semgrep.dev/s/e5El
}
return WpOrg\Requests\Autoload::load($class);
}
/**
* Register the built-in autoloader
*
* @deprecated 2.0.0 Include the `WpOrg\Requests\Autoload` class and
* call `WpOrg\Requests\Autoload::register()` instead.
*
* @codeCoverageIgnore
*/
public static function register_autoloader() {
require_once dirname(__DIR__) . '/src/Autoload.php'; // nosemgrep : https://semgrep.dev/s/e5El
WpOrg\Requests\Autoload::register();
}
}

View File

@@ -0,0 +1,36 @@
<?php
/**
* Authentication provider interface
*
* @package Requests\Authentication
*/
namespace WpOrg\Requests;
use WpOrg\Requests\Hooks;
/**
* Authentication provider interface
*
* Implement this interface to act as an authentication provider.
*
* Parameters should be passed via the constructor where possible, as this
* makes it much easier for users to use your provider.
*
* @see \WpOrg\Requests\Hooks
*
* @package Requests\Authentication
*/
interface Auth {
/**
* Register hooks as needed
*
* This method is called in {@see \WpOrg\Requests\Requests::request()} when the user
* has set an instance as the 'auth' option. Use this callback to register all the
* hooks you'll need.
*
* @see \WpOrg\Requests\Hooks::register()
* @param \WpOrg\Requests\Hooks $hooks Hook system
*/
public function register(Hooks $hooks);
}

View File

@@ -0,0 +1,103 @@
<?php
/**
* Basic Authentication provider
*
* @package Requests\Authentication
*/
namespace WpOrg\Requests\Auth;
use WpOrg\Requests\Auth;
use WpOrg\Requests\Exception\ArgumentCount;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Hooks;
/**
* Basic Authentication provider
*
* Provides a handler for Basic HTTP authentication via the Authorization
* header.
*
* @package Requests\Authentication
*/
class Basic implements Auth {
/**
* Username
*
* @var string
*/
public $user;
/**
* Password
*
* @var string
*/
public $pass;
/**
* Constructor
*
* @since 2.0 Throws an `InvalidArgument` exception.
* @since 2.0 Throws an `ArgumentCount` exception instead of the Requests base `Exception.
*
* @param array|null $args Array of user and password. Must have exactly two elements
*
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not an array or null.
* @throws \WpOrg\Requests\Exception\ArgumentCount On incorrect number of array elements (`authbasicbadargs`).
*/
public function __construct($args = null) {
if (is_array($args)) {
if (count($args) !== 2) {
throw ArgumentCount::create('an array with exactly two elements', count($args), 'authbasicbadargs');
}
list($this->user, $this->pass) = $args;
return;
}
if ($args !== null) {
throw InvalidArgument::create(1, '$args', 'array|null', gettype($args));
}
}
/**
* Register the necessary callbacks
*
* @see \WpOrg\Requests\Auth\Basic::curl_before_send()
* @see \WpOrg\Requests\Auth\Basic::fsockopen_header()
* @param \WpOrg\Requests\Hooks $hooks Hook system
*/
public function register(Hooks $hooks) {
$hooks->register('curl.before_send', [$this, 'curl_before_send']);
$hooks->register('fsockopen.after_headers', [$this, 'fsockopen_header']);
}
/**
* Set cURL parameters before the data is sent
*
* @param resource|\CurlHandle $handle cURL handle
*/
public function curl_before_send(&$handle) {
curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString());
}
/**
* Add extra headers to the request before sending
*
* @param string $out HTTP header string
*/
public function fsockopen_header(&$out) {
$out .= sprintf("Authorization: Basic %s\r\n", base64_encode($this->getAuthString()));
}
/**
* Get the authentication string (user:pass)
*
* @return string
*/
public function getAuthString() {
return $this->user . ':' . $this->pass;
}
}

View File

@@ -0,0 +1,187 @@
<?php
/**
* Autoloader for Requests for PHP.
*
* Include this file if you'd like to avoid having to create your own autoloader.
*
* @package Requests
* @since 2.0.0
*
* @codeCoverageIgnore
*/
namespace WpOrg\Requests;
/*
* Ensure the autoloader is only declared once.
* This safeguard is in place as this is the typical entry point for this library
* and this file being required unconditionally could easily cause
* fatal "Class already declared" errors.
*/
if (class_exists('WpOrg\Requests\Autoload') === false) {
/**
* Autoloader for Requests for PHP.
*
* This autoloader supports the PSR-4 based Requests 2.0.0 classes in a case-sensitive manner
* as the most common server OS-es are case-sensitive and the file names are in mixed case.
*
* For the PSR-0 Requests 1.x BC-layer, requested classes will be treated case-insensitively.
*
* @package Requests
*/
final class Autoload {
/**
* List of the old PSR-0 class names in lowercase as keys with their PSR-4 case-sensitive name as a value.
*
* @var array
*/
private static $deprecated_classes = [
// Interfaces.
'requests_auth' => '\WpOrg\Requests\Auth',
'requests_hooker' => '\WpOrg\Requests\HookManager',
'requests_proxy' => '\WpOrg\Requests\Proxy',
'requests_transport' => '\WpOrg\Requests\Transport',
// Classes.
'requests_cookie' => '\WpOrg\Requests\Cookie',
'requests_exception' => '\WpOrg\Requests\Exception',
'requests_hooks' => '\WpOrg\Requests\Hooks',
'requests_idnaencoder' => '\WpOrg\Requests\IdnaEncoder',
'requests_ipv6' => '\WpOrg\Requests\Ipv6',
'requests_iri' => '\WpOrg\Requests\Iri',
'requests_response' => '\WpOrg\Requests\Response',
'requests_session' => '\WpOrg\Requests\Session',
'requests_ssl' => '\WpOrg\Requests\Ssl',
'requests_auth_basic' => '\WpOrg\Requests\Auth\Basic',
'requests_cookie_jar' => '\WpOrg\Requests\Cookie\Jar',
'requests_proxy_http' => '\WpOrg\Requests\Proxy\Http',
'requests_response_headers' => '\WpOrg\Requests\Response\Headers',
'requests_transport_curl' => '\WpOrg\Requests\Transport\Curl',
'requests_transport_fsockopen' => '\WpOrg\Requests\Transport\Fsockopen',
'requests_utility_caseinsensitivedictionary' => '\WpOrg\Requests\Utility\CaseInsensitiveDictionary',
'requests_utility_filterediterator' => '\WpOrg\Requests\Utility\FilteredIterator',
'requests_exception_http' => '\WpOrg\Requests\Exception\Http',
'requests_exception_transport' => '\WpOrg\Requests\Exception\Transport',
'requests_exception_transport_curl' => '\WpOrg\Requests\Exception\Transport\Curl',
'requests_exception_http_304' => '\WpOrg\Requests\Exception\Http\Status304',
'requests_exception_http_305' => '\WpOrg\Requests\Exception\Http\Status305',
'requests_exception_http_306' => '\WpOrg\Requests\Exception\Http\Status306',
'requests_exception_http_400' => '\WpOrg\Requests\Exception\Http\Status400',
'requests_exception_http_401' => '\WpOrg\Requests\Exception\Http\Status401',
'requests_exception_http_402' => '\WpOrg\Requests\Exception\Http\Status402',
'requests_exception_http_403' => '\WpOrg\Requests\Exception\Http\Status403',
'requests_exception_http_404' => '\WpOrg\Requests\Exception\Http\Status404',
'requests_exception_http_405' => '\WpOrg\Requests\Exception\Http\Status405',
'requests_exception_http_406' => '\WpOrg\Requests\Exception\Http\Status406',
'requests_exception_http_407' => '\WpOrg\Requests\Exception\Http\Status407',
'requests_exception_http_408' => '\WpOrg\Requests\Exception\Http\Status408',
'requests_exception_http_409' => '\WpOrg\Requests\Exception\Http\Status409',
'requests_exception_http_410' => '\WpOrg\Requests\Exception\Http\Status410',
'requests_exception_http_411' => '\WpOrg\Requests\Exception\Http\Status411',
'requests_exception_http_412' => '\WpOrg\Requests\Exception\Http\Status412',
'requests_exception_http_413' => '\WpOrg\Requests\Exception\Http\Status413',
'requests_exception_http_414' => '\WpOrg\Requests\Exception\Http\Status414',
'requests_exception_http_415' => '\WpOrg\Requests\Exception\Http\Status415',
'requests_exception_http_416' => '\WpOrg\Requests\Exception\Http\Status416',
'requests_exception_http_417' => '\WpOrg\Requests\Exception\Http\Status417',
'requests_exception_http_418' => '\WpOrg\Requests\Exception\Http\Status418',
'requests_exception_http_428' => '\WpOrg\Requests\Exception\Http\Status428',
'requests_exception_http_429' => '\WpOrg\Requests\Exception\Http\Status429',
'requests_exception_http_431' => '\WpOrg\Requests\Exception\Http\Status431',
'requests_exception_http_500' => '\WpOrg\Requests\Exception\Http\Status500',
'requests_exception_http_501' => '\WpOrg\Requests\Exception\Http\Status501',
'requests_exception_http_502' => '\WpOrg\Requests\Exception\Http\Status502',
'requests_exception_http_503' => '\WpOrg\Requests\Exception\Http\Status503',
'requests_exception_http_504' => '\WpOrg\Requests\Exception\Http\Status504',
'requests_exception_http_505' => '\WpOrg\Requests\Exception\Http\Status505',
'requests_exception_http_511' => '\WpOrg\Requests\Exception\Http\Status511',
'requests_exception_http_unknown' => '\WpOrg\Requests\Exception\Http\StatusUnknown',
];
/**
* Register the autoloader.
*
* Note: the autoloader is *prepended* in the autoload queue.
* This is done to ensure that the Requests 2.0 autoloader takes precedence
* over a potentially (dependency-registered) Requests 1.x autoloader.
*
* @internal This method contains a safeguard against the autoloader being
* registered multiple times. This safeguard uses a global constant to
* (hopefully/in most cases) still function correctly, even if the
* class would be renamed.
*
* @return void
*/
public static function register() {
if (defined('REQUESTS_AUTOLOAD_REGISTERED') === false) {
spl_autoload_register([self::class, 'load'], true);
define('REQUESTS_AUTOLOAD_REGISTERED', true);
}
}
/**
* Autoloader.
*
* @param string $class_name Name of the class name to load.
*
* @return bool Whether a class was loaded or not.
*/
public static function load($class_name) {
// Check that the class starts with "Requests" (PSR-0) or "WpOrg\Requests" (PSR-4).
$psr_4_prefix_pos = strpos($class_name, 'WpOrg\\Requests\\');
if (stripos($class_name, 'Requests') !== 0 && $psr_4_prefix_pos !== 0) {
return false;
}
$class_lower = strtolower($class_name);
if ($class_lower === 'requests') {
// Reference to the original PSR-0 Requests class.
$file = dirname(__DIR__) . '/library/Requests.php';
} elseif ($psr_4_prefix_pos === 0) {
// PSR-4 classname.
$file = __DIR__ . '/' . strtr(substr($class_name, 15), '\\', '/') . '.php';
}
if (isset($file) && file_exists($file)) {
include $file; // nosemgrep : https://semgrep.dev/s/e5El
return true;
}
/*
* Okay, so the class starts with "Requests", but we couldn't find the file.
* If this is one of the deprecated/renamed PSR-0 classes being requested,
* let's alias it to the new name and throw a deprecation notice.
*/
if (isset(self::$deprecated_classes[$class_lower])) {
/*
* Integrators who cannot yet upgrade to the PSR-4 class names can silence deprecations
* by defining a `REQUESTS_SILENCE_PSR0_DEPRECATIONS` constant and setting it to `true`.
* The constant needs to be defined before the first deprecated class is requested
* via this autoloader.
*/
if (!defined('REQUESTS_SILENCE_PSR0_DEPRECATIONS') || REQUESTS_SILENCE_PSR0_DEPRECATIONS !== true) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
trigger_error(
'The PSR-0 `Requests_...` class names in the Request library are deprecated.'
. ' Switch to the PSR-4 `WpOrg\Requests\...` class names at your earliest convenience.',
E_USER_DEPRECATED
);
// Prevent the deprecation notice from being thrown twice.
if (!defined('REQUESTS_SILENCE_PSR0_DEPRECATIONS')) {
define('REQUESTS_SILENCE_PSR0_DEPRECATIONS', true);
}
}
// Create an alias and let the autoloader recursively kick in to load the PSR-4 class.
return class_alias(self::$deprecated_classes[$class_lower], $class_name, true);
}
return false;
}
}
}

View File

@@ -0,0 +1,36 @@
<?php
/**
* Capability interface declaring the known capabilities.
*
* @package Requests\Utilities
*/
namespace WpOrg\Requests;
/**
* Capability interface declaring the known capabilities.
*
* This is used as the authoritative source for which capabilities can be queried.
*
* @package Requests\Utilities
*/
interface Capability {
/**
* Support for SSL.
*
* @var string
*/
const SSL = 'ssl';
/**
* Collection of all capabilities supported in Requests.
*
* Note: this does not automatically mean that the capability will be supported for your chosen transport!
*
* @var array<string>
*/
const ALL = [
self::SSL,
];
}

View File

@@ -0,0 +1,522 @@
<?php
/**
* Cookie storage object
*
* @package Requests\Cookies
*/
namespace WpOrg\Requests;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Iri;
use WpOrg\Requests\Response\Headers;
use WpOrg\Requests\Utility\CaseInsensitiveDictionary;
use WpOrg\Requests\Utility\InputValidator;
/**
* Cookie storage object
*
* @package Requests\Cookies
*/
class Cookie {
/**
* Cookie name.
*
* @var string
*/
public $name;
/**
* Cookie value.
*
* @var string
*/
public $value;
/**
* Cookie attributes
*
* Valid keys are (currently) path, domain, expires, max-age, secure and
* httponly.
*
* @var \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array Array-like object
*/
public $attributes = [];
/**
* Cookie flags
*
* Valid keys are (currently) creation, last-access, persistent and
* host-only.
*
* @var array
*/
public $flags = [];
/**
* Reference time for relative calculations
*
* This is used in place of `time()` when calculating Max-Age expiration and
* checking time validity.
*
* @var int
*/
public $reference_time = 0;
/**
* Create a new cookie object
*
* @param string $name
* @param string $value
* @param array|\WpOrg\Requests\Utility\CaseInsensitiveDictionary $attributes Associative array of attribute data
* @param array $flags
* @param int|null $reference_time
*
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $name argument is not a string.
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $value argument is not a string.
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $attributes argument is not an array or iterable object with array access.
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $flags argument is not an array.
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $reference_time argument is not an integer or null.
*/
public function __construct($name, $value, $attributes = [], $flags = [], $reference_time = null) {
if (is_string($name) === false) {
throw InvalidArgument::create(1, '$name', 'string', gettype($name));
}
if (is_string($value) === false) {
throw InvalidArgument::create(2, '$value', 'string', gettype($value));
}
if (InputValidator::has_array_access($attributes) === false || InputValidator::is_iterable($attributes) === false) {
throw InvalidArgument::create(3, '$attributes', 'array|ArrayAccess&Traversable', gettype($attributes));
}
if (is_array($flags) === false) {
throw InvalidArgument::create(4, '$flags', 'array', gettype($flags));
}
if ($reference_time !== null && is_int($reference_time) === false) {
throw InvalidArgument::create(5, '$reference_time', 'integer|null', gettype($reference_time));
}
$this->name = $name;
$this->value = $value;
$this->attributes = $attributes;
$default_flags = [
'creation' => time(),
'last-access' => time(),
'persistent' => false,
'host-only' => true,
];
$this->flags = array_merge($default_flags, $flags);
$this->reference_time = time();
if ($reference_time !== null) {
$this->reference_time = $reference_time;
}
$this->normalize();
}
/**
* Get the cookie value
*
* Attributes and other data can be accessed via methods.
*/
public function __toString() {
return $this->value;
}
/**
* Check if a cookie is expired.
*
* Checks the age against $this->reference_time to determine if the cookie
* is expired.
*
* @return boolean True if expired, false if time is valid.
*/
public function is_expired() {
// RFC6265, s. 4.1.2.2:
// If a cookie has both the Max-Age and the Expires attribute, the Max-
// Age attribute has precedence and controls the expiration date of the
// cookie.
if (isset($this->attributes['max-age'])) {
$max_age = $this->attributes['max-age'];
return $max_age < $this->reference_time;
}
if (isset($this->attributes['expires'])) {
$expires = $this->attributes['expires'];
return $expires < $this->reference_time;
}
return false;
}
/**
* Check if a cookie is valid for a given URI
*
* @param \WpOrg\Requests\Iri $uri URI to check
* @return boolean Whether the cookie is valid for the given URI
*/
public function uri_matches(Iri $uri) {
if (!$this->domain_matches($uri->host)) {
return false;
}
if (!$this->path_matches($uri->path)) {
return false;
}
return empty($this->attributes['secure']) || $uri->scheme === 'https';
}
/**
* Check if a cookie is valid for a given domain
*
* @param string $domain Domain to check
* @return boolean Whether the cookie is valid for the given domain
*/
public function domain_matches($domain) {
if (is_string($domain) === false) {
return false;
}
if (!isset($this->attributes['domain'])) {
// Cookies created manually; cookies created by Requests will set
// the domain to the requested domain
return true;
}
$cookie_domain = $this->attributes['domain'];
if ($cookie_domain === $domain) {
// The cookie domain and the passed domain are identical.
return true;
}
// If the cookie is marked as host-only and we don't have an exact
// match, reject the cookie
if ($this->flags['host-only'] === true) {
return false;
}
if (strlen($domain) <= strlen($cookie_domain)) {
// For obvious reasons, the cookie domain cannot be a suffix if the passed domain
// is shorter than the cookie domain
return false;
}
if (substr($domain, -1 * strlen($cookie_domain)) !== $cookie_domain) {
// The cookie domain should be a suffix of the passed domain.
return false;
}
$prefix = substr($domain, 0, strlen($domain) - strlen($cookie_domain));
if (substr($prefix, -1) !== '.') {
// The last character of the passed domain that is not included in the
// domain string should be a %x2E (".") character.
return false;
}
// The passed domain should be a host name (i.e., not an IP address).
return !preg_match('#^(.+\.)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $domain);
}
/**
* Check if a cookie is valid for a given path
*
* From the path-match check in RFC 6265 section 5.1.4
*
* @param string $request_path Path to check
* @return boolean Whether the cookie is valid for the given path
*/
public function path_matches($request_path) {
if (empty($request_path)) {
// Normalize empty path to root
$request_path = '/';
}
if (!isset($this->attributes['path'])) {
// Cookies created manually; cookies created by Requests will set
// the path to the requested path
return true;
}
if (is_scalar($request_path) === false) {
return false;
}
$cookie_path = $this->attributes['path'];
if ($cookie_path === $request_path) {
// The cookie-path and the request-path are identical.
return true;
}
if (strlen($request_path) > strlen($cookie_path) && substr($request_path, 0, strlen($cookie_path)) === $cookie_path) {
if (substr($cookie_path, -1) === '/') {
// The cookie-path is a prefix of the request-path, and the last
// character of the cookie-path is %x2F ("/").
return true;
}
if (substr($request_path, strlen($cookie_path), 1) === '/') {
// The cookie-path is a prefix of the request-path, and the
// first character of the request-path that is not included in
// the cookie-path is a %x2F ("/") character.
return true;
}
}
return false;
}
/**
* Normalize cookie and attributes
*
* @return boolean Whether the cookie was successfully normalized
*/
public function normalize() {
foreach ($this->attributes as $key => $value) {
$orig_value = $value;
$value = $this->normalize_attribute($key, $value);
if ($value === null) {
unset($this->attributes[$key]);
continue;
}
if ($value !== $orig_value) {
$this->attributes[$key] = $value;
}
}
return true;
}
/**
* Parse an individual cookie attribute
*
* Handles parsing individual attributes from the cookie values.
*
* @param string $name Attribute name
* @param string|boolean $value Attribute value (string value, or true if empty/flag)
* @return mixed Value if available, or null if the attribute value is invalid (and should be skipped)
*/
protected function normalize_attribute($name, $value) {
switch (strtolower($name)) {
case 'expires':
// Expiration parsing, as per RFC 6265 section 5.2.1
if (is_int($value)) {
return $value;
}
$expiry_time = strtotime($value);
if ($expiry_time === false) {
return null;
}
return $expiry_time;
case 'max-age':
// Expiration parsing, as per RFC 6265 section 5.2.2
if (is_int($value)) {
return $value;
}
// Check that we have a valid age
if (!preg_match('/^-?\d+$/', $value)) {
return null;
}
$delta_seconds = (int) $value;
if ($delta_seconds <= 0) {
$expiry_time = 0;
} else {
$expiry_time = $this->reference_time + $delta_seconds;
}
return $expiry_time;
case 'domain':
// Domains are not required as per RFC 6265 section 5.2.3
if (empty($value)) {
return null;
}
// Domain normalization, as per RFC 6265 section 5.2.3
if ($value[0] === '.') {
$value = substr($value, 1);
}
return $value;
default:
return $value;
}
}
/**
* Format a cookie for a Cookie header
*
* This is used when sending cookies to a server.
*
* @return string Cookie formatted for Cookie header
*/
public function format_for_header() {
return sprintf('%s=%s', $this->name, $this->value);
}
/**
* Format a cookie for a Set-Cookie header
*
* This is used when sending cookies to clients. This isn't really
* applicable to client-side usage, but might be handy for debugging.
*
* @return string Cookie formatted for Set-Cookie header
*/
public function format_for_set_cookie() {
$header_value = $this->format_for_header();
if (!empty($this->attributes)) {
$parts = [];
foreach ($this->attributes as $key => $value) {
// Ignore non-associative attributes
if (is_numeric($key)) {
$parts[] = $value;
} else {
$parts[] = sprintf('%s=%s', $key, $value);
}
}
$header_value .= '; ' . implode('; ', $parts);
}
return $header_value;
}
/**
* Parse a cookie string into a cookie object
*
* Based on Mozilla's parsing code in Firefox and related projects, which
* is an intentional deviation from RFC 2109 and RFC 2616. RFC 6265
* specifies some of this handling, but not in a thorough manner.
*
* @param string $cookie_header Cookie header value (from a Set-Cookie header)
* @param string $name
* @param int|null $reference_time
* @return \WpOrg\Requests\Cookie Parsed cookie object
*
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $cookie_header argument is not a string.
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $name argument is not a string.
*/
public static function parse($cookie_header, $name = '', $reference_time = null) {
if (is_string($cookie_header) === false) {
throw InvalidArgument::create(1, '$cookie_header', 'string', gettype($cookie_header));
}
if (is_string($name) === false) {
throw InvalidArgument::create(2, '$name', 'string', gettype($name));
}
$parts = explode(';', $cookie_header);
$kvparts = array_shift($parts);
if (!empty($name)) {
$value = $cookie_header;
} elseif (strpos($kvparts, '=') === false) {
// Some sites might only have a value without the equals separator.
// Deviate from RFC 6265 and pretend it was actually a blank name
// (`=foo`)
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=169091
$name = '';
$value = $kvparts;
} else {
list($name, $value) = explode('=', $kvparts, 2);
}
$name = trim($name);
$value = trim($value);
// Attribute keys are handled case-insensitively
$attributes = new CaseInsensitiveDictionary();
if (!empty($parts)) {
foreach ($parts as $part) {
if (strpos($part, '=') === false) {
$part_key = $part;
$part_value = true;
} else {
list($part_key, $part_value) = explode('=', $part, 2);
$part_value = trim($part_value);
}
$part_key = trim($part_key);
$attributes[$part_key] = $part_value;
}
}
return new static($name, $value, $attributes, [], $reference_time);
}
/**
* Parse all Set-Cookie headers from request headers
*
* @param \WpOrg\Requests\Response\Headers $headers Headers to parse from
* @param \WpOrg\Requests\Iri|null $origin URI for comparing cookie origins
* @param int|null $time Reference time for expiration calculation
* @return array
*/
public static function parse_from_headers(Headers $headers, Iri $origin = null, $time = null) {
$cookie_headers = $headers->getValues('Set-Cookie');
if (empty($cookie_headers)) {
return [];
}
$cookies = [];
foreach ($cookie_headers as $header) {
$parsed = self::parse($header, '', $time);
// Default domain/path attributes
if (empty($parsed->attributes['domain']) && !empty($origin)) {
$parsed->attributes['domain'] = $origin->host;
$parsed->flags['host-only'] = true;
} else {
$parsed->flags['host-only'] = false;
}
$path_is_valid = (!empty($parsed->attributes['path']) && $parsed->attributes['path'][0] === '/');
if (!$path_is_valid && !empty($origin)) {
$path = $origin->path;
// Default path normalization as per RFC 6265 section 5.1.4
if (substr($path, 0, 1) !== '/') {
// If the uri-path is empty or if the first character of
// the uri-path is not a %x2F ("/") character, output
// %x2F ("/") and skip the remaining steps.
$path = '/';
} elseif (substr_count($path, '/') === 1) {
// If the uri-path contains no more than one %x2F ("/")
// character, output %x2F ("/") and skip the remaining
// step.
$path = '/';
} else {
// Output the characters of the uri-path from the first
// character up to, but not including, the right-most
// %x2F ("/").
$path = substr($path, 0, strrpos($path, '/'));
}
$parsed->attributes['path'] = $path;
}
// Reject invalid cookie domains
if (!empty($origin) && !$parsed->domain_matches($origin->host)) {
continue;
}
$cookies[$parsed->name] = $parsed;
}
return $cookies;
}
}

View File

@@ -0,0 +1,186 @@
<?php
/**
* Cookie holder object
*
* @package Requests\Cookies
*/
namespace WpOrg\Requests\Cookie;
use ArrayAccess;
use ArrayIterator;
use IteratorAggregate;
use ReturnTypeWillChange;
use WpOrg\Requests\Cookie;
use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\HookManager;
use WpOrg\Requests\Iri;
use WpOrg\Requests\Response;
/**
* Cookie holder object
*
* @package Requests\Cookies
*/
class Jar implements ArrayAccess, IteratorAggregate {
/**
* Actual item data
*
* @var array
*/
protected $cookies = [];
/**
* Create a new jar
*
* @param array $cookies Existing cookie values
*
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not an array.
*/
public function __construct($cookies = []) {
if (is_array($cookies) === false) {
throw InvalidArgument::create(1, '$cookies', 'array', gettype($cookies));
}
$this->cookies = $cookies;
}
/**
* Normalise cookie data into a \WpOrg\Requests\Cookie
*
* @param string|\WpOrg\Requests\Cookie $cookie
* @return \WpOrg\Requests\Cookie
*/
public function normalize_cookie($cookie, $key = '') {
if ($cookie instanceof Cookie) {
return $cookie;
}
return Cookie::parse($cookie, $key);
}
/**
* Check if the given item exists
*
* @param string $offset Item key
* @return boolean Does the item exist?
*/
#[ReturnTypeWillChange]
public function offsetExists($offset) {
return isset($this->cookies[$offset]);
}
/**
* Get the value for the item
*
* @param string $offset Item key
* @return string|null Item value (null if offsetExists is false)
*/
#[ReturnTypeWillChange]
public function offsetGet($offset) {
if (!isset($this->cookies[$offset])) {
return null;
}
return $this->cookies[$offset];
}
/**
* Set the given item
*
* @param string $offset Item name
* @param string $value Item value
*
* @throws \WpOrg\Requests\Exception On attempting to use dictionary as list (`invalidset`)
*/
#[ReturnTypeWillChange]
public function offsetSet($offset, $value) {
if ($offset === null) {
throw new Exception('Object is a dictionary, not a list', 'invalidset');
}
$this->cookies[$offset] = $value;
}
/**
* Unset the given header
*
* @param string $offset
*/
#[ReturnTypeWillChange]
public function offsetUnset($offset) {
unset($this->cookies[$offset]);
}
/**
* Get an iterator for the data
*
* @return \ArrayIterator
*/
#[ReturnTypeWillChange]
public function getIterator() {
return new ArrayIterator($this->cookies);
}
/**
* Register the cookie handler with the request's hooking system
*
* @param \WpOrg\Requests\HookManager $hooks Hooking system
*/
public function register(HookManager $hooks) {
$hooks->register('requests.before_request', [$this, 'before_request']);
$hooks->register('requests.before_redirect_check', [$this, 'before_redirect_check']);
}
/**
* Add Cookie header to a request if we have any
*
* As per RFC 6265, cookies are separated by '; '
*
* @param string $url
* @param array $headers
* @param array $data
* @param string $type
* @param array $options
*/
public function before_request($url, &$headers, &$data, &$type, &$options) {
if (!$url instanceof Iri) {
$url = new Iri($url);
}
if (!empty($this->cookies)) {
$cookies = [];
foreach ($this->cookies as $key => $cookie) {
$cookie = $this->normalize_cookie($cookie, $key);
// Skip expired cookies
if ($cookie->is_expired()) {
continue;
}
if ($cookie->domain_matches($url->host)) {
$cookies[] = $cookie->format_for_header();
}
}
$headers['Cookie'] = implode('; ', $cookies);
}
}
/**
* Parse all cookies from a response and attach them to the response
*
* @param \WpOrg\Requests\Response $response
*/
public function before_redirect_check(Response $response) {
$url = $response->url;
if (!$url instanceof Iri) {
$url = new Iri($url);
}
$cookies = Cookie::parse_from_headers($response->headers, $url);
$this->cookies = array_merge($this->cookies, $cookies);
$response->cookies = $this;
}
}

View File

@@ -0,0 +1,66 @@
<?php
/**
* Exception for HTTP requests
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests;
use Exception as PHPException;
/**
* Exception for HTTP requests
*
* @package Requests\Exceptions
*/
class Exception extends PHPException {
/**
* Type of exception
*
* @var string
*/
protected $type;
/**
* Data associated with the exception
*
* @var mixed
*/
protected $data;
/**
* Create a new exception
*
* @param string $message Exception message
* @param string $type Exception type
* @param mixed $data Associated data
* @param integer $code Exception numerical code, if applicable
*/
public function __construct($message, $type, $data = null, $code = 0) {
parent::__construct($message, $code);
$this->type = $type;
$this->data = $data;
}
/**
* Like {@see \Exception::getCode()}, but a string code.
*
* @codeCoverageIgnore
* @return string
*/
public function getType() {
return $this->type;
}
/**
* Gives any relevant data
*
* @codeCoverageIgnore
* @return mixed
*/
public function getData() {
return $this->data;
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace WpOrg\Requests\Exception;
use WpOrg\Requests\Exception;
/**
* Exception for when an incorrect number of arguments are passed to a method.
*
* Typically, this exception is used when all arguments for a method are optional,
* but certain arguments need to be passed together, i.e. a method which can be called
* with no arguments or with two arguments, but not with one argument.
*
* Along the same lines, this exception is also used if a method expects an array
* with a certain number of elements and the provided number of elements does not comply.
*
* @package Requests\Exceptions
* @since 2.0.0
*/
final class ArgumentCount extends Exception {
/**
* Create a new argument count exception with a standardized text.
*
* @param string $expected The argument count expected as a phrase.
* For example: `at least 2 arguments` or `exactly 1 argument`.
* @param int $received The actual argument count received.
* @param string $type Exception type.
*
* @return \WpOrg\Requests\Exception\ArgumentCount
*/
public static function create($expected, $received, $type) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
$stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
return new self(
sprintf(
'%s::%s() expects %s, %d given',
$stack[1]['class'],
$stack[1]['function'],
$expected,
$received
),
$type
);
}
}

View File

@@ -0,0 +1,78 @@
<?php
/**
* Exception based on HTTP response
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception;
use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\Http\StatusUnknown;
/**
* Exception based on HTTP response
*
* @package Requests\Exceptions
*/
class Http extends Exception {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 0;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Unknown';
/**
* Create a new exception
*
* There is no mechanism to pass in the status code, as this is set by the
* subclass used. Reason phrases can vary, however.
*
* @param string|null $reason Reason phrase
* @param mixed $data Associated data
*/
public function __construct($reason = null, $data = null) {
if ($reason !== null) {
$this->reason = $reason;
}
$message = sprintf('%d %s', $this->code, $this->reason);
parent::__construct($message, 'httpresponse', $data, $this->code);
}
/**
* Get the status message.
*
* @return string
*/
public function getReason() {
return $this->reason;
}
/**
* Get the correct exception class for a given error code
*
* @param int|bool $code HTTP status code, or false if unavailable
* @return string Exception class name to use
*/
public static function get_class($code) {
if (!$code) {
return StatusUnknown::class;
}
$class = sprintf('\WpOrg\Requests\Exception\Http\Status%d', $code);
if (class_exists($class)) {
return $class;
}
return StatusUnknown::class;
}
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 304 Not Modified responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 304 Not Modified responses
*
* @package Requests\Exceptions
*/
final class Status304 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 304;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Not Modified';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 305 Use Proxy responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 305 Use Proxy responses
*
* @package Requests\Exceptions
*/
final class Status305 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 305;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Use Proxy';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 306 Switch Proxy responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 306 Switch Proxy responses
*
* @package Requests\Exceptions
*/
final class Status306 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 306;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Switch Proxy';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 400 Bad Request responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 400 Bad Request responses
*
* @package Requests\Exceptions
*/
final class Status400 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 400;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Bad Request';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 401 Unauthorized responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 401 Unauthorized responses
*
* @package Requests\Exceptions
*/
final class Status401 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 401;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Unauthorized';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 402 Payment Required responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 402 Payment Required responses
*
* @package Requests\Exceptions
*/
final class Status402 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 402;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Payment Required';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 403 Forbidden responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 403 Forbidden responses
*
* @package Requests\Exceptions
*/
final class Status403 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 403;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Forbidden';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 404 Not Found responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 404 Not Found responses
*
* @package Requests\Exceptions
*/
final class Status404 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 404;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Not Found';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 405 Method Not Allowed responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 405 Method Not Allowed responses
*
* @package Requests\Exceptions
*/
final class Status405 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 405;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Method Not Allowed';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 406 Not Acceptable responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 406 Not Acceptable responses
*
* @package Requests\Exceptions
*/
final class Status406 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 406;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Not Acceptable';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 407 Proxy Authentication Required responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 407 Proxy Authentication Required responses
*
* @package Requests\Exceptions
*/
final class Status407 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 407;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Proxy Authentication Required';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 408 Request Timeout responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 408 Request Timeout responses
*
* @package Requests\Exceptions
*/
final class Status408 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 408;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Request Timeout';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 409 Conflict responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 409 Conflict responses
*
* @package Requests\Exceptions
*/
final class Status409 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 409;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Conflict';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 410 Gone responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 410 Gone responses
*
* @package Requests\Exceptions
*/
final class Status410 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 410;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Gone';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 411 Length Required responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 411 Length Required responses
*
* @package Requests\Exceptions
*/
final class Status411 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 411;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Length Required';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 412 Precondition Failed responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 412 Precondition Failed responses
*
* @package Requests\Exceptions
*/
final class Status412 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 412;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Precondition Failed';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 413 Request Entity Too Large responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 413 Request Entity Too Large responses
*
* @package Requests\Exceptions
*/
final class Status413 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 413;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Request Entity Too Large';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 414 Request-URI Too Large responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 414 Request-URI Too Large responses
*
* @package Requests\Exceptions
*/
final class Status414 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 414;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Request-URI Too Large';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 415 Unsupported Media Type responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 415 Unsupported Media Type responses
*
* @package Requests\Exceptions
*/
final class Status415 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 415;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Unsupported Media Type';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 416 Requested Range Not Satisfiable responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 416 Requested Range Not Satisfiable responses
*
* @package Requests\Exceptions
*/
final class Status416 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 416;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Requested Range Not Satisfiable';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 417 Expectation Failed responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 417 Expectation Failed responses
*
* @package Requests\Exceptions
*/
final class Status417 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 417;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Expectation Failed';
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* Exception for 418 I'm A Teapot responses
*
* @link https://tools.ietf.org/html/rfc2324
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 418 I'm A Teapot responses
*
* @link https://tools.ietf.org/html/rfc2324
*
* @package Requests\Exceptions
*/
final class Status418 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 418;
/**
* Reason phrase
*
* @var string
*/
protected $reason = "I'm A Teapot";
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* Exception for 428 Precondition Required responses
*
* @link https://tools.ietf.org/html/rfc6585
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 428 Precondition Required responses
*
* @link https://tools.ietf.org/html/rfc6585
*
* @package Requests\Exceptions
*/
final class Status428 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 428;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Precondition Required';
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* Exception for 429 Too Many Requests responses
*
* @link https://tools.ietf.org/html/draft-nottingham-http-new-status-04
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 429 Too Many Requests responses
*
* @link https://tools.ietf.org/html/draft-nottingham-http-new-status-04
*
* @package Requests\Exceptions
*/
final class Status429 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 429;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Too Many Requests';
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* Exception for 431 Request Header Fields Too Large responses
*
* @link https://tools.ietf.org/html/rfc6585
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 431 Request Header Fields Too Large responses
*
* @link https://tools.ietf.org/html/rfc6585
*
* @package Requests\Exceptions
*/
final class Status431 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 431;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Request Header Fields Too Large';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 500 Internal Server Error responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 500 Internal Server Error responses
*
* @package Requests\Exceptions
*/
final class Status500 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 500;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Internal Server Error';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 501 Not Implemented responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 501 Not Implemented responses
*
* @package Requests\Exceptions
*/
final class Status501 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 501;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Not Implemented';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 502 Bad Gateway responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 502 Bad Gateway responses
*
* @package Requests\Exceptions
*/
final class Status502 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 502;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Bad Gateway';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 503 Service Unavailable responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 503 Service Unavailable responses
*
* @package Requests\Exceptions
*/
final class Status503 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 503;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Service Unavailable';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 504 Gateway Timeout responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 504 Gateway Timeout responses
*
* @package Requests\Exceptions
*/
final class Status504 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 504;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Gateway Timeout';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Exception for 505 HTTP Version Not Supported responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 505 HTTP Version Not Supported responses
*
* @package Requests\Exceptions
*/
final class Status505 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 505;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'HTTP Version Not Supported';
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* Exception for 511 Network Authentication Required responses
*
* @link https://tools.ietf.org/html/rfc6585
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
/**
* Exception for 511 Network Authentication Required responses
*
* @link https://tools.ietf.org/html/rfc6585
*
* @package Requests\Exceptions
*/
final class Status511 extends Http {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 511;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Network Authentication Required';
}

View File

@@ -0,0 +1,49 @@
<?php
/**
* Exception for unknown status responses
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Response;
/**
* Exception for unknown status responses
*
* @package Requests\Exceptions
*/
final class StatusUnknown extends Http {
/**
* HTTP status code
*
* @var integer|bool Code if available, false if an error occurred
*/
protected $code = 0;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Unknown';
/**
* Create a new exception
*
* If `$data` is an instance of {@see \WpOrg\Requests\Response}, uses the status
* code from it. Otherwise, sets as 0
*
* @param string|null $reason Reason phrase
* @param mixed $data Associated data
*/
public function __construct($reason = null, $data = null) {
if ($data instanceof Response) {
$this->code = (int) $data->status_code;
}
parent::__construct($reason, $data);
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace WpOrg\Requests\Exception;
use InvalidArgumentException;
/**
* Exception for an invalid argument passed.
*
* @package Requests\Exceptions
* @since 2.0.0
*/
final class InvalidArgument extends InvalidArgumentException {
/**
* Create a new invalid argument exception with a standardized text.
*
* @param int $position The argument position in the function signature. 1-based.
* @param string $name The argument name in the function signature.
* @param string $expected The argument type expected as a string.
* @param string $received The actual argument type received.
*
* @return \WpOrg\Requests\Exception\InvalidArgument
*/
public static function create($position, $name, $expected, $received) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
$stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
return new self(
sprintf(
'%s::%s(): Argument #%d (%s) must be of type %s, %s given',
$stack[1]['class'],
$stack[1]['function'],
$position,
$name,
$expected,
$received
)
);
}
}

View File

@@ -0,0 +1,17 @@
<?php
/**
* Transport Exception
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception;
use WpOrg\Requests\Exception;
/**
* Transport Exception
*
* @package Requests\Exceptions
*/
class Transport extends Exception {}

View File

@@ -0,0 +1,80 @@
<?php
/**
* CURL Transport Exception.
*
* @package Requests\Exceptions
*/
namespace WpOrg\Requests\Exception\Transport;
use WpOrg\Requests\Exception\Transport;
/**
* CURL Transport Exception.
*
* @package Requests\Exceptions
*/
final class Curl extends Transport {
const EASY = 'cURLEasy';
const MULTI = 'cURLMulti';
const SHARE = 'cURLShare';
/**
* cURL error code
*
* @var integer
*/
protected $code = -1;
/**
* Which type of cURL error
*
* EASY|MULTI|SHARE
*
* @var string
*/
protected $type = 'Unknown';
/**
* Clear text error message
*
* @var string
*/
protected $reason = 'Unknown';
/**
* Create a new exception.
*
* @param string $message Exception message.
* @param string $type Exception type.
* @param mixed $data Associated data, if applicable.
* @param int $code Exception numerical code, if applicable.
*/
public function __construct($message, $type, $data = null, $code = 0) {
if ($type !== null) {
$this->type = $type;
}
if ($code !== null) {
$this->code = (int) $code;
}
if ($message !== null) {
$this->reason = $message;
}
$message = sprintf('%d %s', $this->code, $this->reason);
parent::__construct($message, $this->type, $data, $this->code);
}
/**
* Get the error message.
*
* @return string
*/
public function getReason() {
return $this->reason;
}
}

View File

@@ -0,0 +1,33 @@
<?php
/**
* Event dispatcher
*
* @package Requests\EventDispatcher
*/
namespace WpOrg\Requests;
/**
* Event dispatcher
*
* @package Requests\EventDispatcher
*/
interface HookManager {
/**
* Register a callback for a hook
*
* @param string $hook Hook name
* @param callable $callback Function/method to call on event
* @param int $priority Priority number. <0 is executed earlier, >0 is executed later
*/
public function register($hook, $callback, $priority = 0);
/**
* Dispatch a message
*
* @param string $hook Hook name
* @param array $parameters Parameters to pass to callbacks
* @return boolean Successfulness
*/
public function dispatch($hook, $parameters = []);
}

View File

@@ -0,0 +1,99 @@
<?php
/**
* Handles adding and dispatching events
*
* @package Requests\EventDispatcher
*/
namespace WpOrg\Requests;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\HookManager;
use WpOrg\Requests\Utility\InputValidator;
/**
* Handles adding and dispatching events
*
* @package Requests\EventDispatcher
*/
class Hooks implements HookManager {
/**
* Registered callbacks for each hook
*
* @var array
*/
protected $hooks = [];
/**
* Register a callback for a hook
*
* @param string $hook Hook name
* @param callable $callback Function/method to call on event
* @param int $priority Priority number. <0 is executed earlier, >0 is executed later
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $hook argument is not a string.
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $callback argument is not callable.
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $priority argument is not an integer.
*/
public function register($hook, $callback, $priority = 0) {
if (is_string($hook) === false) {
throw InvalidArgument::create(1, '$hook', 'string', gettype($hook));
}
if (is_callable($callback) === false) {
throw InvalidArgument::create(2, '$callback', 'callable', gettype($callback));
}
if (InputValidator::is_numeric_array_key($priority) === false) {
throw InvalidArgument::create(3, '$priority', 'integer', gettype($priority));
}
if (!isset($this->hooks[$hook])) {
$this->hooks[$hook] = [
$priority => [],
];
} elseif (!isset($this->hooks[$hook][$priority])) {
$this->hooks[$hook][$priority] = [];
}
$this->hooks[$hook][$priority][] = $callback;
}
/**
* Dispatch a message
*
* @param string $hook Hook name
* @param array $parameters Parameters to pass to callbacks
* @return boolean Successfulness
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $hook argument is not a string.
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $parameters argument is not an array.
*/
public function dispatch($hook, $parameters = []) {
if (is_string($hook) === false) {
throw InvalidArgument::create(1, '$hook', 'string', gettype($hook));
}
// Check strictly against array, as Array* objects don't work in combination with `call_user_func_array()`.
if (is_array($parameters) === false) {
throw InvalidArgument::create(2, '$parameters', 'array', gettype($parameters));
}
if (empty($this->hooks[$hook])) {
return false;
}
if (!empty($parameters)) {
// Strip potential keys from the array to prevent them being interpreted as parameter names in PHP 8.0.
$parameters = array_values($parameters);
}
ksort($this->hooks[$hook]);
foreach ($this->hooks[$hook] as $priority => $hooked) {
foreach ($hooked as $callback) {
$callback(...$parameters);
}
}
return true;
}
}

View File

@@ -0,0 +1,412 @@
<?php
namespace WpOrg\Requests;
use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Utility\InputValidator;
/**
* IDNA URL encoder
*
* Note: Not fully compliant, as nameprep does nothing yet.
*
* @package Requests\Utilities
*
* @link https://tools.ietf.org/html/rfc3490 IDNA specification
* @link https://tools.ietf.org/html/rfc3492 Punycode/Bootstrap specification
*/
class IdnaEncoder {
/**
* ACE prefix used for IDNA
*
* @link https://tools.ietf.org/html/rfc3490#section-5
* @var string
*/
const ACE_PREFIX = 'xn--';
/**
* Maximum length of a IDNA URL in ASCII.
*
* @see \WpOrg\Requests\IdnaEncoder::to_ascii()
*
* @since 2.0.0
*
* @var int
*/
const MAX_LENGTH = 64;
/**#@+
* Bootstrap constant for Punycode
*
* @link https://tools.ietf.org/html/rfc3492#section-5
* @var int
*/
const BOOTSTRAP_BASE = 36;
const BOOTSTRAP_TMIN = 1;
const BOOTSTRAP_TMAX = 26;
const BOOTSTRAP_SKEW = 38;
const BOOTSTRAP_DAMP = 700;
const BOOTSTRAP_INITIAL_BIAS = 72;
const BOOTSTRAP_INITIAL_N = 128;
/**#@-*/
/**
* Encode a hostname using Punycode
*
* @param string|Stringable $hostname Hostname
* @return string Punycode-encoded hostname
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string or a stringable object.
*/
public static function encode($hostname) {
if (InputValidator::is_string_or_stringable($hostname) === false) {
throw InvalidArgument::create(1, '$hostname', 'string|Stringable', gettype($hostname));
}
$parts = explode('.', $hostname);
foreach ($parts as &$part) {
$part = self::to_ascii($part);
}
return implode('.', $parts);
}
/**
* Convert a UTF-8 text string to an ASCII string using Punycode
*
* @param string $text ASCII or UTF-8 string (max length 64 characters)
* @return string ASCII string
*
* @throws \WpOrg\Requests\Exception Provided string longer than 64 ASCII characters (`idna.provided_too_long`)
* @throws \WpOrg\Requests\Exception Prepared string longer than 64 ASCII characters (`idna.prepared_too_long`)
* @throws \WpOrg\Requests\Exception Provided string already begins with xn-- (`idna.provided_is_prefixed`)
* @throws \WpOrg\Requests\Exception Encoded string longer than 64 ASCII characters (`idna.encoded_too_long`)
*/
public static function to_ascii($text) {
// Step 1: Check if the text is already ASCII
if (self::is_ascii($text)) {
// Skip to step 7
if (strlen($text) < self::MAX_LENGTH) {
return $text;
}
throw new Exception('Provided string is too long', 'idna.provided_too_long', $text);
}
// Step 2: nameprep
$text = self::nameprep($text);
// Step 3: UseSTD3ASCIIRules is false, continue
// Step 4: Check if it's ASCII now
if (self::is_ascii($text)) {
// Skip to step 7
/*
* As the `nameprep()` method returns the original string, this code will never be reached until
* that method is properly implemented.
*/
// @codeCoverageIgnoreStart
if (strlen($text) < self::MAX_LENGTH) {
return $text;
}
throw new Exception('Prepared string is too long', 'idna.prepared_too_long', $text);
// @codeCoverageIgnoreEnd
}
// Step 5: Check ACE prefix
if (strpos($text, self::ACE_PREFIX) === 0) {
throw new Exception('Provided string begins with ACE prefix', 'idna.provided_is_prefixed', $text);
}
// Step 6: Encode with Punycode
$text = self::punycode_encode($text);
// Step 7: Prepend ACE prefix
$text = self::ACE_PREFIX . $text;
// Step 8: Check size
if (strlen($text) < self::MAX_LENGTH) {
return $text;
}
throw new Exception('Encoded string is too long', 'idna.encoded_too_long', $text);
}
/**
* Check whether a given text string contains only ASCII characters
*
* @internal (Testing found regex was the fastest implementation)
*
* @param string $text
* @return bool Is the text string ASCII-only?
*/
protected static function is_ascii($text) {
return (preg_match('/(?:[^\x00-\x7F])/', $text) !== 1);
}
/**
* Prepare a text string for use as an IDNA name
*
* @todo Implement this based on RFC 3491 and the newer 5891
* @param string $text
* @return string Prepared string
*/
protected static function nameprep($text) {
return $text;
}
/**
* Convert a UTF-8 string to a UCS-4 codepoint array
*
* Based on \WpOrg\Requests\Iri::replace_invalid_with_pct_encoding()
*
* @param string $input
* @return array Unicode code points
*
* @throws \WpOrg\Requests\Exception Invalid UTF-8 codepoint (`idna.invalidcodepoint`)
*/
protected static function utf8_to_codepoints($input) {
$codepoints = [];
// Get number of bytes
$strlen = strlen($input);
// phpcs:ignore Generic.CodeAnalysis.JumbledIncrementer -- This is a deliberate choice.
for ($position = 0; $position < $strlen; $position++) {
$value = ord($input[$position]);
if ((~$value & 0x80) === 0x80) { // One byte sequence:
$character = $value;
$length = 1;
$remaining = 0;
} elseif (($value & 0xE0) === 0xC0) { // Two byte sequence:
$character = ($value & 0x1F) << 6;
$length = 2;
$remaining = 1;
} elseif (($value & 0xF0) === 0xE0) { // Three byte sequence:
$character = ($value & 0x0F) << 12;
$length = 3;
$remaining = 2;
} elseif (($value & 0xF8) === 0xF0) { // Four byte sequence:
$character = ($value & 0x07) << 18;
$length = 4;
$remaining = 3;
} else { // Invalid byte:
throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $value);
}
if ($remaining > 0) {
if ($position + $length > $strlen) {
throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
}
for ($position++; $remaining > 0; $position++) {
$value = ord($input[$position]);
// If it is invalid, count the sequence as invalid and reprocess the current byte:
if (($value & 0xC0) !== 0x80) {
throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
}
--$remaining;
$character |= ($value & 0x3F) << ($remaining * 6);
}
$position--;
}
if (// Non-shortest form sequences are invalid
$length > 1 && $character <= 0x7F
|| $length > 2 && $character <= 0x7FF
|| $length > 3 && $character <= 0xFFFF
// Outside of range of ucschar codepoints
// Noncharacters
|| ($character & 0xFFFE) === 0xFFFE
|| $character >= 0xFDD0 && $character <= 0xFDEF
|| (
// Everything else not in ucschar
$character > 0xD7FF && $character < 0xF900
|| $character < 0x20
|| $character > 0x7E && $character < 0xA0
|| $character > 0xEFFFD
)
) {
throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
}
$codepoints[] = $character;
}
return $codepoints;
}
/**
* RFC3492-compliant encoder
*
* @internal Pseudo-code from Section 6.3 is commented with "#" next to relevant code
*
* @param string $input UTF-8 encoded string to encode
* @return string Punycode-encoded string
*
* @throws \WpOrg\Requests\Exception On character outside of the domain (never happens with Punycode) (`idna.character_outside_domain`)
*/
public static function punycode_encode($input) {
$output = '';
// let n = initial_n
$n = self::BOOTSTRAP_INITIAL_N;
// let delta = 0
$delta = 0;
// let bias = initial_bias
$bias = self::BOOTSTRAP_INITIAL_BIAS;
// let h = b = the number of basic code points in the input
$h = 0;
$b = 0; // see loop
// copy them to the output in order
$codepoints = self::utf8_to_codepoints($input);
$extended = [];
foreach ($codepoints as $char) {
if ($char < 128) {
// Character is valid ASCII
// TODO: this should also check if it's valid for a URL
$output .= chr($char);
$h++;
// Check if the character is non-ASCII, but below initial n
// This never occurs for Punycode, so ignore in coverage
// @codeCoverageIgnoreStart
} elseif ($char < $n) {
throw new Exception('Invalid character', 'idna.character_outside_domain', $char);
// @codeCoverageIgnoreEnd
} else {
$extended[$char] = true;
}
}
$extended = array_keys($extended);
sort($extended);
$b = $h;
// [copy them] followed by a delimiter if b > 0
if (strlen($output) > 0) {
$output .= '-';
}
// {if the input contains a non-basic code point < n then fail}
// while h < length(input) do begin
$codepointcount = count($codepoints);
while ($h < $codepointcount) {
// let m = the minimum code point >= n in the input
$m = array_shift($extended);
//printf('next code point to insert is %s' . PHP_EOL, dechex($m));
// let delta = delta + (m - n) * (h + 1), fail on overflow
$delta += ($m - $n) * ($h + 1);
// let n = m
$n = $m;
// for each code point c in the input (in order) do begin
for ($num = 0; $num < $codepointcount; $num++) {
$c = $codepoints[$num];
// if c < n then increment delta, fail on overflow
if ($c < $n) {
$delta++;
} elseif ($c === $n) { // if c == n then begin
// let q = delta
$q = $delta;
// for k = base to infinity in steps of base do begin
for ($k = self::BOOTSTRAP_BASE; ; $k += self::BOOTSTRAP_BASE) {
// let t = tmin if k <= bias {+ tmin}, or
// tmax if k >= bias + tmax, or k - bias otherwise
if ($k <= ($bias + self::BOOTSTRAP_TMIN)) {
$t = self::BOOTSTRAP_TMIN;
} elseif ($k >= ($bias + self::BOOTSTRAP_TMAX)) {
$t = self::BOOTSTRAP_TMAX;
} else {
$t = $k - $bias;
}
// if q < t then break
if ($q < $t) {
break;
}
// output the code point for digit t + ((q - t) mod (base - t))
$digit = $t + (($q - $t) % (self::BOOTSTRAP_BASE - $t));
$output .= self::digit_to_char($digit);
// let q = (q - t) div (base - t)
$q = floor(($q - $t) / (self::BOOTSTRAP_BASE - $t));
} // end
// output the code point for digit q
$output .= self::digit_to_char($q);
// let bias = adapt(delta, h + 1, test h equals b?)
$bias = self::adapt($delta, $h + 1, $h === $b);
// let delta = 0
$delta = 0;
// increment h
$h++;
} // end
} // end
// increment delta and n
$delta++;
$n++;
} // end
return $output;
}
/**
* Convert a digit to its respective character
*
* @link https://tools.ietf.org/html/rfc3492#section-5
*
* @param int $digit Digit in the range 0-35
* @return string Single character corresponding to digit
*
* @throws \WpOrg\Requests\Exception On invalid digit (`idna.invalid_digit`)
*/
protected static function digit_to_char($digit) {
// @codeCoverageIgnoreStart
// As far as I know, this never happens, but still good to be sure.
if ($digit < 0 || $digit > 35) {
throw new Exception(sprintf('Invalid digit %d', $digit), 'idna.invalid_digit', $digit);
}
// @codeCoverageIgnoreEnd
$digits = 'abcdefghijklmnopqrstuvwxyz0123456789';
return substr($digits, $digit, 1);
}
/**
* Adapt the bias
*
* @link https://tools.ietf.org/html/rfc3492#section-6.1
* @param int $delta
* @param int $numpoints
* @param bool $firsttime
* @return int New bias
*
* function adapt(delta,numpoints,firsttime):
*/
protected static function adapt($delta, $numpoints, $firsttime) {
// if firsttime then let delta = delta div damp
if ($firsttime) {
$delta = floor($delta / self::BOOTSTRAP_DAMP);
} else {
// else let delta = delta div 2
$delta = floor($delta / 2);
}
// let delta = delta + (delta div numpoints)
$delta += floor($delta / $numpoints);
// let k = 0
$k = 0;
// while delta > ((base - tmin) * tmax) div 2 do begin
$max = floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN) * self::BOOTSTRAP_TMAX) / 2);
while ($delta > $max) {
// let delta = delta div (base - tmin)
$delta = floor($delta / (self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN));
// let k = k + base
$k += self::BOOTSTRAP_BASE;
} // end
// return k + (((base - tmin + 1) * delta) div (delta + skew))
return $k + floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN + 1) * $delta) / ($delta + self::BOOTSTRAP_SKEW));
}
}

View File

@@ -0,0 +1,203 @@
<?php
/**
* Class to validate and to work with IPv6 addresses
*
* @package Requests\Utilities
*/
namespace WpOrg\Requests;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Utility\InputValidator;
/**
* Class to validate and to work with IPv6 addresses
*
* This was originally based on the PEAR class of the same name, but has been
* entirely rewritten.
*
* @package Requests\Utilities
*/
final class Ipv6 {
/**
* Uncompresses an IPv6 address
*
* RFC 4291 allows you to compress consecutive zero pieces in an address to
* '::'. This method expects a valid IPv6 address and expands the '::' to
* the required number of zero pieces.
*
* Example: FF01::101 -> FF01:0:0:0:0:0:0:101
* ::1 -> 0:0:0:0:0:0:0:1
*
* @author Alexander Merz <alexander.merz@web.de>
* @author elfrink at introweb dot nl
* @author Josh Peck <jmp at joshpeck dot org>
* @copyright 2003-2005 The PHP Group
* @license https://opensource.org/licenses/bsd-license.php
*
* @param string|Stringable $ip An IPv6 address
* @return string The uncompressed IPv6 address
*
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string or a stringable object.
*/
public static function uncompress($ip) {
if (InputValidator::is_string_or_stringable($ip) === false) {
throw InvalidArgument::create(1, '$ip', 'string|Stringable', gettype($ip));
}
$ip = (string) $ip;
if (substr_count($ip, '::') !== 1) {
return $ip;
}
list($ip1, $ip2) = explode('::', $ip);
$c1 = ($ip1 === '') ? -1 : substr_count($ip1, ':');
$c2 = ($ip2 === '') ? -1 : substr_count($ip2, ':');
if (strpos($ip2, '.') !== false) {
$c2++;
}
if ($c1 === -1 && $c2 === -1) {
// ::
$ip = '0:0:0:0:0:0:0:0';
} elseif ($c1 === -1) {
// ::xxx
$fill = str_repeat('0:', 7 - $c2);
$ip = str_replace('::', $fill, $ip);
} elseif ($c2 === -1) {
// xxx::
$fill = str_repeat(':0', 7 - $c1);
$ip = str_replace('::', $fill, $ip);
} else {
// xxx::xxx
$fill = ':' . str_repeat('0:', 6 - $c2 - $c1);
$ip = str_replace('::', $fill, $ip);
}
return $ip;
}
/**
* Compresses an IPv6 address
*
* RFC 4291 allows you to compress consecutive zero pieces in an address to
* '::'. This method expects a valid IPv6 address and compresses consecutive
* zero pieces to '::'.
*
* Example: FF01:0:0:0:0:0:0:101 -> FF01::101
* 0:0:0:0:0:0:0:1 -> ::1
*
* @see \WpOrg\Requests\Ipv6::uncompress()
*
* @param string $ip An IPv6 address
* @return string The compressed IPv6 address
*/
public static function compress($ip) {
// Prepare the IP to be compressed.
// Note: Input validation is handled in the `uncompress()` method, which is the first call made in this method.
$ip = self::uncompress($ip);
$ip_parts = self::split_v6_v4($ip);
// Replace all leading zeros
$ip_parts[0] = preg_replace('/(^|:)0+([0-9])/', '\1\2', $ip_parts[0]);
// Find bunches of zeros
if (preg_match_all('/(?:^|:)(?:0(?::|$))+/', $ip_parts[0], $matches, PREG_OFFSET_CAPTURE)) {
$max = 0;
$pos = null;
foreach ($matches[0] as $match) {
if (strlen($match[0]) > $max) {
$max = strlen($match[0]);
$pos = $match[1];
}
}
$ip_parts[0] = substr_replace($ip_parts[0], '::', $pos, $max);
}
if ($ip_parts[1] !== '') {
return implode(':', $ip_parts);
} else {
return $ip_parts[0];
}
}
/**
* Splits an IPv6 address into the IPv6 and IPv4 representation parts
*
* RFC 4291 allows you to represent the last two parts of an IPv6 address
* using the standard IPv4 representation
*
* Example: 0:0:0:0:0:0:13.1.68.3
* 0:0:0:0:0:FFFF:129.144.52.38
*
* @param string $ip An IPv6 address
* @return string[] [0] contains the IPv6 represented part, and [1] the IPv4 represented part
*/
private static function split_v6_v4($ip) {
if (strpos($ip, '.') !== false) {
$pos = strrpos($ip, ':');
$ipv6_part = substr($ip, 0, $pos);
$ipv4_part = substr($ip, $pos + 1);
return [$ipv6_part, $ipv4_part];
} else {
return [$ip, ''];
}
}
/**
* Checks an IPv6 address
*
* Checks if the given IP is a valid IPv6 address
*
* @param string $ip An IPv6 address
* @return bool true if $ip is a valid IPv6 address
*/
public static function check_ipv6($ip) {
// Note: Input validation is handled in the `uncompress()` method, which is the first call made in this method.
$ip = self::uncompress($ip);
list($ipv6, $ipv4) = self::split_v6_v4($ip);
$ipv6 = explode(':', $ipv6);
$ipv4 = explode('.', $ipv4);
if (count($ipv6) === 8 && count($ipv4) === 1 || count($ipv6) === 6 && count($ipv4) === 4) {
foreach ($ipv6 as $ipv6_part) {
// The section can't be empty
if ($ipv6_part === '') {
return false;
}
// Nor can it be over four characters
if (strlen($ipv6_part) > 4) {
return false;
}
// Remove leading zeros (this is safe because of the above)
$ipv6_part = ltrim($ipv6_part, '0');
if ($ipv6_part === '') {
$ipv6_part = '0';
}
// Check the value is valid
$value = hexdec($ipv6_part);
if (dechex($value) !== strtolower($ipv6_part) || $value < 0 || $value > 0xFFFF) {
return false;
}
}
if (count($ipv4) === 4) {
foreach ($ipv4 as $ipv4_part) {
$value = (int) $ipv4_part;
if ((string) $value !== $ipv4_part || $value < 0 || $value > 0xFF) {
return false;
}
}
}
return true;
} else {
return false;
}
}
}

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