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