]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
pumpio: Editing and deleting of own comments is now possible.
[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
223                 //$s .= t("You are not authenticated to pumpio");
224         } else {
225                 $s .= '<div id="pumpio-import-wrapper">';
226                 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
227                 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
228                 $s .= '</div><div class="clear"></div>';
229
230                 $s .= '<div id="pumpio-enable-wrapper">';
231                 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
232                 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
233                 $s .= '</div><div class="clear"></div>';
234
235                 $s .= '<div id="pumpio-bydefault-wrapper">';
236                 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
237                 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
238                 $s .= '</div><div class="clear"></div>';
239
240                 $s .= '<div id="pumpio-public-wrapper">';
241                 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
242                 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
243                 $s .= '</div><div class="clear"></div>';
244
245                 $s .= '<div id="pumpio-mirror-wrapper">';
246                 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
247                 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
248                 $s .= '</div><div class="clear"></div>';
249
250                 $s .= '<div id="pumpio-delete-wrapper">';
251                 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
252                 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
253                 $s .= '</div><div class="clear"></div>';
254
255                 //$s .= '<div id="pumpio-authenticate-wrapper">';
256                 //$s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Reauthenticate your pump.io connection").'</a>';
257                 //$s .= '</div><div class="clear"></div>';
258
259         }
260
261         $s .= '</div><div class="clear"></div>';
262     }
263
264     /* provide a submit button */
265
266     $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
267
268 }
269
270
271 function pumpio_settings_post(&$a,&$b) {
272
273         if(x($_POST,'pumpio-submit')) {
274                 if(x($_POST,'pumpio_delete')) {
275                         set_pconfig(local_user(),'pumpio','consumer_key','');
276                         set_pconfig(local_user(),'pumpio','consumer_secret','');
277                         set_pconfig(local_user(),'pumpio','host','');
278                         set_pconfig(local_user(),'pumpio','oauth_token','');
279                         set_pconfig(local_user(),'pumpio','oauth_token_secret','');
280                         set_pconfig(local_user(),'pumpio','post',false);
281                         set_pconfig(local_user(),'pumpio','post_by_default',false);
282                         set_pconfig(local_user(),'pumpio','user','');
283                 } else {
284                         // filtering the username if it is filled wrong
285                         $user = $_POST['pumpio_user'];
286                         if (strstr($user, "@")) {
287                                 $pos = strpos($user, "@");
288                                 if ($pos > 0)
289                                         $user = substr($user, 0, $pos);
290                         }
291
292                         // Filtering the hostname if someone is entering it with "http"
293                         $host = $_POST['pumpio_host'];
294                         $host = trim($host);
295                         $host = str_replace(array("https://", "http://"), array("", ""), $host);
296
297                         set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
298                         set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
299                         set_pconfig(local_user(),'pumpio','host',$host);
300                         set_pconfig(local_user(),'pumpio','user',$user);
301                         set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
302                         set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
303                         set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
304                 }
305         }
306 }
307
308 function pumpio_post_local(&$a,&$b) {
309
310         // This can probably be changed to allow editing by pointing to a different API endpoint
311
312         if($b['edit'])
313                 return;
314
315         if((! local_user()) || (local_user() != $b['uid']))
316                 return;
317
318         if($b['private'] || $b['parent'])
319                 return;
320
321         $pumpio_post   = intval(get_pconfig(local_user(),'pumpio','post'));
322
323         $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
324
325         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
326                 $pumpio_enable = 1;
327
328         if(! $pumpio_enable)
329                 return;
330
331         if(strlen($b['postopts']))
332                 $b['postopts'] .= ',';
333
334         $b['postopts'] .= 'pumpio';
335 }
336
337
338
339
340 function pumpio_send(&$a,&$b) {
341         logger("pumpio_send: parameter ".print_r($b, true));
342
343         if($b['verb'] == ACTIVITY_LIKE) {
344                 if ($b['deleted'])
345                         pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
346                 else
347                         pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
348                 return;
349         }
350
351         if($b['verb'] == ACTIVITY_DISLIKE)
352                 return;
353
354         if (($b['verb'] == ACTIVITY_POST) AND ($b['created'] !== $b['edited']) AND !$b['deleted'])
355                         pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
356
357         if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
358                         pumpio_action($a, $b["uid"], $b["uri"], "delete");
359
360         if($b['deleted'] || ($b['created'] !== $b['edited']))
361                 return;
362
363         if($b['parent'] != $b['id']) {
364                 // Looking if its a reply to a pumpio post
365                 $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",
366                         intval($b["parent"]),
367                         intval($b["uid"]),
368                         dbesc(NETWORK_PUMPIO));
369
370                 if(!count($r))
371                         return;
372                 else {
373                         $iscomment = true;
374                         $orig_post = $r[0];
375                 }
376         } else {
377                 $iscomment = false;
378
379                 if(! strstr($b['postopts'],'pumpio'))
380                         return;
381
382                 if($b['private'])
383                         return;
384         }
385
386         // if post comes from pump.io don't send it back
387         if($b['app'] == "pump.io")
388                 return;
389
390
391         $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
392         $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
393         $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
394         $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
395
396         $host = get_pconfig($b['uid'], "pumpio", "host");
397         $user = get_pconfig($b['uid'], "pumpio", "user");
398         $public = get_pconfig($b['uid'], "pumpio", "public");
399
400         if($oauth_token && $oauth_token_secret) {
401
402                 require_once('include/bbcode.php');
403
404                 $title = trim($b['title']);
405
406                 if ($title != '')
407                         $title = "<h4>".$title."</h4>";
408
409                 $content = bbcode($b['body'], false, false);
410
411                 // Enhance the way, videos are displayed
412                 $content = preg_replace('/<a.*?href="(https?:\/\/www.youtube.com\/.*?)".*?>(.*?)<\/a>/ism',"\n[url]$1[/url]\n",$content);
413                 $content = preg_replace('/<a.*?href="(https?:\/\/youtu.be\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
414                 $content = preg_replace('/<a.*?href="(https?:\/\/vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
415                 $content = preg_replace('/<a.*?href="(https?:\/\/player.vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
416
417                 $URLSearchString = "^\[\]";
418                 $content = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$content);
419
420                 $params = array();
421
422                 $params["verb"] = "post";
423
424                 if (!$iscomment) {
425                         $params["object"] = array(
426                                                 'objectType' => "note",
427                                                 'content' => $title.$content);
428
429                         if ($public)
430                                 $params["to"] = array(Array(
431                                                         "objectType" => "collection",
432                                                         "id" => "http://activityschema.org/collection/public"));
433                  } else {
434                         $inReplyTo = array("id" => $orig_post["uri"],
435                                         "objectType" => "note");
436
437                         $params["object"] = array(
438                                                 'objectType' => "comment",
439                                                 'content' => $title.$content,
440                                                 'inReplyTo' => $inReplyTo);
441                 }
442
443                 $client = new oauth_client_class;
444                 $client->oauth_version = '1.0a';
445                 $client->url_parameters = false;
446                 $client->authorization_header = true;
447                 $client->access_token = $oauth_token;
448                 $client->access_token_secret = $oauth_token_secret;
449                 $client->client_id = $consumer_key;
450                 $client->client_secret = $consumer_secret;
451
452                 $username = $user.'@'.$host;
453                 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
454
455                 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
456                 //$success = false;
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         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
486         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
487         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
488         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
489         $hostname = get_pconfig($uid, 'pumpio','host');
490         $username = get_pconfig($uid, "pumpio", "user");
491
492         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
493                                 dbesc($uri),
494                                 intval($uid)
495         );
496
497         if (!count($r))
498                 return;
499
500         $orig_post = $r[0];
501
502         if ($orig_post["extid"])
503                 $uri = $orig_post["extid"];
504         else
505                 $uri = $orig_post["uri"];
506
507         if (strstr($uri, "/api/comment/"))
508                 $objectType = "comment";
509         elseif (strstr($uri, "/api/note/"))
510                 $objectType = "note";
511         elseif (strstr($uri, "/api/image/"))
512                 $objectType = "image";
513
514         $params["verb"] = $action;
515         $params["object"] = array('id' => $uri,
516                                 "objectType" => $objectType,
517                                 "content" => $content);
518
519         $client = new oauth_client_class;
520         $client->oauth_version = '1.0a';
521         $client->authorization_header = true;
522         $client->url_parameters = false;
523
524         $client->client_id = $ckey;
525         $client->client_secret = $csecret;
526         $client->access_token = $otoken;
527         $client->access_token_secret = $osecret;
528
529         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
530
531         $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
532
533         if($success)
534                 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
535         else {
536                 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
537
538                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
539                 if (count($r))
540                         $a->contact = $r[0]["id"];
541
542                 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
543                 require_once('include/queue_fn.php');
544                 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
545                 notice(t('Pump.io like failed. Queued for retry.').EOL);
546         }
547 }
548
549
550 function pumpio_cron($a,$b) {
551         $last = get_config('pumpio','last_poll');
552
553         $poll_interval = intval(get_config('pumpio','poll_interval'));
554         if(! $poll_interval)
555                 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
556
557         if($last) {
558                 $next = $last + ($poll_interval * 60);
559 //                if($next > time()) {
560 //                        logger('pumpio: poll intervall not reached');
561 //                        return;
562 //                }
563         }
564         logger('pumpio: cron_start');
565
566         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
567         if(count($r)) {
568                 foreach($r as $rr) {
569                         logger('pumpio: mirroring user '.$rr['uid']);
570                         pumpio_fetchtimeline($a, $rr['uid']);
571                 }
572         }
573
574         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
575         if(count($r)) {
576                 foreach($r as $rr) {
577                         logger('pumpio: importing timeline from user '.$rr['uid']);
578                         pumpio_fetchinbox($a, $rr['uid']);
579                 }
580         }
581
582         // To-Do:
583         //pumpio_getallusers($a, $uid);
584
585         logger('pumpio: cron_end');
586
587         set_config('pumpio','last_poll', time());
588 }
589
590 function pumpio_fetchtimeline($a, $uid) {
591         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
592         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
593         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
594         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
595         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
596         $hostname = get_pconfig($uid, 'pumpio','host');
597         $username = get_pconfig($uid, "pumpio", "user");
598
599         $application_name  = get_config('pumpio', 'application_name');
600
601         if ($application_name == "")
602                 $application_name = $a->get_hostname();
603
604         $first_time = ($lastdate == "");
605
606         $client = new oauth_client_class;
607         $client->oauth_version = '1.0a';
608         $client->authorization_header = true;
609         $client->url_parameters = false;
610
611         $client->client_id = $ckey;
612         $client->client_secret = $csecret;
613         $client->access_token = $otoken;
614         $client->access_token_secret = $osecret;
615
616         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
617
618         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
619
620         $username = $user.'@'.$host;
621
622         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
623
624         if (!$success) {
625                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
626                 return;
627         }
628
629         $posts = array_reverse($user->items);
630
631         $initiallastdate = $lastdate;
632         $lastdate = '';
633
634         if (count($posts)) {
635                 foreach ($posts as $post) {
636                         if ($post->generator->published <= $initiallastdate)
637                                 continue;
638
639                         if ($lastdate < $post->generator->published)
640                                 $lastdate = $post->generator->published;
641
642                         if ($first_time)
643                                 continue;
644
645                         $receiptians = array();
646                         if (@is_array($post->cc))
647                                 $receiptians = array_merge($receiptians, $post->cc);
648
649                         if (@is_array($post->to))
650                                 $receiptians = array_merge($receiptians, $post->to);
651
652                         $public = false;
653                         foreach ($receiptians AS $receiver)
654                                 if (is_string($receiver->objectType))
655                                         if ($receiver->id == "http://activityschema.org/collection/public")
656                                                 $public = true;
657
658                         if ($public AND !strstr($post->generator->displayName, $application_name)) {
659                                 require_once('include/html2bbcode.php');
660
661                                 $_SESSION["authenticated"] = true;
662                                 $_SESSION["uid"] = $uid;
663
664                                 unset($_REQUEST);
665                                 $_REQUEST["type"] = "wall";
666                                 $_REQUEST["api_source"] = true;
667                                 $_REQUEST["profile_uid"] = $uid;
668                                 $_REQUEST["source"] = "pump.io";
669
670                                 if ($post->object->displayName != "")
671                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
672                                 else
673                                         $_REQUEST["title"] = "";
674
675                                 $_REQUEST["body"] = html2bbcode($post->object->content);
676
677                                 if ($post->object->fullImage->url != "")
678                                         $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
679
680                                 logger('pumpio: posting for user '.$uid);
681
682                                 require_once('mod/item.php');
683                                 //print_r($_REQUEST);
684                                 item_post($a);
685                                 logger('pumpio: posting done - user '.$uid);
686                         }
687                 }
688         }
689
690         //$lastdate = '2013-05-16T20:22:12Z';
691
692         if ($lastdate != 0)
693                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
694 }
695
696 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
697         // Searching for the unliked post
698         // Two queries for speed issues
699         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
700                                 dbesc($post->object->id),
701                                 intval($uid)
702                 );
703
704         if (count($r))
705                 $orig_post = $r[0];
706         else {
707                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
708                                         dbesc($post->object->id),
709                                         intval($uid)
710                         );
711
712                 if (!count($r))
713                         return;
714                 else
715                         $orig_post = $r[0];
716         }
717
718         $contactid = 0;
719
720         if(link_compare($post->actor->url, $own_id)) {
721                 $contactid = $self[0]['id'];
722         } else {
723                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
724                         dbesc($post->actor->url),
725                         intval($uid)
726                 );
727
728                 if(count($r))
729                         $contactid = $r[0]['id'];
730
731                 if($contactid == 0)
732                         $contactid = $orig_post['contact-id'];
733         }
734
735         $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'",
736                 dbesc(datetime_convert()),
737                 dbesc(ACTIVITY_LIKE),
738                 intval($uid),
739                 intval($contactid),
740                 dbesc($orig_post['uri'])
741         );
742
743         if(count($r))
744                 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
745         else
746                 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
747 }
748
749 function pumpio_dolike(&$a, $uid, $self, $post, $own_id) {
750
751         // Searching for the liked post
752         // Two queries for speed issues
753         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
754                                 dbesc($post->object->id),
755                                 intval($uid)
756                 );
757
758         if (count($r))
759                 $orig_post = $r[0];
760         else {
761                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
762                                         dbesc($post->object->id),
763                                         intval($uid)
764                         );
765
766                 if (!count($r))
767                         return;
768                 else
769                         $orig_post = $r[0];
770         }
771
772         $contactid = 0;
773
774         if(link_compare($post->actor->url, $own_id)) {
775                 $contactid = $self[0]['id'];
776                 $post->actor->displayName = $self[0]['name'];
777                 $post->actor->url = $self[0]['url'];
778                 $post->actor->image->url = $self[0]['photo'];
779         } else {
780                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
781                         dbesc($post->actor->url),
782                         intval($uid)
783                 );
784
785                 if(count($r))
786                         $contactid = $r[0]['id'];
787
788                 if($contactid == 0)
789                         $contactid = $orig_post['contact-id'];
790         }
791
792         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
793                 dbesc(ACTIVITY_LIKE),
794                 intval($uid),
795                 intval($contactid),
796                 dbesc($orig_post['uri'])
797         );
798
799         if(count($r)) {
800                 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
801                 return;
802         }
803
804         $likedata = array();
805         $likedata['parent'] = $orig_post['id'];
806         $likedata['verb'] = ACTIVITY_LIKE;
807         $likedata['gravity'] = 3;
808         $likedata['uid'] = $uid;
809         $likedata['wall'] = 0;
810         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
811         $likedata['parent-uri'] = $orig_post["uri"];
812         $likedata['contact-id'] = $contactid;
813         $likedata['app'] = $post->generator->displayName;
814         $likedata['verb'] = ACTIVITY_LIKE;
815         $likedata['author-name'] = $post->actor->displayName;
816         $likedata['author-link'] = $post->actor->url;
817         $likedata['author-avatar'] = $post->actor->image->url;
818
819         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
820         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
821         $post_type = t('status');
822         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
823         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
824
825         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
826
827         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
828                 '<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>';
829
830         $ret = item_store($likedata);
831
832         logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
833 }
834
835 function pumpio_get_contact($uid, $contact) {
836
837         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
838                 intval($uid), dbesc($contact->url));
839
840         if(!count($r)) {
841                 // create contact record
842                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
843                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
844                                         `writable`, `blocked`, `readonly`, `pending` )
845                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
846                         intval($uid),
847                         dbesc(datetime_convert()),
848                         dbesc($contact->url),
849                         dbesc(normalise_link($contact->url)),
850                         dbesc(str_replace("acct:", "", $contact->id)),
851                         dbesc(''),
852                         dbesc($contact->id), // To-Do?
853                         dbesc('pump.io ' . $contact->id), // To-Do?
854                         dbesc($contact->displayName),
855                         dbesc($contact->preferredUsername),
856                         dbesc($contact->image->url),
857                         dbesc(NETWORK_PUMPIO),
858                         intval(CONTACT_IS_FRIEND),
859                         intval(1),
860                         intval(1)
861                 );
862
863                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
864                         dbesc($contact->url),
865                         intval($uid)
866                         );
867
868                 if(! count($r))
869                         return(false);
870
871                 $contact_id  = $r[0]['id'];
872
873                 $g = q("select def_gid from user where uid = %d limit 1",
874                         intval($uid)
875                 );
876
877                 if($g && intval($g[0]['def_gid'])) {
878                         require_once('include/group.php');
879                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
880                 }
881
882                 require_once("Photo.php");
883
884                 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
885
886                 q("UPDATE `contact` SET `photo` = '%s',
887                                         `thumb` = '%s',
888                                         `micro` = '%s',
889                                         `name-date` = '%s',
890                                         `uri-date` = '%s',
891                                         `avatar-date` = '%s'
892                                 WHERE `id` = %d LIMIT 1
893                         ",
894                 dbesc($photos[0]),
895                 dbesc($photos[1]),
896                 dbesc($photos[2]),
897                 dbesc(datetime_convert()),
898                 dbesc(datetime_convert()),
899                 dbesc(datetime_convert()),
900                 intval($contact_id)
901                 );
902         } else {
903                 // update profile photos once every two weeks as we have no notification of when they change.
904
905                 $update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
906
907                 // check that we have all the photos, this has been known to fail on occasion
908
909                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
910                         require_once("Photo.php");
911
912                         $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
913
914                         q("UPDATE `contact` SET `photo` = '%s',
915                                         `thumb` = '%s',
916                                         `micro` = '%s',
917                                         `name-date` = '%s',
918                                         `uri-date` = '%s',
919                                         `avatar-date` = '%s'
920                                         WHERE `id` = %d LIMIT 1
921                                 ",
922                         dbesc($photos[0]),
923                         dbesc($photos[1]),
924                         dbesc($photos[2]),
925                         dbesc(datetime_convert()),
926                         dbesc(datetime_convert()),
927                         dbesc(datetime_convert()),
928                         intval($r[0]['id'])
929                         );
930                 }
931
932         }
933
934         return($r[0]["id"]);
935 }
936
937 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
938
939         // Two queries for speed issues
940         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
941                                 dbesc($post->object->id),
942                                 intval($uid)
943                 );
944
945         if (count($r)) {
946                 drop_item($r[0]["id"], $false);
947                 return;
948         }
949
950         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
951                                 dbesc($post->object->id),
952                                 intval($uid)
953                 );
954
955         if (count($r)) {
956                 drop_item($r[0]["id"], $false);
957                 return;
958         }
959 }
960
961 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id) {
962         require_once('include/items.php');
963
964         if (($post->verb == "like") OR ($post->verb == "favorite")) {
965                 pumpio_dolike(&$a, $uid, $self, $post, $own_id);
966                 return;
967         }
968
969         if (($post->verb == "unlike") OR ($post->verb == "unfavorite")) {
970                 pumpio_dounlike(&$a, $uid, $self, $post, $own_id);
971                 return;
972         }
973
974         if ($post->verb == "delete") {
975                 pumpio_dodelete(&$a, $uid, $self, $post, $own_id);
976                 return;
977         }
978
979         if ($post->verb != "update") {
980                 // Two queries for speed issues
981                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
982                                         dbesc($post->object->id),
983                                         intval($uid)
984                         );
985
986                 if (count($r))
987                         return;
988
989                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
990                                         dbesc($post->object->id),
991                                         intval($uid)
992                         );
993
994                 if (count($r))
995                         return;
996         }
997
998         // Only handle these three types
999         if (!strstr("post|share|update", $post->verb))
1000                 return;
1001
1002         $receiptians = array();
1003         if (@is_array($post->cc))
1004                 $receiptians = array_merge($receiptians, $post->cc);
1005
1006         if (@is_array($post->to))
1007                 $receiptians = array_merge($receiptians, $post->to);
1008
1009         foreach ($receiptians AS $receiver)
1010                 if (is_string($receiver->objectType))
1011                         if ($receiver->id == "http://activityschema.org/collection/public")
1012                                 $public = true;
1013
1014         $postarray = array();
1015         $postarray['gravity'] = 0;
1016         $postarray['uid'] = $uid;
1017         $postarray['wall'] = 0;
1018         $postarray['uri'] = $post->object->id;
1019
1020         if ($post->object->objectType != "comment") {
1021                 $contact_id = pumpio_get_contact($uid, $post->actor);
1022
1023                 if (!$contact_id)
1024                         $contact_id = $self[0]['id'];
1025
1026                 $postarray['parent-uri'] = $post->object->id;
1027         } else {
1028                 $contact_id = 0;
1029
1030                 if(link_compare($post->actor->url, $own_id)) {
1031                         $contact_id = $self[0]['id'];
1032                         $post->actor->displayName = $self[0]['name'];
1033                         $post->actor->url = $self[0]['url'];
1034                         $post->actor->image->url = $self[0]['photo'];
1035                 } else {
1036                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1037                         $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1038                                 dbesc($post->actor->url),
1039                                 intval($uid)
1040                         );
1041
1042                         if(count($r))
1043                                 $contact_id = $r[0]['id'];
1044                         else {
1045                                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1046                                         dbesc($post->actor->url),
1047                                         intval($uid)
1048                                 );
1049
1050                                 if(count($r))
1051                                         $contact_id = $r[0]['id'];
1052                                 else
1053                                         $contact_id = $self[0]['id'];
1054                         }
1055                 }
1056
1057                 $reply->verb = "note";
1058                 $reply->cc = $post->cc;
1059                 $reply->to = $post->to;
1060                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1061                 $reply->object->content = $post->object->inReplyTo->content;
1062                 $reply->object->id = $post->object->inReplyTo->id;
1063                 $reply->actor = $post->object->inReplyTo->author;
1064                 $reply->url = $post->object->inReplyTo->url;
1065                 $reply->generator->displayName = "pumpio";
1066                 $reply->published = $post->object->inReplyTo->published;
1067                 $reply->received = $post->object->inReplyTo->updated;
1068                 $reply->url = $post->object->inReplyTo->url;
1069                 pumpio_dopost(&$a, $client, $uid, $self, $reply, $own_id);
1070
1071                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1072         }
1073
1074         $postarray['contact-id'] = $contact_id;
1075         $postarray['verb'] = ACTIVITY_POST;
1076         $postarray['owner-name'] = $post->actor->displayName;
1077         $postarray['owner-link'] = $post->actor->url;
1078         $postarray['owner-avatar'] = $post->actor->image->url;
1079         $postarray['author-name'] = $post->actor->displayName;
1080         $postarray['author-link'] = $post->actor->url;
1081         $postarray['author-avatar'] = $post->actor->image->url;
1082         $postarray['plink'] = $post->object->url;
1083         $postarray['app'] = $post->generator->displayName;
1084         $postarray['body'] = html2bbcode($post->object->content);
1085
1086         if ($post->object->fullImage->url != "")
1087                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1088
1089         if ($post->object->displayName != "")
1090                 $postarray['title'] = $post->object->displayName;
1091
1092         //$postarray['location'] = ""
1093         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1094         $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1095         if (!$public) {
1096                 $postarray['private'] = 1;
1097                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1098         }
1099
1100         if ($post->verb == "share") {
1101                 $postarray['body'] = "[share author='".$post->object->author->displayName.
1102                                 "' profile='".$post->object->author->url.
1103                                 "' avatar='".$post->object->author->image->url.
1104                                 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1105         }
1106
1107         if (trim($postarray['body']) == "")
1108                 return;
1109
1110         $top_item = item_store($postarray);
1111
1112         if (($top_item == 0) AND ($post->verb == "update")) {
1113                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1114                         dbesc($postarray["title"]),
1115                         dbesc($postarray["body"]),
1116                         dbesc($postarray["edited"]),
1117                         dbesc($postarray["uri"]),
1118                         intval($uid)
1119                         );
1120         }
1121
1122         if ($post->object->objectType == "comment") {
1123
1124                 $hostname = get_pconfig($uid, 'pumpio','host');
1125                 $username = get_pconfig($uid, "pumpio", "user");
1126
1127                 $foreign_url = "https://".$hostname."/".$username;
1128
1129                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1130                                 intval($uid)
1131                         );
1132
1133                 if(!count($user))
1134                         return;
1135
1136                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1137
1138                 if (link_compare($foreign_url, $postarray['author-link']))
1139                         return;
1140
1141                 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1142                                 dbesc($postarray['parent-uri']),
1143                                 intval($uid)
1144                                 );
1145
1146                 if(count($myconv)) {
1147
1148                         foreach($myconv as $conv) {
1149                                 // now if we find a match, it means we're in this conversation
1150
1151                                 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$foreign_url))
1152                                         continue;
1153
1154                                 require_once('include/enotify.php');
1155
1156                                 $conv_parent = $conv['parent'];
1157
1158                                 notification(array(
1159                                         'type'         => NOTIFY_COMMENT,
1160                                         'notify_flags' => $user[0]['notify-flags'],
1161                                         'language'     => $user[0]['language'],
1162                                         'to_name'      => $user[0]['username'],
1163                                         'to_email'     => $user[0]['email'],
1164                                         'uid'          => $user[0]['uid'],
1165                                         'item'         => $postarray,
1166                                         'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1167                                         'source_name'  => $postarray['author-name'],
1168                                         'source_link'  => $postarray['author-link'],
1169                                         'source_photo' => $postarray['author-avatar'],
1170                                         'verb'         => ACTIVITY_POST,
1171                                         'otype'        => 'item',
1172                                         'parent'       => $conv_parent,
1173                                         ));
1174
1175                                 // only send one notification
1176                                 break;
1177                         }
1178                 }
1179         }
1180 }
1181
1182 function pumpio_fetchinbox($a, $uid) {
1183
1184         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1185         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1186         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1187         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1188         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1189         $hostname = get_pconfig($uid, 'pumpio','host');
1190         $username = get_pconfig($uid, "pumpio", "user");
1191
1192         $own_id = "https://".$hostname."/".$username;
1193
1194         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1195                 intval($uid));
1196
1197         $client = new oauth_client_class;
1198         $client->oauth_version = '1.0a';
1199         $client->authorization_header = true;
1200         $client->url_parameters = false;
1201
1202         $client->client_id = $ckey;
1203         $client->client_secret = $csecret;
1204         $client->access_token = $otoken;
1205         $client->access_token_secret = $osecret;
1206
1207         $last_id = get_pconfig($uid,'pumpio','last_id');
1208
1209         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1210
1211         if ($last_id != "")
1212                 $url .= '?since='.urlencode($last_id);
1213
1214         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1215         $posts = array_reverse($user->items);
1216
1217         if (count($posts))
1218                 foreach ($posts as $post) {
1219                         $last_id = $post->id;
1220                         pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id);
1221                 }
1222
1223         set_pconfig($uid,'pumpio','last_id', $last_id);
1224
1225         // Fetching the minor events
1226         $last_minor_id = get_pconfig($uid,'pumpio','last_minor_id');
1227
1228         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox/minor';
1229
1230         if ($last_minor_id != "")
1231                 $url .= '?since='.urlencode($last_minor_id);
1232
1233         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1234         $posts = array_reverse($user->items);
1235
1236         if (count($posts))
1237                 foreach ($posts as $post) {
1238                         $last_minor_id = $post->id;
1239                         pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id);
1240                 }
1241
1242         set_pconfig($uid,'pumpio','last_minor_id', $last_minor_id);
1243 }
1244
1245 function pumpio_getallusers($a, $uid) {
1246         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1247         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1248         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1249         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1250         $hostname = get_pconfig($uid, 'pumpio','host');
1251         $username = get_pconfig($uid, "pumpio", "user");
1252
1253         $client = new oauth_client_class;
1254         $client->oauth_version = '1.0a';
1255         $client->authorization_header = true;
1256         $client->url_parameters = false;
1257
1258         $client->client_id = $ckey;
1259         $client->client_secret = $csecret;
1260         $client->access_token = $otoken;
1261         $client->access_token_secret = $osecret;
1262
1263         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1264
1265         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1266
1267         if ($users->totalItems > count($users->items)) {
1268                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1269
1270                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1271         }
1272
1273         foreach ($users->items AS $user)
1274                 echo pumpio_get_contact($uid, $user)."\n";
1275 }
1276
1277 function pumpio_queue_hook(&$a,&$b) {
1278
1279         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1280                 dbesc(NETWORK_PUMPIO)
1281         );
1282         if(! count($qi))
1283                 return;
1284
1285         require_once('include/queue_fn.php');
1286
1287         foreach($qi as $x) {
1288                 if($x['network'] !== NETWORK_PUMPIO)
1289                         continue;
1290
1291                 logger('pumpio_queue: run');
1292
1293                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
1294                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1295                         intval($x['cid'])
1296                 );
1297                 if(! count($r))
1298                         continue;
1299
1300                 $user = $r[0];
1301
1302                 $oauth_token = get_pconfig($user['uid'], "pumpio", "oauth_token");
1303                 $oauth_token_secret = get_pconfig($user['uid'], "pumpio", "oauth_token_secret");
1304                 $consumer_key = get_pconfig($user['uid'], "pumpio","consumer_key");
1305                 $consumer_secret = get_pconfig($user['uid'], "pumpio","consumer_secret");
1306
1307                 $host = get_pconfig($user['uid'], "pumpio", "host");
1308                 $user = get_pconfig($user['uid'], "pumpio", "user");
1309
1310                 $success = false;
1311
1312                 if ($oauth_token AND $oauth_token_secret AND
1313                         $consumer_key AND $consumer_secret) {
1314                         $username = $user.'@'.$host;
1315
1316                         logger('pumpio_queue: able to post for user '.$username);
1317
1318                         $z = unserialize($x['content']);
1319
1320                         $client = new oauth_client_class;
1321                         $client->oauth_version = '1.0a';
1322                         $client->url_parameters = false;
1323                         $client->authorization_header = true;
1324                         $client->access_token = $oauth_token;
1325                         $client->access_token_secret = $oauth_token_secret;
1326                         $client->client_id = $consumer_key;
1327                         $client->client_secret = $consumer_secret;
1328
1329                         $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1330
1331                         if($success) {
1332                                 $post_id = $user->object->id;
1333                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1334                                 if($post_id AND $iscomment) {
1335                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1336                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
1337                                                 dbesc($post_id),
1338                                                 intval($z['item'])
1339                                         );
1340                                 }
1341                                 remove_queue_item($x['id']);
1342                         } else
1343                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1344                 } else
1345                         logger("pumpio_queue: Error getting tokens for user ".$user['uid']);
1346
1347                 if (!$success) {
1348                         logger('pumpio_queue: delayed');
1349                         update_queue_time($x['id']);
1350                 }
1351         }
1352 }
1353
1354 /*
1355 To-Do:
1356
1357 Could be hard to do:
1358  - Threads completion
1359  - edit own notes
1360  - delete own notes
1361
1362 Known issues:
1363  - refresh after post
1364
1365 */