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