]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
[various] Set config loaded from default values to SOURCE_STATIC
[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
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(App $a)
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($a);
70                                 break;
71
72                         default:
73                                 $o = print_r(DI::args()->getArgv(), true);
74                                 break;
75                 }
76         } else {
77                 $o = pumpio_connect($a);
78         }
79         return $o;
80 }
81
82 function pumpio_check_item_notification(App $a, 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(App $a, $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()->getHostname();
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()->get() . '/images/friendica-256.png';
109         $params['redirect_uris'] = DI::baseUrl()->get() . '/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 ', $values);
127                 return $values;
128         }
129         Logger::info('pumpio_registerclient: failed: ', $curl_info);
130         return false;
131
132 }
133
134 function pumpio_connect(App $a)
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($a, $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()->get() . '/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()->get() . '/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(App $a, 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(App $a, 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()->get() . '/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(App $a, 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(App $a, ConfigFileLoader $loader)
322 {
323         $a->getConfigCache()->load($loader->loadAddonConfig('pumpio'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
324 }
325
326 function pumpio_hook_fork(App $a, 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(App $a, 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(App $a, 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($a, $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 forum 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($a, $b['uid'], $b['thr-parent'], 'unlike');
430                 } else {
431                         pumpio_action($a, $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($a, $b['uid'], $b['uri'], 'update', $b['body']);
442         }
443
444         if (($b['verb'] == Activity::POST) && $b['deleted']) {
445                 pumpio_action($a, $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(App $a, 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(App $a)
629 {
630         if (!Addon::isEnabled('pumpio')) {
631                 return;
632         }
633
634         $last = DI::config()->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($a, $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($a, $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($a, $rr['uid']);
682                         DI::pConfig()->set($rr['uid'], 'pumpio', 'contact_check', time());
683                 }
684         }
685
686         Logger::notice('pumpio: cron_end');
687
688         DI::config()->set('pumpio', 'last_poll', time());
689 }
690
691 function pumpio_cron(App $a, $b)
692 {
693         Worker::add(Worker::PRIORITY_MEDIUM, 'addon/pumpio/pumpio_sync.php');
694 }
695
696 function pumpio_fetchtimeline(App $a, 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()->getHostname();
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                                 $_SESSION['authenticated'] = true;
784                                 $_SESSION['uid'] = $uid;
785
786                                 unset($_REQUEST);
787                                 $_REQUEST['api_source'] = true;
788                                 $_REQUEST['profile_uid'] = $uid;
789                                 $_REQUEST['source'] = 'pump.io';
790
791                                 if (isset($post->object->id)) {
792                                         $_REQUEST['message_id'] = Protocol::PUMPIO . ':' . $post->object->id;
793                                 }
794
795                                 if ($post->object->displayName != '') {
796                                         $_REQUEST['title'] = HTML::toBBCode($post->object->displayName);
797                                 } else {
798                                         $_REQUEST['title'] = '';
799                                 }
800
801                                 $_REQUEST['body'] = HTML::toBBCode($post->object->content);
802
803                                 // To-Do: Picture has to be cached and stored locally
804                                 if ($post->object->fullImage->url != '') {
805                                         if ($post->object->fullImage->pump_io->proxyURL != '') {
806                                                 $_REQUEST['body'] = '[url=' . $post->object->fullImage->pump_io->proxyURL . '][img]' . $post->object->image->pump_io->proxyURL . "[/img][/url]\n" . $_REQUEST['body'];
807                                         } else {
808                                                 $_REQUEST['body'] = '[url=' . $post->object->fullImage->url . '][img]' . $post->object->image->url . "[/img][/url]\n" . $_REQUEST['body'];
809                                         }
810                                 }
811
812                                 Logger::notice('pumpio: posting for user ' . $uid);
813
814                                 require_once 'mod/item.php';
815
816                                 item_post($a);
817                                 Logger::notice('pumpio: posting done - user ' . $uid);
818                         }
819                 }
820         }
821
822         if ($lastdate != 0) {
823                 DI::pConfig()->set($uid, 'pumpio', 'lastdate', $lastdate);
824         }
825 }
826
827 function pumpio_dounlike(App $a, int $uid, array $self, $post, string $own_id)
828 {
829         // Searching for the unliked post
830         // Two queries for speed issues
831         $orig_post = Post::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
832         if (!DBA::isResult($orig_post)) {
833                 $orig_post = Post::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
834                 if (!DBA::isResult($orig_post)) {
835                         return;
836                 }
837         }
838
839         $contactid = 0;
840
841         if (Strings::compareLink($post->actor->url, $own_id)) {
842                 $contactid = $self['id'];
843         } else {
844                 $contact = Contact::selectFirst([], ['nurl' => Strings::normaliseLink($post->actor->url), 'uid' => $uid, 'blocked' => false, 'readonly' => false]);
845                 if (DBA::isResult($contact)) {
846                         $contactid = $contact['id'];
847                 }
848
849                 if ($contactid == 0) {
850                         $contactid = $orig_post['contact-id'];
851                 }
852         }
853
854         Item::markForDeletion(['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
855
856         if (DBA::isResult($contact)) {
857                 Logger::notice('pumpio_dounlike: unliked existing like. User ' . $own_id . ' ' . $uid . ' Contact: ' . $contactid . ' URI ' . $orig_post['uri']);
858         } else {
859                 Logger::notice('pumpio_dounlike: not found. User ' . $own_id . ' ' . $uid . ' Contact: ' . $contactid . ' Url ' . $orig_post['uri']);
860         }
861 }
862
863 function pumpio_dolike(App $a, int $uid, array $self, $post, string $own_id, $threadcompletion = true)
864 {
865         if (empty($post->object->id)) {
866                 Logger::info('Got empty like: '.print_r($post, true));
867                 return;
868         }
869
870         // Searching for the liked post
871         // Two queries for speed issues
872         $orig_post = Post::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
873         if (!DBA::isResult($orig_post)) {
874                 $orig_post = Post::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
875                 if (!DBA::isResult($orig_post)) {
876                         return;
877                 }
878         }
879
880         // thread completion
881         if ($threadcompletion) {
882                 pumpio_fetchallcomments($a, $uid, $post->object->id);
883         }
884
885         $contactid = 0;
886
887         if (Strings::compareLink($post->actor->url, $own_id)) {
888                 $contactid = $self['id'];
889                 $post->actor->displayName = $self['name'];
890                 $post->actor->url = $self['url'];
891                 $post->actor->image->url = $self['photo'];
892         } else {
893                 $contact = Contact::selectFirst([], ['nurl' => Strings::normaliseLink($post->actor->url), 'uid' => $uid, 'blocked' => false, 'readonly' => false]);
894                 if (DBA::isResult($contact)) {
895                         $contactid = $contact['id'];
896                 }
897
898                 if ($contactid == 0) {
899                         $contactid = $orig_post['contact-id'];
900                 }
901         }
902
903         $condition = [
904                 'verb' => Activity::LIKE,
905                 'uid' => $uid,
906                 'contact-id' => $contactid,
907                 'thr-parent' => $orig_post['uri'],
908         ];
909
910         if (Post::exists($condition)) {
911                 Logger::notice('pumpio_dolike: found existing like. User ' . $own_id . ' ' . $uid . ' Contact: ' . $contactid . ' URI ' . $orig_post['uri']);
912                 return;
913         }
914
915         $likedata = [];
916         $likedata['parent'] = $orig_post['id'];
917         $likedata['verb'] = Activity::LIKE;
918         $likedata['gravity'] = Item::GRAVITY_ACTIVITY;
919         $likedata['uid'] = $uid;
920         $likedata['wall'] = 0;
921         $likedata['network'] = Protocol::PUMPIO;
922         $likedata['uri'] = Item::newURI();
923         $likedata['thr-parent'] = $orig_post['uri'];
924         $likedata['contact-id'] = $contactid;
925         $likedata['app'] = $post->generator->displayName;
926         $likedata['author-name'] = $post->actor->displayName;
927         $likedata['author-link'] = $post->actor->url;
928         if (!empty($post->actor->image)) {
929                 $likedata['author-avatar'] = $post->actor->image->url;
930         }
931
932         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
933         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
934         $post_type = DI::l10n()->t('status');
935         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
936         $likedata['object-type'] = Activity\ObjectType::NOTE;
937
938         $likedata['body'] = DI::l10n()->t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
939
940         $likedata['object'] = '<object><type>' . Activity\ObjectType::NOTE . '</type><local>1</local>' .
941                 '<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>';
942
943         $ret = Item::insert($likedata);
944
945         Logger::notice('pumpio_dolike: ' . $ret . ' User ' . $own_id . ' ' . $uid . ' Contact: ' . $contactid . ' URI ' . $orig_post['uri']);
946 }
947
948 function pumpio_get_contact($uid, $contact, $no_insert = false)
949 {
950         $cid = Contact::getIdForURL($contact->url, $uid);
951
952         if ($no_insert) {
953                 return $cid;
954         }
955
956         $r = Contact::selectFirst([], ['uid' => $uid, 'nurl' => Strings::normaliseLink($contact->url)]);
957         if (!DBA::isResult($r)) {
958                 // create contact record
959                 Contact::insert([
960                         'uid'      => $uid,
961                         'created'  => DateTimeFormat::utcNow(),
962                         'url'      => $contact->url,
963                         'nurl'     => Strings::normaliseLink($contact->url),
964                         'addr'     => str_replace('acct:', '', $contact->id),
965                         'alias'    => '',
966                         'notify'   => $contact->id,
967                         'poll'     => 'pump.io ' . $contact->id,
968                         'name'     => $contact->displayName,
969                         'nick'     => $contact->preferredUsername,
970                         'photo'    => $contact->image->url,
971                         'network'  => Protocol::PUMPIO,
972                         'rel'      => Contact::FRIEND,
973                         'priority' => 1,
974                         'location' => $contact->location->displayName,
975                         'about'    => $contact->summary,
976                         'writable' => 1,
977                         'blocked'  => 0,
978                         'readonly' => 0,
979                         'pending'  => 0
980                 ]);
981
982                 $r = Contact::selectFirst([], ['uid' => $uid, 'nurl' => Strings::normaliseLink($contact->url)]);
983                 if (!DBA::isResult($r)) {
984                         return false;
985                 }
986
987                 $contact_id = $r['id'];
988
989                 Group::addMember(User::getDefaultGroup($uid), $contact_id);
990         } else {
991                 $contact_id = $r['id'];
992         }
993
994         if (!empty($contact->image->url)) {
995                 Contact::updateAvatar($contact_id, $contact->image->url);
996         }
997
998         return $contact_id;
999 }
1000
1001 function pumpio_dodelete(App $a, int $uid, array $self, $post, string $own_id)
1002 {
1003         // Two queries for speed issues
1004         $condition = ['uri' => $post->object->id, 'uid' => $uid];
1005         if (Post::exists($condition)) {
1006                 Item::markForDeletion($condition);
1007                 return true;
1008         }
1009
1010         $condition = ['extid' => $post->object->id, 'uid' => $uid];
1011         if (Post::exists($condition)) {
1012                 Item::markForDeletion($condition);
1013                 return true;
1014         }
1015         return false;
1016 }
1017
1018 function pumpio_dopost(App $a, $client, int $uid, array $self, $post, string $own_id, bool $threadcompletion = true)
1019 {
1020         if (($post->verb == 'like') || ($post->verb == 'favorite')) {
1021                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1022         }
1023
1024         if (($post->verb == 'unlike') || ($post->verb == 'unfavorite')) {
1025                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1026         }
1027
1028         if ($post->verb == 'delete') {
1029                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1030         }
1031
1032         if ($post->verb != 'update') {
1033                 // Two queries for speed issues
1034                 if (Post::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1035                         return false;
1036                 }
1037                 if (Post::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1038                         return false;
1039                 }
1040         }
1041
1042         // Only handle these three types
1043         if (!strstr('post|share|update', $post->verb)) {
1044                 return false;
1045         }
1046
1047         $receiptians = [];
1048         if (@is_array($post->cc)) {
1049                 $receiptians = array_merge($receiptians, $post->cc);
1050         }
1051
1052         if (@is_array($post->to)) {
1053                 $receiptians = array_merge($receiptians, $post->to);
1054         }
1055
1056         $public = false;
1057
1058         foreach ($receiptians as $receiver) {
1059                 if (is_string($receiver->objectType) && ($receiver->id == 'http://activityschema.org/collection/public')) {
1060                         $public = true;
1061                 }
1062         }
1063
1064         $postarray = [];
1065         $postarray['network'] = Protocol::PUMPIO;
1066         $postarray['uid'] = $uid;
1067         $postarray['wall'] = 0;
1068         $postarray['uri'] = $post->object->id;
1069         $postarray['object-type'] = ActivityNamespace::ACTIVITY_SCHEMA . strtolower($post->object->objectType);
1070
1071         if ($post->object->objectType != 'comment') {
1072                 $contact_id = pumpio_get_contact($uid, $post->actor);
1073
1074                 if (!$contact_id) {
1075                         $contact_id = $self['id'];
1076                 }
1077
1078                 $postarray['thr-parent'] = $post->object->id;
1079
1080                 if (!$public) {
1081                         $postarray['private'] = 1;
1082                         $postarray['allow_cid'] = '<' . $self['id'] . '>';
1083                 }
1084         } else {
1085                 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1086
1087                 if (Strings::compareLink($post->actor->url, $own_id)) {
1088                         $contact_id = $self['id'];
1089                         $post->actor->displayName = $self['name'];
1090                         $post->actor->url = $self['url'];
1091                         $post->actor->image->url = $self['photo'];
1092                 } elseif ($contact_id == 0) {
1093                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1094                         $contact = Contact::selectFirst([], ['nurl' => Strings::normaliseLink($post->actor->url), 'uid' => $uid, 'blocked' => false, 'readonly' => false]);
1095                         if (DBA::isResult($contact)) {
1096                                 $contact_id = $contact['id'];
1097                         } else {
1098                                 $contact_id = $self['id'];
1099                         }
1100                 }
1101
1102                 $reply = new stdClass;
1103                 $reply->verb = 'note';
1104
1105                 if (isset($post->cc)) {
1106                         $reply->cc = $post->cc;
1107                 }
1108
1109                 if (isset($post->to)) {
1110                         $reply->to = $post->to;
1111                 }
1112
1113                 $reply->object = new stdClass;
1114                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1115                 $reply->object->content = $post->object->inReplyTo->content;
1116                 $reply->object->id = $post->object->inReplyTo->id;
1117                 $reply->actor = $post->object->inReplyTo->author;
1118                 $reply->url = $post->object->inReplyTo->url;
1119                 $reply->generator = new stdClass;
1120                 $reply->generator->displayName = 'pumpio';
1121                 $reply->published = $post->object->inReplyTo->published;
1122                 $reply->received = $post->object->inReplyTo->updated;
1123                 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1124
1125                 $postarray['thr-parent'] = $post->object->inReplyTo->id;
1126         }
1127
1128         // When there is no content there is no need to continue
1129         if (empty($post->object->content)) {
1130                 return false;
1131         }
1132
1133         if (!empty($post->object->pump_io->proxyURL)) {
1134                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1135         }
1136
1137         $postarray['contact-id'] = $contact_id;
1138         $postarray['verb'] = Activity::POST;
1139         $postarray['owner-name'] = $post->actor->displayName;
1140         $postarray['owner-link'] = $post->actor->url;
1141         $postarray['author-name'] = $postarray['owner-name'];
1142         $postarray['author-link'] = $postarray['owner-link'];
1143         if (!empty($post->actor->image)) {
1144                 $postarray['owner-avatar'] = $post->actor->image->url;
1145                 $postarray['author-avatar'] = $postarray['owner-avatar'];
1146         }
1147         $postarray['plink'] = $post->object->url;
1148         $postarray['app'] = $post->generator->displayName;
1149         $postarray['title'] = '';
1150         $postarray['body'] = HTML::toBBCode($post->object->content);
1151         $postarray['object'] = json_encode($post);
1152
1153         if (!empty($post->object->fullImage->url)) {
1154                 $postarray['body'] = '[url=' . $post->object->fullImage->url . '][img]' . $post->object->image->url . "[/img][/url]\n" . $postarray['body'];
1155         }
1156
1157         if (!empty($post->object->displayName)) {
1158                 $postarray['title'] = $post->object->displayName;
1159         }
1160
1161         $postarray['created'] = DateTimeFormat::utc($post->published);
1162         if (isset($post->updated)) {
1163                 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1164         } elseif (isset($post->received)) {
1165                 $postarray['edited'] = DateTimeFormat::utc($post->received);
1166         } else {
1167                 $postarray['edited'] = $postarray['created'];
1168         }
1169
1170         if ($post->verb == 'share') {
1171                 if (isset($post->object->author->displayName) && ($post->object->author->displayName != '')) {
1172                         $share_author = $post->object->author->displayName;
1173                 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != '')) {
1174                         $share_author = $post->object->author->preferredUsername;
1175                 } else {
1176                         $share_author = $post->object->author->url;
1177                 }
1178
1179                 if (isset($post->object->created)) {
1180                         $created = DateTimeFormat::utc($post->object->created);
1181                 } else {
1182                         $created = '';
1183                 }
1184
1185                 $postarray['body'] = Friendica\Content\Text\BBCode::getShareOpeningTag($share_author, $post->object->author->url,
1186                                                 $post->object->author->image->url, $post->links->self->href, $created) .
1187                                         $postarray['body'] . '[/share]';
1188         }
1189
1190         if (trim($postarray['body']) == '') {
1191                 return false;
1192         }
1193
1194         $top_item = Item::insert($postarray);
1195         $postarray['id'] = $top_item;
1196
1197         if (($top_item == 0) && ($post->verb == 'update')) {
1198                 $fields = [
1199                         'title' => $postarray['title'],
1200                         'body' => $postarray['body'],
1201                         'changed' => $postarray['edited'],
1202                 ];
1203                 $condition = ['uri' => $postarray['uri'], 'uid' => $uid];
1204                 Item::update($fields, $condition);
1205         }
1206
1207         if (($post->object->objectType == 'comment') && $threadcompletion) {
1208                 pumpio_fetchallcomments($a, $uid, $postarray['thr-parent']);
1209         }
1210
1211         return $top_item;
1212 }
1213
1214 function pumpio_fetchinbox(App $a, int $uid)
1215 {
1216         $ckey     = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1217         $csecret  = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1218         $otoken   = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1219         $osecret  = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1220         $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
1221         $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1222         $username = DI::pConfig()->get($uid, 'pumpio', 'user');
1223
1224         $own_id = 'https://' . $hostname . '/' . $username;
1225
1226         $self = User::getOwnerDataById($uid);
1227
1228         $lastitems = DBA::p("SELECT `uri` FROM `post-thread-user`
1229                 INNER JOIN `post-view` ON `post-view`.`uri-id` = `post-thread-user`.`uri-id`
1230                 WHERE `post-thread-user`.`network` = ? AND `post-thread-user`.`uid` = ? AND `post-view`.`extid` != ''
1231                 ORDER BY `post-thread-user`.`commented` DESC LIMIT 10", Protocol::PUMPIO, $uid);
1232
1233         $client = new oauth_client_class();
1234         $client->oauth_version = '1.0a';
1235         $client->authorization_header = true;
1236         $client->url_parameters = false;
1237
1238         $client->client_id = $ckey;
1239         $client->client_secret = $csecret;
1240         $client->access_token = $otoken;
1241         $client->access_token_secret = $osecret;
1242
1243         $last_id = DI::pConfig()->get($uid, 'pumpio', 'last_id');
1244
1245         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1246
1247         if ($last_id != '') {
1248                 $url .= '?since=' . urlencode($last_id);
1249         }
1250
1251         if (pumpio_reachable($url)) {
1252                 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $user);
1253         } else {
1254                 $success = false;
1255         }
1256
1257         if (!$success) {
1258                 return;
1259         }
1260
1261         if (!empty($user->items)) {
1262                 $posts = array_reverse($user->items);
1263
1264                 if (count($posts)) {
1265                         foreach ($posts as $post) {
1266                                 $last_id = $post->id;
1267                                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1268                         }
1269                 }
1270         }
1271
1272         while ($item = DBA::fetch($lastitems)) {
1273                 pumpio_fetchallcomments($a, $uid, $item['uri']);
1274         }
1275         DBA::close($lastitems);
1276
1277         DI::pConfig()->set($uid, 'pumpio', 'last_id', $last_id);
1278 }
1279
1280 function pumpio_getallusers(App &$a, int $uid)
1281 {
1282         $ckey     = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1283         $csecret  = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1284         $otoken   = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1285         $osecret  = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1286         $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1287         $username = DI::pConfig()->get($uid, 'pumpio', 'user');
1288
1289         $client = new oauth_client_class;
1290         $client->oauth_version = '1.0a';
1291         $client->authorization_header = true;
1292         $client->url_parameters = false;
1293
1294         $client->client_id = $ckey;
1295         $client->client_secret = $csecret;
1296         $client->access_token = $otoken;
1297         $client->access_token_secret = $osecret;
1298
1299         $url = 'https://' . $hostname . '/api/user/' . $username . '/following';
1300
1301         if (pumpio_reachable($url)) {
1302                 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1303         } else {
1304                 $success = false;
1305         }
1306
1307         if (empty($users)) {
1308                 return;
1309         }
1310
1311         if ($users->totalItems > count($users->items)) {
1312                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1313
1314                 if (pumpio_reachable($url)) {
1315                         $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1316                 } else {
1317                         $success = false;
1318                 }
1319         }
1320
1321         if (!empty($users->items)) {
1322                 foreach ($users->items as $user) {
1323                         pumpio_get_contact($uid, $user);
1324                 }
1325         }
1326 }
1327
1328 function pumpio_getreceiver(App $a, array $b)
1329 {
1330         $receiver = [];
1331
1332         if (!$b['private']) {
1333                 if (!strstr($b['postopts'], 'pumpio')) {
1334                         return $receiver;
1335                 }
1336
1337                 $public = DI::pConfig()->get($b['uid'], 'pumpio', 'public');
1338
1339                 if ($public) {
1340                         $receiver['to'][] = [
1341                                 'objectType' => 'collection',
1342                                 'id' => 'http://activityschema.org/collection/public'
1343                         ];
1344                 }
1345         } else {
1346                 $cids = explode('><', $b['allow_cid']);
1347                 $gids = explode('><', $b['allow_gid']);
1348
1349                 foreach ($cids as $cid) {
1350                         $cid = trim($cid, ' <>');
1351
1352                         $contact = Contact::selectFirst(['name', 'nick', 'url'], ['id' => $cid, 'uid' => $b['uid'], 'network' => Protocol::PUMPIO, 'blocked' => false, 'readonly' => false]);
1353                         if (DBA::isResult($contact)) {
1354                                 $receiver['bcc'][] = [
1355                                         'displayName' => $contact['name'],
1356                                         'objectType' => 'person',
1357                                         'preferredUsername' => $contact['nick'],
1358                                         'url' => $contact['url'],
1359                                 ];
1360                         }
1361                 }
1362                 foreach ($gids as $gid) {
1363                         $gid = trim($gid, ' <>');
1364
1365                         $contacts = DBA::p("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network`
1366                                 FROM `group_member`, `contact` WHERE `group_member`.`gid` = ?
1367                                 AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = ?",
1368                                 $gid, Protocol::PUMPIO);
1369
1370                         while ($row = DBA::fetch($contacts)) {
1371                                 $receiver['bcc'][] = [
1372                                         'displayName' => $row['name'],
1373                                         'objectType' => 'person',
1374                                         'preferredUsername' => $row['nick'],
1375                                         'url' => $row['url'],
1376                                 ];
1377                         }
1378                         DBA::close($contacts);
1379                 }
1380         }
1381
1382         if ($b['inform'] != '') {
1383                 $inform = explode(',', $b['inform']);
1384
1385                 foreach ($inform as $cid) {
1386                         if (substr($cid, 0, 4) != 'cid:') {
1387                                 continue;
1388                         }
1389
1390                         $cid = str_replace('cid:', '', $cid);
1391
1392                         $contact = Contact::selectFirst(['name', 'nick', 'url'], ['id' => $cid, 'uid' => $b['uid'], 'network' => Protocol::PUMPIO, 'blocked' => false, 'readonly' => false]);
1393                         if (DBA::isResult($contact)) {
1394                                 $receiver['to'][] = [
1395                                         'displayName' => $contact['name'],
1396                                         'objectType' => 'person',
1397                                         'preferredUsername' => $contact['nick'],
1398                                         'url' => $contact['url'],
1399                                 ];
1400                         }
1401                 }
1402         }
1403
1404         return $receiver;
1405 }
1406
1407 function pumpio_fetchallcomments(App $a, $uid, $id)
1408 {
1409         $ckey     = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1410         $csecret  = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1411         $otoken   = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1412         $osecret  = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1413         $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1414         $username = DI::pConfig()->get($uid, 'pumpio', 'user');
1415
1416         Logger::notice('pumpio_fetchallcomments: completing comment for user ' . $uid . ' post id ' . $id);
1417
1418         $own_id = 'https://' . $hostname . '/' . $username;
1419
1420         $self = User::getOwnerDataById($uid);
1421
1422         // Fetching the original post
1423         $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1424         $original = Post::selectFirst(['extid'], $condition);
1425         if (!DBA::isResult($original)) {
1426                 return false;
1427         }
1428
1429         $url = $original['extid'];
1430
1431         $client = new oauth_client_class;
1432         $client->oauth_version = '1.0a';
1433         $client->authorization_header = true;
1434         $client->url_parameters = false;
1435
1436         $client->client_id = $ckey;
1437         $client->client_secret = $csecret;
1438         $client->access_token = $otoken;
1439         $client->access_token_secret = $osecret;
1440
1441         Logger::notice('pumpio_fetchallcomments: fetching comment for user ' . $uid . ', URL ' . $url);
1442
1443         if (pumpio_reachable($url)) {
1444                 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $item);
1445         } else {
1446                 $success = false;
1447         }
1448
1449         if (!$success) {
1450                 return;
1451         }
1452
1453         if ($item->likes->totalItems != 0) {
1454                 foreach ($item->likes->items as $post) {
1455                         $like = new stdClass;
1456                         $like->object = new stdClass;
1457                         $like->object->id = $item->id;
1458                         $like->actor = new stdClass;
1459                         if (!empty($item->displayName)) {
1460                                 $like->actor->displayName = $item->displayName;
1461                         }
1462                         //$like->actor->preferredUsername = $item->preferredUsername;
1463                         //$like->actor->image = $item->image;
1464                         $like->actor->url = $item->url;
1465                         $like->generator = new stdClass;
1466                         $like->generator->displayName = 'pumpio';
1467                         pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1468                 }
1469         }
1470
1471         if ($item->replies->totalItems == 0) {
1472                 return;
1473         }
1474
1475         foreach ($item->replies->items as $item) {
1476                 if ($item->id == $id) {
1477                         continue;
1478                 }
1479
1480                 // Checking if the comment already exists - Two queries for speed issues
1481                 if (Post::exists(['uri' => $item->id, 'uid' => $uid])) {
1482                         continue;
1483                 }
1484
1485                 if (Post::exists(['extid' => $item->id, 'uid' => $uid])) {
1486                         continue;
1487                 }
1488
1489                 $post = new stdClass;
1490                 $post->verb = 'post';
1491                 $post->actor = $item->author;
1492                 $post->published = $item->published;
1493                 $post->received = $item->updated;
1494                 $post->generator = new stdClass;
1495                 $post->generator->displayName = 'pumpio';
1496                 // To-Do: Check for public post
1497
1498                 unset($item->author);
1499                 unset($item->published);
1500                 unset($item->updated);
1501
1502                 $post->object = $item;
1503
1504                 Logger::notice('pumpio_fetchallcomments: posting comment ' . $post->object->id . ' ', json_decode(json_encode($post), true));
1505                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1506         }
1507 }
1508
1509 function pumpio_reachable(string $url): bool
1510 {
1511         return DI::httpClient()->get($url, HttpClientAccept::DEFAULT, [HttpClientOptions::TIMEOUT => 10])->isSuccess();
1512 }
1513
1514 /*
1515 To-Do:
1516  - edit own notes
1517  - delete own notes
1518 */