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