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