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