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