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