3 * Name: pump.io Post Connector
4 * Description: Post to pump.io
6 * Author: Michael Vogel <http://pirati.ca/profile/heluecht>
8 require('addon/pumpio/oauth/http.php');
9 require('addon/pumpio/oauth/oauth_client.php');
11 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
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');
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');
33 function pumpio_module() {}
35 function pumpio_content(&$a) {
38 notice( t('Permission denied.') . EOL);
42 require_once("mod/settings.php");
45 if (isset($a->argv[1]))
46 switch ($a->argv[1]) {
48 $o = pumpio_connect($a);
51 $o = print_r($a->argv, true);
55 $o = pumpio_connect($a);
60 function pumpio_registerclient(&$a, $host) {
62 $url = "https://".$host."/api/client/register";
66 $application_name = get_config('pumpio', 'application_name');
68 if ($application_name == "")
69 $application_name = $a->get_hostname();
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";
78 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
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");
88 $curl_info = curl_getinfo($ch);
90 if ($curl_info["http_code"] == "200") {
91 $values = json_decode($s);
92 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
95 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
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
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');
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);
115 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
116 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
118 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
121 if (($consumer_key == "") OR ($consumer_secret == "")) {
122 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
124 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
128 // The callback URL is the script that gets called after the user authenticates with pumpio
129 $callback_url = $a->get_baseurl()."/pumpio/connect";
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.
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;
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;
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);
157 $success = $client->Finalize($success);
160 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
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>';
167 logger("pumpio_connect: could not connect");
168 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
174 function pumpio_jot_nets(&$a,&$b) {
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>';
188 function pumpio_settings(&$a,&$s) {
193 /* Add our stylesheet to the page so we can make our settings look nice */
195 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
197 /* Get the current state of our config variables */
199 $import_enabled = get_pconfig(local_user(),'pumpio','import');
200 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
202 $enabled = get_pconfig(local_user(),'pumpio','post');
203 $checked = (($enabled) ? ' checked="checked" ' : '');
204 $css = (($enabled) ? '' : '-disabled');
206 $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default');
207 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
209 $public_enabled = get_pconfig(local_user(),'pumpio','public');
210 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
212 $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror');
213 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
215 $servername = get_pconfig(local_user(), "pumpio", "host");
216 $username = get_pconfig(local_user(), "pumpio", "user");
218 /* Add some HTML to the existing form */
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>';
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>';
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>';
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>';
238 if (($username != '') AND ($servername != '')) {
240 $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token");
241 $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret");
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>';
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>';
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>';
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>';
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>';
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>';
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>';
280 $s .= '</div><div class="clear"></div>';
283 /* provide a submit button */
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>';
289 function pumpio_settings_post(&$a,&$b) {
291 if(x($_POST,'pumpio-submit')) {
292 if(x($_POST,'pumpio_delete')) {
293 set_pconfig(local_user(),'pumpio','consumer_key','');
294 set_pconfig(local_user(),'pumpio','consumer_secret','');
295 set_pconfig(local_user(),'pumpio','oauth_token','');
296 set_pconfig(local_user(),'pumpio','oauth_token_secret','');
297 set_pconfig(local_user(),'pumpio','post',false);
298 set_pconfig(local_user(),'pumpio','import',false);
299 set_pconfig(local_user(),'pumpio','host','');
300 set_pconfig(local_user(),'pumpio','user','');
301 set_pconfig(local_user(),'pumpio','public',false);
302 set_pconfig(local_user(),'pumpio','mirror',false);
303 set_pconfig(local_user(),'pumpio','post_by_default',false);
304 set_pconfig(local_user(),'pumpio','lastdate', 0);
306 // filtering the username if it is filled wrong
307 $user = $_POST['pumpio_user'];
308 if (strstr($user, "@")) {
309 $pos = strpos($user, "@");
311 $user = substr($user, 0, $pos);
314 // Filtering the hostname if someone is entering it with "http"
315 $host = $_POST['pumpio_host'];
317 $host = str_replace(array("https://", "http://"), array("", ""), $host);
319 set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
320 set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
321 set_pconfig(local_user(),'pumpio','host',$host);
322 set_pconfig(local_user(),'pumpio','user',$user);
323 set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
324 set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
325 set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
327 if (!$_POST['pumpio_mirror'])
328 del_pconfig(local_user(),'pumpio','lastdate');
330 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
335 function pumpio_post_local(&$a,&$b) {
337 if((! local_user()) || (local_user() != $b['uid']))
340 $pumpio_post = intval(get_pconfig(local_user(),'pumpio','post'));
342 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
344 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
350 if(strlen($b['postopts']))
351 $b['postopts'] .= ',';
353 $b['postopts'] .= 'pumpio';
359 function pumpio_send(&$a,&$b) {
361 if (!get_pconfig($b["uid"],'pumpio','import')) {
362 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
366 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
368 if($b['parent'] != $b['id']) {
369 // Looking if its a reply to a pumpio post
370 $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",
371 intval($b["parent"]),
373 dbesc(NETWORK_PUMPIO));
376 logger("pumpio_send: no pumpio post ".$b["parent"]);
385 $receiver = pumpio_getreceiver($a, $b);
387 logger("pumpio_send: receiver ".print_r($receiver, true));
389 if (!count($receiver) AND ($b['private'] OR !strstr($b['postopts'],'pumpio')))
393 if($b['verb'] == ACTIVITY_LIKE) {
395 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
397 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
401 if($b['verb'] == ACTIVITY_DISLIKE)
404 if (($b['verb'] == ACTIVITY_POST) AND ($b['created'] !== $b['edited']) AND !$b['deleted'])
405 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
407 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
408 pumpio_action($a, $b["uid"], $b["uri"], "delete");
410 if($b['deleted'] || ($b['created'] !== $b['edited']))
413 // if post comes from pump.io don't send it back
414 if($b['app'] == "pump.io")
418 // Support for native shares
419 // http://<hostname>/api/<type>/shares?id=<the-object-id>
421 $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
422 $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
423 $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
424 $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
426 $host = get_pconfig($b['uid'], "pumpio", "host");
427 $user = get_pconfig($b['uid'], "pumpio", "user");
428 $public = get_pconfig($b['uid'], "pumpio", "public");
430 if($oauth_token && $oauth_token_secret) {
432 require_once('include/bbcode.php');
434 $title = trim($b['title']);
437 $title = "<h4>".$title."</h4>";
439 $content = bbcode($b['body'], false, false, 4);
441 // Enhance the way, videos are displayed
442 $content = preg_replace('/<a href="(https?:\/\/www.youtube.com\/.*?)".*?>(.*?)<\/a>/ism',"\n[url]$1[/url]\n",$content);
443 $content = preg_replace('/<a href="(https?:\/\/youtu.be\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
444 $content = preg_replace('/<a href="(https?:\/\/vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
445 $content = preg_replace('/<a href="(https?:\/\/player.vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
447 $URLSearchString = "^\[\]";
448 $content = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$content);
452 $params["verb"] = "post";
455 $params["object"] = array(
456 'objectType' => "note",
457 'content' => $title.$content);
459 if (count($receiver["to"]))
460 $params["to"] = $receiver["to"];
462 if (count($receiver["bto"]))
463 $params["bto"] = $receiver["bto"];
465 if (count($receiver["cc"]))
466 $params["cc"] = $receiver["cc"];
468 if (count($receiver["bcc"]))
469 $params["bcc"] = $receiver["bcc"];
472 $inReplyTo = array("id" => $orig_post["uri"],
473 "objectType" => "note");
475 if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
476 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
478 $params["object"] = array(
479 'objectType' => "comment",
480 'content' => $title.$content,
481 'inReplyTo' => $inReplyTo);
484 $client = new oauth_client_class;
485 $client->oauth_version = '1.0a';
486 $client->url_parameters = false;
487 $client->authorization_header = true;
488 $client->access_token = $oauth_token;
489 $client->access_token_secret = $oauth_token_secret;
490 $client->client_id = $consumer_key;
491 $client->client_secret = $consumer_secret;
493 $username = $user.'@'.$host;
494 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
496 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
499 $post_id = $user->object->id;
500 logger('pumpio_send '.$username.': success '.$post_id);
501 if($post_id AND $iscomment) {
502 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
503 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
509 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
511 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
513 $a->contact = $r[0]["id"];
515 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
516 require_once('include/queue_fn.php');
517 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
518 notice(t('Pump.io post failed. Queued for retry.').EOL);
524 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
526 // Don't do likes and other stuff if you don't import the timeline
527 if (!get_pconfig($uid,'pumpio','import'))
530 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
531 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
532 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
533 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
534 $hostname = get_pconfig($uid, 'pumpio','host');
535 $username = get_pconfig($uid, "pumpio", "user");
537 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
547 if ($orig_post["extid"] AND !strstr($orig_post["extid"], "/proxy/"))
548 $uri = $orig_post["extid"];
550 $uri = $orig_post["uri"];
552 if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
553 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
554 elseif (strstr($uri, "/api/comment/"))
555 $objectType = "comment";
556 elseif (strstr($uri, "/api/note/"))
557 $objectType = "note";
558 elseif (strstr($uri, "/api/image/"))
559 $objectType = "image";
561 $params["verb"] = $action;
562 $params["object"] = array('id' => $uri,
563 "objectType" => $objectType,
564 "content" => $content);
566 $client = new oauth_client_class;
567 $client->oauth_version = '1.0a';
568 $client->authorization_header = true;
569 $client->url_parameters = false;
571 $client->client_id = $ckey;
572 $client->client_secret = $csecret;
573 $client->access_token = $otoken;
574 $client->access_token_secret = $osecret;
576 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
578 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
581 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
583 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
585 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
587 $a->contact = $r[0]["id"];
589 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
590 require_once('include/queue_fn.php');
591 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
592 notice(t('Pump.io like failed. Queued for retry.').EOL);
597 function pumpio_cron(&$a,$b) {
598 $last = get_config('pumpio','last_poll');
600 $poll_interval = intval(get_config('pumpio','poll_interval'));
602 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
605 $next = $last + ($poll_interval * 60);
607 logger('pumpio: poll intervall not reached');
611 logger('pumpio: cron_start');
613 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
616 logger('pumpio: mirroring user '.$rr['uid']);
617 pumpio_fetchtimeline($a, $rr['uid']);
621 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
624 logger('pumpio: importing timeline from user '.$rr['uid']);
625 pumpio_fetchinbox($a, $rr['uid']);
627 // check for new contacts once a day
628 $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check');
629 if($last_contact_check)
630 $next_contact_check = $last_contact_check + 86400;
632 $next_contact_check = 0;
634 if($next_contact_check <= time()) {
635 pumpio_getallusers($a, $rr["uid"]);
636 set_pconfig($rr['uid'],'pumpio','contact_check',time());
641 logger('pumpio: cron_end');
643 set_config('pumpio','last_poll', time());
646 function pumpio_fetchtimeline(&$a, $uid) {
647 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
648 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
649 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
650 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
651 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
652 $hostname = get_pconfig($uid, 'pumpio','host');
653 $username = get_pconfig($uid, "pumpio", "user");
655 $application_name = get_config('pumpio', 'application_name');
657 if ($application_name == "")
658 $application_name = $a->get_hostname();
660 $first_time = ($lastdate == "");
662 $client = new oauth_client_class;
663 $client->oauth_version = '1.0a';
664 $client->authorization_header = true;
665 $client->url_parameters = false;
667 $client->client_id = $ckey;
668 $client->client_secret = $csecret;
669 $client->access_token = $otoken;
670 $client->access_token_secret = $osecret;
672 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
674 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
676 $username = $user.'@'.$host;
678 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
681 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
685 $posts = array_reverse($user->items);
687 $initiallastdate = $lastdate;
691 foreach ($posts as $post) {
692 if ($post->published <= $initiallastdate)
695 if ($lastdate < $post->published)
696 $lastdate = $post->published;
701 $receiptians = array();
702 if (@is_array($post->cc))
703 $receiptians = array_merge($receiptians, $post->cc);
705 if (@is_array($post->to))
706 $receiptians = array_merge($receiptians, $post->to);
709 foreach ($receiptians AS $receiver)
710 if (is_string($receiver->objectType))
711 if ($receiver->id == "http://activityschema.org/collection/public")
714 if ($public AND !strstr($post->generator->displayName, $application_name)) {
715 require_once('include/html2bbcode.php');
717 $_SESSION["authenticated"] = true;
718 $_SESSION["uid"] = $uid;
721 $_REQUEST["type"] = "wall";
722 $_REQUEST["api_source"] = true;
723 $_REQUEST["profile_uid"] = $uid;
724 $_REQUEST["source"] = "pump.io";
726 if ($post->object->displayName != "")
727 $_REQUEST["title"] = html2bbcode($post->object->displayName);
729 $_REQUEST["title"] = "";
731 $_REQUEST["body"] = html2bbcode($post->object->content);
733 // To-Do: Picture has to be cached and stored locally
734 if ($post->object->fullImage->url != "") {
735 if ($post->object->fullImage->pump_io->proxyURL != "")
736 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
738 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
741 logger('pumpio: posting for user '.$uid);
743 require_once('mod/item.php');
746 logger('pumpio: posting done - user '.$uid);
752 set_pconfig($uid,'pumpio','lastdate', $lastdate);
755 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
756 // Searching for the unliked post
757 // Two queries for speed issues
758 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
759 dbesc($post->object->id),
766 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
767 dbesc($post->object->id),
779 if(link_compare($post->actor->url, $own_id)) {
780 $contactid = $self[0]['id'];
782 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
783 dbesc($post->actor->url),
788 $contactid = $r[0]['id'];
791 $contactid = $orig_post['contact-id'];
794 $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'",
795 dbesc(datetime_convert()),
796 dbesc(ACTIVITY_LIKE),
799 dbesc($orig_post['uri'])
803 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
805 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
808 function pumpio_dolike(&$a, $uid, $self, $post, $own_id) {
810 // Searching for the liked post
811 // Two queries for speed issues
812 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
813 dbesc($post->object->id),
820 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
821 dbesc($post->object->id),
833 if(link_compare($post->actor->url, $own_id)) {
834 $contactid = $self[0]['id'];
835 $post->actor->displayName = $self[0]['name'];
836 $post->actor->url = $self[0]['url'];
837 $post->actor->image->url = $self[0]['photo'];
839 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
840 dbesc($post->actor->url),
845 $contactid = $r[0]['id'];
848 $contactid = $orig_post['contact-id'];
851 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
852 dbesc(ACTIVITY_LIKE),
855 dbesc($orig_post['uri'])
859 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
864 $likedata['parent'] = $orig_post['id'];
865 $likedata['verb'] = ACTIVITY_LIKE;
866 $likedata['gravity'] = 3;
867 $likedata['uid'] = $uid;
868 $likedata['wall'] = 0;
869 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
870 $likedata['parent-uri'] = $orig_post["uri"];
871 $likedata['contact-id'] = $contactid;
872 $likedata['app'] = $post->generator->displayName;
873 $likedata['author-name'] = $post->actor->displayName;
874 $likedata['author-link'] = $post->actor->url;
875 $likedata['author-avatar'] = $post->actor->image->url;
877 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
878 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
879 $post_type = t('status');
880 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
881 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
883 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
885 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
886 '<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>';
888 $ret = item_store($likedata);
890 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
893 function pumpio_get_contact($uid, $contact) {
895 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
896 dbesc(normalise_link($contact->url)));
899 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
900 dbesc(normalise_link($contact->url)),
901 dbesc($contact->displayName),
902 dbesc($contact->preferredUsername),
903 dbesc($contact->image->url));
905 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
906 dbesc($contact->displayName),
907 dbesc($contact->preferredUsername),
908 dbesc($contact->image->url),
909 dbesc(normalise_link($contact->url)));
911 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
912 intval($uid), dbesc($contact->url));
915 // create contact record
916 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
917 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
918 `writable`, `blocked`, `readonly`, `pending` )
919 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
921 dbesc(datetime_convert()),
922 dbesc($contact->url),
923 dbesc(normalise_link($contact->url)),
924 dbesc(str_replace("acct:", "", $contact->id)),
926 dbesc($contact->id), // What is it for?
927 dbesc('pump.io ' . $contact->id), // What is it for?
928 dbesc($contact->displayName),
929 dbesc($contact->preferredUsername),
930 dbesc($contact->image->url),
931 dbesc(NETWORK_PUMPIO),
932 intval(CONTACT_IS_FRIEND),
937 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
938 dbesc($contact->url),
945 $contact_id = $r[0]['id'];
947 $g = q("select def_gid from user where uid = %d limit 1",
951 if($g && intval($g[0]['def_gid'])) {
952 require_once('include/group.php');
953 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
956 require_once("Photo.php");
958 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
960 q("UPDATE `contact` SET `photo` = '%s',
971 dbesc(datetime_convert()),
972 dbesc(datetime_convert()),
973 dbesc(datetime_convert()),
977 // update profile photos once every two weeks as we have no notification of when they change.
979 $update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
981 // check that we have all the photos, this has been known to fail on occasion
983 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
984 require_once("Photo.php");
986 $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
988 q("UPDATE `contact` SET `photo` = '%s',
993 `avatar-date` = '%s',
1001 dbesc(datetime_convert()),
1002 dbesc(datetime_convert()),
1003 dbesc(datetime_convert()),
1004 dbesc($contact->displayName),
1005 dbesc($contact->preferredUsername),
1012 return($r[0]["id"]);
1015 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1017 // Two queries for speed issues
1018 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1019 dbesc($post->object->id),
1024 return drop_item($r[0]["id"], $false);
1026 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1027 dbesc($post->object->id),
1032 return drop_item($r[0]["id"], $false);
1035 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = false) {
1036 require_once('include/items.php');
1037 require_once('include/html2bbcode.php');
1039 if (($post->verb == "like") OR ($post->verb == "favorite"))
1040 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1042 if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
1043 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1045 if ($post->verb == "delete")
1046 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1048 if ($post->verb != "update") {
1049 // Two queries for speed issues
1050 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1051 dbesc($post->object->id),
1058 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1059 dbesc($post->object->id),
1067 // Only handle these three types
1068 if (!strstr("post|share|update", $post->verb))
1071 $receiptians = array();
1072 if (@is_array($post->cc))
1073 $receiptians = array_merge($receiptians, $post->cc);
1075 if (@is_array($post->to))
1076 $receiptians = array_merge($receiptians, $post->to);
1078 foreach ($receiptians AS $receiver)
1079 if (is_string($receiver->objectType))
1080 if ($receiver->id == "http://activityschema.org/collection/public")
1083 $postarray = array();
1084 $postarray['gravity'] = 0;
1085 $postarray['uid'] = $uid;
1086 $postarray['wall'] = 0;
1087 $postarray['uri'] = $post->object->id;
1088 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1090 if ($post->object->objectType != "comment") {
1091 $contact_id = pumpio_get_contact($uid, $post->actor);
1094 $contact_id = $self[0]['id'];
1096 $postarray['parent-uri'] = $post->object->id;
1100 if(link_compare($post->actor->url, $own_id)) {
1101 $contact_id = $self[0]['id'];
1102 $post->actor->displayName = $self[0]['name'];
1103 $post->actor->url = $self[0]['url'];
1104 $post->actor->image->url = $self[0]['photo'];
1106 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1107 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1108 dbesc($post->actor->url),
1113 $contact_id = $r[0]['id'];
1115 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1116 dbesc($post->actor->url),
1121 $contact_id = $r[0]['id'];
1123 $contact_id = $self[0]['id'];
1127 $reply = new stdClass;
1128 $reply->verb = "note";
1129 $reply->cc = $post->cc;
1130 $reply->to = $post->to;
1131 $reply->object = new stdClass;
1132 $reply->object->objectType = $post->object->inReplyTo->objectType;
1133 $reply->object->content = $post->object->inReplyTo->content;
1134 $reply->object->id = $post->object->inReplyTo->id;
1135 $reply->actor = $post->object->inReplyTo->author;
1136 $reply->url = $post->object->inReplyTo->url;
1137 $reply->generator = new stdClass;
1138 $reply->generator->displayName = "pumpio";
1139 $reply->published = $post->object->inReplyTo->published;
1140 $reply->received = $post->object->inReplyTo->updated;
1141 $reply->url = $post->object->inReplyTo->url;
1142 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id);
1144 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1147 if ($post->object->pump_io->proxyURL)
1148 $postarray['extid'] = $post->object->pump_io->proxyURL;
1150 $postarray['contact-id'] = $contact_id;
1151 $postarray['verb'] = ACTIVITY_POST;
1152 $postarray['owner-name'] = $post->actor->displayName;
1153 $postarray['owner-link'] = $post->actor->url;
1154 $postarray['owner-avatar'] = $post->actor->image->url;
1155 $postarray['author-name'] = $post->actor->displayName;
1156 $postarray['author-link'] = $post->actor->url;
1157 $postarray['author-avatar'] = $post->actor->image->url;
1158 $postarray['plink'] = $post->object->url;
1159 $postarray['app'] = $post->generator->displayName;
1160 $postarray['body'] = html2bbcode($post->object->content);
1162 if ($post->object->fullImage->url != "")
1163 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1165 if ($post->object->displayName != "")
1166 $postarray['title'] = $post->object->displayName;
1168 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1169 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1171 $postarray['private'] = 1;
1172 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1175 if ($post->verb == "share") {
1176 if (!intval(get_config('system','wall-to-wall_share'))) {
1177 $postarray['body'] = "[share author='".$post->object->author->displayName.
1178 "' profile='".$post->object->author->url.
1179 "' avatar='".$post->object->author->image->url.
1180 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1182 // Let shares look like wall-to-wall posts
1183 $postarray['author-name'] = $post->object->author->displayName;
1184 $postarray['author-link'] = $post->object->author->url;
1185 $postarray['author-avatar'] = $post->object->author->image->url;
1189 if (trim($postarray['body']) == "")
1192 $top_item = item_store($postarray);
1194 if (($top_item == 0) AND ($post->verb == "update")) {
1195 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1196 dbesc($postarray["title"]),
1197 dbesc($postarray["body"]),
1198 dbesc($postarray["edited"]),
1199 dbesc($postarray["uri"]),
1204 if ($post->object->objectType == "comment") {
1206 if ($threadcompletion)
1207 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1209 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1216 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1218 if (link_compare($own_id, $postarray['author-link']))
1221 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1222 dbesc($postarray['parent-uri']),
1226 if(count($myconv)) {
1228 foreach($myconv as $conv) {
1229 // now if we find a match, it means we're in this conversation
1231 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_id))
1234 require_once('include/enotify.php');
1236 $conv_parent = $conv['parent'];
1239 'type' => NOTIFY_COMMENT,
1240 'notify_flags' => $user[0]['notify-flags'],
1241 'language' => $user[0]['language'],
1242 'to_name' => $user[0]['username'],
1243 'to_email' => $user[0]['email'],
1244 'uid' => $user[0]['uid'],
1245 'item' => $postarray,
1246 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1247 'source_name' => $postarray['author-name'],
1248 'source_link' => $postarray['author-link'],
1249 'source_photo' => $postarray['author-avatar'],
1250 'verb' => ACTIVITY_POST,
1252 'parent' => $conv_parent,
1255 // only send one notification
1264 function pumpio_fetchinbox(&$a, $uid) {
1266 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1267 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1268 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1269 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1270 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1271 $hostname = get_pconfig($uid, 'pumpio','host');
1272 $username = get_pconfig($uid, "pumpio", "user");
1274 $own_id = "https://".$hostname."/".$username;
1276 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1279 $client = new oauth_client_class;
1280 $client->oauth_version = '1.0a';
1281 $client->authorization_header = true;
1282 $client->url_parameters = false;
1284 $client->client_id = $ckey;
1285 $client->client_secret = $csecret;
1286 $client->access_token = $otoken;
1287 $client->access_token_secret = $osecret;
1289 $last_id = get_pconfig($uid,'pumpio','last_id');
1291 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1294 $url .= '?since='.urlencode($last_id);
1296 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1299 $posts = array_reverse($user->items);
1302 foreach ($posts as $post) {
1303 $last_id = $post->id;
1304 pumpio_dopost($a, $client, $uid, $self, $post, $own_id);
1308 set_pconfig($uid,'pumpio','last_id', $last_id);
1311 function pumpio_getallusers(&$a, $uid) {
1312 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1313 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1314 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1315 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1316 $hostname = get_pconfig($uid, 'pumpio','host');
1317 $username = get_pconfig($uid, "pumpio", "user");
1319 $client = new oauth_client_class;
1320 $client->oauth_version = '1.0a';
1321 $client->authorization_header = true;
1322 $client->url_parameters = false;
1324 $client->client_id = $ckey;
1325 $client->client_secret = $csecret;
1326 $client->access_token = $otoken;
1327 $client->access_token_secret = $osecret;
1329 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1331 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1333 if ($users->totalItems > count($users->items)) {
1334 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1336 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1339 foreach ($users->items AS $user)
1340 pumpio_get_contact($uid, $user);
1343 function pumpio_queue_hook(&$a,&$b) {
1345 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1346 dbesc(NETWORK_PUMPIO)
1351 require_once('include/queue_fn.php');
1353 foreach($qi as $x) {
1354 if($x['network'] !== NETWORK_PUMPIO)
1357 logger('pumpio_queue: run');
1359 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
1360 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1368 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1370 $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token");
1371 $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret");
1372 $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key");
1373 $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret");
1375 $host = get_pconfig($userdata['uid'], "pumpio", "host");
1376 $user = get_pconfig($userdata['uid'], "pumpio", "user");
1380 if ($oauth_token AND $oauth_token_secret AND
1381 $consumer_key AND $consumer_secret) {
1382 $username = $user.'@'.$host;
1384 logger('pumpio_queue: able to post for user '.$username);
1386 $z = unserialize($x['content']);
1388 $client = new oauth_client_class;
1389 $client->oauth_version = '1.0a';
1390 $client->url_parameters = false;
1391 $client->authorization_header = true;
1392 $client->access_token = $oauth_token;
1393 $client->access_token_secret = $oauth_token_secret;
1394 $client->client_id = $consumer_key;
1395 $client->client_secret = $consumer_secret;
1397 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1400 $post_id = $user->object->id;
1401 logger('pumpio_queue: send '.$username.': success '.$post_id);
1402 if($post_id AND $iscomment) {
1403 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1404 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1409 remove_queue_item($x['id']);
1411 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1413 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1416 logger('pumpio_queue: delayed');
1417 update_queue_time($x['id']);
1422 function pumpio_getreceiver(&$a, $b) {
1424 $receiver = array();
1426 if (!$b["private"]) {
1428 if(! strstr($b['postopts'],'pumpio'))
1431 $public = get_pconfig($b['uid'], "pumpio", "public");
1434 $receiver["to"][] = Array(
1435 "objectType" => "collection",
1436 "id" => "http://activityschema.org/collection/public");
1438 $cids = explode("><", $b["allow_cid"]);
1439 $gids = explode("><", $b["allow_gid"]);
1441 foreach ($cids AS $cid) {
1442 $cid = trim($cid, " <>");
1444 $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",
1447 dbesc(NETWORK_PUMPIO)
1451 $receiver["bcc"][] = Array(
1452 "displayName" => $r[0]["name"],
1453 "objectType" => "person",
1454 "preferredUsername" => $r[0]["nick"],
1455 "url" => $r[0]["url"]);
1458 foreach ($gids AS $gid) {
1459 $gid = trim($gid, " <>");
1461 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1462 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1463 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1466 dbesc(NETWORK_PUMPIO)
1469 foreach ($r AS $row)
1470 $receiver["bcc"][] = Array(
1471 "displayName" => $row["name"],
1472 "objectType" => "person",
1473 "preferredUsername" => $row["nick"],
1474 "url" => $row["url"]);
1478 if ($b["inform"] != "") {
1480 $inform = explode(",", $b["inform"]);
1482 foreach ($inform AS $cid) {
1483 if (substr($cid, 0, 4) != "cid:")
1486 $cid = str_replace("cid:", "", $cid);
1488 $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",
1491 dbesc(NETWORK_PUMPIO)
1495 $receiver["to"][] = Array(
1496 "displayName" => $r[0]["name"],
1497 "objectType" => "person",
1498 "preferredUsername" => $r[0]["nick"],
1499 "url" => $r[0]["url"]);
1507 function pumpio_fetchallcomments(&$a, $uid, $id) {
1508 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1509 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1510 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1511 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1512 $hostname = get_pconfig($uid, 'pumpio','host');
1513 $username = get_pconfig($uid, "pumpio", "user");
1515 $own_id = "https://".$hostname."/".$username;
1517 logger("pumpio_fetchallcomments: completing comment for user ".$uid." url ".$url);
1519 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1522 // Fetching the original post - Two queries for speed issues
1523 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1529 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1539 $url = $r[0]["extid"];
1543 $client = new oauth_client_class;
1544 $client->oauth_version = '1.0a';
1545 $client->authorization_header = true;
1546 $client->url_parameters = false;
1548 $client->client_id = $ckey;
1549 $client->client_secret = $csecret;
1550 $client->access_token = $otoken;
1551 $client->access_token_secret = $osecret;
1553 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1555 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1560 if ($item->replies->totalItems == 0)
1563 foreach ($item->replies->items AS $item) {
1564 if ($item->id == $id)
1567 // Checking if the comment already exists - Two queries for speed issues
1568 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1576 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1584 $post->verb = "post";
1585 $post->actor = $item->author;
1586 $post->published = $item->published;
1587 $post->received = $item->updated;
1588 $post->generator->displayName = "pumpio";
1590 unset($item->author);
1591 unset($item->published);
1592 unset($item->updated);
1594 $post->object = $item;
1596 logger("pumpio_fetchallcomments: posting comment ".$post->object->id);
1597 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1603 - refresh after post doesn't always happen