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