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