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