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