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