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