]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
Merge pull request #170 from tobiasd/20131220-public_server
[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 Post Settings') . '</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 Post Settings') . '</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);
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 * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
884                 intval($uid), dbesc($contact->url));
885
886         if(!count($r)) {
887                 // create contact record
888                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
889                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
890                                         `writable`, `blocked`, `readonly`, `pending` )
891                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
892                         intval($uid),
893                         dbesc(datetime_convert()),
894                         dbesc($contact->url),
895                         dbesc(normalise_link($contact->url)),
896                         dbesc(str_replace("acct:", "", $contact->id)),
897                         dbesc(''),
898                         dbesc($contact->id), // What is it for?
899                         dbesc('pump.io ' . $contact->id), // What is it for?
900                         dbesc($contact->displayName),
901                         dbesc($contact->preferredUsername),
902                         dbesc($contact->image->url),
903                         dbesc(NETWORK_PUMPIO),
904                         intval(CONTACT_IS_FRIEND),
905                         intval(1),
906                         intval(1)
907                 );
908
909                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
910                         dbesc($contact->url),
911                         intval($uid)
912                         );
913
914                 if(! count($r))
915                         return(false);
916
917                 $contact_id  = $r[0]['id'];
918
919                 $g = q("select def_gid from user where uid = %d limit 1",
920                         intval($uid)
921                 );
922
923                 if($g && intval($g[0]['def_gid'])) {
924                         require_once('include/group.php');
925                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
926                 }
927
928                 require_once("Photo.php");
929
930                 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
931
932                 q("UPDATE `contact` SET `photo` = '%s',
933                                         `thumb` = '%s',
934                                         `micro` = '%s',
935                                         `name-date` = '%s',
936                                         `uri-date` = '%s',
937                                         `avatar-date` = '%s'
938                                 WHERE `id` = %d
939                         ",
940                 dbesc($photos[0]),
941                 dbesc($photos[1]),
942                 dbesc($photos[2]),
943                 dbesc(datetime_convert()),
944                 dbesc(datetime_convert()),
945                 dbesc(datetime_convert()),
946                 intval($contact_id)
947                 );
948         } else {
949                 // update profile photos once every two weeks as we have no notification of when they change.
950
951                 $update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
952
953                 // check that we have all the photos, this has been known to fail on occasion
954
955                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
956                         require_once("Photo.php");
957
958                         $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
959
960                         q("UPDATE `contact` SET `photo` = '%s',
961                                         `thumb` = '%s',
962                                         `micro` = '%s',
963                                         `name-date` = '%s',
964                                         `uri-date` = '%s',
965                                         `avatar-date` = '%s',
966                                         `name` = '%s',
967                                         `nick` = '%s'
968                                         WHERE `id` = %d
969                                 ",
970                         dbesc($photos[0]),
971                         dbesc($photos[1]),
972                         dbesc($photos[2]),
973                         dbesc(datetime_convert()),
974                         dbesc(datetime_convert()),
975                         dbesc(datetime_convert()),
976                         dbesc($contact->displayName),
977                         dbesc($contact->preferredUsername),
978                         intval($r[0]['id'])
979                         );
980                 }
981
982         }
983
984         return($r[0]["id"]);
985 }
986
987 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
988
989         // Two queries for speed issues
990         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
991                                 dbesc($post->object->id),
992                                 intval($uid)
993                 );
994
995         if (count($r))
996                 return drop_item($r[0]["id"], $false);
997
998         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
999                                 dbesc($post->object->id),
1000                                 intval($uid)
1001                 );
1002
1003         if (count($r))
1004                 return drop_item($r[0]["id"], $false);
1005 }
1006
1007 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = false) {
1008         require_once('include/items.php');
1009
1010         if (($post->verb == "like") OR ($post->verb == "favorite"))
1011                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1012
1013         if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
1014                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1015
1016         if ($post->verb == "delete")
1017                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1018
1019         if ($post->verb != "update") {
1020                 // Two queries for speed issues
1021                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1022                                         dbesc($post->object->id),
1023                                         intval($uid)
1024                         );
1025
1026                 if (count($r))
1027                         return false;
1028
1029                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1030                                         dbesc($post->object->id),
1031                                         intval($uid)
1032                         );
1033
1034                 if (count($r))
1035                         return false;
1036         }
1037
1038         // Only handle these three types
1039         if (!strstr("post|share|update", $post->verb))
1040                 return false;
1041
1042         $receiptians = array();
1043         if (@is_array($post->cc))
1044                 $receiptians = array_merge($receiptians, $post->cc);
1045
1046         if (@is_array($post->to))
1047                 $receiptians = array_merge($receiptians, $post->to);
1048
1049         foreach ($receiptians AS $receiver)
1050                 if (is_string($receiver->objectType))
1051                         if ($receiver->id == "http://activityschema.org/collection/public")
1052                                 $public = true;
1053
1054         $postarray = array();
1055         $postarray['gravity'] = 0;
1056         $postarray['uid'] = $uid;
1057         $postarray['wall'] = 0;
1058         $postarray['uri'] = $post->object->id;
1059
1060         if ($post->object->objectType != "comment") {
1061                 $contact_id = pumpio_get_contact($uid, $post->actor);
1062
1063                 if (!$contact_id)
1064                         $contact_id = $self[0]['id'];
1065
1066                 $postarray['parent-uri'] = $post->object->id;
1067         } else {
1068                 $contact_id = 0;
1069
1070                 if(link_compare($post->actor->url, $own_id)) {
1071                         $contact_id = $self[0]['id'];
1072                         $post->actor->displayName = $self[0]['name'];
1073                         $post->actor->url = $self[0]['url'];
1074                         $post->actor->image->url = $self[0]['photo'];
1075                 } else {
1076                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1077                         $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1078                                 dbesc($post->actor->url),
1079                                 intval($uid)
1080                         );
1081
1082                         if(count($r))
1083                                 $contact_id = $r[0]['id'];
1084                         else {
1085                                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1086                                         dbesc($post->actor->url),
1087                                         intval($uid)
1088                                 );
1089
1090                                 if(count($r))
1091                                         $contact_id = $r[0]['id'];
1092                                 else
1093                                         $contact_id = $self[0]['id'];
1094                         }
1095                 }
1096
1097                 $reply = new stdClass;
1098                 $reply->verb = "note";
1099                 $reply->cc = $post->cc;
1100                 $reply->to = $post->to;
1101                 $reply->object = new stdClass;
1102                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1103                 $reply->object->content = $post->object->inReplyTo->content;
1104                 $reply->object->id = $post->object->inReplyTo->id;
1105                 $reply->actor = $post->object->inReplyTo->author;
1106                 $reply->url = $post->object->inReplyTo->url;
1107                 $reply->generator = new stdClass;
1108                 $reply->generator->displayName = "pumpio";
1109                 $reply->published = $post->object->inReplyTo->published;
1110                 $reply->received = $post->object->inReplyTo->updated;
1111                 $reply->url = $post->object->inReplyTo->url;
1112                 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id);
1113
1114                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1115         }
1116
1117         if ($post->object->pump_io->proxyURL)
1118                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1119
1120         $postarray['contact-id'] = $contact_id;
1121         $postarray['verb'] = ACTIVITY_POST;
1122         $postarray['owner-name'] = $post->actor->displayName;
1123         $postarray['owner-link'] = $post->actor->url;
1124         $postarray['owner-avatar'] = $post->actor->image->url;
1125         $postarray['author-name'] = $post->actor->displayName;
1126         $postarray['author-link'] = $post->actor->url;
1127         $postarray['author-avatar'] = $post->actor->image->url;
1128         $postarray['plink'] = $post->object->url;
1129         $postarray['app'] = $post->generator->displayName;
1130         $postarray['body'] = html2bbcode($post->object->content);
1131
1132         if ($post->object->fullImage->url != "")
1133                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1134
1135         if ($post->object->displayName != "")
1136                 $postarray['title'] = $post->object->displayName;
1137
1138         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1139         $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1140         if (!$public) {
1141                 $postarray['private'] = 1;
1142                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1143         }
1144
1145         if ($post->verb == "share") {
1146                 if (!intval(get_config('system','wall-to-wall_share'))) {
1147                         $postarray['body'] = "[share author='".$post->object->author->displayName.
1148                                         "' profile='".$post->object->author->url.
1149                                         "' avatar='".$post->object->author->image->url.
1150                                         "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1151                 } else {
1152                         // Let shares look like wall-to-wall posts
1153                         $postarray['author-name'] = $post->object->author->displayName;
1154                         $postarray['author-link'] = $post->object->author->url;
1155                         $postarray['author-avatar'] = $post->object->author->image->url;
1156                 }
1157         }
1158
1159         if (trim($postarray['body']) == "")
1160                 return false;
1161
1162         $top_item = item_store($postarray);
1163
1164         if (($top_item == 0) AND ($post->verb == "update")) {
1165                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1166                         dbesc($postarray["title"]),
1167                         dbesc($postarray["body"]),
1168                         dbesc($postarray["edited"]),
1169                         dbesc($postarray["uri"]),
1170                         intval($uid)
1171                         );
1172         }
1173
1174         if ($post->object->objectType == "comment") {
1175
1176                 if ($threadcompletion)
1177                         pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1178
1179                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1180                                 intval($uid)
1181                         );
1182
1183                 if(!count($user))
1184                         return $top_item;
1185
1186                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1187
1188                 if (link_compare($own_id, $postarray['author-link']))
1189                         return $top_item;
1190
1191                 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1192                                 dbesc($postarray['parent-uri']),
1193                                 intval($uid)
1194                                 );
1195
1196                 if(count($myconv)) {
1197
1198                         foreach($myconv as $conv) {
1199                                 // now if we find a match, it means we're in this conversation
1200
1201                                 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_id))
1202                                         continue;
1203
1204                                 require_once('include/enotify.php');
1205
1206                                 $conv_parent = $conv['parent'];
1207
1208                                 notification(array(
1209                                         'type'         => NOTIFY_COMMENT,
1210                                         'notify_flags' => $user[0]['notify-flags'],
1211                                         'language'     => $user[0]['language'],
1212                                         'to_name'      => $user[0]['username'],
1213                                         'to_email'     => $user[0]['email'],
1214                                         'uid'          => $user[0]['uid'],
1215                                         'item'         => $postarray,
1216                                         'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1217                                         'source_name'  => $postarray['author-name'],
1218                                         'source_link'  => $postarray['author-link'],
1219                                         'source_photo' => $postarray['author-avatar'],
1220                                         'verb'         => ACTIVITY_POST,
1221                                         'otype'        => 'item',
1222                                         'parent'       => $conv_parent,
1223                                         ));
1224
1225                                 // only send one notification
1226                                 break;
1227                         }
1228                 }
1229         }
1230
1231         return $top_item;
1232 }
1233
1234 function pumpio_fetchinbox(&$a, $uid) {
1235
1236         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1237         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1238         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1239         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1240         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1241         $hostname = get_pconfig($uid, 'pumpio','host');
1242         $username = get_pconfig($uid, "pumpio", "user");
1243
1244         $own_id = "https://".$hostname."/".$username;
1245
1246         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1247                 intval($uid));
1248
1249         $client = new oauth_client_class;
1250         $client->oauth_version = '1.0a';
1251         $client->authorization_header = true;
1252         $client->url_parameters = false;
1253
1254         $client->client_id = $ckey;
1255         $client->client_secret = $csecret;
1256         $client->access_token = $otoken;
1257         $client->access_token_secret = $osecret;
1258
1259         $last_id = get_pconfig($uid,'pumpio','last_id');
1260
1261         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1262
1263         if ($last_id != "")
1264                 $url .= '?since='.urlencode($last_id);
1265
1266         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1267
1268         if ($user->items) {
1269             $posts = array_reverse($user->items);
1270
1271             if (count($posts))
1272                     foreach ($posts as $post) {
1273                             $last_id = $post->id;
1274                             pumpio_dopost($a, $client, $uid, $self, $post, $own_id);
1275                     }
1276         }
1277
1278         set_pconfig($uid,'pumpio','last_id', $last_id);
1279 }
1280
1281 function pumpio_getallusers(&$a, $uid) {
1282         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1283         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1284         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1285         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1286         $hostname = get_pconfig($uid, 'pumpio','host');
1287         $username = get_pconfig($uid, "pumpio", "user");
1288
1289         $client = new oauth_client_class;
1290         $client->oauth_version = '1.0a';
1291         $client->authorization_header = true;
1292         $client->url_parameters = false;
1293
1294         $client->client_id = $ckey;
1295         $client->client_secret = $csecret;
1296         $client->access_token = $otoken;
1297         $client->access_token_secret = $osecret;
1298
1299         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1300
1301         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1302
1303         if ($users->totalItems > count($users->items)) {
1304                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1305
1306                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1307         }
1308
1309         foreach ($users->items AS $user)
1310                 echo pumpio_get_contact($uid, $user)."\n";
1311 }
1312
1313 function pumpio_queue_hook(&$a,&$b) {
1314
1315         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1316                 dbesc(NETWORK_PUMPIO)
1317         );
1318         if(! count($qi))
1319                 return;
1320
1321         require_once('include/queue_fn.php');
1322
1323         foreach($qi as $x) {
1324                 if($x['network'] !== NETWORK_PUMPIO)
1325                         continue;
1326
1327                 logger('pumpio_queue: run');
1328
1329                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
1330                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1331                         intval($x['cid'])
1332                 );
1333                 if(! count($r))
1334                         continue;
1335
1336                 $userdata = $r[0];
1337
1338                 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1339
1340                 $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token");
1341                 $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret");
1342                 $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key");
1343                 $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret");
1344
1345                 $host = get_pconfig($userdata['uid'], "pumpio", "host");
1346                 $user = get_pconfig($userdata['uid'], "pumpio", "user");
1347
1348                 $success = false;
1349
1350                 if ($oauth_token AND $oauth_token_secret AND
1351                         $consumer_key AND $consumer_secret) {
1352                         $username = $user.'@'.$host;
1353
1354                         logger('pumpio_queue: able to post for user '.$username);
1355
1356                         $z = unserialize($x['content']);
1357
1358                         $client = new oauth_client_class;
1359                         $client->oauth_version = '1.0a';
1360                         $client->url_parameters = false;
1361                         $client->authorization_header = true;
1362                         $client->access_token = $oauth_token;
1363                         $client->access_token_secret = $oauth_token_secret;
1364                         $client->client_id = $consumer_key;
1365                         $client->client_secret = $consumer_secret;
1366
1367                         $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1368
1369                         if($success) {
1370                                 $post_id = $user->object->id;
1371                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1372                                 if($post_id AND $iscomment) {
1373                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1374                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1375                                                 dbesc($post_id),
1376                                                 intval($z['item'])
1377                                         );
1378                                 }
1379                                 remove_queue_item($x['id']);
1380                         } else
1381                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1382                 } else
1383                         logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1384
1385                 if (!$success) {
1386                         logger('pumpio_queue: delayed');
1387                         update_queue_time($x['id']);
1388                 }
1389         }
1390 }
1391
1392 function pumpio_getreceiver(&$a, $b) {
1393
1394         $receiver = array();
1395
1396         if (!$b["private"]) {
1397
1398                 if(! strstr($b['postopts'],'pumpio'))
1399                         return $receiver;
1400
1401                 $public = get_pconfig($b['uid'], "pumpio", "public");
1402
1403                 if ($public)
1404                         $receiver["to"][] = Array(
1405                                                 "objectType" => "collection",
1406                                                 "id" => "http://activityschema.org/collection/public");
1407         } else {
1408                 $cids = explode("><", $b["allow_cid"]);
1409                 $gids = explode("><", $b["allow_gid"]);
1410
1411                 foreach ($cids AS $cid) {
1412                         $cid = trim($cid, " <>");
1413
1414                         $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",
1415                                 intval($cid),
1416                                 intval($b["uid"]),
1417                                 dbesc(NETWORK_PUMPIO)
1418                                 );
1419
1420                         if (count($r)) {
1421                                 $receiver["bcc"][] = Array(
1422                                                         "displayName" => $r[0]["name"],
1423                                                         "objectType" => "person",
1424                                                         "preferredUsername" => $r[0]["nick"],
1425                                                         "url" => $r[0]["url"]);
1426                         }
1427                 }
1428                 foreach ($gids AS $gid) {
1429                         $gid = trim($gid, " <>");
1430
1431                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1432                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1433                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1434                                         intval($gid),
1435                                         intval($b["uid"]),
1436                                         dbesc(NETWORK_PUMPIO)
1437                                 );
1438
1439                         foreach ($r AS $row)
1440                                 $receiver["bcc"][] = Array(
1441                                                         "displayName" => $row["name"],
1442                                                         "objectType" => "person",
1443                                                         "preferredUsername" => $row["nick"],
1444                                                         "url" => $row["url"]);
1445                 }
1446         }
1447
1448         if ($b["inform"] != "") {
1449
1450                 $inform = explode(",", $b["inform"]);
1451
1452                 foreach ($inform AS $cid) {
1453                         if (substr($cid, 0, 4) != "cid:")
1454                                 continue;
1455
1456                         $cid = str_replace("cid:", "", $cid);
1457
1458                         $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",
1459                                 intval($cid),
1460                                 intval($b["uid"]),
1461                                 dbesc(NETWORK_PUMPIO)
1462                                 );
1463
1464                         if (count($r)) {
1465                                         $receiver["to"][] = Array(
1466                                                                 "displayName" => $r[0]["name"],
1467                                                                 "objectType" => "person",
1468                                                                 "preferredUsername" => $r[0]["nick"],
1469                                                                 "url" => $r[0]["url"]);
1470                         }
1471                 }
1472         }
1473
1474         return $receiver;
1475 }
1476
1477 function pumpio_fetchallcomments(&$a, $uid, $id) {
1478         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1479         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1480         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1481         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1482         $hostname = get_pconfig($uid, 'pumpio','host');
1483         $username = get_pconfig($uid, "pumpio", "user");
1484
1485         $own_id = "https://".$hostname."/".$username;
1486
1487         logger("pumpio_fetchallcomments: completing comment for user ".$uid." url ".$url);
1488
1489         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1490                 intval($uid));
1491
1492         // Fetching the original post - Two queries for speed issues
1493         $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1494                         dbesc($url),
1495                         intval($uid)
1496                 );
1497
1498         if (!count($r)) {
1499                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1500                                 dbesc($url),
1501                                 intval($uid)
1502                         );
1503
1504                 if (!count($r))
1505                         return false;
1506         }
1507
1508         if ($r[0]["extid"])
1509                 $url = $r[0]["extid"];
1510         else
1511                 $url = $id;
1512
1513         $client = new oauth_client_class;
1514         $client->oauth_version = '1.0a';
1515         $client->authorization_header = true;
1516         $client->url_parameters = false;
1517
1518         $client->client_id = $ckey;
1519         $client->client_secret = $csecret;
1520         $client->access_token = $otoken;
1521         $client->access_token_secret = $osecret;
1522
1523         logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1524
1525         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1526
1527         if (!$success)
1528                 return;
1529
1530         if ($item->replies->totalItems == 0)
1531                 return;
1532
1533         foreach ($item->replies->items AS $item) {
1534                 if ($item->id == $id)
1535                         continue;
1536
1537                 // Checking if the comment already exists - Two queries for speed issues
1538                 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1539                                 dbesc($url),
1540                                 intval($uid)
1541                         );
1542
1543                 if (count($r))
1544                         continue;
1545
1546                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1547                                 dbesc($url),
1548                                 intval($uid)
1549                         );
1550
1551                 if (count($r))
1552                         continue;
1553
1554                 $post->verb = "post";
1555                 $post->actor = $item->author;
1556                 $post->published = $item->published;
1557                 $post->received = $item->updated;
1558                 $post->generator->displayName = "pumpio";
1559
1560                 unset($item->author);
1561                 unset($item->published);
1562                 unset($item->updated);
1563
1564                 $post->object = $item;
1565
1566                 logger("pumpio_fetchallcomments: posting comment ".$post->object->id);
1567                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1568         }
1569 }
1570
1571 /*
1572 Bugs:
1573  - refresh after post doesn't always happen
1574
1575 To-Do:
1576  - edit own notes
1577  - delete own notes
1578
1579 */