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