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