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