]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
Deprecated parts removed
[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 == "") OR ($consumer_secret == "")) AND ($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 == "") OR ($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 != '') AND ($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 == "") OR ($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         $pumpio_post   = intval(get_pconfig(local_user(),'pumpio','post'));
358
359         $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
360
361         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
362                 $pumpio_enable = 1;
363
364         if(! $pumpio_enable)
365                 return;
366
367         if(strlen($b['postopts']))
368                 $b['postopts'] .= ',';
369
370         $b['postopts'] .= 'pumpio';
371 }
372
373
374
375
376 function pumpio_send(&$a,&$b) {
377
378         if (!get_pconfig($b["uid"],'pumpio','import')) {
379                 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
380                         return;
381         }
382
383         logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
384
385         if($b['parent'] != $b['id']) {
386                 // Looking if its a reply to a pumpio post
387                 $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",
388                         intval($b["parent"]),
389                         intval($b["uid"]),
390                         dbesc(NETWORK_PUMPIO));
391
392                 if(!count($r)) {
393                         logger("pumpio_send: no pumpio post ".$b["parent"]);
394                         return;
395                 } else {
396                         $iscomment = true;
397                         $orig_post = $r[0];
398                 }
399         } else {
400                 $iscomment = false;
401
402                 $receiver = pumpio_getreceiver($a, $b);
403
404                 logger("pumpio_send: receiver ".print_r($receiver, true));
405
406                 if (!count($receiver) AND ($b['private'] OR !strstr($b['postopts'],'pumpio')))
407                         return;
408         }
409
410         if($b['verb'] == ACTIVITY_LIKE) {
411                 if ($b['deleted'])
412                         pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
413                 else
414                         pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
415                 return;
416         }
417
418         if($b['verb'] == ACTIVITY_DISLIKE)
419                 return;
420
421         if (($b['verb'] == ACTIVITY_POST) AND ($b['created'] !== $b['edited']) AND !$b['deleted'])
422                         pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
423
424         if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
425                         pumpio_action($a, $b["uid"], $b["uri"], "delete");
426
427         if($b['deleted'] || ($b['created'] !== $b['edited']))
428                 return;
429
430         // if post comes from pump.io don't send it back
431         if($b['app'] == "pump.io")
432                 return;
433
434         // To-Do;
435         // Support for native shares
436         // http://<hostname>/api/<type>/shares?id=<the-object-id>
437
438         $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
439         $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
440         $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
441         $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
442
443         $host = get_pconfig($b['uid'], "pumpio", "host");
444         $user = get_pconfig($b['uid'], "pumpio", "user");
445         $public = get_pconfig($b['uid'], "pumpio", "public");
446
447         if($oauth_token && $oauth_token_secret) {
448
449                 require_once('include/bbcode.php');
450
451                 $title = trim($b['title']);
452
453                 $content = bbcode($b['body'], false, false, 4);
454
455                 $params = array();
456
457                 $params["verb"] = "post";
458
459                 if (!$iscomment) {
460                         $params["object"] = array(
461                                                 'objectType' => "note",
462                                                 'content' => $content);
463
464                         if ($title != "")
465                                 $params["object"]["displayName"] = $title;
466
467                         if (count($receiver["to"]))
468                                 $params["to"] = $receiver["to"];
469
470                         if (count($receiver["bto"]))
471                                 $params["bto"] = $receiver["bto"];
472
473                         if (count($receiver["cc"]))
474                                 $params["cc"] = $receiver["cc"];
475
476                         if (count($receiver["bcc"]))
477                                 $params["bcc"] = $receiver["bcc"];
478
479                  } else {
480                         $inReplyTo = array("id" => $orig_post["uri"],
481                                         "objectType" => "note");
482
483                         if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
484                                 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
485
486                         $params["object"] = array(
487                                                 'objectType' => "comment",
488                                                 'content' => $content,
489                                                 'inReplyTo' => $inReplyTo);
490
491                         if ($title != "")
492                                 $params["object"]["displayName"] = $title;
493                 }
494
495                 $client = new oauth_client_class;
496                 $client->oauth_version = '1.0a';
497                 $client->url_parameters = false;
498                 $client->authorization_header = true;
499                 $client->access_token = $oauth_token;
500                 $client->access_token_secret = $oauth_token_secret;
501                 $client->client_id = $consumer_key;
502                 $client->client_secret = $consumer_secret;
503
504                 $username = $user.'@'.$host;
505                 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
506
507                 if (pumpio_reachable($url))
508                         $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
509                 else
510                         $success = false;
511
512                 if($success) {
513
514                         if ($user->generator->displayName)
515                                 set_pconfig($b["uid"], "pumpio", "application_name", $user->generator->displayName);
516
517                         $post_id = $user->object->id;
518                         logger('pumpio_send '.$username.': success '.$post_id);
519                         if($post_id AND $iscomment) {
520                                 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
521                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
522                                         dbesc($post_id),
523                                         intval($b['id'])
524                                 );
525                         }
526                 } else {
527                         logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
528
529                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
530                         if (count($r))
531                                 $a->contact = $r[0]["id"];
532
533                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
534                         require_once('include/queue_fn.php');
535                         add_to_queue($a->contact,NETWORK_PUMPIO,$s);
536                         notice(t('Pump.io post failed. Queued for retry.').EOL);
537                 }
538
539         }
540 }
541
542 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
543
544         // Don't do likes and other stuff if you don't import the timeline
545         if (!get_pconfig($uid,'pumpio','import'))
546                 return;
547
548         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
549         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
550         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
551         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
552         $hostname = get_pconfig($uid, 'pumpio','host');
553         $username = get_pconfig($uid, "pumpio", "user");
554
555         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
556                                 dbesc($uri),
557                                 intval($uid)
558         );
559
560         if (!count($r))
561                 return;
562
563         $orig_post = $r[0];
564
565         if ($orig_post["extid"] AND !strstr($orig_post["extid"], "/proxy/"))
566                 $uri = $orig_post["extid"];
567         else
568                 $uri = $orig_post["uri"];
569
570         if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
571                 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
572         elseif (strstr($uri, "/api/comment/"))
573                 $objectType = "comment";
574         elseif (strstr($uri, "/api/note/"))
575                 $objectType = "note";
576         elseif (strstr($uri, "/api/image/"))
577                 $objectType = "image";
578
579         $params["verb"] = $action;
580         $params["object"] = array('id' => $uri,
581                                 "objectType" => $objectType,
582                                 "content" => $content);
583
584         $client = new oauth_client_class;
585         $client->oauth_version = '1.0a';
586         $client->authorization_header = true;
587         $client->url_parameters = false;
588
589         $client->client_id = $ckey;
590         $client->client_secret = $csecret;
591         $client->access_token = $otoken;
592         $client->access_token_secret = $osecret;
593
594         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
595
596         if (pumpio_reachable($url))
597                 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
598         else
599                 $success = false;
600
601         if($success)
602                 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
603         else {
604                 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
605
606                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
607                 if (count($r))
608                         $a->contact = $r[0]["id"];
609
610                 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
611                 require_once('include/queue_fn.php');
612                 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
613                 notice(t('Pump.io like failed. Queued for retry.').EOL);
614         }
615 }
616
617 function pumpio_sync(&$a) {
618         $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
619                 $plugin);
620
621         if (!count($r))
622                 return;
623
624         $last = get_config('pumpio','last_poll');
625
626         $poll_interval = intval(get_config('pumpio','poll_interval'));
627         if(! $poll_interval)
628                 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
629
630         if($last) {
631                 $next = $last + ($poll_interval * 60);
632                 if($next > time()) {
633                         logger('pumpio: poll intervall not reached');
634                         return;
635                 }
636         }
637         logger('pumpio: cron_start');
638
639         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
640         if(count($r)) {
641                 foreach($r as $rr) {
642                         logger('pumpio: mirroring user '.$rr['uid']);
643                         pumpio_fetchtimeline($a, $rr['uid']);
644                 }
645         }
646
647         $abandon_days = intval(get_config('system','account_abandon_days'));
648         if ($abandon_days < 1)
649                 $abandon_days = 0;
650
651         $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
652
653         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
654         if(count($r)) {
655                 foreach($r as $rr) {
656                         if ($abandon_days != 0) {
657                                 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
658                                 if (!count($user)) {
659                                         logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
660                                         continue;
661                                 }
662                         }
663
664                         logger('pumpio: importing timeline from user '.$rr['uid']);
665                         pumpio_fetchinbox($a, $rr['uid']);
666
667                         // check for new contacts once a day
668                         $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check');
669                         if($last_contact_check)
670                                 $next_contact_check = $last_contact_check + 86400;
671                         else
672                                 $next_contact_check = 0;
673
674                         if($next_contact_check <= time()) {
675                                 pumpio_getallusers($a, $rr["uid"]);
676                                 set_pconfig($rr['uid'],'pumpio','contact_check',time());
677                         }
678                 }
679         }
680
681         logger('pumpio: cron_end');
682
683         set_config('pumpio','last_poll', time());
684 }
685
686 function pumpio_cron(&$a,$b) {
687         //pumpio_sync($a);
688         proc_run("php","addon/pumpio/pumpio_sync.php");
689 }
690
691 function pumpio_fetchtimeline(&$a, $uid) {
692         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
693         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
694         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
695         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
696         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
697         $hostname = get_pconfig($uid, 'pumpio','host');
698         $username = get_pconfig($uid, "pumpio", "user");
699
700         //  get the application name for the pump.io app
701         //  1st try personal config, then system config and fallback to the
702         //  hostname of the node if neither one is set.
703         $application_name  = get_pconfig( $uid, 'pumpio', 'application_name');
704         if ($application_name == "")
705                 $application_name  = get_config('pumpio', 'application_name');
706         if ($application_name == "")
707                 $application_name = $a->get_hostname();
708
709         $first_time = ($lastdate == "");
710
711         $client = new oauth_client_class;
712         $client->oauth_version = '1.0a';
713         $client->authorization_header = true;
714         $client->url_parameters = false;
715
716         $client->client_id = $ckey;
717         $client->client_secret = $csecret;
718         $client->access_token = $otoken;
719         $client->access_token_secret = $osecret;
720
721         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
722
723         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
724
725         $username = $user.'@'.$host;
726
727         if (pumpio_reachable($url))
728                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
729         else
730                 $success = false;
731
732         if (!$success) {
733                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
734                 return;
735         }
736
737         $posts = array_reverse($user->items);
738
739         $initiallastdate = $lastdate;
740         $lastdate = '';
741
742         if (count($posts)) {
743                 foreach ($posts as $post) {
744                         if ($post->published <= $initiallastdate)
745                                 continue;
746
747                         if ($lastdate < $post->published)
748                                 $lastdate = $post->published;
749
750                         if ($first_time)
751                                 continue;
752
753                         $receiptians = array();
754                         if (@is_array($post->cc))
755                                 $receiptians = array_merge($receiptians, $post->cc);
756
757                         if (@is_array($post->to))
758                                 $receiptians = array_merge($receiptians, $post->to);
759
760                         $public = false;
761                         foreach ($receiptians AS $receiver)
762                                 if (is_string($receiver->objectType))
763                                         if ($receiver->id == "http://activityschema.org/collection/public")
764                                                 $public = true;
765
766                         if ($public AND !stristr($post->generator->displayName, $application_name)) {
767                                 require_once('include/html2bbcode.php');
768
769                                 $_SESSION["authenticated"] = true;
770                                 $_SESSION["uid"] = $uid;
771
772                                 unset($_REQUEST);
773                                 $_REQUEST["type"] = "wall";
774                                 $_REQUEST["api_source"] = true;
775                                 $_REQUEST["profile_uid"] = $uid;
776                                 $_REQUEST["source"] = "pump.io";
777
778                                 if (isset($post->object->id)) {
779                                         $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
780                                 }
781
782                                 if ($post->object->displayName != "")
783                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
784                                 else
785                                         $_REQUEST["title"] = "";
786
787                                 $_REQUEST["body"] = html2bbcode($post->object->content);
788
789                                 // To-Do: Picture has to be cached and stored locally
790                                 if ($post->object->fullImage->url != "") {
791                                         if ($post->object->fullImage->pump_io->proxyURL != "")
792                                                 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
793                                         else
794                                                 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
795                                 }
796
797                                 logger('pumpio: posting for user '.$uid);
798
799                                 require_once('mod/item.php');
800
801                                 item_post($a);
802                                 logger('pumpio: posting done - user '.$uid);
803                         }
804                 }
805         }
806
807         if ($lastdate != 0)
808                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
809 }
810
811 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
812         // Searching for the unliked post
813         // Two queries for speed issues
814         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
815                                 dbesc($post->object->id),
816                                 intval($uid)
817                 );
818
819         if (count($r))
820                 $orig_post = $r[0];
821         else {
822                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
823                                         dbesc($post->object->id),
824                                         intval($uid)
825                         );
826
827                 if (!count($r))
828                         return;
829                 else
830                         $orig_post = $r[0];
831         }
832
833         $contactid = 0;
834
835         if(link_compare($post->actor->url, $own_id)) {
836                 $contactid = $self[0]['id'];
837         } else {
838                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
839                         dbesc(normalise_link($post->actor->url)),
840                         intval($uid)
841                 );
842
843                 if(count($r))
844                         $contactid = $r[0]['id'];
845
846                 if($contactid == 0)
847                         $contactid = $orig_post['contact-id'];
848         }
849
850         $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'",
851                 dbesc(datetime_convert()),
852                 dbesc(ACTIVITY_LIKE),
853                 intval($uid),
854                 intval($contactid),
855                 dbesc($orig_post['uri'])
856         );
857
858         if(count($r))
859                 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
860         else
861                 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
862 }
863
864 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
865         require_once('include/items.php');
866
867         if ($post->object->id == "") {
868                 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
869                 return;
870         }
871
872         // Searching for the liked post
873         // Two queries for speed issues
874         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
875                                 dbesc($post->object->id),
876                                 intval($uid),
877                                 dbesc(NETWORK_PUMPIO)
878                 );
879
880         if (count($r))
881                 $orig_post = $r[0];
882         else {
883                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
884                                         dbesc($post->object->id),
885                                         intval($uid),
886                                         dbesc(NETWORK_PUMPIO)
887                         );
888
889                 if (!count($r))
890                         return;
891                 else
892                         $orig_post = $r[0];
893         }
894
895         // thread completion
896         if ($threadcompletion)
897                 pumpio_fetchallcomments($a, $uid, $post->object->id);
898
899         $contactid = 0;
900
901         if(link_compare($post->actor->url, $own_id)) {
902                 $contactid = $self[0]['id'];
903                 $post->actor->displayName = $self[0]['name'];
904                 $post->actor->url = $self[0]['url'];
905                 $post->actor->image->url = $self[0]['photo'];
906         } else {
907                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
908                         dbesc(normalise_link($post->actor->url)),
909                         intval($uid)
910                 );
911
912                 if(count($r))
913                         $contactid = $r[0]['id'];
914
915                 if($contactid == 0)
916                         $contactid = $orig_post['contact-id'];
917         }
918
919         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
920                 dbesc(ACTIVITY_LIKE),
921                 intval($uid),
922                 intval($contactid),
923                 dbesc($orig_post['uri'])
924         );
925
926         if(count($r)) {
927                 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
928                 return;
929         }
930
931         $likedata = array();
932         $likedata['parent'] = $orig_post['id'];
933         $likedata['verb'] = ACTIVITY_LIKE;
934         $likedata['gravity'] = 3;
935         $likedata['uid'] = $uid;
936         $likedata['wall'] = 0;
937         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
938         $likedata['parent-uri'] = $orig_post["uri"];
939         $likedata['contact-id'] = $contactid;
940         $likedata['app'] = $post->generator->displayName;
941         $likedata['author-name'] = $post->actor->displayName;
942         $likedata['author-link'] = $post->actor->url;
943         $likedata['author-avatar'] = $post->actor->image->url;
944
945         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
946         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
947         $post_type = t('status');
948         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
949         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
950
951         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
952
953         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
954                 '<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>';
955
956         $ret = item_store($likedata);
957
958         logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
959 }
960
961 function pumpio_get_contact($uid, $contact, $no_insert = false) {
962
963         update_gcontact(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
964                         "photo" => $contact->image->url, "name" => $contact->displayName,  "hide" => true,
965                         "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
966                         "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
967         $cid = get_contact($contact->url, $uid);
968
969         if ($no_insert)
970                 return($cid);
971
972         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
973                 intval($uid), dbesc(normalise_link($contact->url)));
974
975         if (!count($r)) {
976                 // create contact record
977                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
978                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
979                                         `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
980                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
981                         intval($uid),
982                         dbesc(datetime_convert()),
983                         dbesc($contact->url),
984                         dbesc(normalise_link($contact->url)),
985                         dbesc(str_replace("acct:", "", $contact->id)),
986                         dbesc(''),
987                         dbesc($contact->id), // What is it for?
988                         dbesc('pump.io ' . $contact->id), // What is it for?
989                         dbesc($contact->displayName),
990                         dbesc($contact->preferredUsername),
991                         dbesc($contact->image->url),
992                         dbesc(NETWORK_PUMPIO),
993                         intval(CONTACT_IS_FRIEND),
994                         intval(1),
995                         dbesc($contact->location->displayName),
996                         dbesc($contact->summary),
997                         intval(1)
998                 );
999
1000                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1001                         dbesc(normalise_link($contact->url)),
1002                         intval($uid)
1003                         );
1004
1005                 if (!count($r)) {
1006                         return(false);
1007                 }
1008
1009                 $contact_id = $r[0]['id'];
1010
1011                 $g = q("select def_gid from user where uid = %d limit 1",
1012                         intval($uid)
1013                 );
1014
1015                 if($g && intval($g[0]['def_gid'])) {
1016                         require_once('include/group.php');
1017                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1018                 }
1019         } else {
1020                 $contact_id = $r[0]["id"];
1021
1022                 /*      if (DB_UPDATE_VERSION >= "1177")
1023                                 q("UPDATE `contact` SET `location` = '%s',
1024                                                         `about` = '%s'
1025                                                 WHERE `id` = %d",
1026                                         dbesc($contact->location->displayName),
1027                                         dbesc($contact->summary),
1028                                         intval($r[0]['id'])
1029                                 );
1030                 */
1031         }
1032
1033         if (function_exists("update_contact_avatar"))
1034                 update_contact_avatar($contact->image->url, $uid, $contact_id);
1035
1036         return($contact_id);
1037 }
1038
1039 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1040
1041         // Two queries for speed issues
1042         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1043                                 dbesc($post->object->id),
1044                                 intval($uid)
1045                 );
1046
1047         if (count($r))
1048                 return drop_item($r[0]["id"], $false);
1049
1050         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1051                                 dbesc($post->object->id),
1052                                 intval($uid)
1053                 );
1054
1055         if (count($r))
1056                 return drop_item($r[0]["id"], $false);
1057 }
1058
1059 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1060         require_once('include/items.php');
1061         require_once('include/html2bbcode.php');
1062
1063         if (($post->verb == "like") OR ($post->verb == "favorite"))
1064                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1065
1066         if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
1067                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1068
1069         if ($post->verb == "delete")
1070                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1071
1072         if ($post->verb != "update") {
1073                 // Two queries for speed issues
1074                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1075                                         dbesc($post->object->id),
1076                                         intval($uid)
1077                         );
1078
1079                 if (count($r))
1080                         return false;
1081
1082                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1083                                         dbesc($post->object->id),
1084                                         intval($uid)
1085                         );
1086
1087                 if (count($r))
1088                         return false;
1089         }
1090
1091         // Only handle these three types
1092         if (!strstr("post|share|update", $post->verb))
1093                 return false;
1094
1095         $receiptians = array();
1096         if (@is_array($post->cc))
1097                 $receiptians = array_merge($receiptians, $post->cc);
1098
1099         if (@is_array($post->to))
1100                 $receiptians = array_merge($receiptians, $post->to);
1101
1102         foreach ($receiptians AS $receiver)
1103                 if (is_string($receiver->objectType))
1104                         if ($receiver->id == "http://activityschema.org/collection/public")
1105                                 $public = true;
1106
1107         $postarray = array();
1108         $postarray['network'] = NETWORK_PUMPIO;
1109         $postarray['gravity'] = 0;
1110         $postarray['uid'] = $uid;
1111         $postarray['wall'] = 0;
1112         $postarray['uri'] = $post->object->id;
1113         $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1114
1115         if ($post->object->objectType != "comment") {
1116                 $contact_id = pumpio_get_contact($uid, $post->actor);
1117
1118                 if (!$contact_id)
1119                         $contact_id = $self[0]['id'];
1120
1121                 $postarray['parent-uri'] = $post->object->id;
1122
1123                 if (!$public) {
1124                         $postarray['private'] = 1;
1125                         $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1126                 }
1127         } else {
1128                 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1129
1130                 if (link_compare($post->actor->url, $own_id)) {
1131                         $contact_id = $self[0]['id'];
1132                         $post->actor->displayName = $self[0]['name'];
1133                         $post->actor->url = $self[0]['url'];
1134                         $post->actor->image->url = $self[0]['photo'];
1135                 } elseif ($contact_id == 0) {
1136                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1137                         $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1138                                 dbesc(normalise_link($post->actor->url)),
1139                                 intval($uid)
1140                         );
1141
1142                         if(count($r))
1143                                 $contact_id = $r[0]['id'];
1144                         else {
1145                                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1146                                         dbesc(normalise_link($post->actor->url)),
1147                                         intval($uid)
1148                                 );
1149
1150                                 if(count($r))
1151                                         $contact_id = $r[0]['id'];
1152                                 else
1153                                         $contact_id = $self[0]['id'];
1154                         }
1155                 }
1156
1157                 $reply = new stdClass;
1158                 $reply->verb = "note";
1159                 $reply->cc = $post->cc;
1160                 $reply->to = $post->to;
1161                 $reply->object = new stdClass;
1162                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1163                 $reply->object->content = $post->object->inReplyTo->content;
1164                 $reply->object->id = $post->object->inReplyTo->id;
1165                 $reply->actor = $post->object->inReplyTo->author;
1166                 $reply->url = $post->object->inReplyTo->url;
1167                 $reply->generator = new stdClass;
1168                 $reply->generator->displayName = "pumpio";
1169                 $reply->published = $post->object->inReplyTo->published;
1170                 $reply->received = $post->object->inReplyTo->updated;
1171                 $reply->url = $post->object->inReplyTo->url;
1172                 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1173
1174                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1175         }
1176
1177         if ($post->object->pump_io->proxyURL)
1178                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1179
1180         $postarray['contact-id'] = $contact_id;
1181         $postarray['verb'] = ACTIVITY_POST;
1182         $postarray['owner-name'] = $post->actor->displayName;
1183         $postarray['owner-link'] = $post->actor->url;
1184         $postarray['owner-avatar'] = $post->actor->image->url;
1185         $postarray['author-name'] = $post->actor->displayName;
1186         $postarray['author-link'] = $post->actor->url;
1187         $postarray['author-avatar'] = $post->actor->image->url;
1188         $postarray['plink'] = $post->object->url;
1189         $postarray['app'] = $post->generator->displayName;
1190         $postarray['body'] = html2bbcode($post->object->content);
1191         $postarray['object'] = json_encode($post);
1192
1193         if ($post->object->fullImage->url != "")
1194                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1195
1196         if ($post->object->displayName != "")
1197                 $postarray['title'] = $post->object->displayName;
1198
1199         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1200         if (isset($post->updated))
1201                 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1202         elseif (isset($post->received))
1203                 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1204         else
1205                 $postarray['edited'] = $postarray['created'];
1206
1207         if ($post->verb == "share") {
1208                 if (!intval(get_config('system','wall-to-wall_share'))) {
1209                         if (isset($post->object->author->displayName) AND ($post->object->author->displayName != ""))
1210                                 $share_author = $post->object->author->displayName;
1211                         elseif (isset($post->object->author->preferredUsername) AND ($post->object->author->preferredUsername != ""))
1212                                 $share_author = $post->object->author->preferredUsername;
1213                         else
1214                                 $share_author = $post->object->author->url;
1215
1216                         $postarray['body'] = share_header($share_author, $post->object->author->url,
1217                                                         $post->object->author->image->url, "",
1218                                                         datetime_convert('UTC','UTC',$post->object->created),
1219                                                         $post->links->self->href).
1220                                                 $postarray['body']."[/share]";
1221
1222                         /*
1223                         $postarray['body'] = "[share author='".$share_author.
1224                                         "' profile='".$post->object->author->url.
1225                                         "' avatar='".$post->object->author->image->url.
1226                                         "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1227                                         "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1228                         */
1229                 } else {
1230                         // Let shares look like wall-to-wall posts
1231                         $postarray['author-name'] = $post->object->author->displayName;
1232                         $postarray['author-link'] = $post->object->author->url;
1233                         $postarray['author-avatar'] = $post->object->author->image->url;
1234                 }
1235         }
1236
1237         if (trim($postarray['body']) == "")
1238                 return false;
1239
1240         $top_item = item_store($postarray);
1241         $postarray["id"] = $top_item;
1242
1243         if (($top_item == 0) AND ($post->verb == "update")) {
1244                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1245                         dbesc($postarray["title"]),
1246                         dbesc($postarray["body"]),
1247                         dbesc($postarray["edited"]),
1248                         dbesc($postarray["uri"]),
1249                         intval($uid)
1250                         );
1251         }
1252
1253         if ($post->object->objectType == "comment") {
1254
1255                 if ($threadcompletion)
1256                         pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1257
1258                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1259                                 intval($uid)
1260                         );
1261
1262                 if(!count($user))
1263                         return $top_item;
1264
1265                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1266
1267                 if (link_compare($own_id, $postarray['author-link']))
1268                         return $top_item;
1269
1270                 if (!function_exists("check_item_notification")) {
1271                         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1272                                         dbesc($postarray['parent-uri']),
1273                                         intval($uid)
1274                                         );
1275
1276                         if(count($myconv)) {
1277
1278                                 foreach($myconv as $conv) {
1279                                         // now if we find a match, it means we're in this conversation
1280
1281                                         if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_id))
1282                                                 continue;
1283
1284                                         require_once('include/enotify.php');
1285
1286                                         $conv_parent = $conv['parent'];
1287
1288                                         notification(array(
1289                                                 'type'         => NOTIFY_COMMENT,
1290                                                 'notify_flags' => $user[0]['notify-flags'],
1291                                                 'language'     => $user[0]['language'],
1292                                                 'to_name'      => $user[0]['username'],
1293                                                 'to_email'     => $user[0]['email'],
1294                                                 'uid'          => $user[0]['uid'],
1295                                                 'item'         => $postarray,
1296                                                 'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1297                                                 'source_name'  => $postarray['author-name'],
1298                                                 'source_link'  => $postarray['author-link'],
1299                                                 'source_photo' => $postarray['author-avatar'],
1300                                                 'verb'         => ACTIVITY_POST,
1301                                                 'otype'        => 'item',
1302                                                 'parent'       => $conv_parent,
1303                                                 ));
1304
1305                                         // only send one notification
1306                                         break;
1307                                 }
1308                         }
1309                 }
1310         }
1311
1312         return $top_item;
1313 }
1314
1315 function pumpio_fetchinbox(&$a, $uid) {
1316
1317         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1318         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1319         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1320         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1321         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1322         $hostname = get_pconfig($uid, 'pumpio','host');
1323         $username = get_pconfig($uid, "pumpio", "user");
1324
1325         $own_id = "https://".$hostname."/".$username;
1326
1327         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1328                 intval($uid));
1329
1330         $lastitems = q("SELECT `uri` FROM `thread`
1331                         INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1332                         WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1333                         ORDER BY `thread`.`commented` DESC LIMIT 10",
1334                                 dbesc(NETWORK_PUMPIO),
1335                                 intval($uid)
1336                         );
1337
1338         $client = new oauth_client_class;
1339         $client->oauth_version = '1.0a';
1340         $client->authorization_header = true;
1341         $client->url_parameters = false;
1342
1343         $client->client_id = $ckey;
1344         $client->client_secret = $csecret;
1345         $client->access_token = $otoken;
1346         $client->access_token_secret = $osecret;
1347
1348         $last_id = get_pconfig($uid,'pumpio','last_id');
1349
1350         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1351
1352         if ($last_id != "")
1353                 $url .= '?since='.urlencode($last_id);
1354
1355         if (pumpio_reachable($url))
1356                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1357         else
1358                 $success = false;
1359
1360         if ($user->items) {
1361             $posts = array_reverse($user->items);
1362
1363             if (count($posts))
1364                     foreach ($posts as $post) {
1365                             $last_id = $post->id;
1366                             pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1367                     }
1368         }
1369
1370         foreach ($lastitems AS $item)
1371                 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1372
1373         set_pconfig($uid,'pumpio','last_id', $last_id);
1374 }
1375
1376 function pumpio_getallusers(&$a, $uid) {
1377         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1378         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1379         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1380         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1381         $hostname = get_pconfig($uid, 'pumpio','host');
1382         $username = get_pconfig($uid, "pumpio", "user");
1383
1384         $client = new oauth_client_class;
1385         $client->oauth_version = '1.0a';
1386         $client->authorization_header = true;
1387         $client->url_parameters = false;
1388
1389         $client->client_id = $ckey;
1390         $client->client_secret = $csecret;
1391         $client->access_token = $otoken;
1392         $client->access_token_secret = $osecret;
1393
1394         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1395
1396         if (pumpio_reachable($url))
1397                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1398         else
1399                 $success = false;
1400
1401         if ($users->totalItems > count($users->items)) {
1402                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1403
1404                 if (pumpio_reachable($url))
1405                         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1406                 else
1407                         $success = false;
1408         }
1409
1410         foreach ($users->items AS $user)
1411                 pumpio_get_contact($uid, $user);
1412 }
1413
1414 function pumpio_queue_hook(&$a,&$b) {
1415
1416         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1417                 dbesc(NETWORK_PUMPIO)
1418         );
1419         if(! count($qi))
1420                 return;
1421
1422         require_once('include/queue_fn.php');
1423
1424         foreach($qi as $x) {
1425                 if($x['network'] !== NETWORK_PUMPIO)
1426                         continue;
1427
1428                 logger('pumpio_queue: run');
1429
1430                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
1431                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1432                         intval($x['cid'])
1433                 );
1434                 if(! count($r))
1435                         continue;
1436
1437                 $userdata = $r[0];
1438
1439                 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1440
1441                 $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token");
1442                 $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret");
1443                 $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key");
1444                 $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret");
1445
1446                 $host = get_pconfig($userdata['uid'], "pumpio", "host");
1447                 $user = get_pconfig($userdata['uid'], "pumpio", "user");
1448
1449                 $success = false;
1450
1451                 if ($oauth_token AND $oauth_token_secret AND
1452                         $consumer_key AND $consumer_secret) {
1453                         $username = $user.'@'.$host;
1454
1455                         logger('pumpio_queue: able to post for user '.$username);
1456
1457                         $z = unserialize($x['content']);
1458
1459                         $client = new oauth_client_class;
1460                         $client->oauth_version = '1.0a';
1461                         $client->url_parameters = false;
1462                         $client->authorization_header = true;
1463                         $client->access_token = $oauth_token;
1464                         $client->access_token_secret = $oauth_token_secret;
1465                         $client->client_id = $consumer_key;
1466                         $client->client_secret = $consumer_secret;
1467
1468                         if (pumpio_reachable($z['url']))
1469                                 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1470                         else
1471                                 $success = false;
1472
1473                         if($success) {
1474                                 $post_id = $user->object->id;
1475                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1476                                 if($post_id AND $iscomment) {
1477                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1478                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1479                                                 dbesc($post_id),
1480                                                 intval($z['item'])
1481                                         );
1482                                 }
1483                                 remove_queue_item($x['id']);
1484                         } else
1485                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1486                 } else
1487                         logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1488
1489                 if (!$success) {
1490                         logger('pumpio_queue: delayed');
1491                         update_queue_time($x['id']);
1492                 }
1493         }
1494 }
1495
1496 function pumpio_getreceiver(&$a, $b) {
1497
1498         $receiver = array();
1499
1500         if (!$b["private"]) {
1501
1502                 if(! strstr($b['postopts'],'pumpio'))
1503                         return $receiver;
1504
1505                 $public = get_pconfig($b['uid'], "pumpio", "public");
1506
1507                 if ($public)
1508                         $receiver["to"][] = Array(
1509                                                 "objectType" => "collection",
1510                                                 "id" => "http://activityschema.org/collection/public");
1511         } else {
1512                 $cids = explode("><", $b["allow_cid"]);
1513                 $gids = explode("><", $b["allow_gid"]);
1514
1515                 foreach ($cids AS $cid) {
1516                         $cid = trim($cid, " <>");
1517
1518                         $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",
1519                                 intval($cid),
1520                                 intval($b["uid"]),
1521                                 dbesc(NETWORK_PUMPIO)
1522                                 );
1523
1524                         if (count($r)) {
1525                                 $receiver["bcc"][] = Array(
1526                                                         "displayName" => $r[0]["name"],
1527                                                         "objectType" => "person",
1528                                                         "preferredUsername" => $r[0]["nick"],
1529                                                         "url" => $r[0]["url"]);
1530                         }
1531                 }
1532                 foreach ($gids AS $gid) {
1533                         $gid = trim($gid, " <>");
1534
1535                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1536                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1537                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1538                                         intval($gid),
1539                                         intval($b["uid"]),
1540                                         dbesc(NETWORK_PUMPIO)
1541                                 );
1542
1543                         foreach ($r AS $row)
1544                                 $receiver["bcc"][] = Array(
1545                                                         "displayName" => $row["name"],
1546                                                         "objectType" => "person",
1547                                                         "preferredUsername" => $row["nick"],
1548                                                         "url" => $row["url"]);
1549                 }
1550         }
1551
1552         if ($b["inform"] != "") {
1553
1554                 $inform = explode(",", $b["inform"]);
1555
1556                 foreach ($inform AS $cid) {
1557                         if (substr($cid, 0, 4) != "cid:")
1558                                 continue;
1559
1560                         $cid = str_replace("cid:", "", $cid);
1561
1562                         $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",
1563                                 intval($cid),
1564                                 intval($b["uid"]),
1565                                 dbesc(NETWORK_PUMPIO)
1566                                 );
1567
1568                         if (count($r)) {
1569                                         $receiver["to"][] = Array(
1570                                                                 "displayName" => $r[0]["name"],
1571                                                                 "objectType" => "person",
1572                                                                 "preferredUsername" => $r[0]["nick"],
1573                                                                 "url" => $r[0]["url"]);
1574                         }
1575                 }
1576         }
1577
1578         return $receiver;
1579 }
1580
1581 function pumpio_fetchallcomments(&$a, $uid, $id) {
1582         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1583         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1584         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1585         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1586         $hostname = get_pconfig($uid, 'pumpio','host');
1587         $username = get_pconfig($uid, "pumpio", "user");
1588
1589         logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1590
1591         $own_id = "https://".$hostname."/".$username;
1592
1593         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1594                 intval($uid));
1595
1596         // Fetching the original post
1597         $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1598                         dbesc($id),
1599                         intval($uid)
1600                 );
1601
1602         if (!count($r))
1603                 return false;
1604
1605         $url = $r[0]["extid"];
1606
1607         $client = new oauth_client_class;
1608         $client->oauth_version = '1.0a';
1609         $client->authorization_header = true;
1610         $client->url_parameters = false;
1611
1612         $client->client_id = $ckey;
1613         $client->client_secret = $csecret;
1614         $client->access_token = $otoken;
1615         $client->access_token_secret = $osecret;
1616
1617         logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1618
1619         if (pumpio_reachable($url))
1620                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1621         else
1622                 $success = false;
1623
1624         if (!$success)
1625                 return;
1626
1627         if ($item->likes->totalItems != 0) {
1628                 foreach ($item->likes->items AS $post) {
1629                         $like = new stdClass;
1630                         $like->object = new stdClass;
1631                         $like->object->id = $item->id;
1632                         $like->actor = new stdClass;
1633                         $like->actor->displayName = $item->displayName;
1634                         $like->actor->preferredUsername = $item->preferredUsername;
1635                         $like->actor->url = $item->url;
1636                         $like->actor->image = $item->image;
1637                         $like->generator = new stdClass;
1638                         $like->generator->displayName = "pumpio";
1639                         pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1640                 }
1641         }
1642
1643         if ($item->replies->totalItems == 0)
1644                 return;
1645
1646         foreach ($item->replies->items AS $item) {
1647                 if ($item->id == $id)
1648                         continue;
1649
1650                 // Checking if the comment already exists - Two queries for speed issues
1651                 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1652                                 dbesc($item->id),
1653                                 intval($uid)
1654                         );
1655
1656                 if (count($r))
1657                         continue;
1658
1659                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1660                                 dbesc($item->id),
1661                                 intval($uid)
1662                         );
1663
1664                 if (count($r))
1665                         continue;
1666
1667                 $post = new stdClass;
1668                 $post->verb = "post";
1669                 $post->actor = $item->author;
1670                 $post->published = $item->published;
1671                 $post->received = $item->updated;
1672                 $post->generator = new stdClass;
1673                 $post->generator->displayName = "pumpio";
1674                 // To-Do: Check for public post
1675
1676                 unset($item->author);
1677                 unset($item->published);
1678                 unset($item->updated);
1679
1680                 $post->object = $item;
1681
1682                 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1683                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1684         }
1685 }
1686
1687
1688 function pumpio_reachable($url) {
1689         $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
1690         return(intval($data['return_code']) != 0);
1691 }
1692
1693 /*
1694 To-Do:
1695  - edit own notes
1696  - delete own notes
1697 */