]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
pump.io: Mirroring looked for the wrong date. Thanks to sazius for finding this.
[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','host','');
297                         set_pconfig(local_user(),'pumpio','oauth_token','');
298                         set_pconfig(local_user(),'pumpio','oauth_token_secret','');
299                         set_pconfig(local_user(),'pumpio','post',false);
300                         set_pconfig(local_user(),'pumpio','post_by_default',false);
301                         set_pconfig(local_user(),'pumpio','user','');
302                 } else {
303                         // filtering the username if it is filled wrong
304                         $user = $_POST['pumpio_user'];
305                         if (strstr($user, "@")) {
306                                 $pos = strpos($user, "@");
307                                 if ($pos > 0)
308                                         $user = substr($user, 0, $pos);
309                         }
310
311                         // Filtering the hostname if someone is entering it with "http"
312                         $host = $_POST['pumpio_host'];
313                         $host = trim($host);
314                         $host = str_replace(array("https://", "http://"), array("", ""), $host);
315
316                         set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
317                         set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
318                         set_pconfig(local_user(),'pumpio','host',$host);
319                         set_pconfig(local_user(),'pumpio','user',$user);
320                         set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
321                         set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
322                         set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
323
324                         //header("Location: ".$a->get_baseurl()."/pumpio/connect");
325                 }
326         }
327 }
328
329 function pumpio_post_local(&$a,&$b) {
330
331         if((! local_user()) || (local_user() != $b['uid']))
332                 return;
333
334         $pumpio_post   = intval(get_pconfig(local_user(),'pumpio','post'));
335
336         $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
337
338         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
339                 $pumpio_enable = 1;
340
341         if(! $pumpio_enable)
342                 return;
343
344         if(strlen($b['postopts']))
345                 $b['postopts'] .= ',';
346
347         $b['postopts'] .= 'pumpio';
348 }
349
350
351
352
353 function pumpio_send(&$a,&$b) {
354
355         if (!get_pconfig($b["uid"],'pumpio','import')) {
356                 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
357                         return;
358         }
359
360         logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
361
362         if($b['parent'] != $b['id']) {
363                 // Looking if its a reply to a pumpio post
364                 $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",
365                         intval($b["parent"]),
366                         intval($b["uid"]),
367                         dbesc(NETWORK_PUMPIO));
368
369                 if(!count($r)) {
370                         logger("pumpio_send: no pumpio post ".$b["parent"]);
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
387         if($b['verb'] == ACTIVITY_LIKE) {
388                 if ($b['deleted'])
389                         pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
390                 else
391                         pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
392                 return;
393         }
394
395         if($b['verb'] == ACTIVITY_DISLIKE)
396                 return;
397
398         if (($b['verb'] == ACTIVITY_POST) AND ($b['created'] !== $b['edited']) AND !$b['deleted'])
399                         pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
400
401         if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
402                         pumpio_action($a, $b["uid"], $b["uri"], "delete");
403
404         if($b['deleted'] || ($b['created'] !== $b['edited']))
405                 return;
406
407         // if post comes from pump.io don't send it back
408         if($b['app'] == "pump.io")
409                 return;
410
411         // To-Do;
412         // Support for native shares
413         // http://<hostname>/api/<type>/shares?id=<the-object-id>
414
415         $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
416         $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
417         $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
418         $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
419
420         $host = get_pconfig($b['uid'], "pumpio", "host");
421         $user = get_pconfig($b['uid'], "pumpio", "user");
422         $public = get_pconfig($b['uid'], "pumpio", "public");
423
424         if($oauth_token && $oauth_token_secret) {
425
426                 require_once('include/bbcode.php');
427
428                 $title = trim($b['title']);
429
430                 if ($title != '')
431                         $title = "<h4>".$title."</h4>";
432
433                 $content = bbcode($b['body'], false, false, 4);
434
435                 // Enhance the way, videos are displayed
436                 $content = preg_replace('/<a href="(https?:\/\/www.youtube.com\/.*?)".*?>(.*?)<\/a>/ism',"\n[url]$1[/url]\n",$content);
437                 $content = preg_replace('/<a href="(https?:\/\/youtu.be\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
438                 $content = preg_replace('/<a href="(https?:\/\/vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
439                 $content = preg_replace('/<a href="(https?:\/\/player.vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
440
441                 $URLSearchString = "^\[\]";
442                 $content = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$content);
443
444                 $params = array();
445
446                 $params["verb"] = "post";
447
448                 if (!$iscomment) {
449                         $params["object"] = array(
450                                                 'objectType' => "note",
451                                                 'content' => $title.$content);
452
453                         if (count($receiver["to"]))
454                                 $params["to"] = $receiver["to"];
455
456                         if (count($receiver["bto"]))
457                                 $params["bto"] = $receiver["bto"];
458
459                         if (count($receiver["cc"]))
460                                 $params["cc"] = $receiver["cc"];
461
462                         if (count($receiver["bcc"]))
463                                 $params["bcc"] = $receiver["bcc"];
464
465                  } else {
466                         $inReplyTo = array("id" => $orig_post["uri"],
467                                         "objectType" => "note");
468
469                         $params["object"] = array(
470                                                 'objectType' => "comment",
471                                                 'content' => $title.$content,
472                                                 'inReplyTo' => $inReplyTo);
473                 }
474
475                 $client = new oauth_client_class;
476                 $client->oauth_version = '1.0a';
477                 $client->url_parameters = false;
478                 $client->authorization_header = true;
479                 $client->access_token = $oauth_token;
480                 $client->access_token_secret = $oauth_token_secret;
481                 $client->client_id = $consumer_key;
482                 $client->client_secret = $consumer_secret;
483
484                 $username = $user.'@'.$host;
485                 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
486
487                 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
488
489                 if($success) {
490                         $post_id = $user->object->id;
491                         logger('pumpio_send '.$username.': success '.$post_id);
492                         if($post_id AND $iscomment) {
493                                 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
494                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
495                                         dbesc($post_id),
496                                         intval($b['id'])
497                                 );
498                         }
499                 } else {
500                         logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
501
502                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
503                         if (count($r))
504                                 $a->contact = $r[0]["id"];
505
506                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
507                         require_once('include/queue_fn.php');
508                         add_to_queue($a->contact,NETWORK_PUMPIO,$s);
509                         notice(t('Pump.io post failed. Queued for retry.').EOL);
510                 }
511
512         }
513 }
514
515 function pumpio_action(&$a, $uid, $uri, $action, $content) {
516
517         // Don't do likes and other stuff if you don't import the timeline
518         if (!get_pconfig($uid,'pumpio','import'))
519                 return;
520
521         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
522         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
523         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
524         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
525         $hostname = get_pconfig($uid, 'pumpio','host');
526         $username = get_pconfig($uid, "pumpio", "user");
527
528         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
529                                 dbesc($uri),
530                                 intval($uid)
531         );
532
533         if (!count($r))
534                 return;
535
536         $orig_post = $r[0];
537
538         if ($orig_post["extid"] AND !strstr($orig_post["extid"], "/proxy/"))
539                 $uri = $orig_post["extid"];
540         else
541                 $uri = $orig_post["uri"];
542
543         if (strstr($uri, "/api/comment/"))
544                 $objectType = "comment";
545         elseif (strstr($uri, "/api/note/"))
546                 $objectType = "note";
547         elseif (strstr($uri, "/api/image/"))
548                 $objectType = "image";
549
550         $params["verb"] = $action;
551         $params["object"] = array('id' => $uri,
552                                 "objectType" => $objectType,
553                                 "content" => $content);
554
555         $client = new oauth_client_class;
556         $client->oauth_version = '1.0a';
557         $client->authorization_header = true;
558         $client->url_parameters = false;
559
560         $client->client_id = $ckey;
561         $client->client_secret = $csecret;
562         $client->access_token = $otoken;
563         $client->access_token_secret = $osecret;
564
565         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
566
567         $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
568
569         if($success)
570                 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
571         else {
572                 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
573
574                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
575                 if (count($r))
576                         $a->contact = $r[0]["id"];
577
578                 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
579                 require_once('include/queue_fn.php');
580                 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
581                 notice(t('Pump.io like failed. Queued for retry.').EOL);
582         }
583 }
584
585
586 function pumpio_cron(&$a,$b) {
587         $last = get_config('pumpio','last_poll');
588
589         $poll_interval = intval(get_config('pumpio','poll_interval'));
590         if(! $poll_interval)
591                 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
592
593         if($last) {
594                 $next = $last + ($poll_interval * 60);
595                 if($next > time()) {
596                         logger('pumpio: poll intervall not reached');
597                         return;
598                 }
599         }
600         logger('pumpio: cron_start');
601
602         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
603         if(count($r)) {
604                 foreach($r as $rr) {
605                         logger('pumpio: mirroring user '.$rr['uid']);
606                         pumpio_fetchtimeline($a, $rr['uid']);
607                 }
608         }
609
610         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
611         if(count($r)) {
612                 foreach($r as $rr) {
613                         logger('pumpio: importing timeline from user '.$rr['uid']);
614                         pumpio_fetchinbox($a, $rr['uid']);
615
616                         // check for new contacts once a day
617                         $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check');
618                         if($last_contact_check)
619                                 $next_contact_check = $last_contact_check + 86400;
620                         else
621                                 $next_contact_check = 0;
622
623                         if($next_contact_check <= time()) {
624                                 pumpio_getallusers($a, $rr["uid"]);
625                                 set_pconfig($rr['uid'],'pumpio','contact_check',time());
626                         }
627                 }
628         }
629
630         logger('pumpio: cron_end');
631
632         set_config('pumpio','last_poll', time());
633 }
634
635 function pumpio_fetchtimeline(&$a, $uid) {
636         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
637         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
638         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
639         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
640         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
641         $hostname = get_pconfig($uid, 'pumpio','host');
642         $username = get_pconfig($uid, "pumpio", "user");
643
644         $application_name  = get_config('pumpio', 'application_name');
645
646         if ($application_name == "")
647                 $application_name = $a->get_hostname();
648
649         $first_time = ($lastdate == "");
650
651         $client = new oauth_client_class;
652         $client->oauth_version = '1.0a';
653         $client->authorization_header = true;
654         $client->url_parameters = false;
655
656         $client->client_id = $ckey;
657         $client->client_secret = $csecret;
658         $client->access_token = $otoken;
659         $client->access_token_secret = $osecret;
660
661         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
662
663         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
664
665         $username = $user.'@'.$host;
666
667         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
668
669         if (!$success) {
670                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
671                 return;
672         }
673
674         $posts = array_reverse($user->items);
675
676         $initiallastdate = $lastdate;
677         $lastdate = '';
678
679         if (count($posts)) {
680                 foreach ($posts as $post) {
681                         if ($post->published <= $initiallastdate)
682                                 continue;
683
684                         if ($lastdate < $post->published)
685                                 $lastdate = $post->published;
686
687                         if ($first_time)
688                                 continue;
689
690                         $receiptians = array();
691                         if (@is_array($post->cc))
692                                 $receiptians = array_merge($receiptians, $post->cc);
693
694                         if (@is_array($post->to))
695                                 $receiptians = array_merge($receiptians, $post->to);
696
697                         $public = false;
698                         foreach ($receiptians AS $receiver)
699                                 if (is_string($receiver->objectType))
700                                         if ($receiver->id == "http://activityschema.org/collection/public")
701                                                 $public = true;
702
703                         if ($public AND !strstr($post->generator->displayName, $application_name)) {
704                                 require_once('include/html2bbcode.php');
705
706                                 $_SESSION["authenticated"] = true;
707                                 $_SESSION["uid"] = $uid;
708
709                                 unset($_REQUEST);
710                                 $_REQUEST["type"] = "wall";
711                                 $_REQUEST["api_source"] = true;
712                                 $_REQUEST["profile_uid"] = $uid;
713                                 $_REQUEST["source"] = "pump.io";
714
715                                 if ($post->object->displayName != "")
716                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
717                                 else
718                                         $_REQUEST["title"] = "";
719
720                                 $_REQUEST["body"] = html2bbcode($post->object->content);
721
722                                 // To-Do: Picture has to be cached and stored locally
723                                 if ($post->object->fullImage->url != "") {
724                                         if ($post->object->fullImage->pump_io->proxyURL != "")
725                                                 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
726                                         else
727                                                 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
728                                 }
729
730                                 logger('pumpio: posting for user '.$uid);
731
732                                 require_once('mod/item.php');
733
734                                 item_post($a);
735                                 logger('pumpio: posting done - user '.$uid);
736                         }
737                 }
738         }
739
740         if ($lastdate != 0)
741                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
742 }
743
744 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
745         // Searching for the unliked post
746         // Two queries for speed issues
747         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
748                                 dbesc($post->object->id),
749                                 intval($uid)
750                 );
751
752         if (count($r))
753                 $orig_post = $r[0];
754         else {
755                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
756                                         dbesc($post->object->id),
757                                         intval($uid)
758                         );
759
760                 if (!count($r))
761                         return;
762                 else
763                         $orig_post = $r[0];
764         }
765
766         $contactid = 0;
767
768         if(link_compare($post->actor->url, $own_id)) {
769                 $contactid = $self[0]['id'];
770         } else {
771                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
772                         dbesc($post->actor->url),
773                         intval($uid)
774                 );
775
776                 if(count($r))
777                         $contactid = $r[0]['id'];
778
779                 if($contactid == 0)
780                         $contactid = $orig_post['contact-id'];
781         }
782
783         $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'",
784                 dbesc(datetime_convert()),
785                 dbesc(ACTIVITY_LIKE),
786                 intval($uid),
787                 intval($contactid),
788                 dbesc($orig_post['uri'])
789         );
790
791         if(count($r))
792                 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
793         else
794                 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
795 }
796
797 function pumpio_dolike(&$a, $uid, $self, $post, $own_id) {
798
799         // Searching for the liked post
800         // Two queries for speed issues
801         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
802                                 dbesc($post->object->id),
803                                 intval($uid)
804                 );
805
806         if (count($r))
807                 $orig_post = $r[0];
808         else {
809                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
810                                         dbesc($post->object->id),
811                                         intval($uid)
812                         );
813
814                 if (!count($r))
815                         return;
816                 else
817                         $orig_post = $r[0];
818         }
819
820         $contactid = 0;
821
822         if(link_compare($post->actor->url, $own_id)) {
823                 $contactid = $self[0]['id'];
824                 $post->actor->displayName = $self[0]['name'];
825                 $post->actor->url = $self[0]['url'];
826                 $post->actor->image->url = $self[0]['photo'];
827         } else {
828                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
829                         dbesc($post->actor->url),
830                         intval($uid)
831                 );
832
833                 if(count($r))
834                         $contactid = $r[0]['id'];
835
836                 if($contactid == 0)
837                         $contactid = $orig_post['contact-id'];
838         }
839
840         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
841                 dbesc(ACTIVITY_LIKE),
842                 intval($uid),
843                 intval($contactid),
844                 dbesc($orig_post['uri'])
845         );
846
847         if(count($r)) {
848                 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
849                 return;
850         }
851
852         $likedata = array();
853         $likedata['parent'] = $orig_post['id'];
854         $likedata['verb'] = ACTIVITY_LIKE;
855         $likedata['gravity'] = 3;
856         $likedata['uid'] = $uid;
857         $likedata['wall'] = 0;
858         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
859         $likedata['parent-uri'] = $orig_post["uri"];
860         $likedata['contact-id'] = $contactid;
861         $likedata['app'] = $post->generator->displayName;
862         $likedata['verb'] = ACTIVITY_LIKE;
863         $likedata['author-name'] = $post->actor->displayName;
864         $likedata['author-link'] = $post->actor->url;
865         $likedata['author-avatar'] = $post->actor->image->url;
866
867         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
868         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
869         $post_type = t('status');
870         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
871         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
872
873         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
874
875         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
876                 '<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>';
877
878         $ret = item_store($likedata);
879
880         logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
881 }
882
883 function pumpio_get_contact($uid, $contact) {
884
885         $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
886                 dbesc(normalise_link($contact->url)));
887
888         if (count($r) == 0)
889                 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
890                         dbesc(normalise_link($contact->url)),
891                         dbesc($contact->displayName),
892                         dbesc($contact->preferredUsername),
893                         dbesc($contact->image->url));
894         else
895                 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
896                         dbesc($contact->displayName),
897                         dbesc($contact->preferredUsername),
898                         dbesc($contact->image->url),
899                         dbesc(normalise_link($contact->url)));
900
901         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
902                 intval($uid), dbesc($contact->url));
903
904         if(!count($r)) {
905                 // create contact record
906                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
907                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
908                                         `writable`, `blocked`, `readonly`, `pending` )
909                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
910                         intval($uid),
911                         dbesc(datetime_convert()),
912                         dbesc($contact->url),
913                         dbesc(normalise_link($contact->url)),
914                         dbesc(str_replace("acct:", "", $contact->id)),
915                         dbesc(''),
916                         dbesc($contact->id), // What is it for?
917                         dbesc('pump.io ' . $contact->id), // What is it for?
918                         dbesc($contact->displayName),
919                         dbesc($contact->preferredUsername),
920                         dbesc($contact->image->url),
921                         dbesc(NETWORK_PUMPIO),
922                         intval(CONTACT_IS_FRIEND),
923                         intval(1),
924                         intval(1)
925                 );
926
927                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
928                         dbesc($contact->url),
929                         intval($uid)
930                         );
931
932                 if(! count($r))
933                         return(false);
934
935                 $contact_id  = $r[0]['id'];
936
937                 $g = q("select def_gid from user where uid = %d limit 1",
938                         intval($uid)
939                 );
940
941                 if($g && intval($g[0]['def_gid'])) {
942                         require_once('include/group.php');
943                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
944                 }
945
946                 require_once("Photo.php");
947
948                 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
949
950                 q("UPDATE `contact` SET `photo` = '%s',
951                                         `thumb` = '%s',
952                                         `micro` = '%s',
953                                         `name-date` = '%s',
954                                         `uri-date` = '%s',
955                                         `avatar-date` = '%s'
956                                 WHERE `id` = %d
957                         ",
958                 dbesc($photos[0]),
959                 dbesc($photos[1]),
960                 dbesc($photos[2]),
961                 dbesc(datetime_convert()),
962                 dbesc(datetime_convert()),
963                 dbesc(datetime_convert()),
964                 intval($contact_id)
965                 );
966         } else {
967                 // update profile photos once every two weeks as we have no notification of when they change.
968
969                 $update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
970
971                 // check that we have all the photos, this has been known to fail on occasion
972
973                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
974                         require_once("Photo.php");
975
976                         $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
977
978                         q("UPDATE `contact` SET `photo` = '%s',
979                                         `thumb` = '%s',
980                                         `micro` = '%s',
981                                         `name-date` = '%s',
982                                         `uri-date` = '%s',
983                                         `avatar-date` = '%s',
984                                         `name` = '%s',
985                                         `nick` = '%s'
986                                         WHERE `id` = %d
987                                 ",
988                         dbesc($photos[0]),
989                         dbesc($photos[1]),
990                         dbesc($photos[2]),
991                         dbesc(datetime_convert()),
992                         dbesc(datetime_convert()),
993                         dbesc(datetime_convert()),
994                         dbesc($contact->displayName),
995                         dbesc($contact->preferredUsername),
996                         intval($r[0]['id'])
997                         );
998                 }
999
1000         }
1001
1002         return($r[0]["id"]);
1003 }
1004
1005 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1006
1007         // Two queries for speed issues
1008         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1009                                 dbesc($post->object->id),
1010                                 intval($uid)
1011                 );
1012
1013         if (count($r))
1014                 return drop_item($r[0]["id"], $false);
1015
1016         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1017                                 dbesc($post->object->id),
1018                                 intval($uid)
1019                 );
1020
1021         if (count($r))
1022                 return drop_item($r[0]["id"], $false);
1023 }
1024
1025 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = false) {
1026         require_once('include/items.php');
1027         require_once('include/html2bbcode.php');
1028
1029         if (($post->verb == "like") OR ($post->verb == "favorite"))
1030                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1031
1032         if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
1033                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1034
1035         if ($post->verb == "delete")
1036                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1037
1038         if ($post->verb != "update") {
1039                 // Two queries for speed issues
1040                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1041                                         dbesc($post->object->id),
1042                                         intval($uid)
1043                         );
1044
1045                 if (count($r))
1046                         return false;
1047
1048                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1049                                         dbesc($post->object->id),
1050                                         intval($uid)
1051                         );
1052
1053                 if (count($r))
1054                         return false;
1055         }
1056
1057         // Only handle these three types
1058         if (!strstr("post|share|update", $post->verb))
1059                 return false;
1060
1061         $receiptians = array();
1062         if (@is_array($post->cc))
1063                 $receiptians = array_merge($receiptians, $post->cc);
1064
1065         if (@is_array($post->to))
1066                 $receiptians = array_merge($receiptians, $post->to);
1067
1068         foreach ($receiptians AS $receiver)
1069                 if (is_string($receiver->objectType))
1070                         if ($receiver->id == "http://activityschema.org/collection/public")
1071                                 $public = true;
1072
1073         $postarray = array();
1074         $postarray['gravity'] = 0;
1075         $postarray['uid'] = $uid;
1076         $postarray['wall'] = 0;
1077         $postarray['uri'] = $post->object->id;
1078
1079         if ($post->object->objectType != "comment") {
1080                 $contact_id = pumpio_get_contact($uid, $post->actor);
1081
1082                 if (!$contact_id)
1083                         $contact_id = $self[0]['id'];
1084
1085                 $postarray['parent-uri'] = $post->object->id;
1086         } else {
1087                 $contact_id = 0;
1088
1089                 if(link_compare($post->actor->url, $own_id)) {
1090                         $contact_id = $self[0]['id'];
1091                         $post->actor->displayName = $self[0]['name'];
1092                         $post->actor->url = $self[0]['url'];
1093                         $post->actor->image->url = $self[0]['photo'];
1094                 } else {
1095                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1096                         $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1097                                 dbesc($post->actor->url),
1098                                 intval($uid)
1099                         );
1100
1101                         if(count($r))
1102                                 $contact_id = $r[0]['id'];
1103                         else {
1104                                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1105                                         dbesc($post->actor->url),
1106                                         intval($uid)
1107                                 );
1108
1109                                 if(count($r))
1110                                         $contact_id = $r[0]['id'];
1111                                 else
1112                                         $contact_id = $self[0]['id'];
1113                         }
1114                 }
1115
1116                 $reply = new stdClass;
1117                 $reply->verb = "note";
1118                 $reply->cc = $post->cc;
1119                 $reply->to = $post->to;
1120                 $reply->object = new stdClass;
1121                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1122                 $reply->object->content = $post->object->inReplyTo->content;
1123                 $reply->object->id = $post->object->inReplyTo->id;
1124                 $reply->actor = $post->object->inReplyTo->author;
1125                 $reply->url = $post->object->inReplyTo->url;
1126                 $reply->generator = new stdClass;
1127                 $reply->generator->displayName = "pumpio";
1128                 $reply->published = $post->object->inReplyTo->published;
1129                 $reply->received = $post->object->inReplyTo->updated;
1130                 $reply->url = $post->object->inReplyTo->url;
1131                 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id);
1132
1133                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1134         }
1135
1136         if ($post->object->pump_io->proxyURL)
1137                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1138
1139         $postarray['contact-id'] = $contact_id;
1140         $postarray['verb'] = ACTIVITY_POST;
1141         $postarray['owner-name'] = $post->actor->displayName;
1142         $postarray['owner-link'] = $post->actor->url;
1143         $postarray['owner-avatar'] = $post->actor->image->url;
1144         $postarray['author-name'] = $post->actor->displayName;
1145         $postarray['author-link'] = $post->actor->url;
1146         $postarray['author-avatar'] = $post->actor->image->url;
1147         $postarray['plink'] = $post->object->url;
1148         $postarray['app'] = $post->generator->displayName;
1149         $postarray['body'] = html2bbcode($post->object->content);
1150
1151         if ($post->object->fullImage->url != "")
1152                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1153
1154         if ($post->object->displayName != "")
1155                 $postarray['title'] = $post->object->displayName;
1156
1157         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1158         $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1159         if (!$public) {
1160                 $postarray['private'] = 1;
1161                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1162         }
1163
1164         if ($post->verb == "share") {
1165                 if (!intval(get_config('system','wall-to-wall_share'))) {
1166                         $postarray['body'] = "[share author='".$post->object->author->displayName.
1167                                         "' profile='".$post->object->author->url.
1168                                         "' avatar='".$post->object->author->image->url.
1169                                         "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1170                 } else {
1171                         // Let shares look like wall-to-wall posts
1172                         $postarray['author-name'] = $post->object->author->displayName;
1173                         $postarray['author-link'] = $post->object->author->url;
1174                         $postarray['author-avatar'] = $post->object->author->image->url;
1175                 }
1176         }
1177
1178         if (trim($postarray['body']) == "")
1179                 return false;
1180
1181         $top_item = item_store($postarray);
1182
1183         if (($top_item == 0) AND ($post->verb == "update")) {
1184                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1185                         dbesc($postarray["title"]),
1186                         dbesc($postarray["body"]),
1187                         dbesc($postarray["edited"]),
1188                         dbesc($postarray["uri"]),
1189                         intval($uid)
1190                         );
1191         }
1192
1193         if ($post->object->objectType == "comment") {
1194
1195                 if ($threadcompletion)
1196                         pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1197
1198                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1199                                 intval($uid)
1200                         );
1201
1202                 if(!count($user))
1203                         return $top_item;
1204
1205                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1206
1207                 if (link_compare($own_id, $postarray['author-link']))
1208                         return $top_item;
1209
1210                 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1211                                 dbesc($postarray['parent-uri']),
1212                                 intval($uid)
1213                                 );
1214
1215                 if(count($myconv)) {
1216
1217                         foreach($myconv as $conv) {
1218                                 // now if we find a match, it means we're in this conversation
1219
1220                                 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_id))
1221                                         continue;
1222
1223                                 require_once('include/enotify.php');
1224
1225                                 $conv_parent = $conv['parent'];
1226
1227                                 notification(array(
1228                                         'type'         => NOTIFY_COMMENT,
1229                                         'notify_flags' => $user[0]['notify-flags'],
1230                                         'language'     => $user[0]['language'],
1231                                         'to_name'      => $user[0]['username'],
1232                                         'to_email'     => $user[0]['email'],
1233                                         'uid'          => $user[0]['uid'],
1234                                         'item'         => $postarray,
1235                                         'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1236                                         'source_name'  => $postarray['author-name'],
1237                                         'source_link'  => $postarray['author-link'],
1238                                         'source_photo' => $postarray['author-avatar'],
1239                                         'verb'         => ACTIVITY_POST,
1240                                         'otype'        => 'item',
1241                                         'parent'       => $conv_parent,
1242                                         ));
1243
1244                                 // only send one notification
1245                                 break;
1246                         }
1247                 }
1248         }
1249
1250         return $top_item;
1251 }
1252
1253 function pumpio_fetchinbox(&$a, $uid) {
1254
1255         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1256         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1257         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1258         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1259         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1260         $hostname = get_pconfig($uid, 'pumpio','host');
1261         $username = get_pconfig($uid, "pumpio", "user");
1262
1263         $own_id = "https://".$hostname."/".$username;
1264
1265         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1266                 intval($uid));
1267
1268         $client = new oauth_client_class;
1269         $client->oauth_version = '1.0a';
1270         $client->authorization_header = true;
1271         $client->url_parameters = false;
1272
1273         $client->client_id = $ckey;
1274         $client->client_secret = $csecret;
1275         $client->access_token = $otoken;
1276         $client->access_token_secret = $osecret;
1277
1278         $last_id = get_pconfig($uid,'pumpio','last_id');
1279
1280         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1281
1282         if ($last_id != "")
1283                 $url .= '?since='.urlencode($last_id);
1284
1285         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1286
1287         if ($user->items) {
1288             $posts = array_reverse($user->items);
1289
1290             if (count($posts))
1291                     foreach ($posts as $post) {
1292                             $last_id = $post->id;
1293                             pumpio_dopost($a, $client, $uid, $self, $post, $own_id);
1294                     }
1295         }
1296
1297         set_pconfig($uid,'pumpio','last_id', $last_id);
1298 }
1299
1300 function pumpio_getallusers(&$a, $uid) {
1301         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1302         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1303         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1304         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1305         $hostname = get_pconfig($uid, 'pumpio','host');
1306         $username = get_pconfig($uid, "pumpio", "user");
1307
1308         $client = new oauth_client_class;
1309         $client->oauth_version = '1.0a';
1310         $client->authorization_header = true;
1311         $client->url_parameters = false;
1312
1313         $client->client_id = $ckey;
1314         $client->client_secret = $csecret;
1315         $client->access_token = $otoken;
1316         $client->access_token_secret = $osecret;
1317
1318         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1319
1320         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1321
1322         if ($users->totalItems > count($users->items)) {
1323                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1324
1325                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1326         }
1327
1328         foreach ($users->items AS $user)
1329                 echo pumpio_get_contact($uid, $user)."\n";
1330 }
1331
1332 function pumpio_queue_hook(&$a,&$b) {
1333
1334         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1335                 dbesc(NETWORK_PUMPIO)
1336         );
1337         if(! count($qi))
1338                 return;
1339
1340         require_once('include/queue_fn.php');
1341
1342         foreach($qi as $x) {
1343                 if($x['network'] !== NETWORK_PUMPIO)
1344                         continue;
1345
1346                 logger('pumpio_queue: run');
1347
1348                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
1349                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1350                         intval($x['cid'])
1351                 );
1352                 if(! count($r))
1353                         continue;
1354
1355                 $userdata = $r[0];
1356
1357                 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1358
1359                 $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token");
1360                 $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret");
1361                 $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key");
1362                 $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret");
1363
1364                 $host = get_pconfig($userdata['uid'], "pumpio", "host");
1365                 $user = get_pconfig($userdata['uid'], "pumpio", "user");
1366
1367                 $success = false;
1368
1369                 if ($oauth_token AND $oauth_token_secret AND
1370                         $consumer_key AND $consumer_secret) {
1371                         $username = $user.'@'.$host;
1372
1373                         logger('pumpio_queue: able to post for user '.$username);
1374
1375                         $z = unserialize($x['content']);
1376
1377                         $client = new oauth_client_class;
1378                         $client->oauth_version = '1.0a';
1379                         $client->url_parameters = false;
1380                         $client->authorization_header = true;
1381                         $client->access_token = $oauth_token;
1382                         $client->access_token_secret = $oauth_token_secret;
1383                         $client->client_id = $consumer_key;
1384                         $client->client_secret = $consumer_secret;
1385
1386                         $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1387
1388                         if($success) {
1389                                 $post_id = $user->object->id;
1390                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1391                                 if($post_id AND $iscomment) {
1392                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1393                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1394                                                 dbesc($post_id),
1395                                                 intval($z['item'])
1396                                         );
1397                                 }
1398                                 remove_queue_item($x['id']);
1399                         } else
1400                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1401                 } else
1402                         logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1403
1404                 if (!$success) {
1405                         logger('pumpio_queue: delayed');
1406                         update_queue_time($x['id']);
1407                 }
1408         }
1409 }
1410
1411 function pumpio_getreceiver(&$a, $b) {
1412
1413         $receiver = array();
1414
1415         if (!$b["private"]) {
1416
1417                 if(! strstr($b['postopts'],'pumpio'))
1418                         return $receiver;
1419
1420                 $public = get_pconfig($b['uid'], "pumpio", "public");
1421
1422                 if ($public)
1423                         $receiver["to"][] = Array(
1424                                                 "objectType" => "collection",
1425                                                 "id" => "http://activityschema.org/collection/public");
1426         } else {
1427                 $cids = explode("><", $b["allow_cid"]);
1428                 $gids = explode("><", $b["allow_gid"]);
1429
1430                 foreach ($cids AS $cid) {
1431                         $cid = trim($cid, " <>");
1432
1433                         $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",
1434                                 intval($cid),
1435                                 intval($b["uid"]),
1436                                 dbesc(NETWORK_PUMPIO)
1437                                 );
1438
1439                         if (count($r)) {
1440                                 $receiver["bcc"][] = Array(
1441                                                         "displayName" => $r[0]["name"],
1442                                                         "objectType" => "person",
1443                                                         "preferredUsername" => $r[0]["nick"],
1444                                                         "url" => $r[0]["url"]);
1445                         }
1446                 }
1447                 foreach ($gids AS $gid) {
1448                         $gid = trim($gid, " <>");
1449
1450                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1451                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1452                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1453                                         intval($gid),
1454                                         intval($b["uid"]),
1455                                         dbesc(NETWORK_PUMPIO)
1456                                 );
1457
1458                         foreach ($r AS $row)
1459                                 $receiver["bcc"][] = Array(
1460                                                         "displayName" => $row["name"],
1461                                                         "objectType" => "person",
1462                                                         "preferredUsername" => $row["nick"],
1463                                                         "url" => $row["url"]);
1464                 }
1465         }
1466
1467         if ($b["inform"] != "") {
1468
1469                 $inform = explode(",", $b["inform"]);
1470
1471                 foreach ($inform AS $cid) {
1472                         if (substr($cid, 0, 4) != "cid:")
1473                                 continue;
1474
1475                         $cid = str_replace("cid:", "", $cid);
1476
1477                         $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",
1478                                 intval($cid),
1479                                 intval($b["uid"]),
1480                                 dbesc(NETWORK_PUMPIO)
1481                                 );
1482
1483                         if (count($r)) {
1484                                         $receiver["to"][] = Array(
1485                                                                 "displayName" => $r[0]["name"],
1486                                                                 "objectType" => "person",
1487                                                                 "preferredUsername" => $r[0]["nick"],
1488                                                                 "url" => $r[0]["url"]);
1489                         }
1490                 }
1491         }
1492
1493         return $receiver;
1494 }
1495
1496 function pumpio_fetchallcomments(&$a, $uid, $id) {
1497         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1498         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1499         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1500         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1501         $hostname = get_pconfig($uid, 'pumpio','host');
1502         $username = get_pconfig($uid, "pumpio", "user");
1503
1504         $own_id = "https://".$hostname."/".$username;
1505
1506         logger("pumpio_fetchallcomments: completing comment for user ".$uid." url ".$url);
1507
1508         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1509                 intval($uid));
1510
1511         // Fetching the original post - Two queries for speed issues
1512         $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1513                         dbesc($url),
1514                         intval($uid)
1515                 );
1516
1517         if (!count($r)) {
1518                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1519                                 dbesc($url),
1520                                 intval($uid)
1521                         );
1522
1523                 if (!count($r))
1524                         return false;
1525         }
1526
1527         if ($r[0]["extid"])
1528                 $url = $r[0]["extid"];
1529         else
1530                 $url = $id;
1531
1532         $client = new oauth_client_class;
1533         $client->oauth_version = '1.0a';
1534         $client->authorization_header = true;
1535         $client->url_parameters = false;
1536
1537         $client->client_id = $ckey;
1538         $client->client_secret = $csecret;
1539         $client->access_token = $otoken;
1540         $client->access_token_secret = $osecret;
1541
1542         logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1543
1544         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1545
1546         if (!$success)
1547                 return;
1548
1549         if ($item->replies->totalItems == 0)
1550                 return;
1551
1552         foreach ($item->replies->items AS $item) {
1553                 if ($item->id == $id)
1554                         continue;
1555
1556                 // Checking if the comment already exists - Two queries for speed issues
1557                 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1558                                 dbesc($url),
1559                                 intval($uid)
1560                         );
1561
1562                 if (count($r))
1563                         continue;
1564
1565                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1566                                 dbesc($url),
1567                                 intval($uid)
1568                         );
1569
1570                 if (count($r))
1571                         continue;
1572
1573                 $post->verb = "post";
1574                 $post->actor = $item->author;
1575                 $post->published = $item->published;
1576                 $post->received = $item->updated;
1577                 $post->generator->displayName = "pumpio";
1578
1579                 unset($item->author);
1580                 unset($item->published);
1581                 unset($item->updated);
1582
1583                 $post->object = $item;
1584
1585                 logger("pumpio_fetchallcomments: posting comment ".$post->object->id);
1586                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1587         }
1588 }
1589
1590 /*
1591 Bugs:
1592  - refresh after post doesn't always happen
1593
1594 To-Do:
1595  - edit own notes
1596  - delete own notes
1597
1598 */