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