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