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