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