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