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