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>
9 use Friendica\Core\Config;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\Worker;
12 use Friendica\Model\GContact;
14 require 'addon/pumpio/oauth/http.php';
15 require 'addon/pumpio/oauth/oauth_client.php';
16 require_once 'include/enotify.php';
17 require_once "include/Photo.php";
18 require_once "mod/share.php";
20 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
22 function pumpio_install() {
23 register_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
24 register_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
25 register_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
26 register_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
27 register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
28 register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
29 register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
30 register_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
33 function pumpio_uninstall() {
34 unregister_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
35 unregister_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
36 unregister_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
37 unregister_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
38 unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
39 unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
40 unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
41 unregister_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
44 function pumpio_module() {}
46 function pumpio_content(&$a) {
49 notice( t('Permission denied.') . EOL);
53 require_once("mod/settings.php");
56 if (isset($a->argv[1]))
57 switch ($a->argv[1]) {
59 $o = pumpio_connect($a);
62 $o = print_r($a->argv, true);
66 $o = pumpio_connect($a);
71 function pumpio_check_item_notification($a, &$notification_data) {
72 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
73 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
75 $notification_data["profiles"][] = "https://".$hostname."/".$username;
79 function pumpio_registerclient(&$a, $host) {
81 $url = "https://".$host."/api/client/register";
85 $application_name = Config::get('pumpio', 'application_name');
87 if ($application_name == "")
88 $application_name = $a->get_hostname();
90 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
92 $params["type"] = "client_associate";
93 $params["contacts"] = $adminlist[0];
94 $params["application_type"] = "native";
95 $params["application_name"] = $application_name;
96 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
97 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
99 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
101 $ch = curl_init($url);
102 curl_setopt($ch, CURLOPT_HEADER, false);
103 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
104 curl_setopt($ch, CURLOPT_POST,1);
105 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
106 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
109 $curl_info = curl_getinfo($ch);
111 if ($curl_info["http_code"] == "200") {
112 $values = json_decode($s);
113 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
116 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
121 function pumpio_connect(&$a) {
122 // Start a session. This is necessary to hold on to a few keys the callback script will also need
125 // Define the needed keys
126 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
127 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
128 $hostname = PConfig::get(local_user(), 'pumpio','host');
130 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
131 logger("pumpio_connect: register client");
132 $clientdata = pumpio_registerclient($a, $hostname);
133 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
134 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
136 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
137 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
139 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
142 if (($consumer_key == "") || ($consumer_secret == "")) {
143 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
145 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
149 // The callback URL is the script that gets called after the user authenticates with pumpio
150 $callback_url = $a->get_baseurl()."/pumpio/connect";
152 // Let's begin. First we need a Request Token. The request token is required to send the user
153 // to pumpio's login page.
155 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
156 // Consumer Key and Consumer Secret
157 $client = new oauth_client_class;
159 $client->server = '';
160 $client->oauth_version = '1.0a';
161 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
162 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
163 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
164 $client->url_parameters = false;
165 $client->authorization_header = true;
166 $client->redirect_uri = $callback_url;
167 $client->client_id = $consumer_key;
168 $client->client_secret = $consumer_secret;
170 if (($success = $client->Initialize())) {
171 if (($success = $client->Process())) {
172 if (strlen($client->access_token)) {
173 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
174 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
175 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
178 $success = $client->Finalize($success);
181 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
184 logger("pumpio_connect: authenticated");
185 $o .= t("You are now authenticated to pumpio.");
186 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
188 logger("pumpio_connect: could not connect");
189 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
195 function pumpio_jot_nets(&$a,&$b) {
199 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
200 if(intval($pumpio_post) == 1) {
201 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
202 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
203 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
204 . t('Post to pumpio') . '</div>';
209 function pumpio_settings(&$a,&$s) {
214 /* Add our stylesheet to the page so we can make our settings look nice */
216 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
218 /* Get the current state of our config variables */
220 $import_enabled = PConfig::get(local_user(),'pumpio','import');
221 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
223 $enabled = PConfig::get(local_user(),'pumpio','post');
224 $checked = (($enabled) ? ' checked="checked" ' : '');
225 $css = (($enabled) ? '' : '-disabled');
227 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
228 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
230 $public_enabled = PConfig::get(local_user(),'pumpio','public');
231 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
233 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
234 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
236 $servername = PConfig::get(local_user(), "pumpio", "host");
237 $username = PConfig::get(local_user(), "pumpio", "user");
239 /* Add some HTML to the existing form */
241 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
242 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
244 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
245 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
246 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
249 $s .= '<div id="pumpio-username-wrapper">';
250 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
251 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
252 $s .= '</div><div class="clear"></div>';
254 $s .= '<div id="pumpio-servername-wrapper">';
255 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
256 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
257 $s .= '</div><div class="clear"></div>';
259 if (($username != '') && ($servername != '')) {
261 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
262 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
264 $s .= '<div id="pumpio-password-wrapper">';
265 if (($oauth_token == "") || ($oauth_token_secret == "")) {
266 $s .= '<div id="pumpio-authenticate-wrapper">';
267 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
268 $s .= '</div><div class="clear"></div>';
270 $s .= '<div id="pumpio-import-wrapper">';
271 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
272 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
273 $s .= '</div><div class="clear"></div>';
275 $s .= '<div id="pumpio-enable-wrapper">';
276 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
277 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
278 $s .= '</div><div class="clear"></div>';
280 $s .= '<div id="pumpio-bydefault-wrapper">';
281 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
282 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
283 $s .= '</div><div class="clear"></div>';
285 $s .= '<div id="pumpio-public-wrapper">';
286 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
287 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
288 $s .= '</div><div class="clear"></div>';
290 $s .= '<div id="pumpio-mirror-wrapper">';
291 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
292 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
293 $s .= '</div><div class="clear"></div>';
295 $s .= '<div id="pumpio-delete-wrapper">';
296 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
297 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
298 $s .= '</div><div class="clear"></div>';
301 $s .= '</div><div class="clear"></div>';
304 /* provide a submit button */
306 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
310 function pumpio_settings_post(&$a,&$b) {
312 if(x($_POST,'pumpio-submit')) {
313 if(x($_POST,'pumpio_delete')) {
314 PConfig::set(local_user(),'pumpio','consumer_key','');
315 PConfig::set(local_user(),'pumpio','consumer_secret','');
316 PConfig::set(local_user(),'pumpio','oauth_token','');
317 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
318 PConfig::set(local_user(),'pumpio','post',false);
319 PConfig::set(local_user(),'pumpio','import',false);
320 PConfig::set(local_user(),'pumpio','host','');
321 PConfig::set(local_user(),'pumpio','user','');
322 PConfig::set(local_user(),'pumpio','public',false);
323 PConfig::set(local_user(),'pumpio','mirror',false);
324 PConfig::set(local_user(),'pumpio','post_by_default',false);
325 PConfig::set(local_user(),'pumpio','lastdate', 0);
326 PConfig::set(local_user(),'pumpio','last_id', '');
328 // filtering the username if it is filled wrong
329 $user = $_POST['pumpio_user'];
330 if (strstr($user, "@")) {
331 $pos = strpos($user, "@");
333 $user = substr($user, 0, $pos);
336 // Filtering the hostname if someone is entering it with "http"
337 $host = $_POST['pumpio_host'];
339 $host = str_replace(array("https://", "http://"), array("", ""), $host);
341 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
342 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
343 PConfig::set(local_user(),'pumpio','host',$host);
344 PConfig::set(local_user(),'pumpio','user',$user);
345 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
346 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
347 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
349 if (!$_POST['pumpio_mirror'])
350 PConfig::delete(local_user(),'pumpio','lastdate');
352 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
357 function pumpio_post_local(&$a, &$b) {
359 if (!local_user() || (local_user() != $b['uid'])) {
363 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
365 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
367 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
371 if (!$pumpio_enable) {
375 if (strlen($b['postopts'])) {
376 $b['postopts'] .= ',';
379 $b['postopts'] .= 'pumpio';
385 function pumpio_send(&$a,&$b) {
387 if (!PConfig::get($b["uid"],'pumpio','import')) {
388 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
392 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
394 if($b['parent'] != $b['id']) {
395 // Looking if its a reply to a pumpio post
396 $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",
397 intval($b["parent"]),
399 dbesc(NETWORK_PUMPIO));
402 logger("pumpio_send: no pumpio post ".$b["parent"]);
411 $receiver = pumpio_getreceiver($a, $b);
413 logger("pumpio_send: receiver ".print_r($receiver, true));
415 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio')))
419 if($b['verb'] == ACTIVITY_LIKE) {
421 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
423 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
427 if($b['verb'] == ACTIVITY_DISLIKE)
430 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
431 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
433 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
434 pumpio_action($a, $b["uid"], $b["uri"], "delete");
436 if($b['deleted'] || ($b['created'] !== $b['edited']))
439 // if post comes from pump.io don't send it back
440 if($b['app'] == "pump.io")
444 // Support for native shares
445 // http://<hostname>/api/<type>/shares?id=<the-object-id>
447 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
448 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
449 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
450 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
452 $host = PConfig::get($b['uid'], "pumpio", "host");
453 $user = PConfig::get($b['uid'], "pumpio", "user");
454 $public = PConfig::get($b['uid'], "pumpio", "public");
456 if($oauth_token && $oauth_token_secret) {
458 require_once('include/bbcode.php');
460 $title = trim($b['title']);
462 $content = bbcode($b['body'], false, false, 4);
466 $params["verb"] = "post";
469 $params["object"] = array(
470 'objectType' => "note",
471 'content' => $content);
474 $params["object"]["displayName"] = $title;
476 if (count($receiver["to"]))
477 $params["to"] = $receiver["to"];
479 if (count($receiver["bto"]))
480 $params["bto"] = $receiver["bto"];
482 if (count($receiver["cc"]))
483 $params["cc"] = $receiver["cc"];
485 if (count($receiver["bcc"]))
486 $params["bcc"] = $receiver["bcc"];
489 $inReplyTo = array("id" => $orig_post["uri"],
490 "objectType" => "note");
492 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
493 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
495 $params["object"] = array(
496 'objectType' => "comment",
497 'content' => $content,
498 'inReplyTo' => $inReplyTo);
501 $params["object"]["displayName"] = $title;
504 $client = new oauth_client_class;
505 $client->oauth_version = '1.0a';
506 $client->url_parameters = false;
507 $client->authorization_header = true;
508 $client->access_token = $oauth_token;
509 $client->access_token_secret = $oauth_token_secret;
510 $client->client_id = $consumer_key;
511 $client->client_secret = $consumer_secret;
513 $username = $user.'@'.$host;
514 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
516 if (pumpio_reachable($url))
517 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
523 if ($user->generator->displayName)
524 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
526 $post_id = $user->object->id;
527 logger('pumpio_send '.$username.': success '.$post_id);
528 if($post_id && $iscomment) {
529 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
530 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
536 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
538 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
540 $a->contact = $r[0]["id"];
542 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
543 require_once('include/queue_fn.php');
544 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
545 notice(t('Pump.io post failed. Queued for retry.').EOL);
551 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
553 // Don't do likes and other stuff if you don't import the timeline
554 if (!PConfig::get($uid,'pumpio','import'))
557 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
558 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
559 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
560 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
561 $hostname = PConfig::get($uid, 'pumpio','host');
562 $username = PConfig::get($uid, "pumpio", "user");
564 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
574 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
575 $uri = $orig_post["extid"];
577 $uri = $orig_post["uri"];
579 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
580 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
581 elseif (strstr($uri, "/api/comment/"))
582 $objectType = "comment";
583 elseif (strstr($uri, "/api/note/"))
584 $objectType = "note";
585 elseif (strstr($uri, "/api/image/"))
586 $objectType = "image";
588 $params["verb"] = $action;
589 $params["object"] = array('id' => $uri,
590 "objectType" => $objectType,
591 "content" => $content);
593 $client = new oauth_client_class;
594 $client->oauth_version = '1.0a';
595 $client->authorization_header = true;
596 $client->url_parameters = false;
598 $client->client_id = $ckey;
599 $client->client_secret = $csecret;
600 $client->access_token = $otoken;
601 $client->access_token_secret = $osecret;
603 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
605 if (pumpio_reachable($url))
606 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
611 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
613 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
615 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
617 $a->contact = $r[0]["id"];
619 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
620 require_once('include/queue_fn.php');
621 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
622 notice(t('Pump.io like failed. Queued for retry.').EOL);
626 function pumpio_sync(&$a) {
627 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
633 $last = Config::get('pumpio','last_poll');
635 $poll_interval = intval(Config::get('pumpio','poll_interval'));
637 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
640 $next = $last + ($poll_interval * 60);
642 logger('pumpio: poll intervall not reached');
646 logger('pumpio: cron_start');
648 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
651 logger('pumpio: mirroring user '.$rr['uid']);
652 pumpio_fetchtimeline($a, $rr['uid']);
656 $abandon_days = intval(Config::get('system','account_abandon_days'));
657 if ($abandon_days < 1)
660 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
662 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
665 if ($abandon_days != 0) {
666 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
668 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
673 logger('pumpio: importing timeline from user '.$rr['uid']);
674 pumpio_fetchinbox($a, $rr['uid']);
676 // check for new contacts once a day
677 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
678 if($last_contact_check)
679 $next_contact_check = $last_contact_check + 86400;
681 $next_contact_check = 0;
683 if($next_contact_check <= time()) {
684 pumpio_getallusers($a, $rr["uid"]);
685 PConfig::set($rr['uid'],'pumpio','contact_check',time());
690 logger('pumpio: cron_end');
692 Config::set('pumpio','last_poll', time());
695 function pumpio_cron(&$a,$b) {
696 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
699 function pumpio_fetchtimeline(&$a, $uid) {
700 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
701 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
702 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
703 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
704 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
705 $hostname = PConfig::get($uid, 'pumpio','host');
706 $username = PConfig::get($uid, "pumpio", "user");
708 // get the application name for the pump.io app
709 // 1st try personal config, then system config and fallback to the
710 // hostname of the node if neither one is set.
711 $application_name = PConfig::get( $uid, 'pumpio', 'application_name');
712 if ($application_name == "")
713 $application_name = Config::get('pumpio', 'application_name');
714 if ($application_name == "")
715 $application_name = $a->get_hostname();
717 $first_time = ($lastdate == "");
719 $client = new oauth_client_class;
720 $client->oauth_version = '1.0a';
721 $client->authorization_header = true;
722 $client->url_parameters = false;
724 $client->client_id = $ckey;
725 $client->client_secret = $csecret;
726 $client->access_token = $otoken;
727 $client->access_token_secret = $osecret;
729 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
731 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
733 $username = $user.'@'.$host;
735 if (pumpio_reachable($url))
736 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
741 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
745 $posts = array_reverse($user->items);
747 $initiallastdate = $lastdate;
751 foreach ($posts as $post) {
752 if ($post->published <= $initiallastdate)
755 if ($lastdate < $post->published)
756 $lastdate = $post->published;
761 $receiptians = array();
762 if (@is_array($post->cc))
763 $receiptians = array_merge($receiptians, $post->cc);
765 if (@is_array($post->to))
766 $receiptians = array_merge($receiptians, $post->to);
769 foreach ($receiptians AS $receiver)
770 if (is_string($receiver->objectType))
771 if ($receiver->id == "http://activityschema.org/collection/public")
774 if ($public && !stristr($post->generator->displayName, $application_name)) {
775 require_once('include/html2bbcode.php');
777 $_SESSION["authenticated"] = true;
778 $_SESSION["uid"] = $uid;
781 $_REQUEST["type"] = "wall";
782 $_REQUEST["api_source"] = true;
783 $_REQUEST["profile_uid"] = $uid;
784 $_REQUEST["source"] = "pump.io";
786 if (isset($post->object->id)) {
787 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
790 if ($post->object->displayName != "")
791 $_REQUEST["title"] = html2bbcode($post->object->displayName);
793 $_REQUEST["title"] = "";
795 $_REQUEST["body"] = html2bbcode($post->object->content);
797 // To-Do: Picture has to be cached and stored locally
798 if ($post->object->fullImage->url != "") {
799 if ($post->object->fullImage->pump_io->proxyURL != "")
800 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
802 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
805 logger('pumpio: posting for user '.$uid);
807 require_once('mod/item.php');
810 logger('pumpio: posting done - user '.$uid);
816 PConfig::set($uid,'pumpio','lastdate', $lastdate);
819 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
820 // Searching for the unliked post
821 // Two queries for speed issues
822 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
823 dbesc($post->object->id),
830 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
831 dbesc($post->object->id),
843 if(link_compare($post->actor->url, $own_id)) {
844 $contactid = $self[0]['id'];
846 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
847 dbesc(normalise_link($post->actor->url)),
852 $contactid = $r[0]['id'];
855 $contactid = $orig_post['contact-id'];
858 $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'",
859 dbesc(datetime_convert()),
860 dbesc(ACTIVITY_LIKE),
863 dbesc($orig_post['uri'])
867 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
869 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
872 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
873 require_once('include/items.php');
875 if ($post->object->id == "") {
876 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
880 // Searching for the liked post
881 // Two queries for speed issues
882 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
883 dbesc($post->object->id),
885 dbesc(NETWORK_PUMPIO)
891 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
892 dbesc($post->object->id),
894 dbesc(NETWORK_PUMPIO)
904 if ($threadcompletion)
905 pumpio_fetchallcomments($a, $uid, $post->object->id);
909 if(link_compare($post->actor->url, $own_id)) {
910 $contactid = $self[0]['id'];
911 $post->actor->displayName = $self[0]['name'];
912 $post->actor->url = $self[0]['url'];
913 $post->actor->image->url = $self[0]['photo'];
915 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
916 dbesc(normalise_link($post->actor->url)),
921 $contactid = $r[0]['id'];
924 $contactid = $orig_post['contact-id'];
927 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
928 dbesc(ACTIVITY_LIKE),
931 dbesc($orig_post['uri'])
935 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
940 $likedata['parent'] = $orig_post['id'];
941 $likedata['verb'] = ACTIVITY_LIKE;
942 $likedata['gravity'] = 3;
943 $likedata['uid'] = $uid;
944 $likedata['wall'] = 0;
945 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
946 $likedata['parent-uri'] = $orig_post["uri"];
947 $likedata['contact-id'] = $contactid;
948 $likedata['app'] = $post->generator->displayName;
949 $likedata['author-name'] = $post->actor->displayName;
950 $likedata['author-link'] = $post->actor->url;
951 $likedata['author-avatar'] = $post->actor->image->url;
953 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
954 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
955 $post_type = t('status');
956 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
957 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
959 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
961 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
962 '<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>';
964 $ret = item_store($likedata);
966 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
969 function pumpio_get_contact($uid, $contact, $no_insert = false) {
971 GContact::update(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
972 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
973 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
974 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
975 $cid = get_contact($contact->url, $uid);
980 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
981 intval($uid), dbesc(normalise_link($contact->url)));
984 // create contact record
985 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
986 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
987 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
988 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
990 dbesc(datetime_convert()),
991 dbesc($contact->url),
992 dbesc(normalise_link($contact->url)),
993 dbesc(str_replace("acct:", "", $contact->id)),
995 dbesc($contact->id), // What is it for?
996 dbesc('pump.io ' . $contact->id), // What is it for?
997 dbesc($contact->displayName),
998 dbesc($contact->preferredUsername),
999 dbesc($contact->image->url),
1000 dbesc(NETWORK_PUMPIO),
1001 intval(CONTACT_IS_FRIEND),
1003 dbesc($contact->location->displayName),
1004 dbesc($contact->summary),
1008 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1009 dbesc(normalise_link($contact->url)),
1017 $contact_id = $r[0]['id'];
1019 $g = q("select def_gid from user where uid = %d limit 1",
1023 if($g && intval($g[0]['def_gid'])) {
1024 require_once('include/group.php');
1025 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1028 $contact_id = $r[0]["id"];
1030 /* if (DB_UPDATE_VERSION >= "1177")
1031 q("UPDATE `contact` SET `location` = '%s',
1034 dbesc($contact->location->displayName),
1035 dbesc($contact->summary),
1041 if (function_exists("update_contact_avatar"))
1042 update_contact_avatar($contact->image->url, $uid, $contact_id);
1044 return($contact_id);
1047 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
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),
1056 return drop_item($r[0]["id"], $false);
1058 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1059 dbesc($post->object->id),
1064 return drop_item($r[0]["id"], $false);
1067 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1068 require_once('include/items.php');
1069 require_once('include/html2bbcode.php');
1071 if (($post->verb == "like") || ($post->verb == "favorite"))
1072 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1074 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1075 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1077 if ($post->verb == "delete")
1078 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1080 if ($post->verb != "update") {
1081 // Two queries for speed issues
1082 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1083 dbesc($post->object->id),
1090 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1091 dbesc($post->object->id),
1099 // Only handle these three types
1100 if (!strstr("post|share|update", $post->verb))
1103 $receiptians = array();
1104 if (@is_array($post->cc))
1105 $receiptians = array_merge($receiptians, $post->cc);
1107 if (@is_array($post->to))
1108 $receiptians = array_merge($receiptians, $post->to);
1110 foreach ($receiptians AS $receiver)
1111 if (is_string($receiver->objectType))
1112 if ($receiver->id == "http://activityschema.org/collection/public")
1115 $postarray = array();
1116 $postarray['network'] = NETWORK_PUMPIO;
1117 $postarray['gravity'] = 0;
1118 $postarray['uid'] = $uid;
1119 $postarray['wall'] = 0;
1120 $postarray['uri'] = $post->object->id;
1121 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1123 if ($post->object->objectType != "comment") {
1124 $contact_id = pumpio_get_contact($uid, $post->actor);
1127 $contact_id = $self[0]['id'];
1129 $postarray['parent-uri'] = $post->object->id;
1132 $postarray['private'] = 1;
1133 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1136 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1138 if (link_compare($post->actor->url, $own_id)) {
1139 $contact_id = $self[0]['id'];
1140 $post->actor->displayName = $self[0]['name'];
1141 $post->actor->url = $self[0]['url'];
1142 $post->actor->image->url = $self[0]['photo'];
1143 } elseif ($contact_id == 0) {
1144 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1145 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1146 dbesc(normalise_link($post->actor->url)),
1151 $contact_id = $r[0]['id'];
1153 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1154 dbesc(normalise_link($post->actor->url)),
1159 $contact_id = $r[0]['id'];
1161 $contact_id = $self[0]['id'];
1165 $reply = new stdClass;
1166 $reply->verb = "note";
1167 $reply->cc = $post->cc;
1168 $reply->to = $post->to;
1169 $reply->object = new stdClass;
1170 $reply->object->objectType = $post->object->inReplyTo->objectType;
1171 $reply->object->content = $post->object->inReplyTo->content;
1172 $reply->object->id = $post->object->inReplyTo->id;
1173 $reply->actor = $post->object->inReplyTo->author;
1174 $reply->url = $post->object->inReplyTo->url;
1175 $reply->generator = new stdClass;
1176 $reply->generator->displayName = "pumpio";
1177 $reply->published = $post->object->inReplyTo->published;
1178 $reply->received = $post->object->inReplyTo->updated;
1179 $reply->url = $post->object->inReplyTo->url;
1180 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1182 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1185 if ($post->object->pump_io->proxyURL)
1186 $postarray['extid'] = $post->object->pump_io->proxyURL;
1188 $postarray['contact-id'] = $contact_id;
1189 $postarray['verb'] = ACTIVITY_POST;
1190 $postarray['owner-name'] = $post->actor->displayName;
1191 $postarray['owner-link'] = $post->actor->url;
1192 $postarray['owner-avatar'] = $post->actor->image->url;
1193 $postarray['author-name'] = $post->actor->displayName;
1194 $postarray['author-link'] = $post->actor->url;
1195 $postarray['author-avatar'] = $post->actor->image->url;
1196 $postarray['plink'] = $post->object->url;
1197 $postarray['app'] = $post->generator->displayName;
1198 $postarray['body'] = html2bbcode($post->object->content);
1199 $postarray['object'] = json_encode($post);
1201 if ($post->object->fullImage->url != "")
1202 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1204 if ($post->object->displayName != "")
1205 $postarray['title'] = $post->object->displayName;
1207 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1208 if (isset($post->updated))
1209 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1210 elseif (isset($post->received))
1211 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1213 $postarray['edited'] = $postarray['created'];
1215 if ($post->verb == "share") {
1216 if (!intval(Config::get('system','wall-to-wall_share'))) {
1217 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1218 $share_author = $post->object->author->displayName;
1219 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1220 $share_author = $post->object->author->preferredUsername;
1222 $share_author = $post->object->author->url;
1224 $postarray['body'] = share_header($share_author, $post->object->author->url,
1225 $post->object->author->image->url, "",
1226 datetime_convert('UTC','UTC',$post->object->created),
1227 $post->links->self->href).
1228 $postarray['body']."[/share]";
1231 $postarray['body'] = "[share author='".$share_author.
1232 "' profile='".$post->object->author->url.
1233 "' avatar='".$post->object->author->image->url.
1234 "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1235 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1238 // Let shares look like wall-to-wall posts
1239 $postarray['author-name'] = $post->object->author->displayName;
1240 $postarray['author-link'] = $post->object->author->url;
1241 $postarray['author-avatar'] = $post->object->author->image->url;
1245 if (trim($postarray['body']) == "")
1248 $top_item = item_store($postarray);
1249 $postarray["id"] = $top_item;
1251 if (($top_item == 0) && ($post->verb == "update")) {
1252 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1253 dbesc($postarray["title"]),
1254 dbesc($postarray["body"]),
1255 dbesc($postarray["edited"]),
1256 dbesc($postarray["uri"]),
1261 if ($post->object->objectType == "comment") {
1263 if ($threadcompletion)
1264 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1266 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1273 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1275 if (link_compare($own_id, $postarray['author-link']))
1278 if (!function_exists("check_item_notification")) {
1279 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1280 dbesc($postarray['parent-uri']),
1284 if(count($myconv)) {
1286 foreach($myconv as $conv) {
1287 // now if we find a match, it means we're in this conversation
1289 if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1292 require_once('include/enotify.php');
1294 $conv_parent = $conv['parent'];
1297 'type' => NOTIFY_COMMENT,
1298 'notify_flags' => $user[0]['notify-flags'],
1299 'language' => $user[0]['language'],
1300 'to_name' => $user[0]['username'],
1301 'to_email' => $user[0]['email'],
1302 'uid' => $user[0]['uid'],
1303 'item' => $postarray,
1304 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1305 'source_name' => $postarray['author-name'],
1306 'source_link' => $postarray['author-link'],
1307 'source_photo' => $postarray['author-avatar'],
1308 'verb' => ACTIVITY_POST,
1310 'parent' => $conv_parent,
1313 // only send one notification
1323 function pumpio_fetchinbox(&$a, $uid) {
1325 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1326 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1327 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1328 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1329 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1330 $hostname = PConfig::get($uid, 'pumpio','host');
1331 $username = PConfig::get($uid, "pumpio", "user");
1333 $own_id = "https://".$hostname."/".$username;
1335 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1338 $lastitems = q("SELECT `uri` FROM `thread`
1339 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1340 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1341 ORDER BY `thread`.`commented` DESC LIMIT 10",
1342 dbesc(NETWORK_PUMPIO),
1346 $client = new oauth_client_class;
1347 $client->oauth_version = '1.0a';
1348 $client->authorization_header = true;
1349 $client->url_parameters = false;
1351 $client->client_id = $ckey;
1352 $client->client_secret = $csecret;
1353 $client->access_token = $otoken;
1354 $client->access_token_secret = $osecret;
1356 $last_id = PConfig::get($uid,'pumpio','last_id');
1358 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1361 $url .= '?since='.urlencode($last_id);
1363 if (pumpio_reachable($url))
1364 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1369 $posts = array_reverse($user->items);
1372 foreach ($posts as $post) {
1373 $last_id = $post->id;
1374 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1378 foreach ($lastitems AS $item)
1379 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1381 PConfig::set($uid,'pumpio','last_id', $last_id);
1384 function pumpio_getallusers(&$a, $uid) {
1385 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1386 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1387 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1388 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1389 $hostname = PConfig::get($uid, 'pumpio','host');
1390 $username = PConfig::get($uid, "pumpio", "user");
1392 $client = new oauth_client_class;
1393 $client->oauth_version = '1.0a';
1394 $client->authorization_header = true;
1395 $client->url_parameters = false;
1397 $client->client_id = $ckey;
1398 $client->client_secret = $csecret;
1399 $client->access_token = $otoken;
1400 $client->access_token_secret = $osecret;
1402 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1404 if (pumpio_reachable($url))
1405 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1409 if ($users->totalItems > count($users->items)) {
1410 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1412 if (pumpio_reachable($url))
1413 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1418 if (is_array($users->items)) {
1419 foreach ($users->items AS $user) {
1420 pumpio_get_contact($uid, $user);
1425 function pumpio_queue_hook(&$a,&$b) {
1427 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1428 dbesc(NETWORK_PUMPIO)
1433 require_once('include/queue_fn.php');
1435 foreach($qi as $x) {
1436 if($x['network'] !== NETWORK_PUMPIO)
1439 logger('pumpio_queue: run');
1441 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1442 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1450 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1452 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1453 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1454 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1455 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1457 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1458 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1462 if ($oauth_token && $oauth_token_secret &&
1463 $consumer_key && $consumer_secret) {
1464 $username = $user.'@'.$host;
1466 logger('pumpio_queue: able to post for user '.$username);
1468 $z = unserialize($x['content']);
1470 $client = new oauth_client_class;
1471 $client->oauth_version = '1.0a';
1472 $client->url_parameters = false;
1473 $client->authorization_header = true;
1474 $client->access_token = $oauth_token;
1475 $client->access_token_secret = $oauth_token_secret;
1476 $client->client_id = $consumer_key;
1477 $client->client_secret = $consumer_secret;
1479 if (pumpio_reachable($z['url']))
1480 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1485 $post_id = $user->object->id;
1486 logger('pumpio_queue: send '.$username.': success '.$post_id);
1487 if($post_id && $iscomment) {
1488 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1489 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1494 remove_queue_item($x['id']);
1496 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1498 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1501 logger('pumpio_queue: delayed');
1502 update_queue_time($x['id']);
1507 function pumpio_getreceiver(&$a, $b) {
1509 $receiver = array();
1511 if (!$b["private"]) {
1513 if(! strstr($b['postopts'],'pumpio'))
1516 $public = PConfig::get($b['uid'], "pumpio", "public");
1519 $receiver["to"][] = Array(
1520 "objectType" => "collection",
1521 "id" => "http://activityschema.org/collection/public");
1523 $cids = explode("><", $b["allow_cid"]);
1524 $gids = explode("><", $b["allow_gid"]);
1526 foreach ($cids AS $cid) {
1527 $cid = trim($cid, " <>");
1529 $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",
1532 dbesc(NETWORK_PUMPIO)
1536 $receiver["bcc"][] = Array(
1537 "displayName" => $r[0]["name"],
1538 "objectType" => "person",
1539 "preferredUsername" => $r[0]["nick"],
1540 "url" => $r[0]["url"]);
1543 foreach ($gids AS $gid) {
1544 $gid = trim($gid, " <>");
1546 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1547 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1548 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1551 dbesc(NETWORK_PUMPIO)
1554 foreach ($r AS $row)
1555 $receiver["bcc"][] = Array(
1556 "displayName" => $row["name"],
1557 "objectType" => "person",
1558 "preferredUsername" => $row["nick"],
1559 "url" => $row["url"]);
1563 if ($b["inform"] != "") {
1565 $inform = explode(",", $b["inform"]);
1567 foreach ($inform AS $cid) {
1568 if (substr($cid, 0, 4) != "cid:")
1571 $cid = str_replace("cid:", "", $cid);
1573 $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",
1576 dbesc(NETWORK_PUMPIO)
1580 $receiver["to"][] = Array(
1581 "displayName" => $r[0]["name"],
1582 "objectType" => "person",
1583 "preferredUsername" => $r[0]["nick"],
1584 "url" => $r[0]["url"]);
1592 function pumpio_fetchallcomments(&$a, $uid, $id) {
1593 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1594 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1595 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1596 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1597 $hostname = PConfig::get($uid, 'pumpio','host');
1598 $username = PConfig::get($uid, "pumpio", "user");
1600 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1602 $own_id = "https://".$hostname."/".$username;
1604 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1607 // Fetching the original post
1608 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1616 $url = $r[0]["extid"];
1618 $client = new oauth_client_class;
1619 $client->oauth_version = '1.0a';
1620 $client->authorization_header = true;
1621 $client->url_parameters = false;
1623 $client->client_id = $ckey;
1624 $client->client_secret = $csecret;
1625 $client->access_token = $otoken;
1626 $client->access_token_secret = $osecret;
1628 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1630 if (pumpio_reachable($url))
1631 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1638 if ($item->likes->totalItems != 0) {
1639 foreach ($item->likes->items AS $post) {
1640 $like = new stdClass;
1641 $like->object = new stdClass;
1642 $like->object->id = $item->id;
1643 $like->actor = new stdClass;
1644 $like->actor->displayName = $item->displayName;
1645 $like->actor->preferredUsername = $item->preferredUsername;
1646 $like->actor->url = $item->url;
1647 $like->actor->image = $item->image;
1648 $like->generator = new stdClass;
1649 $like->generator->displayName = "pumpio";
1650 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1654 if ($item->replies->totalItems == 0)
1657 foreach ($item->replies->items AS $item) {
1658 if ($item->id == $id)
1661 // Checking if the comment already exists - Two queries for speed issues
1662 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1670 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1678 $post = new stdClass;
1679 $post->verb = "post";
1680 $post->actor = $item->author;
1681 $post->published = $item->published;
1682 $post->received = $item->updated;
1683 $post->generator = new stdClass;
1684 $post->generator->displayName = "pumpio";
1685 // To-Do: Check for public post
1687 unset($item->author);
1688 unset($item->published);
1689 unset($item->updated);
1691 $post->object = $item;
1693 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1694 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1699 function pumpio_reachable($url) {
1700 $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
1701 return(intval($data['return_code']) != 0);