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