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