]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/Requests/Auth/Basic.php
Wordpress 4.6
[autoinstalls/wordpress.git] / wp-includes / Requests / Auth / Basic.php
1 <?php
2 /**
3  * Basic Authentication provider
4  *
5  * @package Requests
6  * @subpackage Authentication
7  */
8
9 /**
10  * Basic Authentication provider
11  *
12  * Provides a handler for Basic HTTP authentication via the Authorization
13  * header.
14  *
15  * @package Requests
16  * @subpackage Authentication
17  */
18 class Requests_Auth_Basic implements Requests_Auth {
19         /**
20          * Username
21          *
22          * @var string
23          */
24         public $user;
25
26         /**
27          * Password
28          *
29          * @var string
30          */
31         public $pass;
32
33         /**
34          * Constructor
35          *
36          * @throws Requests_Exception On incorrect number of arguments (`authbasicbadargs`)
37          * @param array|null $args Array of user and password. Must have exactly two elements
38          */
39         public function __construct($args = null) {
40                 if (is_array($args)) {
41                         if (count($args) !== 2) {
42                                 throw new Requests_Exception('Invalid number of arguments', 'authbasicbadargs');
43                         }
44
45                         list($this->user, $this->pass) = $args;
46                 }
47         }
48
49         /**
50          * Register the necessary callbacks
51          *
52          * @see curl_before_send
53          * @see fsockopen_header
54          * @param Requests_Hooks $hooks Hook system
55          */
56         public function register(Requests_Hooks &$hooks) {
57                 $hooks->register('curl.before_send', array(&$this, 'curl_before_send'));
58                 $hooks->register('fsockopen.after_headers', array(&$this, 'fsockopen_header'));
59         }
60
61         /**
62          * Set cURL parameters before the data is sent
63          *
64          * @param resource $handle cURL resource
65          */
66         public function curl_before_send(&$handle) {
67                 curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
68                 curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString());
69         }
70
71         /**
72          * Add extra headers to the request before sending
73          *
74          * @param string $out HTTP header string
75          */
76         public function fsockopen_header(&$out) {
77                 $out .= sprintf("Authorization: Basic %s\r\n", base64_encode($this->getAuthString()));
78         }
79
80         /**
81          * Get the authentication string (user:pass)
82          *
83          * @return string
84          */
85         public function getAuthString() {
86                 return $this->user . ':' . $this->pass;
87         }
88 }