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