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(get_temppath(), '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 if (count($parts) > 1) {
50 $this->host = $parts[1];
56 public function getDiasporaID() {
57 return $this->user . '@' . $this->host;
60 public function getPodURL() {
61 return $this->getScheme() . '://' . $this->host;
64 public function setPassword($passwd) {
65 $this->password = $passwd;
68 public function setSecureTransport($is_secure) {
69 $this->tls = (bool) $is_secure;
72 private function getScheme() {
73 return ($this->tls) ? 'https' : 'http';
76 private function doHttpRequest($url, $data = [], $headers = []) {
77 if (0 === strpos($url, '/')) {
78 $url = $this->getScheme() . '://' . $this->host . $url;
81 $ch = curl_init($url);
83 if ($this->debug_log) {
84 curl_setopt($ch, CURLOPT_VERBOSE, true);
85 $fh = fopen($this->debug_log, 'a');
86 curl_setopt($ch, CURLOPT_STDERR, $fh);
89 curl_setopt($ch, CURLOPT_HEADER, true);
90 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
93 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
95 if (!empty($headers)) {
96 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
99 curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookiejar);
100 curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookiejar);
102 // Are we doing a special kind of HTTP request?
103 switch ($this->http_method) {
105 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->http_method);
108 curl_setopt($ch, CURLOPT_POST, true);
112 $this->last_http_result = new stdClass();
113 $this->last_http_result->response = curl_exec($ch);
114 $this->last_http_result->info = curl_getinfo($ch);
120 // Maybe update CSRF token
121 $token = $this->parseAuthenticityToken($this->last_http_result->response);
123 $this->csrf_token = $token;
126 return $this->last_http_result;
129 private function doHttpDelete($url, $data = [], $headers = []) {
130 $this->http_method = 'DELETE';
131 $this->doHttpRequest($url, $data, $headers);
132 $this->http_method = null; // reset for next request
135 private function parseAuthenticityToken($str) {
137 preg_match('/<meta (?:name="csrf-token" content="(.*?)"|content="(.*?)" name="csrf-token")/', $str, $m);
138 if (empty($m[1]) && !empty($m[2])) {
140 } elseif (!empty($m[1])) {
143 return !empty($token) ? $token : false;
146 private function readJsonResponse($response) {
147 $lines = explode("\r\n", $response);
149 $lines, array_search('', $lines) + 1 // empty, as "\r\n" was explode()'d
151 $http_body = array_pop($x);
152 return json_decode($http_body);
155 public function logIn() {
156 $this->doHttpRequest('/users/sign_in');
159 'user[username]' => $this->user,
160 'user[password]' => $this->password,
161 'authenticity_token' => $this->csrf_token
163 $this->doHttpRequest('/users/sign_in', $params);
164 $this->doHttpRequest('/stream');
165 return (200 === $this->last_http_result->info['http_code']) ? true : false;
168 public function getAspects() {
169 $this->doHttpRequest('/bookmarklet');
171 preg_match('/"aspects"\:(\[.+?\])/', $this->last_http_result->response, $m);
172 return !empty($m[1]) ? json_decode($m[1]) : false;
175 public function getServices() {
176 $this->doHttpRequest('/bookmarklet');
178 preg_match('/"configured_services"\:(\[.+?\])/', $this->last_http_result->response, $m);
179 return !empty($m[1]) ? json_decode($m[1]) : false;
182 public function getNotifications($notification_type = '', $show = '') {
183 $url = '/notifications?format=json';
185 if (!empty($notification_type)) {
186 $url .= "&type=$notification_type";
189 if ('unread' === $show) {
190 $url .= '&show=unread';
193 $this->doHttpRequest($url);
194 return $this->readJsonResponse($this->last_http_result->response);
197 public function getComments($post_id) {
198 $url = "/posts/$post_id/comments?format=json";
199 $this->doHttpRequest($url);
200 return $this->readJsonResponse($this->last_http_result->response);
203 public function postStatusMessage($msg, $aspect_ids = 'all_aspects', $additional_data = []) {
205 'aspect_ids' => $aspect_ids,
206 'status_message' => [
208 'provider_display_name' => $this->provider
212 if (!empty($additional_data)) {
213 $data += $additional_data;
217 'Content-Type: application/json',
218 'Accept: application/json',
219 'X-CSRF-Token: ' . $this->csrf_token
222 $this->http_method = 'POST';
223 $this->doHttpRequest('/status_messages', json_encode($data), $headers);
224 $this->http_method = null; // reset for next request
225 if (201 !== $this->last_http_result->info['http_code']) {
226 // TODO: Handle error.
228 } elseif (200 !== $this->last_http_result->info['http_code']) {
229 $resp = $this->readJsonResponse($this->last_http_result->response);
234 public function postPhoto($file) {
236 'photo[pending]' => 'true',
237 'qqfile' => basename($file)
239 $query_string = '?' . http_build_query($params);
241 'Accept: application/json',
242 'X-Requested-With: XMLHttpRequest',
243 'X-CSRF-Token: ' . $this->csrf_token,
244 'X-File-Name: ' . basename($file),
245 'Content-Type: application/octet-stream',
247 if ($size = @filesize($file)) {
248 $headers[] = "Content-Length: $size";
250 $data = file_get_contents($file);
251 $this->doHttpRequest('/photos' . $query_string, $data, $headers);
252 return $this->readJsonResponse($this->last_http_result->response);
255 public function deletePost($id) {
256 $headers = ['X-CSRF-Token: ' . $this->csrf_token];
257 $this->doHttpDelete("/posts/$id", [], $headers);
258 return (204 === $this->last_http_result->info['http_code']) ? true : false;
261 public function deleteComment($id) {
262 $headers = ['X-CSRF-Token: ' . $this->csrf_token];
263 $this->doHttpDelete("/comments/$id", [], $headers);
264 return (204 === $this->last_http_result->info['http_code']) ? true : false;