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