]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
pumpio: fix for php > 5.3
[friendica-addons.git] / pumpio / pumpio.php
1 <?php
2 /**
3  * Name: pump.io Post Connector
4  * Description: Post to pump.io
5  * Version: 0.2
6  * Author: Michael Vogel <http://pirati.ca/profile/heluecht>
7  */
8 require('addon/pumpio/oauth/http.php');
9 require('addon/pumpio/oauth/oauth_client.php');
10
11 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
12
13 function pumpio_install() {
14     register_hook('post_local',           'addon/pumpio/pumpio.php', 'pumpio_post_local');
15     register_hook('notifier_normal',      'addon/pumpio/pumpio.php', 'pumpio_send');
16     register_hook('jot_networks',         'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
17     register_hook('connector_settings',      'addon/pumpio/pumpio.php', 'pumpio_settings');
18     register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
19     register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
20     register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
21 }
22
23 function pumpio_uninstall() {
24     unregister_hook('post_local',       'addon/pumpio/pumpio.php', 'pumpio_post_local');
25     unregister_hook('notifier_normal',  'addon/pumpio/pumpio.php', 'pumpio_send');
26     unregister_hook('jot_networks',     'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
27     unregister_hook('connector_settings',      'addon/pumpio/pumpio.php', 'pumpio_settings');
28     unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
29     unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
30     unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
31 }
32
33 function pumpio_module() {}
34
35 function pumpio_content(&$a) {
36
37         if(! local_user()) {
38                 notice( t('Permission denied.') . EOL);
39                 return '';
40         }
41
42         if (isset($a->argv[1]))
43                 switch ($a->argv[1]) {
44                         case "connect":
45                                 $o = pumpio_connect($a);
46                                 break;
47                         default:
48                                 $o = print_r($a->argv, true);
49                                 break;
50                 }
51         else
52                 $o = pumpio_connect($a);
53
54         return $o;
55 }
56
57 function pumpio_registerclient($a, $host) {
58
59         $url = "https://".$host."/api/client/register";
60
61         $params = array();
62
63         $application_name  = get_config('pumpio', 'application_name');
64
65         if ($application_name == "")
66                 $application_name = $a->get_hostname();
67
68         $params["type"] = "client_associate";
69         $params["contacts"] = $a->config['admin_email'];
70         $params["application_type"] = "native";
71         $params["application_name"] = $application_name;
72         $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
73         $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
74
75         $ch = curl_init($url);
76         curl_setopt($ch, CURLOPT_HEADER, false);
77         curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
78         curl_setopt($ch, CURLOPT_POST,1);
79         curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
80         curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
81
82         $s = curl_exec($ch);
83         $curl_info = curl_getinfo($ch);
84
85         if ($curl_info["http_code"] == "200") {
86                 $values = json_decode($s);
87                 return($values);
88         }
89         return(false);
90 }
91
92 function pumpio_connect($a) {
93         // Start a session.  This is necessary to hold on to  a few keys the callback script will also need
94         session_start();
95
96         // Define the needed keys
97         $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
98         $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
99         $hostname = get_pconfig(local_user(), 'pumpio','host');
100
101         if ((($consumer_key == "") OR ($consumer_secret == "")) AND ($hostname != "")) {
102                 $clientdata = pumpio_registerclient($a, $hostname);
103                 set_pconfig(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
104                 set_pconfig(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
105
106                 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
107                 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
108         }
109
110         if (($consumer_key == "") OR ($consumer_secret == ""))
111                 return;
112
113         // The callback URL is the script that gets called after the user authenticates with pumpio
114         $callback_url = $a->get_baseurl()."/pumpio/connect";
115
116         // Let's begin.  First we need a Request Token.  The request token is required to send the user
117         // to pumpio's login page.
118
119         // Create a new instance of the TumblrOAuth library.  For this step, all we need to give the library is our
120         // Consumer Key and Consumer Secret
121         $client = new oauth_client_class;
122         $client->debug = 1;
123         $client->server = '';
124         $client->oauth_version = '1.0a';
125         $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
126         $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
127         $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
128         $client->url_parameters = false;
129         $client->authorization_header = true;
130         $client->redirect_uri = $callback_url;
131         $client->client_id = $consumer_key;
132         $client->client_secret = $consumer_secret;
133
134         if (($success = $client->Initialize())) {
135                 if (($success = $client->Process())) {
136                         if (strlen($client->access_token)) {
137                                 set_pconfig(local_user(), "pumpio", "oauth_token", $client->access_token);
138                                 set_pconfig(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
139                         }
140                 }
141                 $success = $client->Finalize($success);
142         }
143         if($client->exit)
144             $o = 'Could not connect to pumpio. Refresh the page or try again later.';
145
146         if($success) {
147                 $o .= t("You are now authenticated to pumpio.");
148                 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
149         }
150
151         return($o);
152 }
153
154 function pumpio_jot_nets(&$a,&$b) {
155     if(! local_user())
156         return;
157
158     $pumpio_post = get_pconfig(local_user(),'pumpio','post');
159     if(intval($pumpio_post) == 1) {
160         $pumpio_defpost = get_pconfig(local_user(),'pumpio','post_by_default');
161         $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
162         $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
163             . t('Post to pumpio') . '</div>';
164     }
165 }
166
167
168 function pumpio_settings(&$a,&$s) {
169
170     if(! local_user())
171         return;
172
173     /* Add our stylesheet to the page so we can make our settings look nice */
174
175     $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
176
177     /* Get the current state of our config variables */
178
179     $import_enabled = get_pconfig(local_user(),'pumpio','import');
180     $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
181
182     $enabled = get_pconfig(local_user(),'pumpio','post');
183     $checked = (($enabled) ? ' checked="checked" ' : '');
184
185     $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default');
186     $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
187
188     $public_enabled = get_pconfig(local_user(),'pumpio','public');
189     $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
190
191     $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror');
192     $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
193
194     $servername = get_pconfig(local_user(), "pumpio", "host");
195     $username = get_pconfig(local_user(), "pumpio", "user");
196
197     /* Add some HTML to the existing form */
198
199     $s .= '<div class="settings-block">';
200     $s .= '<h3>' . t('Pump.io Post Settings') . '</h3>';
201
202     $s .= '<div id="pumpio-username-wrapper">';
203     $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
204     $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
205     $s .= '</div><div class="clear"></div>';
206
207     $s .= '<div id="pumpio-servername-wrapper">';
208     $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
209     $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
210     $s .= '</div><div class="clear"></div>';
211
212     if (($username != '') AND ($servername != '')) {
213
214         $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token");
215         $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret");
216
217         $s .= '<div id="pumpio-password-wrapper">';
218         if (($oauth_token == "") OR ($oauth_token_secret == "")) {
219                 $s .= '<div id="pumpio-authenticate-wrapper">';
220                 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
221                 $s .= '</div><div class="clear"></div>';
222         } else {
223                 $s .= '<div id="pumpio-import-wrapper">';
224                 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
225                 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
226                 $s .= '</div><div class="clear"></div>';
227
228                 $s .= '<div id="pumpio-enable-wrapper">';
229                 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
230                 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
231                 $s .= '</div><div class="clear"></div>';
232
233                 $s .= '<div id="pumpio-bydefault-wrapper">';
234                 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
235                 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
236                 $s .= '</div><div class="clear"></div>';
237
238                 $s .= '<div id="pumpio-public-wrapper">';
239                 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
240                 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
241                 $s .= '</div><div class="clear"></div>';
242
243                 $s .= '<div id="pumpio-mirror-wrapper">';
244                 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
245                 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
246                 $s .= '</div><div class="clear"></div>';
247
248                 $s .= '<div id="pumpio-delete-wrapper">';
249                 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
250                 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
251                 $s .= '</div><div class="clear"></div>';
252         }
253
254         $s .= '</div><div class="clear"></div>';
255     }
256
257     /* provide a submit button */
258
259     $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
260
261 }
262
263
264 function pumpio_settings_post(&$a,&$b) {
265
266         if(x($_POST,'pumpio-submit')) {
267                 if(x($_POST,'pumpio_delete')) {
268                         set_pconfig(local_user(),'pumpio','consumer_key','');
269                         set_pconfig(local_user(),'pumpio','consumer_secret','');
270                         set_pconfig(local_user(),'pumpio','host','');
271                         set_pconfig(local_user(),'pumpio','oauth_token','');
272                         set_pconfig(local_user(),'pumpio','oauth_token_secret','');
273                         set_pconfig(local_user(),'pumpio','post',false);
274                         set_pconfig(local_user(),'pumpio','post_by_default',false);
275                         set_pconfig(local_user(),'pumpio','user','');
276                 } else {
277                         // filtering the username if it is filled wrong
278                         $user = $_POST['pumpio_user'];
279                         if (strstr($user, "@")) {
280                                 $pos = strpos($user, "@");
281                                 if ($pos > 0)
282                                         $user = substr($user, 0, $pos);
283                         }
284
285                         // Filtering the hostname if someone is entering it with "http"
286                         $host = $_POST['pumpio_host'];
287                         $host = trim($host);
288                         $host = str_replace(array("https://", "http://"), array("", ""), $host);
289
290                         set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
291                         set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
292                         set_pconfig(local_user(),'pumpio','host',$host);
293                         set_pconfig(local_user(),'pumpio','user',$user);
294                         set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
295                         set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
296                         set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
297                 }
298         }
299 }
300
301 function pumpio_post_local(&$a,&$b) {
302
303         if((! local_user()) || (local_user() != $b['uid']))
304                 return;
305
306         $pumpio_post   = intval(get_pconfig(local_user(),'pumpio','post'));
307
308         $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
309
310         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
311                 $pumpio_enable = 1;
312
313         if(! $pumpio_enable)
314                 return;
315
316         if(strlen($b['postopts']))
317                 $b['postopts'] .= ',';
318
319         $b['postopts'] .= 'pumpio';
320 }
321
322
323
324
325 function pumpio_send(&$a,&$b) {
326
327         if (!get_pconfig($b["uid"],'pumpio','import')) {
328                 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
329                         return;
330         }
331
332         logger("pumpio_send: parameter ".print_r($b, true));
333
334         if($b['parent'] != $b['id']) {
335                 // Looking if its a reply to a pumpio post
336                 $r = q("SELECT item.* FROM item, contact WHERE item.id = %d AND item.uid = %d AND contact.id = `contact-id` AND contact.network='%s'LIMIT 1",
337                         intval($b["parent"]),
338                         intval($b["uid"]),
339                         dbesc(NETWORK_PUMPIO));
340
341                 if(!count($r)) {
342                         logger("pumpio_send: no pumpio post ".$b["parent"]);
343                         return;
344                 } else {
345                         $iscomment = true;
346                         $orig_post = $r[0];
347                 }
348         } else {
349                 $iscomment = false;
350
351                 $receiver = pumpio_getreceiver($a, $b);
352
353                 logger("pumpio_send: receiver ".print_r($receiver, true));
354
355                 if (!count($receiver) AND ($b['private'] OR !strstr($b['postopts'],'pumpio')))
356                         return;
357         }
358
359         if($b['verb'] == ACTIVITY_LIKE) {
360                 if ($b['deleted'])
361                         pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
362                 else
363                         pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
364                 return;
365         }
366
367         if($b['verb'] == ACTIVITY_DISLIKE)
368                 return;
369
370         if (($b['verb'] == ACTIVITY_POST) AND ($b['created'] !== $b['edited']) AND !$b['deleted'])
371                         pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
372
373         if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
374                         pumpio_action($a, $b["uid"], $b["uri"], "delete");
375
376         if($b['deleted'] || ($b['created'] !== $b['edited']))
377                 return;
378
379         // if post comes from pump.io don't send it back
380         if($b['app'] == "pump.io")
381                 return;
382
383
384         $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
385         $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
386         $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
387         $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
388
389         $host = get_pconfig($b['uid'], "pumpio", "host");
390         $user = get_pconfig($b['uid'], "pumpio", "user");
391         $public = get_pconfig($b['uid'], "pumpio", "public");
392
393         if($oauth_token && $oauth_token_secret) {
394
395                 require_once('include/bbcode.php');
396
397                 $title = trim($b['title']);
398
399                 if ($title != '')
400                         $title = "<h4>".$title."</h4>";
401
402                 $content = bbcode($b['body'], false, false);
403
404                 // Enhance the way, videos are displayed
405                 $content = preg_replace('/<a.*?href="(https?:\/\/www.youtube.com\/.*?)".*?>(.*?)<\/a>/ism',"\n[url]$1[/url]\n",$content);
406                 $content = preg_replace('/<a.*?href="(https?:\/\/youtu.be\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
407                 $content = preg_replace('/<a.*?href="(https?:\/\/vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
408                 $content = preg_replace('/<a.*?href="(https?:\/\/player.vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
409
410                 $URLSearchString = "^\[\]";
411                 $content = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$content);
412
413                 $params = array();
414
415                 $params["verb"] = "post";
416
417                 if (!$iscomment) {
418                         $params["object"] = array(
419                                                 'objectType' => "note",
420                                                 'content' => $title.$content);
421
422                         if (count($receiver["to"]))
423                                 $params["to"] = $receiver["to"];
424
425                         if (count($receiver["bto"]))
426                                 $params["bto"] = $receiver["bto"];
427
428                         if (count($receiver["cc"]))
429                                 $params["cc"] = $receiver["cc"];
430
431                         if (count($receiver["bcc"]))
432                                 $params["bcc"] = $receiver["bcc"];
433
434                  } else {
435                         $inReplyTo = array("id" => $orig_post["uri"],
436                                         "objectType" => "note");
437
438                         $params["object"] = array(
439                                                 'objectType' => "comment",
440                                                 'content' => $title.$content,
441                                                 'inReplyTo' => $inReplyTo);
442                 }
443
444                 $client = new oauth_client_class;
445                 $client->oauth_version = '1.0a';
446                 $client->url_parameters = false;
447                 $client->authorization_header = true;
448                 $client->access_token = $oauth_token;
449                 $client->access_token_secret = $oauth_token_secret;
450                 $client->client_id = $consumer_key;
451                 $client->client_secret = $consumer_secret;
452
453                 $username = $user.'@'.$host;
454                 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
455
456                 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
457
458                 if($success) {
459                         $post_id = $user->object->id;
460                         logger('pumpio_send '.$username.': success '.$post_id);
461                         if($post_id AND $iscomment) {
462                                 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
463                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
464                                         dbesc($post_id),
465                                         intval($b['id'])
466                                 );
467                         }
468                 } else {
469                         logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
470
471                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
472                         if (count($r))
473                                 $a->contact = $r[0]["id"];
474
475                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
476                         require_once('include/queue_fn.php');
477                         add_to_queue($a->contact,NETWORK_PUMPIO,$s);
478                         notice(t('Pump.io post failed. Queued for retry.').EOL);
479                 }
480
481         }
482 }
483
484 function pumpio_action($a, $uid, $uri, $action, $content) {
485
486         // Don't do likes and other stuff if you don't import the timeline
487         if (!get_pconfig($uid,'pumpio','import'))
488                 return;
489
490         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
491         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
492         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
493         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
494         $hostname = get_pconfig($uid, 'pumpio','host');
495         $username = get_pconfig($uid, "pumpio", "user");
496
497         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
498                                 dbesc($uri),
499                                 intval($uid)
500         );
501
502         if (!count($r))
503                 return;
504
505         $orig_post = $r[0];
506
507         if ($orig_post["extid"] AND !strstr($orig_post["extid"], "/proxy/"))
508                 $uri = $orig_post["extid"];
509         else
510                 $uri = $orig_post["uri"];
511
512         if (strstr($uri, "/api/comment/"))
513                 $objectType = "comment";
514         elseif (strstr($uri, "/api/note/"))
515                 $objectType = "note";
516         elseif (strstr($uri, "/api/image/"))
517                 $objectType = "image";
518
519         $params["verb"] = $action;
520         $params["object"] = array('id' => $uri,
521                                 "objectType" => $objectType,
522                                 "content" => $content);
523
524         $client = new oauth_client_class;
525         $client->oauth_version = '1.0a';
526         $client->authorization_header = true;
527         $client->url_parameters = false;
528
529         $client->client_id = $ckey;
530         $client->client_secret = $csecret;
531         $client->access_token = $otoken;
532         $client->access_token_secret = $osecret;
533
534         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
535
536         $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
537
538         if($success)
539                 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
540         else {
541                 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
542
543                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
544                 if (count($r))
545                         $a->contact = $r[0]["id"];
546
547                 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
548                 require_once('include/queue_fn.php');
549                 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
550                 notice(t('Pump.io like failed. Queued for retry.').EOL);
551         }
552 }
553
554
555 function pumpio_cron($a,$b) {
556         $last = get_config('pumpio','last_poll');
557
558         $poll_interval = intval(get_config('pumpio','poll_interval'));
559         if(! $poll_interval)
560                 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
561
562         if($last) {
563                 $next = $last + ($poll_interval * 60);
564                 if($next > time()) {
565                         logger('pumpio: poll intervall not reached');
566                         return;
567                 }
568         }
569         logger('pumpio: cron_start');
570
571         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
572         if(count($r)) {
573                 foreach($r as $rr) {
574                         logger('pumpio: mirroring user '.$rr['uid']);
575                         pumpio_fetchtimeline($a, $rr['uid']);
576                 }
577         }
578
579         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
580         if(count($r)) {
581                 foreach($r as $rr) {
582                         logger('pumpio: importing timeline from user '.$rr['uid']);
583                         pumpio_fetchinbox($a, $rr['uid']);
584
585                         // check for new contacts once a day
586                         $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check');
587                         if($last_contact_check)
588                                 $next_contact_check = $last_contact_check + 86400;
589                         else
590                                 $next_contact_check = 0;
591
592                         if($next_contact_check <= time()) {
593                                 pumpio_getallusers($a, $rr["uid"]);
594                                 set_pconfig($rr['uid'],'pumpio','contact_check',time());
595                         }
596                 }
597         }
598
599         logger('pumpio: cron_end');
600
601         set_config('pumpio','last_poll', time());
602 }
603
604 function pumpio_fetchtimeline($a, $uid) {
605         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
606         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
607         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
608         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
609         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
610         $hostname = get_pconfig($uid, 'pumpio','host');
611         $username = get_pconfig($uid, "pumpio", "user");
612
613         $application_name  = get_config('pumpio', 'application_name');
614
615         if ($application_name == "")
616                 $application_name = $a->get_hostname();
617
618         $first_time = ($lastdate == "");
619
620         $client = new oauth_client_class;
621         $client->oauth_version = '1.0a';
622         $client->authorization_header = true;
623         $client->url_parameters = false;
624
625         $client->client_id = $ckey;
626         $client->client_secret = $csecret;
627         $client->access_token = $otoken;
628         $client->access_token_secret = $osecret;
629
630         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
631
632         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
633
634         $username = $user.'@'.$host;
635
636         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
637
638         if (!$success) {
639                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
640                 return;
641         }
642
643         $posts = array_reverse($user->items);
644
645         $initiallastdate = $lastdate;
646         $lastdate = '';
647
648         if (count($posts)) {
649                 foreach ($posts as $post) {
650                         if ($post->generator->published <= $initiallastdate)
651                                 continue;
652
653                         if ($lastdate < $post->generator->published)
654                                 $lastdate = $post->generator->published;
655
656                         if ($first_time)
657                                 continue;
658
659                         $receiptians = array();
660                         if (@is_array($post->cc))
661                                 $receiptians = array_merge($receiptians, $post->cc);
662
663                         if (@is_array($post->to))
664                                 $receiptians = array_merge($receiptians, $post->to);
665
666                         $public = false;
667                         foreach ($receiptians AS $receiver)
668                                 if (is_string($receiver->objectType))
669                                         if ($receiver->id == "http://activityschema.org/collection/public")
670                                                 $public = true;
671
672                         if ($public AND !strstr($post->generator->displayName, $application_name)) {
673                                 require_once('include/html2bbcode.php');
674
675                                 $_SESSION["authenticated"] = true;
676                                 $_SESSION["uid"] = $uid;
677
678                                 unset($_REQUEST);
679                                 $_REQUEST["type"] = "wall";
680                                 $_REQUEST["api_source"] = true;
681                                 $_REQUEST["profile_uid"] = $uid;
682                                 $_REQUEST["source"] = "pump.io";
683
684                                 if ($post->object->displayName != "")
685                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
686                                 else
687                                         $_REQUEST["title"] = "";
688
689                                 $_REQUEST["body"] = html2bbcode($post->object->content);
690
691                                 if ($post->object->fullImage->url != "")
692                                         $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
693
694                                 logger('pumpio: posting for user '.$uid);
695
696                                 require_once('mod/item.php');
697
698                                 item_post($a);
699                                 logger('pumpio: posting done - user '.$uid);
700                         }
701                 }
702         }
703
704         if ($lastdate != 0)
705                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
706 }
707
708 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
709         // Searching for the unliked post
710         // Two queries for speed issues
711         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
712                                 dbesc($post->object->id),
713                                 intval($uid)
714                 );
715
716         if (count($r))
717                 $orig_post = $r[0];
718         else {
719                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
720                                         dbesc($post->object->id),
721                                         intval($uid)
722                         );
723
724                 if (!count($r))
725                         return;
726                 else
727                         $orig_post = $r[0];
728         }
729
730         $contactid = 0;
731
732         if(link_compare($post->actor->url, $own_id)) {
733                 $contactid = $self[0]['id'];
734         } else {
735                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
736                         dbesc($post->actor->url),
737                         intval($uid)
738                 );
739
740                 if(count($r))
741                         $contactid = $r[0]['id'];
742
743                 if($contactid == 0)
744                         $contactid = $orig_post['contact-id'];
745         }
746
747         $r = q("UPDATE `item` SET `deleted` = 1, `unseen` = 1, `changed` = '%s' WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s'",
748                 dbesc(datetime_convert()),
749                 dbesc(ACTIVITY_LIKE),
750                 intval($uid),
751                 intval($contactid),
752                 dbesc($orig_post['uri'])
753         );
754
755         if(count($r))
756                 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
757         else
758                 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
759 }
760
761 function pumpio_dolike(&$a, $uid, $self, $post, $own_id) {
762
763         // Searching for the liked post
764         // Two queries for speed issues
765         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
766                                 dbesc($post->object->id),
767                                 intval($uid)
768                 );
769
770         if (count($r))
771                 $orig_post = $r[0];
772         else {
773                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
774                                         dbesc($post->object->id),
775                                         intval($uid)
776                         );
777
778                 if (!count($r))
779                         return;
780                 else
781                         $orig_post = $r[0];
782         }
783
784         $contactid = 0;
785
786         if(link_compare($post->actor->url, $own_id)) {
787                 $contactid = $self[0]['id'];
788                 $post->actor->displayName = $self[0]['name'];
789                 $post->actor->url = $self[0]['url'];
790                 $post->actor->image->url = $self[0]['photo'];
791         } else {
792                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
793                         dbesc($post->actor->url),
794                         intval($uid)
795                 );
796
797                 if(count($r))
798                         $contactid = $r[0]['id'];
799
800                 if($contactid == 0)
801                         $contactid = $orig_post['contact-id'];
802         }
803
804         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
805                 dbesc(ACTIVITY_LIKE),
806                 intval($uid),
807                 intval($contactid),
808                 dbesc($orig_post['uri'])
809         );
810
811         if(count($r)) {
812                 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
813                 return;
814         }
815
816         $likedata = array();
817         $likedata['parent'] = $orig_post['id'];
818         $likedata['verb'] = ACTIVITY_LIKE;
819         $likedata['gravity'] = 3;
820         $likedata['uid'] = $uid;
821         $likedata['wall'] = 0;
822         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
823         $likedata['parent-uri'] = $orig_post["uri"];
824         $likedata['contact-id'] = $contactid;
825         $likedata['app'] = $post->generator->displayName;
826         $likedata['verb'] = ACTIVITY_LIKE;
827         $likedata['author-name'] = $post->actor->displayName;
828         $likedata['author-link'] = $post->actor->url;
829         $likedata['author-avatar'] = $post->actor->image->url;
830
831         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
832         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
833         $post_type = t('status');
834         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
835         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
836
837         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
838
839         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
840                 '<id>' . $orig_post['uri'] . '</id><link>' . xmlify('<link rel="alternate" type="text/html" href="' . xmlify($orig_post['plink']) . '" />') . '</link><title>' . $orig_post['title'] . '</title><content>' . $orig_post['body'] . '</content></object>';
841
842         $ret = item_store($likedata);
843
844         logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
845 }
846
847 function pumpio_get_contact($uid, $contact) {
848
849         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
850                 intval($uid), dbesc($contact->url));
851
852         if(!count($r)) {
853                 // create contact record
854                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
855                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
856                                         `writable`, `blocked`, `readonly`, `pending` )
857                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
858                         intval($uid),
859                         dbesc(datetime_convert()),
860                         dbesc($contact->url),
861                         dbesc(normalise_link($contact->url)),
862                         dbesc(str_replace("acct:", "", $contact->id)),
863                         dbesc(''),
864                         dbesc($contact->id), // What is it for?
865                         dbesc('pump.io ' . $contact->id), // What is it for?
866                         dbesc($contact->displayName),
867                         dbesc($contact->preferredUsername),
868                         dbesc($contact->image->url),
869                         dbesc(NETWORK_PUMPIO),
870                         intval(CONTACT_IS_FRIEND),
871                         intval(1),
872                         intval(1)
873                 );
874
875                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
876                         dbesc($contact->url),
877                         intval($uid)
878                         );
879
880                 if(! count($r))
881                         return(false);
882
883                 $contact_id  = $r[0]['id'];
884
885                 $g = q("select def_gid from user where uid = %d limit 1",
886                         intval($uid)
887                 );
888
889                 if($g && intval($g[0]['def_gid'])) {
890                         require_once('include/group.php');
891                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
892                 }
893
894                 require_once("Photo.php");
895
896                 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
897
898                 q("UPDATE `contact` SET `photo` = '%s',
899                                         `thumb` = '%s',
900                                         `micro` = '%s',
901                                         `name-date` = '%s',
902                                         `uri-date` = '%s',
903                                         `avatar-date` = '%s'
904                                 WHERE `id` = %d LIMIT 1
905                         ",
906                 dbesc($photos[0]),
907                 dbesc($photos[1]),
908                 dbesc($photos[2]),
909                 dbesc(datetime_convert()),
910                 dbesc(datetime_convert()),
911                 dbesc(datetime_convert()),
912                 intval($contact_id)
913                 );
914         } else {
915                 // update profile photos once every two weeks as we have no notification of when they change.
916
917                 $update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
918
919                 // check that we have all the photos, this has been known to fail on occasion
920
921                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
922                         require_once("Photo.php");
923
924                         $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
925
926                         q("UPDATE `contact` SET `photo` = '%s',
927                                         `thumb` = '%s',
928                                         `micro` = '%s',
929                                         `name-date` = '%s',
930                                         `uri-date` = '%s',
931                                         `avatar-date` = '%s'
932                                         WHERE `id` = %d LIMIT 1
933                                 ",
934                         dbesc($photos[0]),
935                         dbesc($photos[1]),
936                         dbesc($photos[2]),
937                         dbesc(datetime_convert()),
938                         dbesc(datetime_convert()),
939                         dbesc(datetime_convert()),
940                         intval($r[0]['id'])
941                         );
942                 }
943
944         }
945
946         return($r[0]["id"]);
947 }
948
949 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
950
951         // Two queries for speed issues
952         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
953                                 dbesc($post->object->id),
954                                 intval($uid)
955                 );
956
957         if (count($r))
958                 return drop_item($r[0]["id"], $false);
959
960         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
961                                 dbesc($post->object->id),
962                                 intval($uid)
963                 );
964
965         if (count($r))
966                 return drop_item($r[0]["id"], $false);
967 }
968
969 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id) {
970         require_once('include/items.php');
971
972         if (($post->verb == "like") OR ($post->verb == "favorite"))
973                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
974
975         if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
976                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
977
978         if ($post->verb == "delete")
979                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
980
981         if ($post->verb != "update") {
982                 // Two queries for speed issues
983                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
984                                         dbesc($post->object->id),
985                                         intval($uid)
986                         );
987
988                 if (count($r))
989                         return false;
990
991                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
992                                         dbesc($post->object->id),
993                                         intval($uid)
994                         );
995
996                 if (count($r))
997                         return false;
998         }
999
1000         // Only handle these three types
1001         if (!strstr("post|share|update", $post->verb))
1002                 return false;
1003
1004         $receiptians = array();
1005         if (@is_array($post->cc))
1006                 $receiptians = array_merge($receiptians, $post->cc);
1007
1008         if (@is_array($post->to))
1009                 $receiptians = array_merge($receiptians, $post->to);
1010
1011         foreach ($receiptians AS $receiver)
1012                 if (is_string($receiver->objectType))
1013                         if ($receiver->id == "http://activityschema.org/collection/public")
1014                                 $public = true;
1015
1016         $postarray = array();
1017         $postarray['gravity'] = 0;
1018         $postarray['uid'] = $uid;
1019         $postarray['wall'] = 0;
1020         $postarray['uri'] = $post->object->id;
1021
1022         if ($post->object->objectType != "comment") {
1023                 $contact_id = pumpio_get_contact($uid, $post->actor);
1024
1025                 if (!$contact_id)
1026                         $contact_id = $self[0]['id'];
1027
1028                 $postarray['parent-uri'] = $post->object->id;
1029         } else {
1030                 $contact_id = 0;
1031
1032                 if(link_compare($post->actor->url, $own_id)) {
1033                         $contact_id = $self[0]['id'];
1034                         $post->actor->displayName = $self[0]['name'];
1035                         $post->actor->url = $self[0]['url'];
1036                         $post->actor->image->url = $self[0]['photo'];
1037                 } else {
1038                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1039                         $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1040                                 dbesc($post->actor->url),
1041                                 intval($uid)
1042                         );
1043
1044                         if(count($r))
1045                                 $contact_id = $r[0]['id'];
1046                         else {
1047                                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1048                                         dbesc($post->actor->url),
1049                                         intval($uid)
1050                                 );
1051
1052                                 if(count($r))
1053                                         $contact_id = $r[0]['id'];
1054                                 else
1055                                         $contact_id = $self[0]['id'];
1056                         }
1057                 }
1058
1059                 $reply->verb = "note";
1060                 $reply->cc = $post->cc;
1061                 $reply->to = $post->to;
1062                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1063                 $reply->object->content = $post->object->inReplyTo->content;
1064                 $reply->object->id = $post->object->inReplyTo->id;
1065                 $reply->actor = $post->object->inReplyTo->author;
1066                 $reply->url = $post->object->inReplyTo->url;
1067                 $reply->generator->displayName = "pumpio";
1068                 $reply->published = $post->object->inReplyTo->published;
1069                 $reply->received = $post->object->inReplyTo->updated;
1070                 $reply->url = $post->object->inReplyTo->url;
1071                 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id);
1072
1073                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1074         }
1075
1076         if ($post->object->pump_io->proxyURL)
1077                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1078
1079         $postarray['contact-id'] = $contact_id;
1080         $postarray['verb'] = ACTIVITY_POST;
1081         $postarray['owner-name'] = $post->actor->displayName;
1082         $postarray['owner-link'] = $post->actor->url;
1083         $postarray['owner-avatar'] = $post->actor->image->url;
1084         $postarray['author-name'] = $post->actor->displayName;
1085         $postarray['author-link'] = $post->actor->url;
1086         $postarray['author-avatar'] = $post->actor->image->url;
1087         $postarray['plink'] = $post->object->url;
1088         $postarray['app'] = $post->generator->displayName;
1089         $postarray['body'] = html2bbcode($post->object->content);
1090
1091         if ($post->object->fullImage->url != "")
1092                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1093
1094         if ($post->object->displayName != "")
1095                 $postarray['title'] = $post->object->displayName;
1096
1097         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1098         $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1099         if (!$public) {
1100                 $postarray['private'] = 1;
1101                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1102         }
1103
1104         if ($post->verb == "share") {
1105                 $postarray['body'] = "[share author='".$post->object->author->displayName.
1106                                 "' profile='".$post->object->author->url.
1107                                 "' avatar='".$post->object->author->image->url.
1108                                 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1109         }
1110
1111         if (trim($postarray['body']) == "")
1112                 return false;
1113
1114         $top_item = item_store($postarray);
1115
1116         if (($top_item == 0) AND ($post->verb == "update")) {
1117                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1118                         dbesc($postarray["title"]),
1119                         dbesc($postarray["body"]),
1120                         dbesc($postarray["edited"]),
1121                         dbesc($postarray["uri"]),
1122                         intval($uid)
1123                         );
1124         }
1125
1126         if ($post->object->objectType == "comment") {
1127
1128                 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1129
1130                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1131                                 intval($uid)
1132                         );
1133
1134                 if(!count($user))
1135                         return $top_item;
1136
1137                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1138
1139                 if (link_compare($own_id, $postarray['author-link']))
1140                         return $top_item;
1141
1142                 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1143                                 dbesc($postarray['parent-uri']),
1144                                 intval($uid)
1145                                 );
1146
1147                 if(count($myconv)) {
1148
1149                         foreach($myconv as $conv) {
1150                                 // now if we find a match, it means we're in this conversation
1151
1152                                 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_id))
1153                                         continue;
1154
1155                                 require_once('include/enotify.php');
1156
1157                                 $conv_parent = $conv['parent'];
1158
1159                                 notification(array(
1160                                         'type'         => NOTIFY_COMMENT,
1161                                         'notify_flags' => $user[0]['notify-flags'],
1162                                         'language'     => $user[0]['language'],
1163                                         'to_name'      => $user[0]['username'],
1164                                         'to_email'     => $user[0]['email'],
1165                                         'uid'          => $user[0]['uid'],
1166                                         'item'         => $postarray,
1167                                         'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1168                                         'source_name'  => $postarray['author-name'],
1169                                         'source_link'  => $postarray['author-link'],
1170                                         'source_photo' => $postarray['author-avatar'],
1171                                         'verb'         => ACTIVITY_POST,
1172                                         'otype'        => 'item',
1173                                         'parent'       => $conv_parent,
1174                                         ));
1175
1176                                 // only send one notification
1177                                 break;
1178                         }
1179                 }
1180         }
1181
1182         return $top_item;
1183 }
1184
1185 function pumpio_fetchinbox($a, $uid) {
1186
1187         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1188         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1189         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1190         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1191         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1192         $hostname = get_pconfig($uid, 'pumpio','host');
1193         $username = get_pconfig($uid, "pumpio", "user");
1194
1195         $own_id = "https://".$hostname."/".$username;
1196
1197         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1198                 intval($uid));
1199
1200         $client = new oauth_client_class;
1201         $client->oauth_version = '1.0a';
1202         $client->authorization_header = true;
1203         $client->url_parameters = false;
1204
1205         $client->client_id = $ckey;
1206         $client->client_secret = $csecret;
1207         $client->access_token = $otoken;
1208         $client->access_token_secret = $osecret;
1209
1210         $last_id = get_pconfig($uid,'pumpio','last_id');
1211
1212         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1213
1214         if ($last_id != "")
1215                 $url .= '?since='.urlencode($last_id);
1216
1217         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1218         $posts = array_reverse($user->items);
1219
1220         if (count($posts))
1221                 foreach ($posts as $post) {
1222                         $last_id = $post->id;
1223                         pumpio_dopost($a, $client, $uid, $self, $post, $own_id);
1224                 }
1225
1226         set_pconfig($uid,'pumpio','last_id', $last_id);
1227 }
1228
1229 function pumpio_getallusers($a, $uid) {
1230         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1231         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1232         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1233         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1234         $hostname = get_pconfig($uid, 'pumpio','host');
1235         $username = get_pconfig($uid, "pumpio", "user");
1236
1237         $client = new oauth_client_class;
1238         $client->oauth_version = '1.0a';
1239         $client->authorization_header = true;
1240         $client->url_parameters = false;
1241
1242         $client->client_id = $ckey;
1243         $client->client_secret = $csecret;
1244         $client->access_token = $otoken;
1245         $client->access_token_secret = $osecret;
1246
1247         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1248
1249         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1250
1251         if ($users->totalItems > count($users->items)) {
1252                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1253
1254                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1255         }
1256
1257         foreach ($users->items AS $user)
1258                 echo pumpio_get_contact($uid, $user)."\n";
1259 }
1260
1261 function pumpio_queue_hook(&$a,&$b) {
1262
1263         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1264                 dbesc(NETWORK_PUMPIO)
1265         );
1266         if(! count($qi))
1267                 return;
1268
1269         require_once('include/queue_fn.php');
1270
1271         foreach($qi as $x) {
1272                 if($x['network'] !== NETWORK_PUMPIO)
1273                         continue;
1274
1275                 logger('pumpio_queue: run');
1276
1277                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
1278                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1279                         intval($x['cid'])
1280                 );
1281                 if(! count($r))
1282                         continue;
1283
1284                 $user = $r[0];
1285
1286                 $oauth_token = get_pconfig($user['uid'], "pumpio", "oauth_token");
1287                 $oauth_token_secret = get_pconfig($user['uid'], "pumpio", "oauth_token_secret");
1288                 $consumer_key = get_pconfig($user['uid'], "pumpio","consumer_key");
1289                 $consumer_secret = get_pconfig($user['uid'], "pumpio","consumer_secret");
1290
1291                 $host = get_pconfig($user['uid'], "pumpio", "host");
1292                 $user = get_pconfig($user['uid'], "pumpio", "user");
1293
1294                 $success = false;
1295
1296                 if ($oauth_token AND $oauth_token_secret AND
1297                         $consumer_key AND $consumer_secret) {
1298                         $username = $user.'@'.$host;
1299
1300                         logger('pumpio_queue: able to post for user '.$username);
1301
1302                         $z = unserialize($x['content']);
1303
1304                         $client = new oauth_client_class;
1305                         $client->oauth_version = '1.0a';
1306                         $client->url_parameters = false;
1307                         $client->authorization_header = true;
1308                         $client->access_token = $oauth_token;
1309                         $client->access_token_secret = $oauth_token_secret;
1310                         $client->client_id = $consumer_key;
1311                         $client->client_secret = $consumer_secret;
1312
1313                         $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1314
1315                         if($success) {
1316                                 $post_id = $user->object->id;
1317                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1318                                 if($post_id AND $iscomment) {
1319                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1320                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
1321                                                 dbesc($post_id),
1322                                                 intval($z['item'])
1323                                         );
1324                                 }
1325                                 remove_queue_item($x['id']);
1326                         } else
1327                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1328                 } else
1329                         logger("pumpio_queue: Error getting tokens for user ".$user['uid']);
1330
1331                 if (!$success) {
1332                         logger('pumpio_queue: delayed');
1333                         update_queue_time($x['id']);
1334                 }
1335         }
1336 }
1337
1338 function pumpio_getreceiver($a, $b) {
1339
1340         $receiver = array();
1341
1342         if (!$b["private"]) {
1343
1344                 if(! strstr($b['postopts'],'pumpio'))
1345                         return $receiver;
1346
1347                 $public = get_pconfig($b['uid'], "pumpio", "public");
1348
1349                 if ($public)
1350                         $receiver["to"][] = Array(
1351                                                 "objectType" => "collection",
1352                                                 "id" => "http://activityschema.org/collection/public");
1353         } else {
1354                 $cids = explode("><", $b["allow_cid"]);
1355                 $gids = explode("><", $b["allow_gid"]);
1356
1357                 foreach ($cids AS $cid) {
1358                         $cid = trim($cid, " <>");
1359
1360                         $r = q("SELECT `name`, `nick`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `network` = '%s' AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1361                                 intval($cid),
1362                                 intval($b["uid"]),
1363                                 dbesc(NETWORK_PUMPIO)
1364                                 );
1365
1366                         if (count($r)) {
1367                                 $receiver["bcc"][] = Array(
1368                                                         "displayName" => $r[0]["name"],
1369                                                         "objectType" => "person",
1370                                                         "preferredUsername" => $r[0]["nick"],
1371                                                         "url" => $r[0]["url"]);
1372                         }
1373                 }
1374                 foreach ($gids AS $gid) {
1375                         $gid = trim($gid, " <>");
1376
1377                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1378                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1379                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1380                                         intval($gid),
1381                                         intval($b["uid"]),
1382                                         dbesc(NETWORK_PUMPIO)
1383                                 );
1384
1385                         foreach ($r AS $row)
1386                                 $receiver["bcc"][] = Array(
1387                                                         "displayName" => $row["name"],
1388                                                         "objectType" => "person",
1389                                                         "preferredUsername" => $row["nick"],
1390                                                         "url" => $row["url"]);
1391                 }
1392         }
1393
1394         if ($b["inform"] != "") {
1395
1396                 $inform = explode(",", $b["inform"]);
1397
1398                 foreach ($inform AS $cid) {
1399                         if (substr($cid, 0, 4) != "cid:")
1400                                 continue;
1401
1402                         $cid = str_replace("cid:", "", $cid);
1403
1404                         $r = q("SELECT `name`, `nick`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `network` = '%s' AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1405                                 intval($cid),
1406                                 intval($b["uid"]),
1407                                 dbesc(NETWORK_PUMPIO)
1408                                 );
1409
1410                         if (count($r)) {
1411                                         $receiver["to"][] = Array(
1412                                                                 "displayName" => $r[0]["name"],
1413                                                                 "objectType" => "person",
1414                                                                 "preferredUsername" => $r[0]["nick"],
1415                                                                 "url" => $r[0]["url"]);
1416                         }
1417                 }
1418         }
1419
1420         return $receiver;
1421 }
1422
1423 function pumpio_fetchallcomments($a, $uid, $id) {
1424         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1425         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1426         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1427         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1428         $hostname = get_pconfig($uid, 'pumpio','host');
1429         $username = get_pconfig($uid, "pumpio", "user");
1430
1431         $own_id = "https://".$hostname."/".$username;
1432
1433         logger("pumpio_fetchallcomments: completing comment for user ".$uid." url ".$url);
1434
1435         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1436                 intval($uid));
1437
1438         // Fetching the original post - Two queries for speed issues
1439         $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1440                         dbesc($url),
1441                         intval($uid)
1442                 );
1443
1444         if (!count($r)) {
1445                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1446                                 dbesc($url),
1447                                 intval($uid)
1448                         );
1449
1450                 if (!count($r))
1451                         return false;
1452         }
1453
1454         if ($r[0]["extid"])
1455                 $url = $r[0]["extid"];
1456         else
1457                 $url = $id;
1458
1459         $client = new oauth_client_class;
1460         $client->oauth_version = '1.0a';
1461         $client->authorization_header = true;
1462         $client->url_parameters = false;
1463
1464         $client->client_id = $ckey;
1465         $client->client_secret = $csecret;
1466         $client->access_token = $otoken;
1467         $client->access_token_secret = $osecret;
1468
1469         logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1470
1471         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1472
1473         if (!$success)
1474                 return;
1475
1476         if ($item->replies->totalItems == 0)
1477                 return;
1478
1479         foreach ($item->replies->items AS $item) {
1480                 if ($item->id == $id)
1481                         continue;
1482
1483                 // Checking if the comment already exists - Two queries for speed issues
1484                 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1485                                 dbesc($url),
1486                                 intval($uid)
1487                         );
1488
1489                 if (count($r))
1490                         continue;
1491
1492                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1493                                 dbesc($url),
1494                                 intval($uid)
1495                         );
1496
1497                 if (count($r))
1498                         continue;
1499
1500                 $post->verb = "post";
1501                 $post->actor = $item->author;
1502                 $post->published = $item->published;
1503                 $post->received = $item->updated;
1504                 $post->generator->displayName = "pumpio";
1505
1506                 unset($item->author);
1507                 unset($item->published);
1508                 unset($item->updated);
1509
1510                 $post->object = $item;
1511
1512                 logger("pumpio_fetchallcomments: posting comment ".$post->object->id);
1513                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id);
1514         }
1515 }
1516
1517 /*
1518 Bugs:
1519  - refresh after post doesn't always happen
1520
1521 To-Do:
1522  - edit own notes
1523  - delete own notes
1524
1525 */