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