]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
pumpio: Sending posts to selected users
[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_action($a, $b["uid"], $b["thr-parent"], "unlike");
346                 else
347                         pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
348                 return;
349         }
350
351         if($b['verb'] == ACTIVITY_DISLIKE)
352                 return;
353
354         if (($b['verb'] == ACTIVITY_POST) AND ($b['created'] !== $b['edited']) AND !$b['deleted'])
355                         pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
356
357         if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
358                         pumpio_action($a, $b["uid"], $b["uri"], "delete");
359
360         if($b['deleted'] || ($b['created'] !== $b['edited']))
361                 return;
362
363         if($b['parent'] != $b['id']) {
364                 // Looking if its a reply to a pumpio post
365                 $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",
366                         intval($b["parent"]),
367                         intval($b["uid"]),
368                         dbesc(NETWORK_PUMPIO));
369
370                 if(!count($r))
371                         return;
372                 else {
373                         $iscomment = true;
374                         $orig_post = $r[0];
375                 }
376         } else {
377                 $iscomment = false;
378
379                 $receiver = pumpio_getreceiver($a, $b);
380
381                 logger("pumpio_send: receiver ".print_r($receiver, true));
382
383                 if (!count($receiver) AND ($b['private'] OR !strstr($b['postopts'],'pumpio')))
384                         return;
385
386                 //if(! strstr($b['postopts'],'pumpio'))
387                 //      return;
388
389                 //if($b['private'])
390                 //      return;
391         }
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                         //if ($public)
449                         //      $params["to"] = array(Array(
450                         //                              "objectType" => "collection",
451                         //                              "id" => "http://activityschema.org/collection/public"));
452                  } else {
453                         $inReplyTo = array("id" => $orig_post["uri"],
454                                         "objectType" => "note");
455
456                         $params["object"] = array(
457                                                 'objectType' => "comment",
458                                                 'content' => $title.$content,
459                                                 'inReplyTo' => $inReplyTo);
460                 }
461
462                 $client = new oauth_client_class;
463                 $client->oauth_version = '1.0a';
464                 $client->url_parameters = false;
465                 $client->authorization_header = true;
466                 $client->access_token = $oauth_token;
467                 $client->access_token_secret = $oauth_token_secret;
468                 $client->client_id = $consumer_key;
469                 $client->client_secret = $consumer_secret;
470
471                 $username = $user.'@'.$host;
472                 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
473
474                 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
475                 //$success = false;
476
477                 if($success) {
478                         $post_id = $user->object->id;
479                         logger('pumpio_send '.$username.': success '.$post_id);
480                         if($post_id AND $iscomment) {
481                                 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
482                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
483                                         dbesc($post_id),
484                                         intval($b['id'])
485                                 );
486                         }
487                 } else {
488                         logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
489
490                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
491                         if (count($r))
492                                 $a->contact = $r[0]["id"];
493
494                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
495                         require_once('include/queue_fn.php');
496                         add_to_queue($a->contact,NETWORK_PUMPIO,$s);
497                         notice(t('Pump.io post failed. Queued for retry.').EOL);
498                 }
499
500         }
501 }
502
503 function pumpio_action($a, $uid, $uri, $action, $content) {
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"])
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         }
600
601         // To-Do:
602         //pumpio_getallusers($a, $uid);
603
604         logger('pumpio: cron_end');
605
606         set_config('pumpio','last_poll', time());
607 }
608
609 function pumpio_fetchtimeline($a, $uid) {
610         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
611         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
612         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
613         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
614         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
615         $hostname = get_pconfig($uid, 'pumpio','host');
616         $username = get_pconfig($uid, "pumpio", "user");
617
618         $application_name  = get_config('pumpio', 'application_name');
619
620         if ($application_name == "")
621                 $application_name = $a->get_hostname();
622
623         $first_time = ($lastdate == "");
624
625         $client = new oauth_client_class;
626         $client->oauth_version = '1.0a';
627         $client->authorization_header = true;
628         $client->url_parameters = false;
629
630         $client->client_id = $ckey;
631         $client->client_secret = $csecret;
632         $client->access_token = $otoken;
633         $client->access_token_secret = $osecret;
634
635         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
636
637         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
638
639         $username = $user.'@'.$host;
640
641         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
642
643         if (!$success) {
644                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
645                 return;
646         }
647
648         $posts = array_reverse($user->items);
649
650         $initiallastdate = $lastdate;
651         $lastdate = '';
652
653         if (count($posts)) {
654                 foreach ($posts as $post) {
655                         if ($post->generator->published <= $initiallastdate)
656                                 continue;
657
658                         if ($lastdate < $post->generator->published)
659                                 $lastdate = $post->generator->published;
660
661                         if ($first_time)
662                                 continue;
663
664                         $receiptians = array();
665                         if (@is_array($post->cc))
666                                 $receiptians = array_merge($receiptians, $post->cc);
667
668                         if (@is_array($post->to))
669                                 $receiptians = array_merge($receiptians, $post->to);
670
671                         $public = false;
672                         foreach ($receiptians AS $receiver)
673                                 if (is_string($receiver->objectType))
674                                         if ($receiver->id == "http://activityschema.org/collection/public")
675                                                 $public = true;
676
677                         if ($public AND !strstr($post->generator->displayName, $application_name)) {
678                                 require_once('include/html2bbcode.php');
679
680                                 $_SESSION["authenticated"] = true;
681                                 $_SESSION["uid"] = $uid;
682
683                                 unset($_REQUEST);
684                                 $_REQUEST["type"] = "wall";
685                                 $_REQUEST["api_source"] = true;
686                                 $_REQUEST["profile_uid"] = $uid;
687                                 $_REQUEST["source"] = "pump.io";
688
689                                 if ($post->object->displayName != "")
690                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
691                                 else
692                                         $_REQUEST["title"] = "";
693
694                                 $_REQUEST["body"] = html2bbcode($post->object->content);
695
696                                 if ($post->object->fullImage->url != "")
697                                         $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
698
699                                 logger('pumpio: posting for user '.$uid);
700
701                                 require_once('mod/item.php');
702                                 //print_r($_REQUEST);
703                                 item_post($a);
704                                 logger('pumpio: posting done - user '.$uid);
705                         }
706                 }
707         }
708
709         //$lastdate = '2013-05-16T20:22:12Z';
710
711         if ($lastdate != 0)
712                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
713 }
714
715 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
716         // Searching for the unliked post
717         // Two queries for speed issues
718         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
719                                 dbesc($post->object->id),
720                                 intval($uid)
721                 );
722
723         if (count($r))
724                 $orig_post = $r[0];
725         else {
726                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
727                                         dbesc($post->object->id),
728                                         intval($uid)
729                         );
730
731                 if (!count($r))
732                         return;
733                 else
734                         $orig_post = $r[0];
735         }
736
737         $contactid = 0;
738
739         if(link_compare($post->actor->url, $own_id)) {
740                 $contactid = $self[0]['id'];
741         } else {
742                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
743                         dbesc($post->actor->url),
744                         intval($uid)
745                 );
746
747                 if(count($r))
748                         $contactid = $r[0]['id'];
749
750                 if($contactid == 0)
751                         $contactid = $orig_post['contact-id'];
752         }
753
754         $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'",
755                 dbesc(datetime_convert()),
756                 dbesc(ACTIVITY_LIKE),
757                 intval($uid),
758                 intval($contactid),
759                 dbesc($orig_post['uri'])
760         );
761
762         if(count($r))
763                 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
764         else
765                 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
766 }
767
768 function pumpio_dolike(&$a, $uid, $self, $post, $own_id) {
769
770         // Searching for the liked post
771         // Two queries for speed issues
772         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
773                                 dbesc($post->object->id),
774                                 intval($uid)
775                 );
776
777         if (count($r))
778                 $orig_post = $r[0];
779         else {
780                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
781                                         dbesc($post->object->id),
782                                         intval($uid)
783                         );
784
785                 if (!count($r))
786                         return;
787                 else
788                         $orig_post = $r[0];
789         }
790
791         $contactid = 0;
792
793         if(link_compare($post->actor->url, $own_id)) {
794                 $contactid = $self[0]['id'];
795                 $post->actor->displayName = $self[0]['name'];
796                 $post->actor->url = $self[0]['url'];
797                 $post->actor->image->url = $self[0]['photo'];
798         } else {
799                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
800                         dbesc($post->actor->url),
801                         intval($uid)
802                 );
803
804                 if(count($r))
805                         $contactid = $r[0]['id'];
806
807                 if($contactid == 0)
808                         $contactid = $orig_post['contact-id'];
809         }
810
811         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
812                 dbesc(ACTIVITY_LIKE),
813                 intval($uid),
814                 intval($contactid),
815                 dbesc($orig_post['uri'])
816         );
817
818         if(count($r)) {
819                 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
820                 return;
821         }
822
823         $likedata = array();
824         $likedata['parent'] = $orig_post['id'];
825         $likedata['verb'] = ACTIVITY_LIKE;
826         $likedata['gravity'] = 3;
827         $likedata['uid'] = $uid;
828         $likedata['wall'] = 0;
829         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
830         $likedata['parent-uri'] = $orig_post["uri"];
831         $likedata['contact-id'] = $contactid;
832         $likedata['app'] = $post->generator->displayName;
833         $likedata['verb'] = ACTIVITY_LIKE;
834         $likedata['author-name'] = $post->actor->displayName;
835         $likedata['author-link'] = $post->actor->url;
836         $likedata['author-avatar'] = $post->actor->image->url;
837
838         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
839         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
840         $post_type = t('status');
841         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
842         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
843
844         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
845
846         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
847                 '<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>';
848
849         $ret = item_store($likedata);
850
851         logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
852 }
853
854 function pumpio_get_contact($uid, $contact) {
855
856         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
857                 intval($uid), dbesc($contact->url));
858
859         if(!count($r)) {
860                 // create contact record
861                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
862                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
863                                         `writable`, `blocked`, `readonly`, `pending` )
864                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
865                         intval($uid),
866                         dbesc(datetime_convert()),
867                         dbesc($contact->url),
868                         dbesc(normalise_link($contact->url)),
869                         dbesc(str_replace("acct:", "", $contact->id)),
870                         dbesc(''),
871                         dbesc($contact->id), // To-Do?
872                         dbesc('pump.io ' . $contact->id), // To-Do?
873                         dbesc($contact->displayName),
874                         dbesc($contact->preferredUsername),
875                         dbesc($contact->image->url),
876                         dbesc(NETWORK_PUMPIO),
877                         intval(CONTACT_IS_FRIEND),
878                         intval(1),
879                         intval(1)
880                 );
881
882                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
883                         dbesc($contact->url),
884                         intval($uid)
885                         );
886
887                 if(! count($r))
888                         return(false);
889
890                 $contact_id  = $r[0]['id'];
891
892                 $g = q("select def_gid from user where uid = %d limit 1",
893                         intval($uid)
894                 );
895
896                 if($g && intval($g[0]['def_gid'])) {
897                         require_once('include/group.php');
898                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
899                 }
900
901                 require_once("Photo.php");
902
903                 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
904
905                 q("UPDATE `contact` SET `photo` = '%s',
906                                         `thumb` = '%s',
907                                         `micro` = '%s',
908                                         `name-date` = '%s',
909                                         `uri-date` = '%s',
910                                         `avatar-date` = '%s'
911                                 WHERE `id` = %d LIMIT 1
912                         ",
913                 dbesc($photos[0]),
914                 dbesc($photos[1]),
915                 dbesc($photos[2]),
916                 dbesc(datetime_convert()),
917                 dbesc(datetime_convert()),
918                 dbesc(datetime_convert()),
919                 intval($contact_id)
920                 );
921         } else {
922                 // update profile photos once every two weeks as we have no notification of when they change.
923
924                 $update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
925
926                 // check that we have all the photos, this has been known to fail on occasion
927
928                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
929                         require_once("Photo.php");
930
931                         $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
932
933                         q("UPDATE `contact` SET `photo` = '%s',
934                                         `thumb` = '%s',
935                                         `micro` = '%s',
936                                         `name-date` = '%s',
937                                         `uri-date` = '%s',
938                                         `avatar-date` = '%s'
939                                         WHERE `id` = %d LIMIT 1
940                                 ",
941                         dbesc($photos[0]),
942                         dbesc($photos[1]),
943                         dbesc($photos[2]),
944                         dbesc(datetime_convert()),
945                         dbesc(datetime_convert()),
946                         dbesc(datetime_convert()),
947                         intval($r[0]['id'])
948                         );
949                 }
950
951         }
952
953         return($r[0]["id"]);
954 }
955
956 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
957
958         // Two queries for speed issues
959         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
960                                 dbesc($post->object->id),
961                                 intval($uid)
962                 );
963
964         if (count($r)) {
965                 drop_item($r[0]["id"], $false);
966                 return;
967         }
968
969         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
970                                 dbesc($post->object->id),
971                                 intval($uid)
972                 );
973
974         if (count($r)) {
975                 drop_item($r[0]["id"], $false);
976                 return;
977         }
978 }
979
980 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id) {
981         require_once('include/items.php');
982
983         if (($post->verb == "like") OR ($post->verb == "favorite")) {
984                 pumpio_dolike(&$a, $uid, $self, $post, $own_id);
985                 return;
986         }
987
988         if (($post->verb == "unlike") OR ($post->verb == "unfavorite")) {
989                 pumpio_dounlike(&$a, $uid, $self, $post, $own_id);
990                 return;
991         }
992
993         if ($post->verb == "delete") {
994                 pumpio_dodelete(&$a, $uid, $self, $post, $own_id);
995                 return;
996         }
997
998         if ($post->verb != "update") {
999                 // Two queries for speed issues
1000                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1001                                         dbesc($post->object->id),
1002                                         intval($uid)
1003                         );
1004
1005                 if (count($r))
1006                         return;
1007
1008                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1009                                         dbesc($post->object->id),
1010                                         intval($uid)
1011                         );
1012
1013                 if (count($r))
1014                         return;
1015         }
1016
1017         // Only handle these three types
1018         if (!strstr("post|share|update", $post->verb))
1019                 return;
1020
1021         $receiptians = array();
1022         if (@is_array($post->cc))
1023                 $receiptians = array_merge($receiptians, $post->cc);
1024
1025         if (@is_array($post->to))
1026                 $receiptians = array_merge($receiptians, $post->to);
1027
1028         foreach ($receiptians AS $receiver)
1029                 if (is_string($receiver->objectType))
1030                         if ($receiver->id == "http://activityschema.org/collection/public")
1031                                 $public = true;
1032
1033         $postarray = array();
1034         $postarray['gravity'] = 0;
1035         $postarray['uid'] = $uid;
1036         $postarray['wall'] = 0;
1037         $postarray['uri'] = $post->object->id;
1038
1039         if ($post->object->objectType != "comment") {
1040                 $contact_id = pumpio_get_contact($uid, $post->actor);
1041
1042                 if (!$contact_id)
1043                         $contact_id = $self[0]['id'];
1044
1045                 $postarray['parent-uri'] = $post->object->id;
1046         } else {
1047                 $contact_id = 0;
1048
1049                 if(link_compare($post->actor->url, $own_id)) {
1050                         $contact_id = $self[0]['id'];
1051                         $post->actor->displayName = $self[0]['name'];
1052                         $post->actor->url = $self[0]['url'];
1053                         $post->actor->image->url = $self[0]['photo'];
1054                 } else {
1055                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1056                         $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1057                                 dbesc($post->actor->url),
1058                                 intval($uid)
1059                         );
1060
1061                         if(count($r))
1062                                 $contact_id = $r[0]['id'];
1063                         else {
1064                                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1065                                         dbesc($post->actor->url),
1066                                         intval($uid)
1067                                 );
1068
1069                                 if(count($r))
1070                                         $contact_id = $r[0]['id'];
1071                                 else
1072                                         $contact_id = $self[0]['id'];
1073                         }
1074                 }
1075
1076                 $reply->verb = "note";
1077                 $reply->cc = $post->cc;
1078                 $reply->to = $post->to;
1079                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1080                 $reply->object->content = $post->object->inReplyTo->content;
1081                 $reply->object->id = $post->object->inReplyTo->id;
1082                 $reply->actor = $post->object->inReplyTo->author;
1083                 $reply->url = $post->object->inReplyTo->url;
1084                 $reply->generator->displayName = "pumpio";
1085                 $reply->published = $post->object->inReplyTo->published;
1086                 $reply->received = $post->object->inReplyTo->updated;
1087                 $reply->url = $post->object->inReplyTo->url;
1088                 pumpio_dopost(&$a, $client, $uid, $self, $reply, $own_id);
1089
1090                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1091         }
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['location'] = ""
1112         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1113         $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1114         if (!$public) {
1115                 $postarray['private'] = 1;
1116                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1117         }
1118
1119         if ($post->verb == "share") {
1120                 $postarray['body'] = "[share author='".$post->object->author->displayName.
1121                                 "' profile='".$post->object->author->url.
1122                                 "' avatar='".$post->object->author->image->url.
1123                                 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1124         }
1125
1126         if (trim($postarray['body']) == "")
1127                 return;
1128
1129         $top_item = item_store($postarray);
1130
1131         if (($top_item == 0) AND ($post->verb == "update")) {
1132                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1133                         dbesc($postarray["title"]),
1134                         dbesc($postarray["body"]),
1135                         dbesc($postarray["edited"]),
1136                         dbesc($postarray["uri"]),
1137                         intval($uid)
1138                         );
1139         }
1140
1141         if ($post->object->objectType == "comment") {
1142
1143                 $hostname = get_pconfig($uid, 'pumpio','host');
1144                 $username = get_pconfig($uid, "pumpio", "user");
1145
1146                 $foreign_url = "https://".$hostname."/".$username;
1147
1148                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1149                                 intval($uid)
1150                         );
1151
1152                 if(!count($user))
1153                         return;
1154
1155                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1156
1157                 if (link_compare($foreign_url, $postarray['author-link']))
1158                         return;
1159
1160                 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1161                                 dbesc($postarray['parent-uri']),
1162                                 intval($uid)
1163                                 );
1164
1165                 if(count($myconv)) {
1166
1167                         foreach($myconv as $conv) {
1168                                 // now if we find a match, it means we're in this conversation
1169
1170                                 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$foreign_url))
1171                                         continue;
1172
1173                                 require_once('include/enotify.php');
1174
1175                                 $conv_parent = $conv['parent'];
1176
1177                                 notification(array(
1178                                         'type'         => NOTIFY_COMMENT,
1179                                         'notify_flags' => $user[0]['notify-flags'],
1180                                         'language'     => $user[0]['language'],
1181                                         'to_name'      => $user[0]['username'],
1182                                         'to_email'     => $user[0]['email'],
1183                                         'uid'          => $user[0]['uid'],
1184                                         'item'         => $postarray,
1185                                         'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1186                                         'source_name'  => $postarray['author-name'],
1187                                         'source_link'  => $postarray['author-link'],
1188                                         'source_photo' => $postarray['author-avatar'],
1189                                         'verb'         => ACTIVITY_POST,
1190                                         'otype'        => 'item',
1191                                         'parent'       => $conv_parent,
1192                                         ));
1193
1194                                 // only send one notification
1195                                 break;
1196                         }
1197                 }
1198         }
1199 }
1200
1201 function pumpio_fetchinbox($a, $uid) {
1202
1203         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1204         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1205         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1206         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1207         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1208         $hostname = get_pconfig($uid, 'pumpio','host');
1209         $username = get_pconfig($uid, "pumpio", "user");
1210
1211         $own_id = "https://".$hostname."/".$username;
1212
1213         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1214                 intval($uid));
1215
1216         $client = new oauth_client_class;
1217         $client->oauth_version = '1.0a';
1218         $client->authorization_header = true;
1219         $client->url_parameters = false;
1220
1221         $client->client_id = $ckey;
1222         $client->client_secret = $csecret;
1223         $client->access_token = $otoken;
1224         $client->access_token_secret = $osecret;
1225
1226         $last_id = get_pconfig($uid,'pumpio','last_id');
1227
1228         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1229
1230         if ($last_id != "")
1231                 $url .= '?since='.urlencode($last_id);
1232
1233         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1234         $posts = array_reverse($user->items);
1235
1236         if (count($posts))
1237                 foreach ($posts as $post) {
1238                         $last_id = $post->id;
1239                         pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id);
1240                 }
1241
1242         set_pconfig($uid,'pumpio','last_id', $last_id);
1243
1244 /*
1245         // Fetching the minor events
1246         $last_minor_id = get_pconfig($uid,'pumpio','last_minor_id');
1247
1248         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox/minor';
1249
1250         if ($last_minor_id != "")
1251                 $url .= '?since='.urlencode($last_minor_id);
1252
1253         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1254         $posts = array_reverse($user->items);
1255
1256         if (count($posts))
1257                 foreach ($posts as $post) {
1258                         $last_minor_id = $post->id;
1259                         pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id);
1260                 }
1261
1262         set_pconfig($uid,'pumpio','last_minor_id', $last_minor_id);
1263 */
1264 }
1265
1266 function pumpio_getallusers($a, $uid) {
1267         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1268         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1269         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1270         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1271         $hostname = get_pconfig($uid, 'pumpio','host');
1272         $username = get_pconfig($uid, "pumpio", "user");
1273
1274         $client = new oauth_client_class;
1275         $client->oauth_version = '1.0a';
1276         $client->authorization_header = true;
1277         $client->url_parameters = false;
1278
1279         $client->client_id = $ckey;
1280         $client->client_secret = $csecret;
1281         $client->access_token = $otoken;
1282         $client->access_token_secret = $osecret;
1283
1284         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1285
1286         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1287
1288         if ($users->totalItems > count($users->items)) {
1289                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1290
1291                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1292         }
1293
1294         foreach ($users->items AS $user)
1295                 echo pumpio_get_contact($uid, $user)."\n";
1296 }
1297
1298 function pumpio_queue_hook(&$a,&$b) {
1299
1300         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1301                 dbesc(NETWORK_PUMPIO)
1302         );
1303         if(! count($qi))
1304                 return;
1305
1306         require_once('include/queue_fn.php');
1307
1308         foreach($qi as $x) {
1309                 if($x['network'] !== NETWORK_PUMPIO)
1310                         continue;
1311
1312                 logger('pumpio_queue: run');
1313
1314                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
1315                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1316                         intval($x['cid'])
1317                 );
1318                 if(! count($r))
1319                         continue;
1320
1321                 $user = $r[0];
1322
1323                 $oauth_token = get_pconfig($user['uid'], "pumpio", "oauth_token");
1324                 $oauth_token_secret = get_pconfig($user['uid'], "pumpio", "oauth_token_secret");
1325                 $consumer_key = get_pconfig($user['uid'], "pumpio","consumer_key");
1326                 $consumer_secret = get_pconfig($user['uid'], "pumpio","consumer_secret");
1327
1328                 $host = get_pconfig($user['uid'], "pumpio", "host");
1329                 $user = get_pconfig($user['uid'], "pumpio", "user");
1330
1331                 $success = false;
1332
1333                 if ($oauth_token AND $oauth_token_secret AND
1334                         $consumer_key AND $consumer_secret) {
1335                         $username = $user.'@'.$host;
1336
1337                         logger('pumpio_queue: able to post for user '.$username);
1338
1339                         $z = unserialize($x['content']);
1340
1341                         $client = new oauth_client_class;
1342                         $client->oauth_version = '1.0a';
1343                         $client->url_parameters = false;
1344                         $client->authorization_header = true;
1345                         $client->access_token = $oauth_token;
1346                         $client->access_token_secret = $oauth_token_secret;
1347                         $client->client_id = $consumer_key;
1348                         $client->client_secret = $consumer_secret;
1349
1350                         $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1351
1352                         if($success) {
1353                                 $post_id = $user->object->id;
1354                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1355                                 if($post_id AND $iscomment) {
1356                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1357                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
1358                                                 dbesc($post_id),
1359                                                 intval($z['item'])
1360                                         );
1361                                 }
1362                                 remove_queue_item($x['id']);
1363                         } else
1364                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1365                 } else
1366                         logger("pumpio_queue: Error getting tokens for user ".$user['uid']);
1367
1368                 if (!$success) {
1369                         logger('pumpio_queue: delayed');
1370                         update_queue_time($x['id']);
1371                 }
1372         }
1373 }
1374
1375 function pumpio_getreceiver($a, $b) {
1376
1377         $receiver = array();
1378
1379         if (!$b["private"]) {
1380
1381                 if(! strstr($b['postopts'],'pumpio'))
1382                         return $receiver;
1383
1384                 $public = get_pconfig($b['uid'], "pumpio", "public");
1385
1386                 if ($public)
1387                         $receiver["to"][] = Array(
1388                                                 "objectType" => "collection",
1389                                                 "id" => "http://activityschema.org/collection/public");
1390         } else {
1391                 $cids = explode("><", $b["allow_cid"]);
1392                 $gids = explode("><", $b["allow_gid"]);
1393
1394                 foreach ($cids AS $cid) {
1395                         $cid = trim($cid, " <>");
1396
1397                         $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",
1398                                 intval($cid),
1399                                 intval($b["uid"]),
1400                                 dbesc(NETWORK_PUMPIO)
1401                                 );
1402
1403                 if (count($r)) {
1404                                 $receiver["bcc"][] = Array(
1405                                                         "displayName" => $r[0]["name"],
1406                                                         "objectType" => "person",
1407                                                         "preferredUsername" => $r[0]["nick"],
1408                                                         "url" => $r[0]["url"]);
1409                                 }
1410                 }
1411                 foreach ($gids AS $gid) {
1412                         $gid = trim($gid, " <>");
1413
1414                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1415                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1416                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1417                                         intval($gid),
1418                                         intval($b["uid"]),
1419                                         dbesc(NETWORK_PUMPIO)
1420                                 );
1421
1422                         foreach ($r AS $row)
1423                                 $receiver["bcc"][] = Array(
1424                                                         "displayName" => $row["name"],
1425                                                         "objectType" => "person",
1426                                                         "preferredUsername" => $row["nick"],
1427                                                         "url" => $row["url"]);
1428                 }
1429         }
1430
1431         return $receiver;
1432 }
1433
1434 /*
1435 To-Do:
1436  - Notification for own imported posts
1437  - Thread completion
1438
1439 Nice to have:
1440  - sending private messages
1441
1442 Could be hard to do:
1443  - edit own notes
1444  - delete own notes
1445
1446 Known issues:
1447  - refresh after post
1448
1449 */