]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
Fixing some notices
[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, 4);
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         require_once('include/items.php');
929
930         if (empty($post->object->id)) {
931                 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
932                 return;
933         }
934
935         // Searching for the liked post
936         // Two queries for speed issues
937         $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
938         if (!DBA::isResult($orig_post)) {
939                 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
940                 if (!DBA::isResult($orig_post)) {
941                         return;
942                 }
943         }
944
945         // thread completion
946         if ($threadcompletion) {
947                 pumpio_fetchallcomments($a, $uid, $post->object->id);
948         }
949
950         $contactid = 0;
951
952         if (Strings::compareLink($post->actor->url, $own_id)) {
953                 $contactid = $self[0]['id'];
954                 $post->actor->displayName = $self[0]['name'];
955                 $post->actor->url = $self[0]['url'];
956                 $post->actor->image->url = $self[0]['photo'];
957         } else {
958                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
959                         DBA::escape(Strings::normaliseLink($post->actor->url)),
960                         intval($uid)
961                 );
962
963                 if (DBA::isResult($r)) {
964                         $contactid = $r[0]['id'];
965                 }
966
967                 if ($contactid == 0) {
968                         $contactid = $orig_post['contact-id'];
969                 }
970         }
971
972         $condition = ['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
973         if (Item::exists($condition)) {
974                 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
975                 return;
976         }
977
978         $likedata = [];
979         $likedata['parent'] = $orig_post['id'];
980         $likedata['verb'] = Activity::LIKE;
981         $likedata['gravity'] = GRAVITY_ACTIVITY;
982         $likedata['uid'] = $uid;
983         $likedata['wall'] = 0;
984         $likedata['network'] = Protocol::PUMPIO;
985         $likedata['uri'] = Item::newURI($uid);
986         $likedata['parent-uri'] = $orig_post["uri"];
987         $likedata['contact-id'] = $contactid;
988         $likedata['app'] = $post->generator->displayName;
989         $likedata['author-name'] = $post->actor->displayName;
990         $likedata['author-link'] = $post->actor->url;
991         if (!empty($post->actor->image)) {
992                 $likedata['author-avatar'] = $post->actor->image->url;
993         }
994
995         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
996         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
997         $post_type = DI::l10n()->t('status');
998         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
999         $likedata['object-type'] = Activity\ObjectType::NOTE;
1000
1001         $likedata['body'] = DI::l10n()->t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
1002
1003         $likedata['object'] = '<object><type>' . Activity\ObjectType::NOTE . '</type><local>1</local>' .
1004                 '<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>';
1005
1006         $ret = Item::insert($likedata);
1007
1008         Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
1009 }
1010
1011 function pumpio_get_contact($uid, $contact, $no_insert = false)
1012 {
1013         $cid = Contact::getIdForURL($contact->url, $uid);
1014
1015         if ($no_insert) {
1016                 return $cid;
1017         }
1018
1019         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1020                 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1021
1022         if (!DBA::isResult($r)) {
1023                 // create contact record
1024                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1025                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1026                                         `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1027                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1028                         intval($uid),
1029                         DBA::escape(DateTimeFormat::utcNow()),
1030                         DBA::escape($contact->url),
1031                         DBA::escape(Strings::normaliseLink($contact->url)),
1032                         DBA::escape(str_replace("acct:", "", $contact->id)),
1033                         DBA::escape(''),
1034                         DBA::escape($contact->id), // What is it for?
1035                         DBA::escape('pump.io ' . $contact->id), // What is it for?
1036                         DBA::escape($contact->displayName),
1037                         DBA::escape($contact->preferredUsername),
1038                         DBA::escape($contact->image->url),
1039                         DBA::escape(Protocol::PUMPIO),
1040                         intval(Contact::FRIEND),
1041                         intval(1),
1042                         DBA::escape($contact->location->displayName),
1043                         DBA::escape($contact->summary),
1044                         intval(1)
1045                 );
1046
1047                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1048                         DBA::escape(Strings::normaliseLink($contact->url)),
1049                         intval($uid)
1050                         );
1051
1052                 if (!DBA::isResult($r)) {
1053                         return false;
1054                 }
1055
1056                 $contact_id = $r[0]['id'];
1057
1058                 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1059         } else {
1060                 $contact_id = $r[0]["id"];
1061
1062                 /*      if (DB_UPDATE_VERSION >= "1177")
1063                                 q("UPDATE `contact` SET `location` = '%s',
1064                                                         `about` = '%s'
1065                                                 WHERE `id` = %d",
1066                                         dbesc($contact->location->displayName),
1067                                         dbesc($contact->summary),
1068                                         intval($r[0]['id'])
1069                                 );
1070                 */
1071         }
1072
1073         if (!empty($contact->image->url)) {
1074                 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1075         }
1076
1077         return $contact_id;
1078 }
1079
1080 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1081 {
1082         // Two queries for speed issues
1083         $condition = ['uri' => $post->object->id, 'uid' => $uid];
1084         if (Item::exists($condition)) {
1085                 Item::markForDeletion($condition);
1086                 return true;
1087         }
1088
1089         $condition = ['extid' => $post->object->id, 'uid' => $uid];
1090         if (Item::exists($condition)) {
1091                 Item::markForDeletion($condition);
1092                 return true;
1093         }
1094         return false;
1095 }
1096
1097 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1098 {
1099         require_once('include/items.php');
1100
1101         if (($post->verb == "like") || ($post->verb == "favorite")) {
1102                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1103         }
1104
1105         if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1106                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1107         }
1108
1109         if ($post->verb == "delete") {
1110                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1111         }
1112
1113         if ($post->verb != "update") {
1114                 // Two queries for speed issues
1115                 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1116                         return false;
1117                 }
1118                 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1119                         return false;
1120                 }
1121         }
1122
1123         // Only handle these three types
1124         if (!strstr("post|share|update", $post->verb)) {
1125                 return false;
1126         }
1127
1128         $receiptians = [];
1129         if (@is_array($post->cc)) {
1130                 $receiptians = array_merge($receiptians, $post->cc);
1131         }
1132
1133         if (@is_array($post->to)) {
1134                 $receiptians = array_merge($receiptians, $post->to);
1135         }
1136
1137         $public = false;
1138
1139         foreach ($receiptians AS $receiver) {
1140                 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1141                         $public = true;
1142                 }
1143         }
1144
1145         $postarray = [];
1146         $postarray['network'] = Protocol::PUMPIO;
1147         $postarray['uid'] = $uid;
1148         $postarray['wall'] = 0;
1149         $postarray['uri'] = $post->object->id;
1150         $postarray['object-type'] = ActivityNamespace::ACTIVITY_SCHEMA . strtolower($post->object->objectType);
1151
1152         if ($post->object->objectType != "comment") {
1153                 $contact_id = pumpio_get_contact($uid, $post->actor);
1154
1155                 if (!$contact_id) {
1156                         $contact_id = $self[0]['id'];
1157                 }
1158
1159                 $postarray['parent-uri'] = $post->object->id;
1160
1161                 if (!$public) {
1162                         $postarray['private'] = 1;
1163                         $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1164                 }
1165         } else {
1166                 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1167
1168                 if (Strings::compareLink($post->actor->url, $own_id)) {
1169                         $contact_id = $self[0]['id'];
1170                         $post->actor->displayName = $self[0]['name'];
1171                         $post->actor->url = $self[0]['url'];
1172                         $post->actor->image->url = $self[0]['photo'];
1173                 } elseif ($contact_id == 0) {
1174                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1175                         $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1176                                 DBA::escape(Strings::normaliseLink($post->actor->url)),
1177                                 intval($uid)
1178                         );
1179
1180                         if (DBA::isResult($r)) {
1181                                 $contact_id = $r[0]['id'];
1182                         } else {
1183                                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1184                                         DBA::escape(Strings::normaliseLink($post->actor->url)),
1185                                         intval($uid)
1186                                 );
1187
1188                                 if (DBA::isResult($r)) {
1189                                         $contact_id = $r[0]['id'];
1190                                 } else {
1191                                         $contact_id = $self[0]['id'];
1192                                 }
1193                         }
1194                 }
1195
1196                 $reply = new stdClass;
1197                 $reply->verb = "note";
1198
1199                 if (isset($post->cc)) {
1200                         $reply->cc = $post->cc;
1201                 }
1202
1203                 if (isset($post->to)) {
1204                         $reply->to = $post->to;
1205                 }
1206
1207                 $reply->object = new stdClass;
1208                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1209                 $reply->object->content = $post->object->inReplyTo->content;
1210                 $reply->object->id = $post->object->inReplyTo->id;
1211                 $reply->actor = $post->object->inReplyTo->author;
1212                 $reply->url = $post->object->inReplyTo->url;
1213                 $reply->generator = new stdClass;
1214                 $reply->generator->displayName = "pumpio";
1215                 $reply->published = $post->object->inReplyTo->published;
1216                 $reply->received = $post->object->inReplyTo->updated;
1217                 $reply->url = $post->object->inReplyTo->url;
1218                 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1219
1220                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1221         }
1222
1223         // When there is no content there is no need to continue
1224         if (empty($post->object->content)) {
1225                 return false;
1226         }
1227
1228         if (!empty($post->object->pump_io->proxyURL)) {
1229                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1230         }
1231
1232         $postarray['contact-id'] = $contact_id;
1233         $postarray['verb'] = Activity::POST;
1234         $postarray['owner-name'] = $post->actor->displayName;
1235         $postarray['owner-link'] = $post->actor->url;
1236         $postarray['author-name'] = $postarray['owner-name'];
1237         $postarray['author-link'] = $postarray['owner-link'];
1238         if (!empty($post->actor->image)) {
1239                 $postarray['owner-avatar'] = $post->actor->image->url;
1240                 $postarray['author-avatar'] = $postarray['owner-avatar'];
1241         }
1242         $postarray['plink'] = $post->object->url;
1243         $postarray['app'] = $post->generator->displayName;
1244         $postarray['title'] = '';
1245         $postarray['body'] = HTML::toBBCode($post->object->content);
1246         $postarray['object'] = json_encode($post);
1247
1248         if (!empty($post->object->fullImage->url)) {
1249                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1250         }
1251
1252         if (!empty($post->object->displayName)) {
1253                 $postarray['title'] = $post->object->displayName;
1254         }
1255
1256         $postarray['created'] = DateTimeFormat::utc($post->published);
1257         if (isset($post->updated)) {
1258                 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1259         } elseif (isset($post->received)) {
1260                 $postarray['edited'] = DateTimeFormat::utc($post->received);
1261         } else {
1262                 $postarray['edited'] = $postarray['created'];
1263         }
1264
1265         if ($post->verb == "share") {
1266                 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1267                         $share_author = $post->object->author->displayName;
1268                 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1269                         $share_author = $post->object->author->preferredUsername;
1270                 } else {
1271                         $share_author = $post->object->author->url;
1272                 }
1273
1274                 if (isset($post->object->created)) {
1275                         $created = DateTimeFormat::utc($post->object->created);
1276                 } else {
1277                         $created = '';
1278                 }
1279
1280                 $postarray['body'] = share_header($share_author, $post->object->author->url,
1281                                                 $post->object->author->image->url, "",
1282                                                 $created, $post->links->self->href).
1283                                         $postarray['body']."[/share]";
1284         }
1285
1286         if (trim($postarray['body']) == "") {
1287                 return false;
1288         }
1289
1290         $top_item = Item::insert($postarray);
1291         $postarray["id"] = $top_item;
1292
1293         if (($top_item == 0) && ($post->verb == "update")) {
1294                 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1295                 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1296                 Item::update($fields, $condition);
1297         }
1298
1299         if (($post->object->objectType == "comment") && $threadcompletion) {
1300                 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1301         }
1302
1303         return $top_item;
1304 }
1305
1306 function pumpio_fetchinbox(App $a, $uid)
1307 {
1308         $ckey     = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1309         $csecret  = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1310         $otoken   = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1311         $osecret  = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1312         $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
1313         $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1314         $username = DI::pConfig()->get($uid, "pumpio", "user");
1315
1316         $own_id = "https://".$hostname."/".$username;
1317
1318         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1319                 intval($uid));
1320
1321         $lastitems = q("SELECT `uri` FROM `thread`
1322                         INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1323                         WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1324                         ORDER BY `thread`.`commented` DESC LIMIT 10",
1325                                 DBA::escape(Protocol::PUMPIO),
1326                                 intval($uid)
1327                         );
1328
1329         $client = new oauth_client_class;
1330         $client->oauth_version = '1.0a';
1331         $client->authorization_header = true;
1332         $client->url_parameters = false;
1333
1334         $client->client_id = $ckey;
1335         $client->client_secret = $csecret;
1336         $client->access_token = $otoken;
1337         $client->access_token_secret = $osecret;
1338
1339         $last_id = DI::pConfig()->get($uid, 'pumpio', 'last_id');
1340
1341         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1342
1343         if ($last_id != "") {
1344                 $url .= '?since='.urlencode($last_id);
1345         }
1346
1347         if (pumpio_reachable($url)) {
1348                 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1349         } else {
1350                 $success = false;
1351         }
1352
1353         if (!$success) {
1354                 return;
1355         }
1356
1357         if (!empty($user->items)) {
1358                 $posts = array_reverse($user->items);
1359
1360                 if (count($posts)) {
1361                         foreach ($posts as $post) {
1362                                 $last_id = $post->id;
1363                                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1364                         }
1365                 }
1366         }
1367
1368         foreach ($lastitems as $item) {
1369                 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1370         }
1371
1372         DI::pConfig()->set($uid, 'pumpio', 'last_id', $last_id);
1373 }
1374
1375 function pumpio_getallusers(App &$a, $uid)
1376 {
1377         $ckey     = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1378         $csecret  = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1379         $otoken   = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1380         $osecret  = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1381         $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1382         $username = DI::pConfig()->get($uid, "pumpio", "user");
1383
1384         $client = new oauth_client_class;
1385         $client->oauth_version = '1.0a';
1386         $client->authorization_header = true;
1387         $client->url_parameters = false;
1388
1389         $client->client_id = $ckey;
1390         $client->client_secret = $csecret;
1391         $client->access_token = $otoken;
1392         $client->access_token_secret = $osecret;
1393
1394         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1395
1396         if (pumpio_reachable($url)) {
1397                 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1398         } else {
1399                 $success = false;
1400         }
1401
1402         if (empty($users)) {
1403                 return;
1404         }
1405
1406         if ($users->totalItems > count($users->items)) {
1407                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1408
1409                 if (pumpio_reachable($url)) {
1410                         $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1411                 } else {
1412                         $success = false;
1413                 }
1414         }
1415
1416         if (!empty($users->items)) {
1417                 foreach ($users->items as $user) {
1418                         pumpio_get_contact($uid, $user);
1419                 }
1420         }
1421 }
1422
1423 function pumpio_getreceiver(App $a, array $b)
1424 {
1425         $receiver = [];
1426
1427         if (!$b["private"]) {
1428                 if (!strstr($b['postopts'], 'pumpio')) {
1429                         return $receiver;
1430                 }
1431
1432                 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
1433
1434                 if ($public) {
1435                         $receiver["to"][] = [
1436                                                 "objectType" => "collection",
1437                                                 "id" => "http://activityschema.org/collection/public"];
1438                 }
1439         } else {
1440                 $cids = explode("><", $b["allow_cid"]);
1441                 $gids = explode("><", $b["allow_gid"]);
1442
1443                 foreach ($cids AS $cid) {
1444                         $cid = trim($cid, " <>");
1445
1446                         $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",
1447                                 intval($cid),
1448                                 intval($b["uid"]),
1449                                 DBA::escape(Protocol::PUMPIO)
1450                                 );
1451
1452                         if (DBA::isResult($r)) {
1453                                 $receiver["bcc"][] = [
1454                                                         "displayName" => $r[0]["name"],
1455                                                         "objectType" => "person",
1456                                                         "preferredUsername" => $r[0]["nick"],
1457                                                         "url" => $r[0]["url"]];
1458                         }
1459                 }
1460                 foreach ($gids AS $gid) {
1461                         $gid = trim($gid, " <>");
1462
1463                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1464                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1465                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1466                                         intval($gid),
1467                                         DBA::escape(Protocol::PUMPIO)
1468                                 );
1469
1470                         foreach ($r AS $row)
1471                                 $receiver["bcc"][] = [
1472                                                         "displayName" => $row["name"],
1473                                                         "objectType" => "person",
1474                                                         "preferredUsername" => $row["nick"],
1475                                                         "url" => $row["url"]];
1476                 }
1477         }
1478
1479         if ($b["inform"] != "") {
1480                 $inform = explode(",", $b["inform"]);
1481
1482                 foreach ($inform AS $cid) {
1483                         if (substr($cid, 0, 4) != "cid:") {
1484                                 continue;
1485                         }
1486
1487                         $cid = str_replace("cid:", "", $cid);
1488
1489                         $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",
1490                                 intval($cid),
1491                                 intval($b["uid"]),
1492                                 DBA::escape(Protocol::PUMPIO)
1493                                 );
1494
1495                         if (DBA::isResult($r)) {
1496                                 $receiver["to"][] = [
1497                                         "displayName" => $r[0]["name"],
1498                                         "objectType" => "person",
1499                                         "preferredUsername" => $r[0]["nick"],
1500                                         "url" => $r[0]["url"]];
1501                         }
1502                 }
1503         }
1504
1505         return $receiver;
1506 }
1507
1508 function pumpio_fetchallcomments(App $a, $uid, $id)
1509 {
1510         $ckey     = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1511         $csecret  = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1512         $otoken   = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1513         $osecret  = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1514         $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1515         $username = DI::pConfig()->get($uid, "pumpio", "user");
1516
1517         Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1518
1519         $own_id = "https://".$hostname."/".$username;
1520
1521         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1522                 intval($uid));
1523
1524         // Fetching the original post
1525         $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1526         $item = Item::selectFirst(['extid'], $condition);
1527         if (!DBA::isResult($item)) {
1528                 return false;
1529         }
1530
1531         $url = $item["extid"];
1532
1533         $client = new oauth_client_class;
1534         $client->oauth_version = '1.0a';
1535         $client->authorization_header = true;
1536         $client->url_parameters = false;
1537
1538         $client->client_id = $ckey;
1539         $client->client_secret = $csecret;
1540         $client->access_token = $otoken;
1541         $client->access_token_secret = $osecret;
1542
1543         Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1544
1545         if (pumpio_reachable($url)) {
1546                 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1547         } else {
1548                 $success = false;
1549         }
1550
1551         if (!$success) {
1552                 return;
1553         }
1554
1555         if ($item->likes->totalItems != 0) {
1556                 foreach ($item->likes->items AS $post) {
1557                         $like = new stdClass;
1558                         $like->object = new stdClass;
1559                         $like->object->id = $item->id;
1560                         $like->actor = new stdClass;
1561                         if (!empty($item->displayName)) {
1562                                 $like->actor->displayName = $item->displayName;
1563                         }
1564                         //$like->actor->preferredUsername = $item->preferredUsername;
1565                         //$like->actor->image = $item->image;
1566                         $like->actor->url = $item->url;
1567                         $like->generator = new stdClass;
1568                         $like->generator->displayName = "pumpio";
1569                         pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1570                 }
1571         }
1572
1573         if ($item->replies->totalItems == 0) {
1574                 return;
1575         }
1576
1577         foreach ($item->replies->items AS $item) {
1578                 if ($item->id == $id) {
1579                         continue;
1580                 }
1581
1582                 // Checking if the comment already exists - Two queries for speed issues
1583                 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1584                         continue;
1585                 }
1586
1587                 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1588                         continue;
1589                 }
1590
1591                 $post = new stdClass;
1592                 $post->verb = "post";
1593                 $post->actor = $item->author;
1594                 $post->published = $item->published;
1595                 $post->received = $item->updated;
1596                 $post->generator = new stdClass;
1597                 $post->generator->displayName = "pumpio";
1598                 // To-Do: Check for public post
1599
1600                 unset($item->author);
1601                 unset($item->published);
1602                 unset($item->updated);
1603
1604                 $post->object = $item;
1605
1606                 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1607                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1608         }
1609 }
1610
1611 function pumpio_reachable($url)
1612 {
1613         return Network::curl($url, false, ['timeout' => 10])->isSuccess();
1614 }
1615
1616 /*
1617 To-Do:
1618  - edit own notes
1619  - delete own notes
1620 */