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