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