]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
pumpio: PHP fixes for 5.4 not warn all time
[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                         header("Location: ".$a->get_baseurl()."/pumpio/connect");
321                 }
322         }
323 }
324
325 function pumpio_post_local(&$a,&$b) {
326
327         if((! local_user()) || (local_user() != $b['uid']))
328                 return;
329
330         $pumpio_post   = intval(get_pconfig(local_user(),'pumpio','post'));
331
332         $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
333
334         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
335                 $pumpio_enable = 1;
336
337         if(! $pumpio_enable)
338                 return;
339
340         if(strlen($b['postopts']))
341                 $b['postopts'] .= ',';
342
343         $b['postopts'] .= 'pumpio';
344 }
345
346
347
348
349 function pumpio_send(&$a,&$b) {
350
351         if (!get_pconfig($b["uid"],'pumpio','import')) {
352                 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
353                         return;
354         }
355
356         logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
357
358         if($b['parent'] != $b['id']) {
359                 // Looking if its a reply to a pumpio post
360                 $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",
361                         intval($b["parent"]),
362                         intval($b["uid"]),
363                         dbesc(NETWORK_PUMPIO));
364
365                 if(!count($r)) {
366                         logger("pumpio_send: no pumpio post ".$b["parent"]);
367                         return;
368                 } else {
369                         $iscomment = true;
370                         $orig_post = $r[0];
371                 }
372         } else {
373                 $iscomment = false;
374
375                 $receiver = pumpio_getreceiver($a, $b);
376
377                 logger("pumpio_send: receiver ".print_r($receiver, true));
378
379                 if (!count($receiver) AND ($b['private'] OR !strstr($b['postopts'],'pumpio')))
380                         return;
381         }
382
383         if($b['verb'] == ACTIVITY_LIKE) {
384                 if ($b['deleted'])
385                         pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
386                 else
387                         pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
388                 return;
389         }
390
391         if($b['verb'] == ACTIVITY_DISLIKE)
392                 return;
393
394         if (($b['verb'] == ACTIVITY_POST) AND ($b['created'] !== $b['edited']) AND !$b['deleted'])
395                         pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
396
397         if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
398                         pumpio_action($a, $b["uid"], $b["uri"], "delete");
399
400         if($b['deleted'] || ($b['created'] !== $b['edited']))
401                 return;
402
403         // if post comes from pump.io don't send it back
404         if($b['app'] == "pump.io")
405                 return;
406
407
408         $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
409         $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
410         $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
411         $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
412
413         $host = get_pconfig($b['uid'], "pumpio", "host");
414         $user = get_pconfig($b['uid'], "pumpio", "user");
415         $public = get_pconfig($b['uid'], "pumpio", "public");
416
417         if($oauth_token && $oauth_token_secret) {
418
419                 require_once('include/bbcode.php');
420
421                 $title = trim($b['title']);
422
423                 if ($title != '')
424                         $title = "<h4>".$title."</h4>";
425
426                 $content = bbcode($b['body'], false, false);
427
428                 // Enhance the way, videos are displayed
429                 $content = preg_replace('/<a.*?href="(https?:\/\/www.youtube.com\/.*?)".*?>(.*?)<\/a>/ism',"\n[url]$1[/url]\n",$content);
430                 $content = preg_replace('/<a.*?href="(https?:\/\/youtu.be\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
431                 $content = preg_replace('/<a.*?href="(https?:\/\/vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
432                 $content = preg_replace('/<a.*?href="(https?:\/\/player.vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
433
434                 $URLSearchString = "^\[\]";
435                 $content = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$content);
436
437                 $params = array();
438
439                 $params["verb"] = "post";
440
441                 if (!$iscomment) {
442                         $params["object"] = array(
443                                                 'objectType' => "note",
444                                                 'content' => $title.$content);
445
446                         if (count($receiver["to"]))
447                                 $params["to"] = $receiver["to"];
448
449                         if (count($receiver["bto"]))
450                                 $params["bto"] = $receiver["bto"];
451
452                         if (count($receiver["cc"]))
453                                 $params["cc"] = $receiver["cc"];
454
455                         if (count($receiver["bcc"]))
456                                 $params["bcc"] = $receiver["bcc"];
457
458                  } else {
459                         $inReplyTo = array("id" => $orig_post["uri"],
460                                         "objectType" => "note");
461
462                         $params["object"] = array(
463                                                 'objectType' => "comment",
464                                                 'content' => $title.$content,
465                                                 'inReplyTo' => $inReplyTo);
466                 }
467
468                 $client = new oauth_client_class;
469                 $client->oauth_version = '1.0a';
470                 $client->url_parameters = false;
471                 $client->authorization_header = true;
472                 $client->access_token = $oauth_token;
473                 $client->access_token_secret = $oauth_token_secret;
474                 $client->client_id = $consumer_key;
475                 $client->client_secret = $consumer_secret;
476
477                 $username = $user.'@'.$host;
478                 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
479
480                 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
481
482                 if($success) {
483                         $post_id = $user->object->id;
484                         logger('pumpio_send '.$username.': success '.$post_id);
485                         if($post_id AND $iscomment) {
486                                 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
487                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
488                                         dbesc($post_id),
489                                         intval($b['id'])
490                                 );
491                         }
492                 } else {
493                         logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
494
495                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
496                         if (count($r))
497                                 $a->contact = $r[0]["id"];
498
499                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
500                         require_once('include/queue_fn.php');
501                         add_to_queue($a->contact,NETWORK_PUMPIO,$s);
502                         notice(t('Pump.io post failed. Queued for retry.').EOL);
503                 }
504
505         }
506 }
507
508 function pumpio_action(&$a, $uid, $uri, $action, $content) {
509
510         // Don't do likes and other stuff if you don't import the timeline
511         if (!get_pconfig($uid,'pumpio','import'))
512                 return;
513
514         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
515         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
516         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
517         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
518         $hostname = get_pconfig($uid, 'pumpio','host');
519         $username = get_pconfig($uid, "pumpio", "user");
520
521         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
522                                 dbesc($uri),
523                                 intval($uid)
524         );
525
526         if (!count($r))
527                 return;
528
529         $orig_post = $r[0];
530
531         if ($orig_post["extid"] AND !strstr($orig_post["extid"], "/proxy/"))
532                 $uri = $orig_post["extid"];
533         else
534                 $uri = $orig_post["uri"];
535
536         if (strstr($uri, "/api/comment/"))
537                 $objectType = "comment";
538         elseif (strstr($uri, "/api/note/"))
539                 $objectType = "note";
540         elseif (strstr($uri, "/api/image/"))
541                 $objectType = "image";
542
543         $params["verb"] = $action;
544         $params["object"] = array('id' => $uri,
545                                 "objectType" => $objectType,
546                                 "content" => $content);
547
548         $client = new oauth_client_class;
549         $client->oauth_version = '1.0a';
550         $client->authorization_header = true;
551         $client->url_parameters = false;
552
553         $client->client_id = $ckey;
554         $client->client_secret = $csecret;
555         $client->access_token = $otoken;
556         $client->access_token_secret = $osecret;
557
558         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
559
560         $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
561
562         if($success)
563                 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
564         else {
565                 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
566
567                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
568                 if (count($r))
569                         $a->contact = $r[0]["id"];
570
571                 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
572                 require_once('include/queue_fn.php');
573                 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
574                 notice(t('Pump.io like failed. Queued for retry.').EOL);
575         }
576 }
577
578
579 function pumpio_cron(&$a,$b) {
580         $last = get_config('pumpio','last_poll');
581
582         $poll_interval = intval(get_config('pumpio','poll_interval'));
583         if(! $poll_interval)
584                 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
585
586         if($last) {
587                 $next = $last + ($poll_interval * 60);
588                 if($next > time()) {
589                         logger('pumpio: poll intervall not reached');
590                         return;
591                 }
592         }
593         logger('pumpio: cron_start');
594
595         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
596         if(count($r)) {
597                 foreach($r as $rr) {
598                         logger('pumpio: mirroring user '.$rr['uid']);
599                         pumpio_fetchtimeline($a, $rr['uid']);
600                 }
601         }
602
603         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
604         if(count($r)) {
605                 foreach($r as $rr) {
606                         logger('pumpio: importing timeline from user '.$rr['uid']);
607                         pumpio_fetchinbox($a, $rr['uid']);
608
609                         // check for new contacts once a day
610                         $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check');
611                         if($last_contact_check)
612                                 $next_contact_check = $last_contact_check + 86400;
613                         else
614                                 $next_contact_check = 0;
615
616                         if($next_contact_check <= time()) {
617                                 pumpio_getallusers($a, $rr["uid"]);
618                                 set_pconfig($rr['uid'],'pumpio','contact_check',time());
619                         }
620                 }
621         }
622
623         logger('pumpio: cron_end');
624
625         set_config('pumpio','last_poll', time());
626 }
627
628 function pumpio_fetchtimeline(&$a, $uid) {
629         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
630         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
631         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
632         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
633         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
634         $hostname = get_pconfig($uid, 'pumpio','host');
635         $username = get_pconfig($uid, "pumpio", "user");
636
637         $application_name  = get_config('pumpio', 'application_name');
638
639         if ($application_name == "")
640                 $application_name = $a->get_hostname();
641
642         $first_time = ($lastdate == "");
643
644         $client = new oauth_client_class;
645         $client->oauth_version = '1.0a';
646         $client->authorization_header = true;
647         $client->url_parameters = false;
648
649         $client->client_id = $ckey;
650         $client->client_secret = $csecret;
651         $client->access_token = $otoken;
652         $client->access_token_secret = $osecret;
653
654         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
655
656         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
657
658         $username = $user.'@'.$host;
659
660         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
661
662         if (!$success) {
663                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
664                 return;
665         }
666
667         $posts = array_reverse($user->items);
668
669         $initiallastdate = $lastdate;
670         $lastdate = '';
671
672         if (count($posts)) {
673                 foreach ($posts as $post) {
674                         if ($post->generator->published <= $initiallastdate)
675                                 continue;
676
677                         if ($lastdate < $post->generator->published)
678                                 $lastdate = $post->generator->published;
679
680                         if ($first_time)
681                                 continue;
682
683                         $receiptians = array();
684                         if (@is_array($post->cc))
685                                 $receiptians = array_merge($receiptians, $post->cc);
686
687                         if (@is_array($post->to))
688                                 $receiptians = array_merge($receiptians, $post->to);
689
690                         $public = false;
691                         foreach ($receiptians AS $receiver)
692                                 if (is_string($receiver->objectType))
693                                         if ($receiver->id == "http://activityschema.org/collection/public")
694                                                 $public = true;
695
696                         if ($public AND !strstr($post->generator->displayName, $application_name)) {
697                                 require_once('include/html2bbcode.php');
698
699                                 $_SESSION["authenticated"] = true;
700                                 $_SESSION["uid"] = $uid;
701
702                                 unset($_REQUEST);
703                                 $_REQUEST["type"] = "wall";
704                                 $_REQUEST["api_source"] = true;
705                                 $_REQUEST["profile_uid"] = $uid;
706                                 $_REQUEST["source"] = "pump.io";
707
708                                 if ($post->object->displayName != "")
709                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
710                                 else
711                                         $_REQUEST["title"] = "";
712
713                                 $_REQUEST["body"] = html2bbcode($post->object->content);
714
715                                 if ($post->object->fullImage->url != "")
716                                         $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
717
718                                 logger('pumpio: posting for user '.$uid);
719
720                                 require_once('mod/item.php');
721
722                                 item_post($a);
723                                 logger('pumpio: posting done - user '.$uid);
724                         }
725                 }
726         }
727
728         if ($lastdate != 0)
729                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
730 }
731
732 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
733         // Searching for the unliked post
734         // Two queries for speed issues
735         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
736                                 dbesc($post->object->id),
737                                 intval($uid)
738                 );
739
740         if (count($r))
741                 $orig_post = $r[0];
742         else {
743                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
744                                         dbesc($post->object->id),
745                                         intval($uid)
746                         );
747
748                 if (!count($r))
749                         return;
750                 else
751                         $orig_post = $r[0];
752         }
753
754         $contactid = 0;
755
756         if(link_compare($post->actor->url, $own_id)) {
757                 $contactid = $self[0]['id'];
758         } else {
759                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
760                         dbesc($post->actor->url),
761                         intval($uid)
762                 );
763
764                 if(count($r))
765                         $contactid = $r[0]['id'];
766
767                 if($contactid == 0)
768                         $contactid = $orig_post['contact-id'];
769         }
770
771         $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'",
772                 dbesc(datetime_convert()),
773                 dbesc(ACTIVITY_LIKE),
774                 intval($uid),
775                 intval($contactid),
776                 dbesc($orig_post['uri'])
777         );
778
779         if(count($r))
780                 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
781         else
782                 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
783 }
784
785 function pumpio_dolike(&$a, $uid, $self, $post, $own_id) {
786
787         // Searching for the liked post
788         // Two queries for speed issues
789         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
790                                 dbesc($post->object->id),
791                                 intval($uid)
792                 );
793
794         if (count($r))
795                 $orig_post = $r[0];
796         else {
797                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
798                                         dbesc($post->object->id),
799                                         intval($uid)
800                         );
801
802                 if (!count($r))
803                         return;
804                 else
805                         $orig_post = $r[0];
806         }
807
808         $contactid = 0;
809
810         if(link_compare($post->actor->url, $own_id)) {
811                 $contactid = $self[0]['id'];
812                 $post->actor->displayName = $self[0]['name'];
813                 $post->actor->url = $self[0]['url'];
814                 $post->actor->image->url = $self[0]['photo'];
815         } else {
816                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
817                         dbesc($post->actor->url),
818                         intval($uid)
819                 );
820
821                 if(count($r))
822                         $contactid = $r[0]['id'];
823
824                 if($contactid == 0)
825                         $contactid = $orig_post['contact-id'];
826         }
827
828         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
829                 dbesc(ACTIVITY_LIKE),
830                 intval($uid),
831                 intval($contactid),
832                 dbesc($orig_post['uri'])
833         );
834
835         if(count($r)) {
836                 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
837                 return;
838         }
839
840         $likedata = array();
841         $likedata['parent'] = $orig_post['id'];
842         $likedata['verb'] = ACTIVITY_LIKE;
843         $likedata['gravity'] = 3;
844         $likedata['uid'] = $uid;
845         $likedata['wall'] = 0;
846         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
847         $likedata['parent-uri'] = $orig_post["uri"];
848         $likedata['contact-id'] = $contactid;
849         $likedata['app'] = $post->generator->displayName;
850         $likedata['verb'] = ACTIVITY_LIKE;
851         $likedata['author-name'] = $post->actor->displayName;
852         $likedata['author-link'] = $post->actor->url;
853         $likedata['author-avatar'] = $post->actor->image->url;
854
855         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
856         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
857         $post_type = t('status');
858         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
859         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
860
861         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
862
863         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
864                 '<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>';
865
866         $ret = item_store($likedata);
867
868         logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
869 }
870
871 function pumpio_get_contact($uid, $contact) {
872
873         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
874                 intval($uid), dbesc($contact->url));
875
876         if(!count($r)) {
877                 // create contact record
878                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
879                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
880                                         `writable`, `blocked`, `readonly`, `pending` )
881                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
882                         intval($uid),
883                         dbesc(datetime_convert()),
884                         dbesc($contact->url),
885                         dbesc(normalise_link($contact->url)),
886                         dbesc(str_replace("acct:", "", $contact->id)),
887                         dbesc(''),
888                         dbesc($contact->id), // What is it for?
889                         dbesc('pump.io ' . $contact->id), // What is it for?
890                         dbesc($contact->displayName),
891                         dbesc($contact->preferredUsername),
892                         dbesc($contact->image->url),
893                         dbesc(NETWORK_PUMPIO),
894                         intval(CONTACT_IS_FRIEND),
895                         intval(1),
896                         intval(1)
897                 );
898
899                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
900                         dbesc($contact->url),
901                         intval($uid)
902                         );
903
904                 if(! count($r))
905                         return(false);
906
907                 $contact_id  = $r[0]['id'];
908
909                 $g = q("select def_gid from user where uid = %d limit 1",
910                         intval($uid)
911                 );
912
913                 if($g && intval($g[0]['def_gid'])) {
914                         require_once('include/group.php');
915                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
916                 }
917
918                 require_once("Photo.php");
919
920                 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
921
922                 q("UPDATE `contact` SET `photo` = '%s',
923                                         `thumb` = '%s',
924                                         `micro` = '%s',
925                                         `name-date` = '%s',
926                                         `uri-date` = '%s',
927                                         `avatar-date` = '%s'
928                                 WHERE `id` = %d LIMIT 1
929                         ",
930                 dbesc($photos[0]),
931                 dbesc($photos[1]),
932                 dbesc($photos[2]),
933                 dbesc(datetime_convert()),
934                 dbesc(datetime_convert()),
935                 dbesc(datetime_convert()),
936                 intval($contact_id)
937                 );
938         } else {
939                 // update profile photos once every two weeks as we have no notification of when they change.
940
941                 $update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
942
943                 // check that we have all the photos, this has been known to fail on occasion
944
945                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
946                         require_once("Photo.php");
947
948                         $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
949
950                         q("UPDATE `contact` SET `photo` = '%s',
951                                         `thumb` = '%s',
952                                         `micro` = '%s',
953                                         `name-date` = '%s',
954                                         `uri-date` = '%s',
955                                         `avatar-date` = '%s'
956                                         WHERE `id` = %d LIMIT 1
957                                 ",
958                         dbesc($photos[0]),
959                         dbesc($photos[1]),
960                         dbesc($photos[2]),
961                         dbesc(datetime_convert()),
962                         dbesc(datetime_convert()),
963                         dbesc(datetime_convert()),
964                         intval($r[0]['id'])
965                         );
966                 }
967
968         }
969
970         return($r[0]["id"]);
971 }
972
973 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
974
975         // Two queries for speed issues
976         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
977                                 dbesc($post->object->id),
978                                 intval($uid)
979                 );
980
981         if (count($r))
982                 return drop_item($r[0]["id"], $false);
983
984         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
985                                 dbesc($post->object->id),
986                                 intval($uid)
987                 );
988
989         if (count($r))
990                 return drop_item($r[0]["id"], $false);
991 }
992
993 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = false) {
994         require_once('include/items.php');
995
996         if (($post->verb == "like") OR ($post->verb == "favorite"))
997                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
998
999         if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
1000                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1001
1002         if ($post->verb == "delete")
1003                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1004
1005         if ($post->verb != "update") {
1006                 // Two queries for speed issues
1007                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1008                                         dbesc($post->object->id),
1009                                         intval($uid)
1010                         );
1011
1012                 if (count($r))
1013                         return false;
1014
1015                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1016                                         dbesc($post->object->id),
1017                                         intval($uid)
1018                         );
1019
1020                 if (count($r))
1021                         return false;
1022         }
1023
1024         // Only handle these three types
1025         if (!strstr("post|share|update", $post->verb))
1026                 return false;
1027
1028         $receiptians = array();
1029         if (@is_array($post->cc))
1030                 $receiptians = array_merge($receiptians, $post->cc);
1031
1032         if (@is_array($post->to))
1033                 $receiptians = array_merge($receiptians, $post->to);
1034
1035         foreach ($receiptians AS $receiver)
1036                 if (is_string($receiver->objectType))
1037                         if ($receiver->id == "http://activityschema.org/collection/public")
1038                                 $public = true;
1039
1040         $postarray = array();
1041         $postarray['gravity'] = 0;
1042         $postarray['uid'] = $uid;
1043         $postarray['wall'] = 0;
1044         $postarray['uri'] = $post->object->id;
1045
1046         if ($post->object->objectType != "comment") {
1047                 $contact_id = pumpio_get_contact($uid, $post->actor);
1048
1049                 if (!$contact_id)
1050                         $contact_id = $self[0]['id'];
1051
1052                 $postarray['parent-uri'] = $post->object->id;
1053         } else {
1054                 $contact_id = 0;
1055
1056                 if(link_compare($post->actor->url, $own_id)) {
1057                         $contact_id = $self[0]['id'];
1058                         $post->actor->displayName = $self[0]['name'];
1059                         $post->actor->url = $self[0]['url'];
1060                         $post->actor->image->url = $self[0]['photo'];
1061                 } else {
1062                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1063                         $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1064                                 dbesc($post->actor->url),
1065                                 intval($uid)
1066                         );
1067
1068                         if(count($r))
1069                                 $contact_id = $r[0]['id'];
1070                         else {
1071                                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1072                                         dbesc($post->actor->url),
1073                                         intval($uid)
1074                                 );
1075
1076                                 if(count($r))
1077                                         $contact_id = $r[0]['id'];
1078                                 else
1079                                         $contact_id = $self[0]['id'];
1080                         }
1081                 }
1082
1083                 $reply = new stdClass;
1084                 $reply->verb = "note";
1085                 $reply->cc = $post->cc;
1086                 $reply->to = $post->to;
1087                 $reply->object = new stdClass;
1088                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1089                 $reply->object->content = $post->object->inReplyTo->content;
1090                 $reply->object->id = $post->object->inReplyTo->id;
1091                 $reply->actor = $post->object->inReplyTo->author;
1092                 $reply->url = $post->object->inReplyTo->url;
1093                 $reply->generator = new stdClass;
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 */