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