]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
Remove direct item sql queries
[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::newURI($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         $condition = ['uri' => $post->object->id, 'uid' => $uid];
1046         if (dba::exists('item', $condition)) {
1047                 Item::delete($condition);
1048                 return true;
1049         }
1050
1051         $condition = ['extid' => $post->object->id, 'uid' => $uid];
1052         if (dba::exists('item', $condition)) {
1053                 Item::delete($condition);
1054                 return true;
1055         }
1056         return false;
1057 }
1058
1059 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1060         require_once('include/items.php');
1061
1062         if (($post->verb == "like") || ($post->verb == "favorite"))
1063                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1064
1065         if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1066                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1067
1068         if ($post->verb == "delete")
1069                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1070
1071         if ($post->verb != "update") {
1072                 // Two queries for speed issues
1073                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1074                                         dbesc($post->object->id),
1075                                         intval($uid)
1076                         );
1077
1078                 if (count($r))
1079                         return false;
1080
1081                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1082                                         dbesc($post->object->id),
1083                                         intval($uid)
1084                         );
1085
1086                 if (count($r))
1087                         return false;
1088         }
1089
1090         // Only handle these three types
1091         if (!strstr("post|share|update", $post->verb))
1092                 return false;
1093
1094         $receiptians = [];
1095         if (@is_array($post->cc))
1096                 $receiptians = array_merge($receiptians, $post->cc);
1097
1098         if (@is_array($post->to))
1099                 $receiptians = array_merge($receiptians, $post->to);
1100
1101         foreach ($receiptians AS $receiver)
1102                 if (is_string($receiver->objectType))
1103                         if ($receiver->id == "http://activityschema.org/collection/public")
1104                                 $public = true;
1105
1106         $postarray = [];
1107         $postarray['network'] = NETWORK_PUMPIO;
1108         $postarray['gravity'] = 0;
1109         $postarray['uid'] = $uid;
1110         $postarray['wall'] = 0;
1111         $postarray['uri'] = $post->object->id;
1112         $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1113
1114         if ($post->object->objectType != "comment") {
1115                 $contact_id = pumpio_get_contact($uid, $post->actor);
1116
1117                 if (!$contact_id)
1118                         $contact_id = $self[0]['id'];
1119
1120                 $postarray['parent-uri'] = $post->object->id;
1121
1122                 if (!$public) {
1123                         $postarray['private'] = 1;
1124                         $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1125                 }
1126         } else {
1127                 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1128
1129                 if (link_compare($post->actor->url, $own_id)) {
1130                         $contact_id = $self[0]['id'];
1131                         $post->actor->displayName = $self[0]['name'];
1132                         $post->actor->url = $self[0]['url'];
1133                         $post->actor->image->url = $self[0]['photo'];
1134                 } elseif ($contact_id == 0) {
1135                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1136                         $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1137                                 dbesc(normalise_link($post->actor->url)),
1138                                 intval($uid)
1139                         );
1140
1141                         if(count($r))
1142                                 $contact_id = $r[0]['id'];
1143                         else {
1144                                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1145                                         dbesc(normalise_link($post->actor->url)),
1146                                         intval($uid)
1147                                 );
1148
1149                                 if(count($r))
1150                                         $contact_id = $r[0]['id'];
1151                                 else
1152                                         $contact_id = $self[0]['id'];
1153                         }
1154                 }
1155
1156                 $reply = new stdClass;
1157                 $reply->verb = "note";
1158                 $reply->cc = $post->cc;
1159                 $reply->to = $post->to;
1160                 $reply->object = new stdClass;
1161                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1162                 $reply->object->content = $post->object->inReplyTo->content;
1163                 $reply->object->id = $post->object->inReplyTo->id;
1164                 $reply->actor = $post->object->inReplyTo->author;
1165                 $reply->url = $post->object->inReplyTo->url;
1166                 $reply->generator = new stdClass;
1167                 $reply->generator->displayName = "pumpio";
1168                 $reply->published = $post->object->inReplyTo->published;
1169                 $reply->received = $post->object->inReplyTo->updated;
1170                 $reply->url = $post->object->inReplyTo->url;
1171                 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1172
1173                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1174         }
1175
1176         if ($post->object->pump_io->proxyURL)
1177                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1178
1179         $postarray['contact-id'] = $contact_id;
1180         $postarray['verb'] = ACTIVITY_POST;
1181         $postarray['owner-name'] = $post->actor->displayName;
1182         $postarray['owner-link'] = $post->actor->url;
1183         $postarray['owner-avatar'] = $post->actor->image->url;
1184         $postarray['author-name'] = $post->actor->displayName;
1185         $postarray['author-link'] = $post->actor->url;
1186         $postarray['author-avatar'] = $post->actor->image->url;
1187         $postarray['plink'] = $post->object->url;
1188         $postarray['app'] = $post->generator->displayName;
1189         $postarray['body'] = HTML::toBBCode($post->object->content);
1190         $postarray['object'] = json_encode($post);
1191
1192         if ($post->object->fullImage->url != "")
1193                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1194
1195         if ($post->object->displayName != "")
1196                 $postarray['title'] = $post->object->displayName;
1197
1198         $postarray['created'] = DateTimeFormat::utc($post->published);
1199         if (isset($post->updated))
1200                 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1201         elseif (isset($post->received))
1202                 $postarray['edited'] = DateTimeFormat::utc($post->received);
1203         else
1204                 $postarray['edited'] = $postarray['created'];
1205
1206         if ($post->verb == "share") {
1207                 if (!intval(Config::get('system','wall-to-wall_share'))) {
1208                         if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1209                                 $share_author = $post->object->author->displayName;
1210                         elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1211                                 $share_author = $post->object->author->preferredUsername;
1212                         else
1213                                 $share_author = $post->object->author->url;
1214
1215                         $postarray['body'] = share_header($share_author, $post->object->author->url,
1216                                                         $post->object->author->image->url, "",
1217                                                         DateTimeFormat::utc($post->object->created),
1218                                                         $post->links->self->href).
1219                                                 $postarray['body']."[/share]";
1220                 } else {
1221                         // Let shares look like wall-to-wall posts
1222                         $postarray['author-name'] = $post->object->author->displayName;
1223                         $postarray['author-link'] = $post->object->author->url;
1224                         $postarray['author-avatar'] = $post->object->author->image->url;
1225                 }
1226         }
1227
1228         if (trim($postarray['body']) == "")
1229                 return false;
1230
1231         $top_item = Item::insert($postarray);
1232         $postarray["id"] = $top_item;
1233
1234         if (($top_item == 0) && ($post->verb == "update")) {
1235                 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1236                 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1237                 Item::update($fields, $condition);
1238         }
1239
1240         if ($post->object->objectType == "comment") {
1241
1242                 if ($threadcompletion)
1243                         pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1244         }
1245
1246         return $top_item;
1247 }
1248
1249 function pumpio_fetchinbox(&$a, $uid) {
1250
1251         $ckey    = PConfig::get($uid, 'pumpio', 'consumer_key');
1252         $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1253         $otoken  = PConfig::get($uid, 'pumpio', 'oauth_token');
1254         $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1255         $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1256         $hostname = PConfig::get($uid, 'pumpio','host');
1257         $username = PConfig::get($uid, "pumpio", "user");
1258
1259         $own_id = "https://".$hostname."/".$username;
1260
1261         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1262                 intval($uid));
1263
1264         $lastitems = q("SELECT `uri` FROM `thread`
1265                         INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1266                         WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1267                         ORDER BY `thread`.`commented` DESC LIMIT 10",
1268                                 dbesc(NETWORK_PUMPIO),
1269                                 intval($uid)
1270                         );
1271
1272         $client = new oauth_client_class;
1273         $client->oauth_version = '1.0a';
1274         $client->authorization_header = true;
1275         $client->url_parameters = false;
1276
1277         $client->client_id = $ckey;
1278         $client->client_secret = $csecret;
1279         $client->access_token = $otoken;
1280         $client->access_token_secret = $osecret;
1281
1282         $last_id = PConfig::get($uid,'pumpio','last_id');
1283
1284         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1285
1286         if ($last_id != "")
1287                 $url .= '?since='.urlencode($last_id);
1288
1289         if (pumpio_reachable($url))
1290                 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1291         else
1292                 $success = false;
1293
1294         if ($user->items) {
1295             $posts = array_reverse($user->items);
1296
1297             if (count($posts))
1298                     foreach ($posts as $post) {
1299                             $last_id = $post->id;
1300                             pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1301                     }
1302         }
1303
1304         foreach ($lastitems AS $item)
1305                 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1306
1307         PConfig::set($uid,'pumpio','last_id', $last_id);
1308 }
1309
1310 function pumpio_getallusers(&$a, $uid) {
1311         $ckey    = PConfig::get($uid, 'pumpio', 'consumer_key');
1312         $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1313         $otoken  = PConfig::get($uid, 'pumpio', 'oauth_token');
1314         $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1315         $hostname = PConfig::get($uid, 'pumpio','host');
1316         $username = PConfig::get($uid, "pumpio", "user");
1317
1318         $client = new oauth_client_class;
1319         $client->oauth_version = '1.0a';
1320         $client->authorization_header = true;
1321         $client->url_parameters = false;
1322
1323         $client->client_id = $ckey;
1324         $client->client_secret = $csecret;
1325         $client->access_token = $otoken;
1326         $client->access_token_secret = $osecret;
1327
1328         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1329
1330         if (pumpio_reachable($url))
1331                 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1332         else
1333                 $success = false;
1334
1335         if ($users->totalItems > count($users->items)) {
1336                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1337
1338                 if (pumpio_reachable($url))
1339                         $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1340                 else
1341                         $success = false;
1342         }
1343
1344         if (is_array($users->items)) {
1345                 foreach ($users->items AS $user) {
1346                         pumpio_get_contact($uid, $user);
1347                 }
1348         }
1349 }
1350
1351 function pumpio_queue_hook(&$a,&$b) {
1352
1353         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1354                 dbesc(NETWORK_PUMPIO)
1355         );
1356         if(! count($qi))
1357                 return;
1358
1359         foreach($qi as $x) {
1360                 if($x['network'] !== NETWORK_PUMPIO)
1361                         continue;
1362
1363                 logger('pumpio_queue: run');
1364
1365                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1366                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1367                         intval($x['cid'])
1368                 );
1369                 if(! count($r))
1370                         continue;
1371
1372                 $userdata = $r[0];
1373
1374                 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1375
1376                 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1377                 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1378                 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1379                 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1380
1381                 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1382                 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1383
1384                 $success = false;
1385
1386                 if ($oauth_token && $oauth_token_secret &&
1387                         $consumer_key && $consumer_secret) {
1388                         $username = $user.'@'.$host;
1389
1390                         logger('pumpio_queue: able to post for user '.$username);
1391
1392                         $z = unserialize($x['content']);
1393
1394                         $client = new oauth_client_class;
1395                         $client->oauth_version = '1.0a';
1396                         $client->url_parameters = false;
1397                         $client->authorization_header = true;
1398                         $client->access_token = $oauth_token;
1399                         $client->access_token_secret = $oauth_token_secret;
1400                         $client->client_id = $consumer_key;
1401                         $client->client_secret = $consumer_secret;
1402
1403                         if (pumpio_reachable($z['url']))
1404                                 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1405                         else
1406                                 $success = false;
1407
1408                         if($success) {
1409                                 $post_id = $user->object->id;
1410                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1411                                 if($post_id && $iscomment) {
1412                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1413                                         Item::update(['extid' => $post_id], ['id' => $z['item']]);
1414                                 }
1415                                 Queue::removeItem($x['id']);
1416                         } else
1417                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1418                 } else
1419                         logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1420
1421                 if (!$success) {
1422                         logger('pumpio_queue: delayed');
1423                         Queue::updateTime($x['id']);
1424                 }
1425         }
1426 }
1427
1428 function pumpio_getreceiver(&$a, $b) {
1429
1430         $receiver = [];
1431
1432         if (!$b["private"]) {
1433
1434                 if(! strstr($b['postopts'],'pumpio'))
1435                         return $receiver;
1436
1437                 $public = PConfig::get($b['uid'], "pumpio", "public");
1438
1439                 if ($public)
1440                         $receiver["to"][] = [
1441                                                 "objectType" => "collection",
1442                                                 "id" => "http://activityschema.org/collection/public"];
1443         } else {
1444                 $cids = explode("><", $b["allow_cid"]);
1445                 $gids = explode("><", $b["allow_gid"]);
1446
1447                 foreach ($cids AS $cid) {
1448                         $cid = trim($cid, " <>");
1449
1450                         $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",
1451                                 intval($cid),
1452                                 intval($b["uid"]),
1453                                 dbesc(NETWORK_PUMPIO)
1454                                 );
1455
1456                         if (count($r)) {
1457                                 $receiver["bcc"][] = [
1458                                                         "displayName" => $r[0]["name"],
1459                                                         "objectType" => "person",
1460                                                         "preferredUsername" => $r[0]["nick"],
1461                                                         "url" => $r[0]["url"]];
1462                         }
1463                 }
1464                 foreach ($gids AS $gid) {
1465                         $gid = trim($gid, " <>");
1466
1467                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1468                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1469                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1470                                         intval($gid),
1471                                         dbesc(NETWORK_PUMPIO)
1472                                 );
1473
1474                         foreach ($r AS $row)
1475                                 $receiver["bcc"][] = [
1476                                                         "displayName" => $row["name"],
1477                                                         "objectType" => "person",
1478                                                         "preferredUsername" => $row["nick"],
1479                                                         "url" => $row["url"]];
1480                 }
1481         }
1482
1483         if ($b["inform"] != "") {
1484
1485                 $inform = explode(",", $b["inform"]);
1486
1487                 foreach ($inform AS $cid) {
1488                         if (substr($cid, 0, 4) != "cid:")
1489                                 continue;
1490
1491                         $cid = str_replace("cid:", "", $cid);
1492
1493                         $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",
1494                                 intval($cid),
1495                                 intval($b["uid"]),
1496                                 dbesc(NETWORK_PUMPIO)
1497                                 );
1498
1499                         if (count($r)) {
1500                                         $receiver["to"][] = [
1501                                                                 "displayName" => $r[0]["name"],
1502                                                                 "objectType" => "person",
1503                                                                 "preferredUsername" => $r[0]["nick"],
1504                                                                 "url" => $r[0]["url"]];
1505                         }
1506                 }
1507         }
1508
1509         return $receiver;
1510 }
1511
1512 function pumpio_fetchallcomments(&$a, $uid, $id) {
1513         $ckey    = PConfig::get($uid, 'pumpio', 'consumer_key');
1514         $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1515         $otoken  = PConfig::get($uid, 'pumpio', 'oauth_token');
1516         $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1517         $hostname = PConfig::get($uid, 'pumpio','host');
1518         $username = PConfig::get($uid, "pumpio", "user");
1519
1520         logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1521
1522         $own_id = "https://".$hostname."/".$username;
1523
1524         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1525                 intval($uid));
1526
1527         // Fetching the original post
1528         $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1529                         dbesc($id),
1530                         intval($uid)
1531                 );
1532
1533         if (!count($r))
1534                 return false;
1535
1536         $url = $r[0]["extid"];
1537
1538         $client = new oauth_client_class;
1539         $client->oauth_version = '1.0a';
1540         $client->authorization_header = true;
1541         $client->url_parameters = false;
1542
1543         $client->client_id = $ckey;
1544         $client->client_secret = $csecret;
1545         $client->access_token = $otoken;
1546         $client->access_token_secret = $osecret;
1547
1548         logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1549
1550         if (pumpio_reachable($url))
1551                 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1552         else
1553                 $success = false;
1554
1555         if (!$success)
1556                 return;
1557
1558         if ($item->likes->totalItems != 0) {
1559                 foreach ($item->likes->items AS $post) {
1560                         $like = new stdClass;
1561                         $like->object = new stdClass;
1562                         $like->object->id = $item->id;
1563                         $like->actor = new stdClass;
1564                         $like->actor->displayName = $item->displayName;
1565                         $like->actor->preferredUsername = $item->preferredUsername;
1566                         $like->actor->url = $item->url;
1567                         $like->actor->image = $item->image;
1568                         $like->generator = new stdClass;
1569                         $like->generator->displayName = "pumpio";
1570                         pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1571                 }
1572         }
1573
1574         if ($item->replies->totalItems == 0)
1575                 return;
1576
1577         foreach ($item->replies->items AS $item) {
1578                 if ($item->id == $id)
1579                         continue;
1580
1581                 // Checking if the comment already exists - Two queries for speed issues
1582                 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1583                                 dbesc($item->id),
1584                                 intval($uid)
1585                         );
1586
1587                 if (count($r))
1588                         continue;
1589
1590                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1591                                 dbesc($item->id),
1592                                 intval($uid)
1593                         );
1594
1595                 if (count($r))
1596                         continue;
1597
1598                 $post = new stdClass;
1599                 $post->verb = "post";
1600                 $post->actor = $item->author;
1601                 $post->published = $item->published;
1602                 $post->received = $item->updated;
1603                 $post->generator = new stdClass;
1604                 $post->generator->displayName = "pumpio";
1605                 // To-Do: Check for public post
1606
1607                 unset($item->author);
1608                 unset($item->published);
1609                 unset($item->updated);
1610
1611                 $post->object = $item;
1612
1613                 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1614                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1615         }
1616 }
1617
1618
1619 function pumpio_reachable($url) {
1620         $data = Network::curl($url, false, $redirects, ['timeout'=>10]);
1621         return(intval($data['return_code']) != 0);
1622 }
1623
1624 /*
1625 To-Do:
1626  - edit own notes
1627  - delete own notes
1628 */