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