| 12
 3
 4
 5
 6
 7
 8
 9
 10
 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
 
 | <?php
 
/*
 * Twitter.class.php - update the status of a twitter user
 * Author: Felix Oghina
 */
 
class Twitter {
 
	private $auth = false;
	private $debug = false;
	public  $error = false;
 
	function __construct($user, $pass, $debug=false) {
		// Store an auth key for the HTTP Authorization: header
		$this->auth = base64_encode($user . ':' . $pass);
		$this->debug = $debug;
	}
 
	function update($new_status) {
		if (strlen($new_status) > 140) {
			$this->error = "Status too long: {$new_status}.";
			return false;
		}
		$fp = @fsockopen('twitter.com', 80, $errno, $errstr);
		if (!$fp) {
			$this->error = "Socket error #{$errno}: {$errstr}";
			return false;
		}
		$post_data = "status=" . urlencode($new_status);
		$to_send  = "POST /statuses/update.xml HTTP/1.1\r\n";
		$to_send .= "Host: twitter.com\r\n";
		$to_send .= "Content-Length: " . strlen($post_data) . "\r\n";
		$to_send .= "Authorization: Basic {$this->auth}\r\n\r\n";
		$to_send .= $post_data . "\r\n\r\n";
		$bytes = fwrite($fp, $to_send);
		if ($bytes === false) {
			$this->error = "Socket error: Error sending data.";
			return false;
		}
		elseif ($bytes < strlen($to_send)) {
			$this->error = "Socket error: Could not send all data.";
			return false;
		}
		if ($this->debug) echo "Sent:\n{$to_send}\n\n";
		$response = '';
		while (!feof($fp)) {
			$buf = fread($fp, 1024);
			if ($buf === false) {
				$this->error = "Socket error: Error reading data.";
				return false;
			}
			$response .= $buf;
		}
		if ($this->debug) echo "Received:\n{$response}";
		$was_error = preg_match(
			"#" .
			preg_quote("<error>") .
			"(.+)" .
			preg_quote("</error>") .
			"#i",
			$response, $matches);
		if ($was_error) {
			$this->error = "Twitter error: {$matches[1]}";
			return false;
		}
		list($first_line) = explode("\r\n", $response);
		if ($first_line != "HTTP/1.1 200 OK") {
			$this->error = "Request error: {$first_line}";
			return false;
		}
		return true;
	}
 
} | 
Partager