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