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