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