3 * Name: pump.io Post Connector
4 * Description: Bidirectional (posting, relaying and reading) connector for 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');
10 require_once('include/enotify.php');
12 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
14 function pumpio_install() {
15 register_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
16 register_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
17 register_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
18 register_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
19 register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
20 register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
21 register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
22 register_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
25 function pumpio_uninstall() {
26 unregister_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
27 unregister_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
28 unregister_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
29 unregister_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
30 unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
31 unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
32 unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
33 unregister_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
36 function pumpio_module() {}
38 function pumpio_content(&$a) {
41 notice( t('Permission denied.') . EOL);
45 require_once("mod/settings.php");
48 if (isset($a->argv[1]))
49 switch ($a->argv[1]) {
51 $o = pumpio_connect($a);
54 $o = print_r($a->argv, true);
58 $o = pumpio_connect($a);
63 function pumpio_check_item_notification($a, &$notification_data) {
64 $hostname = get_pconfig($notification_data["uid"], 'pumpio','host');
65 $username = get_pconfig($notification_data["uid"], "pumpio", "user");
67 $notification_data["profiles"][] = "https://".$hostname."/".$username;
71 function pumpio_registerclient(&$a, $host) {
73 $url = "https://".$host."/api/client/register";
77 $application_name = get_config('pumpio', 'application_name');
79 if ($application_name == "")
80 $application_name = $a->get_hostname();
82 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
84 $params["type"] = "client_associate";
85 $params["contacts"] = $adminlist[0];
86 $params["application_type"] = "native";
87 $params["application_name"] = $application_name;
88 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
89 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
91 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
93 $ch = curl_init($url);
94 curl_setopt($ch, CURLOPT_HEADER, false);
95 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
96 curl_setopt($ch, CURLOPT_POST,1);
97 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
98 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
101 $curl_info = curl_getinfo($ch);
103 if ($curl_info["http_code"] == "200") {
104 $values = json_decode($s);
105 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
108 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
113 function pumpio_connect(&$a) {
114 // Start a session. This is necessary to hold on to a few keys the callback script will also need
117 // Define the needed keys
118 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
119 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
120 $hostname = get_pconfig(local_user(), 'pumpio','host');
122 if ((($consumer_key == "") OR ($consumer_secret == "")) AND ($hostname != "")) {
123 logger("pumpio_connect: register client");
124 $clientdata = pumpio_registerclient($a, $hostname);
125 set_pconfig(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
126 set_pconfig(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
128 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
129 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
131 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
134 if (($consumer_key == "") OR ($consumer_secret == "")) {
135 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
137 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
141 // The callback URL is the script that gets called after the user authenticates with pumpio
142 $callback_url = $a->get_baseurl()."/pumpio/connect";
144 // Let's begin. First we need a Request Token. The request token is required to send the user
145 // to pumpio's login page.
147 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
148 // Consumer Key and Consumer Secret
149 $client = new oauth_client_class;
151 $client->server = '';
152 $client->oauth_version = '1.0a';
153 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
154 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
155 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
156 $client->url_parameters = false;
157 $client->authorization_header = true;
158 $client->redirect_uri = $callback_url;
159 $client->client_id = $consumer_key;
160 $client->client_secret = $consumer_secret;
162 if (($success = $client->Initialize())) {
163 if (($success = $client->Process())) {
164 if (strlen($client->access_token)) {
165 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
166 set_pconfig(local_user(), "pumpio", "oauth_token", $client->access_token);
167 set_pconfig(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
170 $success = $client->Finalize($success);
173 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
176 logger("pumpio_connect: authenticated");
177 $o .= t("You are now authenticated to pumpio.");
178 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
180 logger("pumpio_connect: could not connect");
181 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
187 function pumpio_jot_nets(&$a,&$b) {
191 $pumpio_post = get_pconfig(local_user(),'pumpio','post');
192 if(intval($pumpio_post) == 1) {
193 $pumpio_defpost = get_pconfig(local_user(),'pumpio','post_by_default');
194 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
195 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
196 . t('Post to pumpio') . '</div>';
201 function pumpio_settings(&$a,&$s) {
206 /* Add our stylesheet to the page so we can make our settings look nice */
208 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
210 /* Get the current state of our config variables */
212 $import_enabled = get_pconfig(local_user(),'pumpio','import');
213 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
215 $enabled = get_pconfig(local_user(),'pumpio','post');
216 $checked = (($enabled) ? ' checked="checked" ' : '');
217 $css = (($enabled) ? '' : '-disabled');
219 $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default');
220 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
222 $public_enabled = get_pconfig(local_user(),'pumpio','public');
223 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
225 $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror');
226 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
228 $servername = get_pconfig(local_user(), "pumpio", "host");
229 $username = get_pconfig(local_user(), "pumpio", "user");
231 /* Add some HTML to the existing form */
233 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
234 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
236 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
237 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
238 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
241 $s .= '<div id="pumpio-username-wrapper">';
242 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
243 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
244 $s .= '</div><div class="clear"></div>';
246 $s .= '<div id="pumpio-servername-wrapper">';
247 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
248 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
249 $s .= '</div><div class="clear"></div>';
251 if (($username != '') AND ($servername != '')) {
253 $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token");
254 $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret");
256 $s .= '<div id="pumpio-password-wrapper">';
257 if (($oauth_token == "") OR ($oauth_token_secret == "")) {
258 $s .= '<div id="pumpio-authenticate-wrapper">';
259 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
260 $s .= '</div><div class="clear"></div>';
262 $s .= '<div id="pumpio-import-wrapper">';
263 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
264 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
265 $s .= '</div><div class="clear"></div>';
267 $s .= '<div id="pumpio-enable-wrapper">';
268 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
269 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
270 $s .= '</div><div class="clear"></div>';
272 $s .= '<div id="pumpio-bydefault-wrapper">';
273 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
274 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
275 $s .= '</div><div class="clear"></div>';
277 $s .= '<div id="pumpio-public-wrapper">';
278 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
279 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
280 $s .= '</div><div class="clear"></div>';
282 $s .= '<div id="pumpio-mirror-wrapper">';
283 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
284 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
285 $s .= '</div><div class="clear"></div>';
287 $s .= '<div id="pumpio-delete-wrapper">';
288 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
289 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
290 $s .= '</div><div class="clear"></div>';
293 $s .= '</div><div class="clear"></div>';
296 /* provide a submit button */
298 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
302 function pumpio_settings_post(&$a,&$b) {
304 if(x($_POST,'pumpio-submit')) {
305 if(x($_POST,'pumpio_delete')) {
306 set_pconfig(local_user(),'pumpio','consumer_key','');
307 set_pconfig(local_user(),'pumpio','consumer_secret','');
308 set_pconfig(local_user(),'pumpio','oauth_token','');
309 set_pconfig(local_user(),'pumpio','oauth_token_secret','');
310 set_pconfig(local_user(),'pumpio','post',false);
311 set_pconfig(local_user(),'pumpio','import',false);
312 set_pconfig(local_user(),'pumpio','host','');
313 set_pconfig(local_user(),'pumpio','user','');
314 set_pconfig(local_user(),'pumpio','public',false);
315 set_pconfig(local_user(),'pumpio','mirror',false);
316 set_pconfig(local_user(),'pumpio','post_by_default',false);
317 set_pconfig(local_user(),'pumpio','lastdate', 0);
318 set_pconfig(local_user(),'pumpio','last_id', '');
320 // filtering the username if it is filled wrong
321 $user = $_POST['pumpio_user'];
322 if (strstr($user, "@")) {
323 $pos = strpos($user, "@");
325 $user = substr($user, 0, $pos);
328 // Filtering the hostname if someone is entering it with "http"
329 $host = $_POST['pumpio_host'];
331 $host = str_replace(array("https://", "http://"), array("", ""), $host);
333 set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
334 set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
335 set_pconfig(local_user(),'pumpio','host',$host);
336 set_pconfig(local_user(),'pumpio','user',$user);
337 set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
338 set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
339 set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
341 if (!$_POST['pumpio_mirror'])
342 del_pconfig(local_user(),'pumpio','lastdate');
344 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
349 function pumpio_post_local(&$a,&$b) {
351 if((! local_user()) || (local_user() != $b['uid']))
354 $pumpio_post = intval(get_pconfig(local_user(),'pumpio','post'));
356 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
358 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
364 if(strlen($b['postopts']))
365 $b['postopts'] .= ',';
367 $b['postopts'] .= 'pumpio';
373 function pumpio_send(&$a,&$b) {
375 if (!get_pconfig($b["uid"],'pumpio','import')) {
376 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
380 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
382 if($b['parent'] != $b['id']) {
383 // Looking if its a reply to a pumpio post
384 $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",
385 intval($b["parent"]),
387 dbesc(NETWORK_PUMPIO));
390 logger("pumpio_send: no pumpio post ".$b["parent"]);
399 $receiver = pumpio_getreceiver($a, $b);
401 logger("pumpio_send: receiver ".print_r($receiver, true));
403 if (!count($receiver) AND ($b['private'] OR !strstr($b['postopts'],'pumpio')))
407 if($b['verb'] == ACTIVITY_LIKE) {
409 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
411 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
415 if($b['verb'] == ACTIVITY_DISLIKE)
418 if (($b['verb'] == ACTIVITY_POST) AND ($b['created'] !== $b['edited']) AND !$b['deleted'])
419 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
421 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
422 pumpio_action($a, $b["uid"], $b["uri"], "delete");
424 if($b['deleted'] || ($b['created'] !== $b['edited']))
427 // if post comes from pump.io don't send it back
428 if($b['app'] == "pump.io")
432 // Support for native shares
433 // http://<hostname>/api/<type>/shares?id=<the-object-id>
435 $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
436 $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
437 $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
438 $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
440 $host = get_pconfig($b['uid'], "pumpio", "host");
441 $user = get_pconfig($b['uid'], "pumpio", "user");
442 $public = get_pconfig($b['uid'], "pumpio", "public");
444 if($oauth_token && $oauth_token_secret) {
446 require_once('include/bbcode.php');
448 $title = trim($b['title']);
450 $content = bbcode($b['body'], false, false, 4);
454 $params["verb"] = "post";
457 $params["object"] = array(
458 'objectType' => "note",
459 'content' => $content);
462 $params["object"]["displayName"] = $title;
464 if (count($receiver["to"]))
465 $params["to"] = $receiver["to"];
467 if (count($receiver["bto"]))
468 $params["bto"] = $receiver["bto"];
470 if (count($receiver["cc"]))
471 $params["cc"] = $receiver["cc"];
473 if (count($receiver["bcc"]))
474 $params["bcc"] = $receiver["bcc"];
477 $inReplyTo = array("id" => $orig_post["uri"],
478 "objectType" => "note");
480 if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
481 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
483 $params["object"] = array(
484 'objectType' => "comment",
485 'content' => $content,
486 'inReplyTo' => $inReplyTo);
489 $params["object"]["displayName"] = $title;
492 $client = new oauth_client_class;
493 $client->oauth_version = '1.0a';
494 $client->url_parameters = false;
495 $client->authorization_header = true;
496 $client->access_token = $oauth_token;
497 $client->access_token_secret = $oauth_token_secret;
498 $client->client_id = $consumer_key;
499 $client->client_secret = $consumer_secret;
501 $username = $user.'@'.$host;
502 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
504 if (pumpio_reachable($url))
505 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
511 if ($user->generator->displayName)
512 set_pconfig($b["uid"], "pumpio", "application_name", $user->generator->displayName);
514 $post_id = $user->object->id;
515 logger('pumpio_send '.$username.': success '.$post_id);
516 if($post_id AND $iscomment) {
517 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
518 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
524 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
526 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
528 $a->contact = $r[0]["id"];
530 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
531 require_once('include/queue_fn.php');
532 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
533 notice(t('Pump.io post failed. Queued for retry.').EOL);
539 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
541 // Don't do likes and other stuff if you don't import the timeline
542 if (!get_pconfig($uid,'pumpio','import'))
545 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
546 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
547 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
548 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
549 $hostname = get_pconfig($uid, 'pumpio','host');
550 $username = get_pconfig($uid, "pumpio", "user");
552 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
562 if ($orig_post["extid"] AND !strstr($orig_post["extid"], "/proxy/"))
563 $uri = $orig_post["extid"];
565 $uri = $orig_post["uri"];
567 if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
568 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
569 elseif (strstr($uri, "/api/comment/"))
570 $objectType = "comment";
571 elseif (strstr($uri, "/api/note/"))
572 $objectType = "note";
573 elseif (strstr($uri, "/api/image/"))
574 $objectType = "image";
576 $params["verb"] = $action;
577 $params["object"] = array('id' => $uri,
578 "objectType" => $objectType,
579 "content" => $content);
581 $client = new oauth_client_class;
582 $client->oauth_version = '1.0a';
583 $client->authorization_header = true;
584 $client->url_parameters = false;
586 $client->client_id = $ckey;
587 $client->client_secret = $csecret;
588 $client->access_token = $otoken;
589 $client->access_token_secret = $osecret;
591 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
593 if (pumpio_reachable($url))
594 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
599 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
601 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
603 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
605 $a->contact = $r[0]["id"];
607 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
608 require_once('include/queue_fn.php');
609 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
610 notice(t('Pump.io like failed. Queued for retry.').EOL);
614 function pumpio_sync(&$a) {
615 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
621 $last = get_config('pumpio','last_poll');
623 $poll_interval = intval(get_config('pumpio','poll_interval'));
625 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
628 $next = $last + ($poll_interval * 60);
630 logger('pumpio: poll intervall not reached');
634 logger('pumpio: cron_start');
636 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
639 logger('pumpio: mirroring user '.$rr['uid']);
640 pumpio_fetchtimeline($a, $rr['uid']);
644 $abandon_days = intval(get_config('system','account_abandon_days'));
645 if ($abandon_days < 1)
648 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
650 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
653 if ($abandon_days != 0) {
654 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
656 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
661 logger('pumpio: importing timeline from user '.$rr['uid']);
662 pumpio_fetchinbox($a, $rr['uid']);
664 // check for new contacts once a day
665 $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check');
666 if($last_contact_check)
667 $next_contact_check = $last_contact_check + 86400;
669 $next_contact_check = 0;
671 if($next_contact_check <= time()) {
672 pumpio_getallusers($a, $rr["uid"]);
673 set_pconfig($rr['uid'],'pumpio','contact_check',time());
678 logger('pumpio: cron_end');
680 set_config('pumpio','last_poll', time());
683 function pumpio_cron(&$a,$b) {
685 proc_run("php","addon/pumpio/pumpio_sync.php");
688 function pumpio_fetchtimeline(&$a, $uid) {
689 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
690 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
691 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
692 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
693 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
694 $hostname = get_pconfig($uid, 'pumpio','host');
695 $username = get_pconfig($uid, "pumpio", "user");
697 // get the application name for the pump.io app
698 // 1st try personal config, then system config and fallback to the
699 // hostname of the node if neither one is set.
700 $application_name = get_pconfig( $uid, 'pumpio', 'application_name');
701 if ($application_name == "")
702 $application_name = get_config('pumpio', 'application_name');
703 if ($application_name == "")
704 $application_name = $a->get_hostname();
706 $first_time = ($lastdate == "");
708 $client = new oauth_client_class;
709 $client->oauth_version = '1.0a';
710 $client->authorization_header = true;
711 $client->url_parameters = false;
713 $client->client_id = $ckey;
714 $client->client_secret = $csecret;
715 $client->access_token = $otoken;
716 $client->access_token_secret = $osecret;
718 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
720 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
722 $username = $user.'@'.$host;
724 if (pumpio_reachable($url))
725 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
730 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
734 $posts = array_reverse($user->items);
736 $initiallastdate = $lastdate;
740 foreach ($posts as $post) {
741 if ($post->published <= $initiallastdate)
744 if ($lastdate < $post->published)
745 $lastdate = $post->published;
750 $receiptians = array();
751 if (@is_array($post->cc))
752 $receiptians = array_merge($receiptians, $post->cc);
754 if (@is_array($post->to))
755 $receiptians = array_merge($receiptians, $post->to);
758 foreach ($receiptians AS $receiver)
759 if (is_string($receiver->objectType))
760 if ($receiver->id == "http://activityschema.org/collection/public")
763 if ($public AND !stristr($post->generator->displayName, $application_name)) {
764 require_once('include/html2bbcode.php');
766 $_SESSION["authenticated"] = true;
767 $_SESSION["uid"] = $uid;
770 $_REQUEST["type"] = "wall";
771 $_REQUEST["api_source"] = true;
772 $_REQUEST["profile_uid"] = $uid;
773 $_REQUEST["source"] = "pump.io";
775 if ($post->object->displayName != "")
776 $_REQUEST["title"] = html2bbcode($post->object->displayName);
778 $_REQUEST["title"] = "";
780 $_REQUEST["body"] = html2bbcode($post->object->content);
782 // To-Do: Picture has to be cached and stored locally
783 if ($post->object->fullImage->url != "") {
784 if ($post->object->fullImage->pump_io->proxyURL != "")
785 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
787 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
790 logger('pumpio: posting for user '.$uid);
792 require_once('mod/item.php');
795 logger('pumpio: posting done - user '.$uid);
801 set_pconfig($uid,'pumpio','lastdate', $lastdate);
804 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
805 // Searching for the unliked post
806 // Two queries for speed issues
807 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
808 dbesc($post->object->id),
815 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
816 dbesc($post->object->id),
828 if(link_compare($post->actor->url, $own_id)) {
829 $contactid = $self[0]['id'];
831 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
832 dbesc($post->actor->url),
837 $contactid = $r[0]['id'];
840 $contactid = $orig_post['contact-id'];
843 $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'",
844 dbesc(datetime_convert()),
845 dbesc(ACTIVITY_LIKE),
848 dbesc($orig_post['uri'])
852 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
854 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
857 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
858 require_once('include/items.php');
860 // Searching for the liked post
861 // Two queries for speed issues
862 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
863 dbesc($post->object->id),
865 dbesc(NETWORK_PUMPIO)
871 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
872 dbesc($post->object->id),
874 dbesc(NETWORK_PUMPIO)
884 if ($threadcompletion)
885 pumpio_fetchallcomments($a, $uid, $post->object->id);
889 if(link_compare($post->actor->url, $own_id)) {
890 $contactid = $self[0]['id'];
891 $post->actor->displayName = $self[0]['name'];
892 $post->actor->url = $self[0]['url'];
893 $post->actor->image->url = $self[0]['photo'];
895 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
896 dbesc($post->actor->url),
901 $contactid = $r[0]['id'];
904 $contactid = $orig_post['contact-id'];
907 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
908 dbesc(ACTIVITY_LIKE),
911 dbesc($orig_post['uri'])
915 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
920 $likedata['parent'] = $orig_post['id'];
921 $likedata['verb'] = ACTIVITY_LIKE;
922 $likedata['gravity'] = 3;
923 $likedata['uid'] = $uid;
924 $likedata['wall'] = 0;
925 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
926 $likedata['parent-uri'] = $orig_post["uri"];
927 $likedata['contact-id'] = $contactid;
928 $likedata['app'] = $post->generator->displayName;
929 $likedata['author-name'] = $post->actor->displayName;
930 $likedata['author-link'] = $post->actor->url;
931 $likedata['author-avatar'] = $post->actor->image->url;
933 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
934 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
935 $post_type = t('status');
936 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
937 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
939 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
941 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
942 '<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>';
944 $ret = item_store($likedata);
946 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
949 function pumpio_get_contact($uid, $contact) {
951 if (function_exists("update_gcontact"))
952 update_gcontact(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
953 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
954 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
955 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
958 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
959 dbesc(normalise_link($contact->url)));
962 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
963 dbesc(normalise_link($contact->url)),
964 dbesc($contact->displayName),
965 dbesc($contact->preferredUsername),
966 dbesc($contact->image->url));
968 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
969 dbesc($contact->displayName),
970 dbesc($contact->preferredUsername),
971 dbesc($contact->image->url),
972 dbesc(normalise_link($contact->url)));
974 if (DB_UPDATE_VERSION >= "1177")
975 q("UPDATE `unique_contacts` SET `location` = '%s', `about` = '%s' WHERE url = '%s'",
976 dbesc($contact->location->displayName),
977 dbesc($contact->summary),
978 dbesc(normalise_link($contact->url)));
981 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
982 intval($uid), dbesc($contact->url));
985 // create contact record
986 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
987 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
988 `writable`, `blocked`, `readonly`, `pending` )
989 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
991 dbesc(datetime_convert()),
992 dbesc($contact->url),
993 dbesc(normalise_link($contact->url)),
994 dbesc(str_replace("acct:", "", $contact->id)),
996 dbesc($contact->id), // What is it for?
997 dbesc('pump.io ' . $contact->id), // What is it for?
998 dbesc($contact->displayName),
999 dbesc($contact->preferredUsername),
1000 dbesc($contact->image->url),
1001 dbesc(NETWORK_PUMPIO),
1002 intval(CONTACT_IS_FRIEND),
1007 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
1008 dbesc($contact->url),
1015 $contact_id = $r[0]['id'];
1017 $g = q("select def_gid from user where uid = %d limit 1",
1021 if($g && intval($g[0]['def_gid'])) {
1022 require_once('include/group.php');
1023 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1026 require_once("Photo.php");
1028 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
1030 q("UPDATE `contact` SET `photo` = '%s',
1035 `avatar-date` = '%s'
1041 dbesc(datetime_convert()),
1042 dbesc(datetime_convert()),
1043 dbesc(datetime_convert()),
1047 if (DB_UPDATE_VERSION >= "1177")
1048 q("UPDATE `contact` SET `location` = '%s',
1051 dbesc($contact->location->displayName),
1052 dbesc($contact->summary),
1056 // update profile photos once every two weeks as we have no notification of when they change.
1057 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
1058 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1060 // check that we have all the photos, this has been known to fail on occasion
1062 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1063 require_once("Photo.php");
1065 $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
1067 q("UPDATE `contact` SET `photo` = '%s',
1072 `avatar-date` = '%s',
1080 dbesc(datetime_convert()),
1081 dbesc(datetime_convert()),
1082 dbesc(datetime_convert()),
1083 dbesc($contact->displayName),
1084 dbesc($contact->preferredUsername),
1088 if (DB_UPDATE_VERSION >= "1177")
1089 q("UPDATE `contact` SET `location` = '%s',
1092 dbesc($contact->location->displayName),
1093 dbesc($contact->summary),
1100 return($r[0]["id"]);
1103 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1105 // Two queries for speed issues
1106 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1107 dbesc($post->object->id),
1112 return drop_item($r[0]["id"], $false);
1114 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1115 dbesc($post->object->id),
1120 return drop_item($r[0]["id"], $false);
1123 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1124 require_once('include/items.php');
1125 require_once('include/html2bbcode.php');
1127 if (($post->verb == "like") OR ($post->verb == "favorite"))
1128 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1130 if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
1131 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1133 if ($post->verb == "delete")
1134 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1136 if ($post->verb != "update") {
1137 // Two queries for speed issues
1138 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1139 dbesc($post->object->id),
1146 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1147 dbesc($post->object->id),
1155 // Only handle these three types
1156 if (!strstr("post|share|update", $post->verb))
1159 $receiptians = array();
1160 if (@is_array($post->cc))
1161 $receiptians = array_merge($receiptians, $post->cc);
1163 if (@is_array($post->to))
1164 $receiptians = array_merge($receiptians, $post->to);
1166 foreach ($receiptians AS $receiver)
1167 if (is_string($receiver->objectType))
1168 if ($receiver->id == "http://activityschema.org/collection/public")
1171 $postarray = array();
1172 $postarray['network'] = NETWORK_PUMPIO;
1173 $postarray['gravity'] = 0;
1174 $postarray['uid'] = $uid;
1175 $postarray['wall'] = 0;
1176 $postarray['uri'] = $post->object->id;
1177 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1179 if ($post->object->objectType != "comment") {
1180 $contact_id = pumpio_get_contact($uid, $post->actor);
1183 $contact_id = $self[0]['id'];
1185 $postarray['parent-uri'] = $post->object->id;
1188 $postarray['private'] = 1;
1189 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1194 if(link_compare($post->actor->url, $own_id)) {
1195 $contact_id = $self[0]['id'];
1196 $post->actor->displayName = $self[0]['name'];
1197 $post->actor->url = $self[0]['url'];
1198 $post->actor->image->url = $self[0]['photo'];
1200 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1201 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1202 dbesc($post->actor->url),
1207 $contact_id = $r[0]['id'];
1209 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1210 dbesc($post->actor->url),
1215 $contact_id = $r[0]['id'];
1217 $contact_id = $self[0]['id'];
1221 $reply = new stdClass;
1222 $reply->verb = "note";
1223 $reply->cc = $post->cc;
1224 $reply->to = $post->to;
1225 $reply->object = new stdClass;
1226 $reply->object->objectType = $post->object->inReplyTo->objectType;
1227 $reply->object->content = $post->object->inReplyTo->content;
1228 $reply->object->id = $post->object->inReplyTo->id;
1229 $reply->actor = $post->object->inReplyTo->author;
1230 $reply->url = $post->object->inReplyTo->url;
1231 $reply->generator = new stdClass;
1232 $reply->generator->displayName = "pumpio";
1233 $reply->published = $post->object->inReplyTo->published;
1234 $reply->received = $post->object->inReplyTo->updated;
1235 $reply->url = $post->object->inReplyTo->url;
1236 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1238 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1241 if ($post->object->pump_io->proxyURL)
1242 $postarray['extid'] = $post->object->pump_io->proxyURL;
1244 $postarray['contact-id'] = $contact_id;
1245 $postarray['verb'] = ACTIVITY_POST;
1246 $postarray['owner-name'] = $post->actor->displayName;
1247 $postarray['owner-link'] = $post->actor->url;
1248 $postarray['owner-avatar'] = $post->actor->image->url;
1249 $postarray['author-name'] = $post->actor->displayName;
1250 $postarray['author-link'] = $post->actor->url;
1251 $postarray['author-avatar'] = $post->actor->image->url;
1252 $postarray['plink'] = $post->object->url;
1253 $postarray['app'] = $post->generator->displayName;
1254 $postarray['body'] = html2bbcode($post->object->content);
1255 $postarray['object'] = json_encode($post);
1257 if ($post->object->fullImage->url != "")
1258 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1260 if ($post->object->displayName != "")
1261 $postarray['title'] = $post->object->displayName;
1263 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1264 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1266 if ($post->verb == "share") {
1267 if (!intval(get_config('system','wall-to-wall_share'))) {
1268 $postarray['body'] = "[share author='".$post->object->author->displayName.
1269 "' profile='".$post->object->author->url.
1270 "' avatar='".$post->object->author->image->url.
1271 "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1272 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1274 // Let shares look like wall-to-wall posts
1275 $postarray['author-name'] = $post->object->author->displayName;
1276 $postarray['author-link'] = $post->object->author->url;
1277 $postarray['author-avatar'] = $post->object->author->image->url;
1281 if (trim($postarray['body']) == "")
1284 $top_item = item_store($postarray);
1285 $postarray["id"] = $top_item;
1287 if (($top_item == 0) AND ($post->verb == "update")) {
1288 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1289 dbesc($postarray["title"]),
1290 dbesc($postarray["body"]),
1291 dbesc($postarray["edited"]),
1292 dbesc($postarray["uri"]),
1297 if ($post->object->objectType == "comment") {
1299 if ($threadcompletion)
1300 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1302 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1309 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1311 if (link_compare($own_id, $postarray['author-link']))
1314 if (!function_exists("check_item_notification")) {
1315 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1316 dbesc($postarray['parent-uri']),
1320 if(count($myconv)) {
1322 foreach($myconv as $conv) {
1323 // now if we find a match, it means we're in this conversation
1325 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_id))
1328 require_once('include/enotify.php');
1330 $conv_parent = $conv['parent'];
1333 'type' => NOTIFY_COMMENT,
1334 'notify_flags' => $user[0]['notify-flags'],
1335 'language' => $user[0]['language'],
1336 'to_name' => $user[0]['username'],
1337 'to_email' => $user[0]['email'],
1338 'uid' => $user[0]['uid'],
1339 'item' => $postarray,
1340 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1341 'source_name' => $postarray['author-name'],
1342 'source_link' => $postarray['author-link'],
1343 'source_photo' => $postarray['author-avatar'],
1344 'verb' => ACTIVITY_POST,
1346 'parent' => $conv_parent,
1349 // only send one notification
1359 function pumpio_fetchinbox(&$a, $uid) {
1361 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1362 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1363 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1364 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1365 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1366 $hostname = get_pconfig($uid, 'pumpio','host');
1367 $username = get_pconfig($uid, "pumpio", "user");
1369 $own_id = "https://".$hostname."/".$username;
1371 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1374 $lastitems = q("SELECT uri FROM `item` WHERE `network` = '%s' AND `uid` = %d AND
1375 `extid` != '' AND `id` = `parent`
1376 ORDER BY `commented` DESC LIMIT 10",
1377 dbesc(NETWORK_PUMPIO),
1381 $client = new oauth_client_class;
1382 $client->oauth_version = '1.0a';
1383 $client->authorization_header = true;
1384 $client->url_parameters = false;
1386 $client->client_id = $ckey;
1387 $client->client_secret = $csecret;
1388 $client->access_token = $otoken;
1389 $client->access_token_secret = $osecret;
1391 $last_id = get_pconfig($uid,'pumpio','last_id');
1393 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1396 $url .= '?since='.urlencode($last_id);
1398 if (pumpio_reachable($url))
1399 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1404 $posts = array_reverse($user->items);
1407 foreach ($posts as $post) {
1408 $last_id = $post->id;
1409 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1413 foreach ($lastitems AS $item)
1414 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1416 set_pconfig($uid,'pumpio','last_id', $last_id);
1419 function pumpio_getallusers(&$a, $uid) {
1420 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1421 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1422 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1423 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1424 $hostname = get_pconfig($uid, 'pumpio','host');
1425 $username = get_pconfig($uid, "pumpio", "user");
1427 $client = new oauth_client_class;
1428 $client->oauth_version = '1.0a';
1429 $client->authorization_header = true;
1430 $client->url_parameters = false;
1432 $client->client_id = $ckey;
1433 $client->client_secret = $csecret;
1434 $client->access_token = $otoken;
1435 $client->access_token_secret = $osecret;
1437 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1439 if (pumpio_reachable($url))
1440 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1444 if ($users->totalItems > count($users->items)) {
1445 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1447 if (pumpio_reachable($url))
1448 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1453 foreach ($users->items AS $user)
1454 pumpio_get_contact($uid, $user);
1457 function pumpio_queue_hook(&$a,&$b) {
1459 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1460 dbesc(NETWORK_PUMPIO)
1465 require_once('include/queue_fn.php');
1467 foreach($qi as $x) {
1468 if($x['network'] !== NETWORK_PUMPIO)
1471 logger('pumpio_queue: run');
1473 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
1474 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1482 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1484 $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token");
1485 $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret");
1486 $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key");
1487 $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret");
1489 $host = get_pconfig($userdata['uid'], "pumpio", "host");
1490 $user = get_pconfig($userdata['uid'], "pumpio", "user");
1494 if ($oauth_token AND $oauth_token_secret AND
1495 $consumer_key AND $consumer_secret) {
1496 $username = $user.'@'.$host;
1498 logger('pumpio_queue: able to post for user '.$username);
1500 $z = unserialize($x['content']);
1502 $client = new oauth_client_class;
1503 $client->oauth_version = '1.0a';
1504 $client->url_parameters = false;
1505 $client->authorization_header = true;
1506 $client->access_token = $oauth_token;
1507 $client->access_token_secret = $oauth_token_secret;
1508 $client->client_id = $consumer_key;
1509 $client->client_secret = $consumer_secret;
1511 if (pumpio_reachable($z['url']))
1512 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1517 $post_id = $user->object->id;
1518 logger('pumpio_queue: send '.$username.': success '.$post_id);
1519 if($post_id AND $iscomment) {
1520 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1521 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1526 remove_queue_item($x['id']);
1528 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1530 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1533 logger('pumpio_queue: delayed');
1534 update_queue_time($x['id']);
1539 function pumpio_getreceiver(&$a, $b) {
1541 $receiver = array();
1543 if (!$b["private"]) {
1545 if(! strstr($b['postopts'],'pumpio'))
1548 $public = get_pconfig($b['uid'], "pumpio", "public");
1551 $receiver["to"][] = Array(
1552 "objectType" => "collection",
1553 "id" => "http://activityschema.org/collection/public");
1555 $cids = explode("><", $b["allow_cid"]);
1556 $gids = explode("><", $b["allow_gid"]);
1558 foreach ($cids AS $cid) {
1559 $cid = trim($cid, " <>");
1561 $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",
1564 dbesc(NETWORK_PUMPIO)
1568 $receiver["bcc"][] = Array(
1569 "displayName" => $r[0]["name"],
1570 "objectType" => "person",
1571 "preferredUsername" => $r[0]["nick"],
1572 "url" => $r[0]["url"]);
1575 foreach ($gids AS $gid) {
1576 $gid = trim($gid, " <>");
1578 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1579 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1580 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1583 dbesc(NETWORK_PUMPIO)
1586 foreach ($r AS $row)
1587 $receiver["bcc"][] = Array(
1588 "displayName" => $row["name"],
1589 "objectType" => "person",
1590 "preferredUsername" => $row["nick"],
1591 "url" => $row["url"]);
1595 if ($b["inform"] != "") {
1597 $inform = explode(",", $b["inform"]);
1599 foreach ($inform AS $cid) {
1600 if (substr($cid, 0, 4) != "cid:")
1603 $cid = str_replace("cid:", "", $cid);
1605 $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",
1608 dbesc(NETWORK_PUMPIO)
1612 $receiver["to"][] = Array(
1613 "displayName" => $r[0]["name"],
1614 "objectType" => "person",
1615 "preferredUsername" => $r[0]["nick"],
1616 "url" => $r[0]["url"]);
1624 function pumpio_fetchallcomments(&$a, $uid, $id) {
1625 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1626 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1627 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1628 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1629 $hostname = get_pconfig($uid, 'pumpio','host');
1630 $username = get_pconfig($uid, "pumpio", "user");
1632 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1634 $own_id = "https://".$hostname."/".$username;
1636 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1639 // Fetching the original post
1640 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1648 $url = $r[0]["extid"];
1650 $client = new oauth_client_class;
1651 $client->oauth_version = '1.0a';
1652 $client->authorization_header = true;
1653 $client->url_parameters = false;
1655 $client->client_id = $ckey;
1656 $client->client_secret = $csecret;
1657 $client->access_token = $otoken;
1658 $client->access_token_secret = $osecret;
1660 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1662 if (pumpio_reachable($url))
1663 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1670 if ($item->likes->totalItems != 0) {
1671 foreach ($item->likes->items AS $post) {
1672 $like = new stdClass;
1673 $like->object = new stdClass;
1674 $like->object->id = $item->id;
1675 $like->actor = new stdClass;
1676 $like->actor->displayName = $item->displayName;
1677 $like->actor->preferredUsername = $item->preferredUsername;
1678 $like->actor->url = $item->url;
1679 $like->actor->image = $item->image;
1680 $like->generator = new stdClass;
1681 $like->generator->displayName = "pumpio";
1682 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1686 if ($item->replies->totalItems == 0)
1689 foreach ($item->replies->items AS $item) {
1690 if ($item->id == $id)
1693 // Checking if the comment already exists - Two queries for speed issues
1694 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1702 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1710 $post = new stdClass;
1711 $post->verb = "post";
1712 $post->actor = $item->author;
1713 $post->published = $item->published;
1714 $post->received = $item->updated;
1715 $post->generator = new stdClass;
1716 $post->generator->displayName = "pumpio";
1717 // To-Do: Check for public post
1719 unset($item->author);
1720 unset($item->published);
1721 unset($item->updated);
1723 $post->object = $item;
1725 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1726 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1731 function pumpio_reachable($url) {
1732 $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
1733 return(intval($data['return_code']) != 0);