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