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