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