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