3 * Super-skeletal class to interact with Diaspora.
5 * @author Meitar Moscovitz <meitarm@gmail.com>
6 * Modifications by Michael Vogel <heluecht@pirati.ca>
9 class Diaspora_Connection {
13 private $tls = true; //< Whether to use an SSL/TLS connection or not.
15 private $last_http_result; //< Result of last cURL transaction.
16 private $csrf_token; //< Authenticity token retrieved from last HTTP response.
17 private $http_method; //< Which HTTP verb to use for the next HTTP request.
22 public $provider = '*Diaspora Connection';
24 public function __construct($diaspora_handle = '', $password = '') {
25 if (!empty($diaspora_handle)) {
26 $this->setDiasporaID($diaspora_handle);
28 if (!empty($password)) {
29 $this->setPassword($password);
32 $this->cookiejar = tempnam(sys_get_temp_dir(), 'cookies');
36 public function __destruct() {
37 if (file_exists($this->cookiejar)) {
38 unlink($this->cookiejar);
42 public function setDebugLog($log_file) {
43 $this->debug_log = $log_file;
46 public function setDiasporaID($id) {
47 $parts = explode('@', $id);
48 $this->user = $parts[0];
49 $this->host = $parts[1];
52 public function getDiasporaID() {
53 return $this->user . '@' . $this->host;
56 public function getPodURL() {
57 return $this->getScheme() . '://' . $this->host;
60 public function setPassword($passwd) {
61 $this->password = $passwd;
64 public function setSecureTransport($is_secure) {
65 $this->tls = (bool) $is_secure;
68 private function getScheme() {
69 return ($this->tls) ? 'https' : 'http';
72 private function doHttpRequest($url, $data = [], $headers = []) {
73 if (0 === strpos($url, '/')) {
74 $url = $this->getScheme() . '://' . $this->host . $url;
77 $ch = curl_init($url);
79 if ($this->debug_log) {
80 curl_setopt($ch, CURLOPT_VERBOSE, true);
81 $fh = fopen($this->debug_log, 'a');
82 curl_setopt($ch, CURLOPT_STDERR, $fh);
85 curl_setopt($ch, CURLOPT_HEADER, true);
86 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
89 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
91 if (!empty($headers)) {
92 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
95 curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookiejar);
96 curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookiejar);
98 // Are we doing a special kind of HTTP request?
99 switch ($this->http_method) {
101 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->http_method);
104 curl_setopt($ch, CURLOPT_POST, true);
108 $this->last_http_result = new stdClass();
109 $this->last_http_result->response = curl_exec($ch);
110 $this->last_http_result->info = curl_getinfo($ch);
116 // Maybe update CSRF token
117 $token = $this->parseAuthenticityToken($this->last_http_result->response);
119 $this->csrf_token = $token;
122 return $this->last_http_result;
125 private function doHttpDelete($url, $data = [], $headers = []) {
126 $this->http_method = 'DELETE';
127 $this->doHttpRequest($url, $data, $headers);
128 $this->http_method = null; // reset for next request
131 private function parseAuthenticityToken($str) {
133 preg_match('/<meta (?:name="csrf-token" content="(.*?)"|content="(.*?)" name="csrf-token")/', $str, $m);
134 if (empty($m[1]) && !empty($m[2])) {
136 } elseif (!empty($m[1])) {
139 return (!empty($token)) ? $token : false;
142 private function readJsonResponse($response) {
143 $lines = explode("\r\n", $response);
145 $lines, array_search('', $lines) + 1 // empty, as "\r\n" was explode()'d
147 $http_body = array_pop($x);
148 return json_decode($http_body);
151 public function logIn() {
152 $this->doHttpRequest('/users/sign_in');
155 'user[username]' => $this->user,
156 'user[password]' => $this->password,
157 'authenticity_token' => $this->csrf_token
159 $this->doHttpRequest('/users/sign_in', $params);
160 $this->doHttpRequest('/stream');
161 return (200 === $this->last_http_result->info['http_code']) ? true : false;
164 public function getAspects() {
165 $this->doHttpRequest('/bookmarklet');
167 preg_match('/"aspects"\:(\[.+?\])/', $this->last_http_result->response, $m);
168 return (!empty($m[1])) ? json_decode($m[1]) : false;
171 public function getServices() {
172 $this->doHttpRequest('/bookmarklet');
174 preg_match('/"configured_services"\:(\[.+?\])/', $this->last_http_result->response, $m);
175 return (!empty($m[1])) ? json_decode($m[1]) : false;
178 public function getNotifications($notification_type = '', $show = '') {
179 $url = '/notifications?format=json';
181 if (!empty($notification_type)) {
182 $url .= "&type=$notification_type";
185 if ('unread' === $show) {
186 $url .= '&show=unread';
189 $this->doHttpRequest($url);
190 return $this->readJsonResponse($this->last_http_result->response);
193 public function getComments($post_id) {
194 $url = "/posts/$post_id/comments?format=json";
195 $this->doHttpRequest($url);
196 return $this->readJsonResponse($this->last_http_result->response);
199 public function postStatusMessage($msg, $aspect_ids = 'all_aspects', $additional_data = []) {
201 'aspect_ids' => $aspect_ids,
202 'status_message' => [
204 'provider_display_name' => $this->provider
208 if (!empty($additional_data)) {
209 $data += $additional_data;
213 'Content-Type: application/json',
214 'Accept: application/json',
215 'X-CSRF-Token: ' . $this->csrf_token
218 $this->http_method = 'POST';
219 $this->doHttpRequest('/status_messages', json_encode($data), $headers);
220 $this->http_method = null; // reset for next request
221 if (201 !== $this->last_http_result->info['http_code']) {
222 // TODO: Handle error.
224 } elseif (200 !== $this->last_http_result->info['http_code']) {
225 $resp = $this->readJsonResponse($this->last_http_result->response);
230 public function postPhoto($file) {
232 'photo[pending]' => 'true',
233 'qqfile' => basename($file)
235 $query_string = '?' . http_build_query($params);
237 'Accept: application/json',
238 'X-Requested-With: XMLHttpRequest',
239 'X-CSRF-Token: ' . $this->csrf_token,
240 'X-File-Name: ' . basename($file),
241 'Content-Type: application/octet-stream',
243 if ($size = @filesize($file)) {
244 $headers[] = "Content-Length: $size";
246 $data = file_get_contents($file);
247 $this->doHttpRequest('/photos' . $query_string, $data, $headers);
248 return $this->readJsonResponse($this->last_http_result->response);
251 public function deletePost($id) {
252 $headers = ['X-CSRF-Token: ' . $this->csrf_token];
253 $this->doHttpDelete("/posts/$id", [], $headers);
254 return (204 === $this->last_http_result->info['http_code']) ? true : false;
257 public function deleteComment($id) {
258 $headers = ['X-CSRF-Token: ' . $this->csrf_token];
259 $this->doHttpDelete("/comments/$id", [], $headers);
260 return (204 === $this->last_http_result->info['http_code']) ? true : false;