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