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