]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
pumpio: Complettion of comments is now working. Wehen you address contacts in the...
[friendica-addons.git] / pumpio / pumpio.php
1 <?php
2 /**
3  * Name: pump.io Post Connector
4  * Description: Post to pump.io
5  * Version: 0.1
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         }
586
587         // To-Do:
588         //pumpio_getallusers($a, $uid);
589
590         logger('pumpio: cron_end');
591
592         set_config('pumpio','last_poll', time());
593 }
594
595 function pumpio_fetchtimeline($a, $uid) {
596         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
597         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
598         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
599         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
600         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
601         $hostname = get_pconfig($uid, 'pumpio','host');
602         $username = get_pconfig($uid, "pumpio", "user");
603
604         $application_name  = get_config('pumpio', 'application_name');
605
606         if ($application_name == "")
607                 $application_name = $a->get_hostname();
608
609         $first_time = ($lastdate == "");
610
611         $client = new oauth_client_class;
612         $client->oauth_version = '1.0a';
613         $client->authorization_header = true;
614         $client->url_parameters = false;
615
616         $client->client_id = $ckey;
617         $client->client_secret = $csecret;
618         $client->access_token = $otoken;
619         $client->access_token_secret = $osecret;
620
621         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
622
623         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
624
625         $username = $user.'@'.$host;
626
627         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
628
629         if (!$success) {
630                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
631                 return;
632         }
633
634         $posts = array_reverse($user->items);
635
636         $initiallastdate = $lastdate;
637         $lastdate = '';
638
639         if (count($posts)) {
640                 foreach ($posts as $post) {
641                         if ($post->generator->published <= $initiallastdate)
642                                 continue;
643
644                         if ($lastdate < $post->generator->published)
645                                 $lastdate = $post->generator->published;
646
647                         if ($first_time)
648                                 continue;
649
650                         $receiptians = array();
651                         if (@is_array($post->cc))
652                                 $receiptians = array_merge($receiptians, $post->cc);
653
654                         if (@is_array($post->to))
655                                 $receiptians = array_merge($receiptians, $post->to);
656
657                         $public = false;
658                         foreach ($receiptians AS $receiver)
659                                 if (is_string($receiver->objectType))
660                                         if ($receiver->id == "http://activityschema.org/collection/public")
661                                                 $public = true;
662
663                         if ($public AND !strstr($post->generator->displayName, $application_name)) {
664                                 require_once('include/html2bbcode.php');
665
666                                 $_SESSION["authenticated"] = true;
667                                 $_SESSION["uid"] = $uid;
668
669                                 unset($_REQUEST);
670                                 $_REQUEST["type"] = "wall";
671                                 $_REQUEST["api_source"] = true;
672                                 $_REQUEST["profile_uid"] = $uid;
673                                 $_REQUEST["source"] = "pump.io";
674
675                                 if ($post->object->displayName != "")
676                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
677                                 else
678                                         $_REQUEST["title"] = "";
679
680                                 $_REQUEST["body"] = html2bbcode($post->object->content);
681
682                                 if ($post->object->fullImage->url != "")
683                                         $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
684
685                                 logger('pumpio: posting for user '.$uid);
686
687                                 require_once('mod/item.php');
688
689                                 item_post($a);
690                                 logger('pumpio: posting done - user '.$uid);
691                         }
692                 }
693         }
694
695         if ($lastdate != 0)
696                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
697 }
698
699 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
700         // Searching for the unliked post
701         // Two queries for speed issues
702         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
703                                 dbesc($post->object->id),
704                                 intval($uid)
705                 );
706
707         if (count($r))
708                 $orig_post = $r[0];
709         else {
710                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
711                                         dbesc($post->object->id),
712                                         intval($uid)
713                         );
714
715                 if (!count($r))
716                         return;
717                 else
718                         $orig_post = $r[0];
719         }
720
721         $contactid = 0;
722
723         if(link_compare($post->actor->url, $own_id)) {
724                 $contactid = $self[0]['id'];
725         } else {
726                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
727                         dbesc($post->actor->url),
728                         intval($uid)
729                 );
730
731                 if(count($r))
732                         $contactid = $r[0]['id'];
733
734                 if($contactid == 0)
735                         $contactid = $orig_post['contact-id'];
736         }
737
738         $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'",
739                 dbesc(datetime_convert()),
740                 dbesc(ACTIVITY_LIKE),
741                 intval($uid),
742                 intval($contactid),
743                 dbesc($orig_post['uri'])
744         );
745
746         if(count($r))
747                 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
748         else
749                 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
750 }
751
752 function pumpio_dolike(&$a, $uid, $self, $post, $own_id) {
753
754         // Searching for the liked post
755         // Two queries for speed issues
756         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
757                                 dbesc($post->object->id),
758                                 intval($uid)
759                 );
760
761         if (count($r))
762                 $orig_post = $r[0];
763         else {
764                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
765                                         dbesc($post->object->id),
766                                         intval($uid)
767                         );
768
769                 if (!count($r))
770                         return;
771                 else
772                         $orig_post = $r[0];
773         }
774
775         $contactid = 0;
776
777         if(link_compare($post->actor->url, $own_id)) {
778                 $contactid = $self[0]['id'];
779                 $post->actor->displayName = $self[0]['name'];
780                 $post->actor->url = $self[0]['url'];
781                 $post->actor->image->url = $self[0]['photo'];
782         } else {
783                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
784                         dbesc($post->actor->url),
785                         intval($uid)
786                 );
787
788                 if(count($r))
789                         $contactid = $r[0]['id'];
790
791                 if($contactid == 0)
792                         $contactid = $orig_post['contact-id'];
793         }
794
795         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
796                 dbesc(ACTIVITY_LIKE),
797                 intval($uid),
798                 intval($contactid),
799                 dbesc($orig_post['uri'])
800         );
801
802         if(count($r)) {
803                 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
804                 return;
805         }
806
807         $likedata = array();
808         $likedata['parent'] = $orig_post['id'];
809         $likedata['verb'] = ACTIVITY_LIKE;
810         $likedata['gravity'] = 3;
811         $likedata['uid'] = $uid;
812         $likedata['wall'] = 0;
813         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
814         $likedata['parent-uri'] = $orig_post["uri"];
815         $likedata['contact-id'] = $contactid;
816         $likedata['app'] = $post->generator->displayName;
817         $likedata['verb'] = ACTIVITY_LIKE;
818         $likedata['author-name'] = $post->actor->displayName;
819         $likedata['author-link'] = $post->actor->url;
820         $likedata['author-avatar'] = $post->actor->image->url;
821
822         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
823         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
824         $post_type = t('status');
825         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
826         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
827
828         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
829
830         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
831                 '<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>';
832
833         $ret = item_store($likedata);
834
835         logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
836 }
837
838 function pumpio_get_contact($uid, $contact) {
839
840         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
841                 intval($uid), dbesc($contact->url));
842
843         if(!count($r)) {
844                 // create contact record
845                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
846                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
847                                         `writable`, `blocked`, `readonly`, `pending` )
848                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
849                         intval($uid),
850                         dbesc(datetime_convert()),
851                         dbesc($contact->url),
852                         dbesc(normalise_link($contact->url)),
853                         dbesc(str_replace("acct:", "", $contact->id)),
854                         dbesc(''),
855                         dbesc($contact->id), // To-Do?
856                         dbesc('pump.io ' . $contact->id), // To-Do?
857                         dbesc($contact->displayName),
858                         dbesc($contact->preferredUsername),
859                         dbesc($contact->image->url),
860                         dbesc(NETWORK_PUMPIO),
861                         intval(CONTACT_IS_FRIEND),
862                         intval(1),
863                         intval(1)
864                 );
865
866                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
867                         dbesc($contact->url),
868                         intval($uid)
869                         );
870
871                 if(! count($r))
872                         return(false);
873
874                 $contact_id  = $r[0]['id'];
875
876                 $g = q("select def_gid from user where uid = %d limit 1",
877                         intval($uid)
878                 );
879
880                 if($g && intval($g[0]['def_gid'])) {
881                         require_once('include/group.php');
882                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
883                 }
884
885                 require_once("Photo.php");
886
887                 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
888
889                 q("UPDATE `contact` SET `photo` = '%s',
890                                         `thumb` = '%s',
891                                         `micro` = '%s',
892                                         `name-date` = '%s',
893                                         `uri-date` = '%s',
894                                         `avatar-date` = '%s'
895                                 WHERE `id` = %d LIMIT 1
896                         ",
897                 dbesc($photos[0]),
898                 dbesc($photos[1]),
899                 dbesc($photos[2]),
900                 dbesc(datetime_convert()),
901                 dbesc(datetime_convert()),
902                 dbesc(datetime_convert()),
903                 intval($contact_id)
904                 );
905         } else {
906                 // update profile photos once every two weeks as we have no notification of when they change.
907
908                 $update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
909
910                 // check that we have all the photos, this has been known to fail on occasion
911
912                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
913                         require_once("Photo.php");
914
915                         $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
916
917                         q("UPDATE `contact` SET `photo` = '%s',
918                                         `thumb` = '%s',
919                                         `micro` = '%s',
920                                         `name-date` = '%s',
921                                         `uri-date` = '%s',
922                                         `avatar-date` = '%s'
923                                         WHERE `id` = %d LIMIT 1
924                                 ",
925                         dbesc($photos[0]),
926                         dbesc($photos[1]),
927                         dbesc($photos[2]),
928                         dbesc(datetime_convert()),
929                         dbesc(datetime_convert()),
930                         dbesc(datetime_convert()),
931                         intval($r[0]['id'])
932                         );
933                 }
934
935         }
936
937         return($r[0]["id"]);
938 }
939
940 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
941
942         // Two queries for speed issues
943         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
944                                 dbesc($post->object->id),
945                                 intval($uid)
946                 );
947
948         if (count($r))
949                 return drop_item($r[0]["id"], $false);
950
951         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
952                                 dbesc($post->object->id),
953                                 intval($uid)
954                 );
955
956         if (count($r))
957                 return drop_item($r[0]["id"], $false);
958 }
959
960 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id) {
961         require_once('include/items.php');
962
963         if (($post->verb == "like") OR ($post->verb == "favorite"))
964                 return pumpio_dolike(&$a, $uid, $self, $post, $own_id);
965
966         if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
967                 return pumpio_dounlike(&$a, $uid, $self, $post, $own_id);
968
969         if ($post->verb == "delete")
970                 return pumpio_dodelete(&$a, $uid, $self, $post, $own_id);
971
972         if ($post->verb != "update") {
973                 // Two queries for speed issues
974                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
975                                         dbesc($post->object->id),
976                                         intval($uid)
977                         );
978
979                 if (count($r))
980                         return false;
981
982                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
983                                         dbesc($post->object->id),
984                                         intval($uid)
985                         );
986
987                 if (count($r))
988                         return false;
989         }
990
991         // Only handle these three types
992         if (!strstr("post|share|update", $post->verb))
993                 return false;
994
995         $receiptians = array();
996         if (@is_array($post->cc))
997                 $receiptians = array_merge($receiptians, $post->cc);
998
999         if (@is_array($post->to))
1000                 $receiptians = array_merge($receiptians, $post->to);
1001
1002         foreach ($receiptians AS $receiver)
1003                 if (is_string($receiver->objectType))
1004                         if ($receiver->id == "http://activityschema.org/collection/public")
1005                                 $public = true;
1006
1007         $postarray = array();
1008         $postarray['gravity'] = 0;
1009         $postarray['uid'] = $uid;
1010         $postarray['wall'] = 0;
1011         $postarray['uri'] = $post->object->id;
1012
1013         if ($post->object->objectType != "comment") {
1014                 $contact_id = pumpio_get_contact($uid, $post->actor);
1015
1016                 if (!$contact_id)
1017                         $contact_id = $self[0]['id'];
1018
1019                 $postarray['parent-uri'] = $post->object->id;
1020         } else {
1021                 $contact_id = 0;
1022
1023                 if(link_compare($post->actor->url, $own_id)) {
1024                         $contact_id = $self[0]['id'];
1025                         $post->actor->displayName = $self[0]['name'];
1026                         $post->actor->url = $self[0]['url'];
1027                         $post->actor->image->url = $self[0]['photo'];
1028                 } else {
1029                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1030                         $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1031                                 dbesc($post->actor->url),
1032                                 intval($uid)
1033                         );
1034
1035                         if(count($r))
1036                                 $contact_id = $r[0]['id'];
1037                         else {
1038                                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1039                                         dbesc($post->actor->url),
1040                                         intval($uid)
1041                                 );
1042
1043                                 if(count($r))
1044                                         $contact_id = $r[0]['id'];
1045                                 else
1046                                         $contact_id = $self[0]['id'];
1047                         }
1048                 }
1049
1050                 $reply->verb = "note";
1051                 $reply->cc = $post->cc;
1052                 $reply->to = $post->to;
1053                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1054                 $reply->object->content = $post->object->inReplyTo->content;
1055                 $reply->object->id = $post->object->inReplyTo->id;
1056                 $reply->actor = $post->object->inReplyTo->author;
1057                 $reply->url = $post->object->inReplyTo->url;
1058                 $reply->generator->displayName = "pumpio";
1059                 $reply->published = $post->object->inReplyTo->published;
1060                 $reply->received = $post->object->inReplyTo->updated;
1061                 $reply->url = $post->object->inReplyTo->url;
1062                 pumpio_dopost(&$a, $client, $uid, $self, $reply, $own_id);
1063
1064                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1065         }
1066
1067         if ($post->object->pump_io->proxyURL)
1068                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1069
1070         $postarray['contact-id'] = $contact_id;
1071         $postarray['verb'] = ACTIVITY_POST;
1072         $postarray['owner-name'] = $post->actor->displayName;
1073         $postarray['owner-link'] = $post->actor->url;
1074         $postarray['owner-avatar'] = $post->actor->image->url;
1075         $postarray['author-name'] = $post->actor->displayName;
1076         $postarray['author-link'] = $post->actor->url;
1077         $postarray['author-avatar'] = $post->actor->image->url;
1078         $postarray['plink'] = $post->object->url;
1079         $postarray['app'] = $post->generator->displayName;
1080         $postarray['body'] = html2bbcode($post->object->content);
1081
1082         if ($post->object->fullImage->url != "")
1083                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1084
1085         if ($post->object->displayName != "")
1086                 $postarray['title'] = $post->object->displayName;
1087
1088         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1089         $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1090         if (!$public) {
1091                 $postarray['private'] = 1;
1092                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1093         }
1094
1095         if ($post->verb == "share") {
1096                 $postarray['body'] = "[share author='".$post->object->author->displayName.
1097                                 "' profile='".$post->object->author->url.
1098                                 "' avatar='".$post->object->author->image->url.
1099                                 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1100         }
1101
1102         if (trim($postarray['body']) == "")
1103                 return false;
1104
1105         $top_item = item_store($postarray);
1106
1107         if (($top_item == 0) AND ($post->verb == "update")) {
1108                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1109                         dbesc($postarray["title"]),
1110                         dbesc($postarray["body"]),
1111                         dbesc($postarray["edited"]),
1112                         dbesc($postarray["uri"]),
1113                         intval($uid)
1114                         );
1115         }
1116
1117         if ($post->object->objectType == "comment") {
1118
1119                 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1120
1121                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1122                                 intval($uid)
1123                         );
1124
1125                 if(!count($user))
1126                         return $top_item;
1127
1128                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1129
1130                 if (link_compare($own_id, $postarray['author-link']))
1131                         return $top_item;
1132
1133                 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1134                                 dbesc($postarray['parent-uri']),
1135                                 intval($uid)
1136                                 );
1137
1138                 if(count($myconv)) {
1139
1140                         foreach($myconv as $conv) {
1141                                 // now if we find a match, it means we're in this conversation
1142
1143                                 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_id))
1144                                         continue;
1145
1146                                 require_once('include/enotify.php');
1147
1148                                 $conv_parent = $conv['parent'];
1149
1150                                 notification(array(
1151                                         'type'         => NOTIFY_COMMENT,
1152                                         'notify_flags' => $user[0]['notify-flags'],
1153                                         'language'     => $user[0]['language'],
1154                                         'to_name'      => $user[0]['username'],
1155                                         'to_email'     => $user[0]['email'],
1156                                         'uid'          => $user[0]['uid'],
1157                                         'item'         => $postarray,
1158                                         'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1159                                         'source_name'  => $postarray['author-name'],
1160                                         'source_link'  => $postarray['author-link'],
1161                                         'source_photo' => $postarray['author-avatar'],
1162                                         'verb'         => ACTIVITY_POST,
1163                                         'otype'        => 'item',
1164                                         'parent'       => $conv_parent,
1165                                         ));
1166
1167                                 // only send one notification
1168                                 break;
1169                         }
1170                 }
1171         }
1172
1173         return $top_item;
1174 }
1175
1176 function pumpio_fetchinbox($a, $uid) {
1177
1178         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1179         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1180         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1181         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1182         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1183         $hostname = get_pconfig($uid, 'pumpio','host');
1184         $username = get_pconfig($uid, "pumpio", "user");
1185
1186         $own_id = "https://".$hostname."/".$username;
1187
1188         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1189                 intval($uid));
1190
1191         $client = new oauth_client_class;
1192         $client->oauth_version = '1.0a';
1193         $client->authorization_header = true;
1194         $client->url_parameters = false;
1195
1196         $client->client_id = $ckey;
1197         $client->client_secret = $csecret;
1198         $client->access_token = $otoken;
1199         $client->access_token_secret = $osecret;
1200
1201         $last_id = get_pconfig($uid,'pumpio','last_id');
1202
1203         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1204
1205         if ($last_id != "")
1206                 $url .= '?since='.urlencode($last_id);
1207
1208         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1209         $posts = array_reverse($user->items);
1210
1211         if (count($posts))
1212                 foreach ($posts as $post) {
1213                         $last_id = $post->id;
1214                         pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id);
1215                 }
1216
1217         set_pconfig($uid,'pumpio','last_id', $last_id);
1218 }
1219
1220 function pumpio_getallusers($a, $uid) {
1221         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1222         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1223         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1224         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1225         $hostname = get_pconfig($uid, 'pumpio','host');
1226         $username = get_pconfig($uid, "pumpio", "user");
1227
1228         $client = new oauth_client_class;
1229         $client->oauth_version = '1.0a';
1230         $client->authorization_header = true;
1231         $client->url_parameters = false;
1232
1233         $client->client_id = $ckey;
1234         $client->client_secret = $csecret;
1235         $client->access_token = $otoken;
1236         $client->access_token_secret = $osecret;
1237
1238         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1239
1240         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1241
1242         if ($users->totalItems > count($users->items)) {
1243                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1244
1245                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1246         }
1247
1248         foreach ($users->items AS $user)
1249                 echo pumpio_get_contact($uid, $user)."\n";
1250 }
1251
1252 function pumpio_queue_hook(&$a,&$b) {
1253
1254         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1255                 dbesc(NETWORK_PUMPIO)
1256         );
1257         if(! count($qi))
1258                 return;
1259
1260         require_once('include/queue_fn.php');
1261
1262         foreach($qi as $x) {
1263                 if($x['network'] !== NETWORK_PUMPIO)
1264                         continue;
1265
1266                 logger('pumpio_queue: run');
1267
1268                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
1269                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1270                         intval($x['cid'])
1271                 );
1272                 if(! count($r))
1273                         continue;
1274
1275                 $user = $r[0];
1276
1277                 $oauth_token = get_pconfig($user['uid'], "pumpio", "oauth_token");
1278                 $oauth_token_secret = get_pconfig($user['uid'], "pumpio", "oauth_token_secret");
1279                 $consumer_key = get_pconfig($user['uid'], "pumpio","consumer_key");
1280                 $consumer_secret = get_pconfig($user['uid'], "pumpio","consumer_secret");
1281
1282                 $host = get_pconfig($user['uid'], "pumpio", "host");
1283                 $user = get_pconfig($user['uid'], "pumpio", "user");
1284
1285                 $success = false;
1286
1287                 if ($oauth_token AND $oauth_token_secret AND
1288                         $consumer_key AND $consumer_secret) {
1289                         $username = $user.'@'.$host;
1290
1291                         logger('pumpio_queue: able to post for user '.$username);
1292
1293                         $z = unserialize($x['content']);
1294
1295                         $client = new oauth_client_class;
1296                         $client->oauth_version = '1.0a';
1297                         $client->url_parameters = false;
1298                         $client->authorization_header = true;
1299                         $client->access_token = $oauth_token;
1300                         $client->access_token_secret = $oauth_token_secret;
1301                         $client->client_id = $consumer_key;
1302                         $client->client_secret = $consumer_secret;
1303
1304                         $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1305
1306                         if($success) {
1307                                 $post_id = $user->object->id;
1308                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1309                                 if($post_id AND $iscomment) {
1310                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1311                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
1312                                                 dbesc($post_id),
1313                                                 intval($z['item'])
1314                                         );
1315                                 }
1316                                 remove_queue_item($x['id']);
1317                         } else
1318                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1319                 } else
1320                         logger("pumpio_queue: Error getting tokens for user ".$user['uid']);
1321
1322                 if (!$success) {
1323                         logger('pumpio_queue: delayed');
1324                         update_queue_time($x['id']);
1325                 }
1326         }
1327 }
1328
1329 function pumpio_getreceiver($a, $b) {
1330
1331         $receiver = array();
1332
1333         if (!$b["private"]) {
1334
1335                 if(! strstr($b['postopts'],'pumpio'))
1336                         return $receiver;
1337
1338                 $public = get_pconfig($b['uid'], "pumpio", "public");
1339
1340                 if ($public)
1341                         $receiver["to"][] = Array(
1342                                                 "objectType" => "collection",
1343                                                 "id" => "http://activityschema.org/collection/public");
1344         } else {
1345                 $cids = explode("><", $b["allow_cid"]);
1346                 $gids = explode("><", $b["allow_gid"]);
1347
1348                 foreach ($cids AS $cid) {
1349                         $cid = trim($cid, " <>");
1350
1351                         $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",
1352                                 intval($cid),
1353                                 intval($b["uid"]),
1354                                 dbesc(NETWORK_PUMPIO)
1355                                 );
1356
1357                         if (count($r)) {
1358                                 $receiver["bcc"][] = Array(
1359                                                         "displayName" => $r[0]["name"],
1360                                                         "objectType" => "person",
1361                                                         "preferredUsername" => $r[0]["nick"],
1362                                                         "url" => $r[0]["url"]);
1363                         }
1364                 }
1365                 foreach ($gids AS $gid) {
1366                         $gid = trim($gid, " <>");
1367
1368                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1369                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1370                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1371                                         intval($gid),
1372                                         intval($b["uid"]),
1373                                         dbesc(NETWORK_PUMPIO)
1374                                 );
1375
1376                         foreach ($r AS $row)
1377                                 $receiver["bcc"][] = Array(
1378                                                         "displayName" => $row["name"],
1379                                                         "objectType" => "person",
1380                                                         "preferredUsername" => $row["nick"],
1381                                                         "url" => $row["url"]);
1382                 }
1383         }
1384
1385         if ($b["inform"] != "") {
1386
1387                 $inform = explode(",", $b["inform"]);
1388
1389                 foreach ($inform AS $cid) {
1390                         if (substr($cid, 0, 4) != "cid:")
1391                                 continue;
1392
1393                         $cid = str_replace("cid:", "", $cid);
1394
1395                         $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",
1396                                 intval($cid),
1397                                 intval($b["uid"]),
1398                                 dbesc(NETWORK_PUMPIO)
1399                                 );
1400
1401                         if (count($r)) {
1402                                         $receiver["to"][] = Array(
1403                                                                 "displayName" => $r[0]["name"],
1404                                                                 "objectType" => "person",
1405                                                                 "preferredUsername" => $r[0]["nick"],
1406                                                                 "url" => $r[0]["url"]);
1407                         }
1408                 }
1409         }
1410
1411         return $receiver;
1412 }
1413
1414 function pumpio_fetchallcomments($a, $uid, $id) {
1415         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1416         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1417         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1418         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1419         $hostname = get_pconfig($uid, 'pumpio','host');
1420         $username = get_pconfig($uid, "pumpio", "user");
1421
1422         $own_id = "https://".$hostname."/".$username;
1423
1424         logger("pumpio_fetchallcomments: completing comment for user ".$uid." url ".$url);
1425
1426         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1427                 intval($uid));
1428
1429         // Fetching the original post - Two queries for speed issues
1430         $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1431                         dbesc($url),
1432                         intval($uid)
1433                 );
1434
1435         if (!count($r)) {
1436                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1437                                 dbesc($url),
1438                                 intval($uid)
1439                         );
1440
1441                 if (!count($r))
1442                         return false;
1443         }
1444
1445         if ($r[0]["extid"])
1446                 $url = $r[0]["extid"];
1447         else
1448                 $url = $id;
1449
1450         $client = new oauth_client_class;
1451         $client->oauth_version = '1.0a';
1452         $client->authorization_header = true;
1453         $client->url_parameters = false;
1454
1455         $client->client_id = $ckey;
1456         $client->client_secret = $csecret;
1457         $client->access_token = $otoken;
1458         $client->access_token_secret = $osecret;
1459
1460         logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1461
1462         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1463
1464         if (!$success)
1465                 return;
1466
1467         if ($item->replies->totalItems == 0)
1468                 return;
1469
1470         foreach ($item->replies->items AS $item) {
1471                 if ($item->id == $id)
1472                         continue;
1473
1474                 // Checking if the comment already exists - Two queries for speed issues
1475                 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1476                                 dbesc($url),
1477                                 intval($uid)
1478                         );
1479
1480                 if (count($r))
1481                         continue;
1482
1483                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1484                                 dbesc($url),
1485                                 intval($uid)
1486                         );
1487
1488                 if (count($r))
1489                         continue;
1490
1491                 $post->verb = "post";
1492                 $post->actor = $item->author;
1493                 $post->published = $item->published;
1494                 $post->received = $item->updated;
1495                 $post->generator->displayName = "pumpio";
1496
1497                 unset($item->author);
1498                 unset($item->published);
1499                 unset($item->updated);
1500
1501                 $post->object = $item;
1502
1503                 logger("pumpio_fetchallcomments: posting comment ".$post->object->id);
1504                 pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id);
1505         }
1506 }
1507
1508 /*
1509 Bugs:
1510
1511 To-Do:
1512
1513 Could be hard to do:
1514  - edit own notes
1515  - delete own notes
1516
1517 Known issues:
1518  - refresh after post
1519
1520 */