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