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