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