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