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