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 use Friendica\Core\Config;
9 use Friendica\Core\PConfig;
10 use Friendica\Core\Worker;
11 use Friendica\Model\GlobalContact;
12 use Friendica\Object\Contact;
14 require 'addon/pumpio/oauth/http.php';
15 require 'addon/pumpio/oauth/oauth_client.php';
16 require_once 'include/enotify.php';
17 require_once "mod/share.php";
19 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
21 function pumpio_install() {
22 register_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
23 register_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
24 register_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
25 register_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
26 register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
27 register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
28 register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
29 register_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
32 function pumpio_uninstall() {
33 unregister_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
34 unregister_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
35 unregister_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
36 unregister_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
37 unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
38 unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
39 unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
40 unregister_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
43 function pumpio_module() {}
45 function pumpio_content(&$a) {
48 notice( t('Permission denied.') . EOL);
52 require_once("mod/settings.php");
55 if (isset($a->argv[1]))
56 switch ($a->argv[1]) {
58 $o = pumpio_connect($a);
61 $o = print_r($a->argv, true);
65 $o = pumpio_connect($a);
70 function pumpio_check_item_notification($a, &$notification_data) {
71 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
72 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
74 $notification_data["profiles"][] = "https://".$hostname."/".$username;
78 function pumpio_registerclient(&$a, $host) {
80 $url = "https://".$host."/api/client/register";
84 $application_name = Config::get('pumpio', 'application_name');
86 if ($application_name == "")
87 $application_name = $a->get_hostname();
89 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
91 $params["type"] = "client_associate";
92 $params["contacts"] = $adminlist[0];
93 $params["application_type"] = "native";
94 $params["application_name"] = $application_name;
95 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
96 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
98 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
100 $ch = curl_init($url);
101 curl_setopt($ch, CURLOPT_HEADER, false);
102 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
103 curl_setopt($ch, CURLOPT_POST,1);
104 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
105 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
108 $curl_info = curl_getinfo($ch);
110 if ($curl_info["http_code"] == "200") {
111 $values = json_decode($s);
112 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
115 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
120 function pumpio_connect(&$a) {
121 // Start a session. This is necessary to hold on to a few keys the callback script will also need
124 // Define the needed keys
125 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
126 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
127 $hostname = PConfig::get(local_user(), 'pumpio','host');
129 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
130 logger("pumpio_connect: register client");
131 $clientdata = pumpio_registerclient($a, $hostname);
132 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
133 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
135 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
136 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
138 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
141 if (($consumer_key == "") || ($consumer_secret == "")) {
142 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
144 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
148 // The callback URL is the script that gets called after the user authenticates with pumpio
149 $callback_url = $a->get_baseurl()."/pumpio/connect";
151 // Let's begin. First we need a Request Token. The request token is required to send the user
152 // to pumpio's login page.
154 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
155 // Consumer Key and Consumer Secret
156 $client = new oauth_client_class;
158 $client->server = '';
159 $client->oauth_version = '1.0a';
160 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
161 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
162 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
163 $client->url_parameters = false;
164 $client->authorization_header = true;
165 $client->redirect_uri = $callback_url;
166 $client->client_id = $consumer_key;
167 $client->client_secret = $consumer_secret;
169 if (($success = $client->Initialize())) {
170 if (($success = $client->Process())) {
171 if (strlen($client->access_token)) {
172 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
173 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
174 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
177 $success = $client->Finalize($success);
180 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
183 logger("pumpio_connect: authenticated");
184 $o .= t("You are now authenticated to pumpio.");
185 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
187 logger("pumpio_connect: could not connect");
188 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
194 function pumpio_jot_nets(&$a,&$b) {
198 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
199 if(intval($pumpio_post) == 1) {
200 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
201 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
202 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
203 . t('Post to pumpio') . '</div>';
208 function pumpio_settings(&$a,&$s) {
213 /* Add our stylesheet to the page so we can make our settings look nice */
215 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
217 /* Get the current state of our config variables */
219 $import_enabled = PConfig::get(local_user(),'pumpio','import');
220 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
222 $enabled = PConfig::get(local_user(),'pumpio','post');
223 $checked = (($enabled) ? ' checked="checked" ' : '');
224 $css = (($enabled) ? '' : '-disabled');
226 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
227 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
229 $public_enabled = PConfig::get(local_user(),'pumpio','public');
230 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
232 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
233 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
235 $servername = PConfig::get(local_user(), "pumpio", "host");
236 $username = PConfig::get(local_user(), "pumpio", "user");
238 /* Add some HTML to the existing form */
240 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
241 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
243 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
244 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
245 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
248 $s .= '<div id="pumpio-username-wrapper">';
249 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
250 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
251 $s .= '</div><div class="clear"></div>';
253 $s .= '<div id="pumpio-servername-wrapper">';
254 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
255 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
256 $s .= '</div><div class="clear"></div>';
258 if (($username != '') && ($servername != '')) {
260 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
261 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
263 $s .= '<div id="pumpio-password-wrapper">';
264 if (($oauth_token == "") || ($oauth_token_secret == "")) {
265 $s .= '<div id="pumpio-authenticate-wrapper">';
266 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
267 $s .= '</div><div class="clear"></div>';
269 $s .= '<div id="pumpio-import-wrapper">';
270 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
271 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
272 $s .= '</div><div class="clear"></div>';
274 $s .= '<div id="pumpio-enable-wrapper">';
275 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
276 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
277 $s .= '</div><div class="clear"></div>';
279 $s .= '<div id="pumpio-bydefault-wrapper">';
280 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
281 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
282 $s .= '</div><div class="clear"></div>';
284 $s .= '<div id="pumpio-public-wrapper">';
285 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
286 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
287 $s .= '</div><div class="clear"></div>';
289 $s .= '<div id="pumpio-mirror-wrapper">';
290 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
291 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
292 $s .= '</div><div class="clear"></div>';
294 $s .= '<div id="pumpio-delete-wrapper">';
295 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
296 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
297 $s .= '</div><div class="clear"></div>';
300 $s .= '</div><div class="clear"></div>';
303 /* provide a submit button */
305 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
309 function pumpio_settings_post(&$a,&$b) {
311 if(x($_POST,'pumpio-submit')) {
312 if(x($_POST,'pumpio_delete')) {
313 PConfig::set(local_user(),'pumpio','consumer_key','');
314 PConfig::set(local_user(),'pumpio','consumer_secret','');
315 PConfig::set(local_user(),'pumpio','oauth_token','');
316 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
317 PConfig::set(local_user(),'pumpio','post',false);
318 PConfig::set(local_user(),'pumpio','import',false);
319 PConfig::set(local_user(),'pumpio','host','');
320 PConfig::set(local_user(),'pumpio','user','');
321 PConfig::set(local_user(),'pumpio','public',false);
322 PConfig::set(local_user(),'pumpio','mirror',false);
323 PConfig::set(local_user(),'pumpio','post_by_default',false);
324 PConfig::set(local_user(),'pumpio','lastdate', 0);
325 PConfig::set(local_user(),'pumpio','last_id', '');
327 // filtering the username if it is filled wrong
328 $user = $_POST['pumpio_user'];
329 if (strstr($user, "@")) {
330 $pos = strpos($user, "@");
332 $user = substr($user, 0, $pos);
335 // Filtering the hostname if someone is entering it with "http"
336 $host = $_POST['pumpio_host'];
338 $host = str_replace(array("https://", "http://"), array("", ""), $host);
340 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
341 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
342 PConfig::set(local_user(),'pumpio','host',$host);
343 PConfig::set(local_user(),'pumpio','user',$user);
344 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
345 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
346 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
348 if (!$_POST['pumpio_mirror'])
349 PConfig::delete(local_user(),'pumpio','lastdate');
351 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
356 function pumpio_post_local(&$a, &$b) {
358 if (!local_user() || (local_user() != $b['uid'])) {
362 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
364 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
366 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
370 if (!$pumpio_enable) {
374 if (strlen($b['postopts'])) {
375 $b['postopts'] .= ',';
378 $b['postopts'] .= 'pumpio';
384 function pumpio_send(&$a,&$b) {
386 if (!PConfig::get($b["uid"],'pumpio','import')) {
387 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
391 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
393 if($b['parent'] != $b['id']) {
394 // Looking if its a reply to a pumpio post
395 $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",
396 intval($b["parent"]),
398 dbesc(NETWORK_PUMPIO));
401 logger("pumpio_send: no pumpio post ".$b["parent"]);
410 $receiver = pumpio_getreceiver($a, $b);
412 logger("pumpio_send: receiver ".print_r($receiver, true));
414 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio')))
417 // Dont't post if the post doesn't belong to us.
418 // This is a check for forum postings
419 $self = dba::select('contact', array('id'), array('uid' => $b['uid'], 'self' => true), array('limit' => 1));
420 if ($b['contact-id'] != $self['id']) {
425 if($b['verb'] == ACTIVITY_LIKE) {
427 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
429 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
433 if($b['verb'] == ACTIVITY_DISLIKE)
436 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
437 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
439 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
440 pumpio_action($a, $b["uid"], $b["uri"], "delete");
442 if($b['deleted'] || ($b['created'] !== $b['edited']))
445 // if post comes from pump.io don't send it back
446 if($b['app'] == "pump.io")
450 // Support for native shares
451 // http://<hostname>/api/<type>/shares?id=<the-object-id>
453 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
454 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
455 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
456 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
458 $host = PConfig::get($b['uid'], "pumpio", "host");
459 $user = PConfig::get($b['uid'], "pumpio", "user");
460 $public = PConfig::get($b['uid'], "pumpio", "public");
462 if($oauth_token && $oauth_token_secret) {
464 require_once('include/bbcode.php');
466 $title = trim($b['title']);
468 $content = bbcode($b['body'], false, false, 4);
472 $params["verb"] = "post";
475 $params["object"] = array(
476 'objectType' => "note",
477 'content' => $content);
480 $params["object"]["displayName"] = $title;
482 if (count($receiver["to"]))
483 $params["to"] = $receiver["to"];
485 if (count($receiver["bto"]))
486 $params["bto"] = $receiver["bto"];
488 if (count($receiver["cc"]))
489 $params["cc"] = $receiver["cc"];
491 if (count($receiver["bcc"]))
492 $params["bcc"] = $receiver["bcc"];
495 $inReplyTo = array("id" => $orig_post["uri"],
496 "objectType" => "note");
498 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
499 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
501 $params["object"] = array(
502 'objectType' => "comment",
503 'content' => $content,
504 'inReplyTo' => $inReplyTo);
507 $params["object"]["displayName"] = $title;
510 $client = new oauth_client_class;
511 $client->oauth_version = '1.0a';
512 $client->url_parameters = false;
513 $client->authorization_header = true;
514 $client->access_token = $oauth_token;
515 $client->access_token_secret = $oauth_token_secret;
516 $client->client_id = $consumer_key;
517 $client->client_secret = $consumer_secret;
519 $username = $user.'@'.$host;
520 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
522 if (pumpio_reachable($url))
523 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
529 if ($user->generator->displayName)
530 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
532 $post_id = $user->object->id;
533 logger('pumpio_send '.$username.': success '.$post_id);
534 if($post_id && $iscomment) {
535 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
536 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
542 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
544 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
546 $a->contact = $r[0]["id"];
548 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
549 require_once('include/queue_fn.php');
550 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
551 notice(t('Pump.io post failed. Queued for retry.').EOL);
557 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
559 // Don't do likes and other stuff if you don't import the timeline
560 if (!PConfig::get($uid,'pumpio','import'))
563 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
564 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
565 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
566 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
567 $hostname = PConfig::get($uid, 'pumpio','host');
568 $username = PConfig::get($uid, "pumpio", "user");
570 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
580 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
581 $uri = $orig_post["extid"];
583 $uri = $orig_post["uri"];
585 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
586 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
587 elseif (strstr($uri, "/api/comment/"))
588 $objectType = "comment";
589 elseif (strstr($uri, "/api/note/"))
590 $objectType = "note";
591 elseif (strstr($uri, "/api/image/"))
592 $objectType = "image";
594 $params["verb"] = $action;
595 $params["object"] = array('id' => $uri,
596 "objectType" => $objectType,
597 "content" => $content);
599 $client = new oauth_client_class;
600 $client->oauth_version = '1.0a';
601 $client->authorization_header = true;
602 $client->url_parameters = false;
604 $client->client_id = $ckey;
605 $client->client_secret = $csecret;
606 $client->access_token = $otoken;
607 $client->access_token_secret = $osecret;
609 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
611 if (pumpio_reachable($url))
612 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
617 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
619 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
621 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
623 $a->contact = $r[0]["id"];
625 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
626 require_once('include/queue_fn.php');
627 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
628 notice(t('Pump.io like failed. Queued for retry.').EOL);
632 function pumpio_sync(&$a) {
633 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
639 $last = Config::get('pumpio','last_poll');
641 $poll_interval = intval(Config::get('pumpio','poll_interval'));
643 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
646 $next = $last + ($poll_interval * 60);
648 logger('pumpio: poll intervall not reached');
652 logger('pumpio: cron_start');
654 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
657 logger('pumpio: mirroring user '.$rr['uid']);
658 pumpio_fetchtimeline($a, $rr['uid']);
662 $abandon_days = intval(Config::get('system','account_abandon_days'));
663 if ($abandon_days < 1)
666 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
668 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
671 if ($abandon_days != 0) {
672 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
674 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
679 logger('pumpio: importing timeline from user '.$rr['uid']);
680 pumpio_fetchinbox($a, $rr['uid']);
682 // check for new contacts once a day
683 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
684 if($last_contact_check)
685 $next_contact_check = $last_contact_check + 86400;
687 $next_contact_check = 0;
689 if($next_contact_check <= time()) {
690 pumpio_getallusers($a, $rr["uid"]);
691 PConfig::set($rr['uid'],'pumpio','contact_check',time());
696 logger('pumpio: cron_end');
698 Config::set('pumpio','last_poll', time());
701 function pumpio_cron(&$a,$b) {
702 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
705 function pumpio_fetchtimeline(&$a, $uid) {
706 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
707 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
708 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
709 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
710 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
711 $hostname = PConfig::get($uid, 'pumpio','host');
712 $username = PConfig::get($uid, "pumpio", "user");
714 // get the application name for the pump.io app
715 // 1st try personal config, then system config and fallback to the
716 // hostname of the node if neither one is set.
717 $application_name = PConfig::get( $uid, 'pumpio', 'application_name');
718 if ($application_name == "")
719 $application_name = Config::get('pumpio', 'application_name');
720 if ($application_name == "")
721 $application_name = $a->get_hostname();
723 $first_time = ($lastdate == "");
725 $client = new oauth_client_class;
726 $client->oauth_version = '1.0a';
727 $client->authorization_header = true;
728 $client->url_parameters = false;
730 $client->client_id = $ckey;
731 $client->client_secret = $csecret;
732 $client->access_token = $otoken;
733 $client->access_token_secret = $osecret;
735 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
737 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
739 $username = $user.'@'.$host;
741 if (pumpio_reachable($url))
742 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
747 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
751 $posts = array_reverse($user->items);
753 $initiallastdate = $lastdate;
757 foreach ($posts as $post) {
758 if ($post->published <= $initiallastdate)
761 if ($lastdate < $post->published)
762 $lastdate = $post->published;
767 $receiptians = array();
768 if (@is_array($post->cc))
769 $receiptians = array_merge($receiptians, $post->cc);
771 if (@is_array($post->to))
772 $receiptians = array_merge($receiptians, $post->to);
775 foreach ($receiptians AS $receiver)
776 if (is_string($receiver->objectType))
777 if ($receiver->id == "http://activityschema.org/collection/public")
780 if ($public && !stristr($post->generator->displayName, $application_name)) {
781 require_once('include/html2bbcode.php');
783 $_SESSION["authenticated"] = true;
784 $_SESSION["uid"] = $uid;
787 $_REQUEST["type"] = "wall";
788 $_REQUEST["api_source"] = true;
789 $_REQUEST["profile_uid"] = $uid;
790 $_REQUEST["source"] = "pump.io";
792 if (isset($post->object->id)) {
793 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
796 if ($post->object->displayName != "")
797 $_REQUEST["title"] = html2bbcode($post->object->displayName);
799 $_REQUEST["title"] = "";
801 $_REQUEST["body"] = html2bbcode($post->object->content);
803 // To-Do: Picture has to be cached and stored locally
804 if ($post->object->fullImage->url != "") {
805 if ($post->object->fullImage->pump_io->proxyURL != "")
806 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
808 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
811 logger('pumpio: posting for user '.$uid);
813 require_once('mod/item.php');
816 logger('pumpio: posting done - user '.$uid);
822 PConfig::set($uid,'pumpio','lastdate', $lastdate);
825 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
826 // Searching for the unliked post
827 // Two queries for speed issues
828 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
829 dbesc($post->object->id),
836 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
837 dbesc($post->object->id),
849 if(link_compare($post->actor->url, $own_id)) {
850 $contactid = $self[0]['id'];
852 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
853 dbesc(normalise_link($post->actor->url)),
858 $contactid = $r[0]['id'];
861 $contactid = $orig_post['contact-id'];
864 $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'",
865 dbesc(datetime_convert()),
866 dbesc(ACTIVITY_LIKE),
869 dbesc($orig_post['uri'])
873 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
875 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
878 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
879 require_once('include/items.php');
881 if ($post->object->id == "") {
882 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
886 // Searching for the liked post
887 // Two queries for speed issues
888 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
889 dbesc($post->object->id),
891 dbesc(NETWORK_PUMPIO)
897 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
898 dbesc($post->object->id),
900 dbesc(NETWORK_PUMPIO)
910 if ($threadcompletion)
911 pumpio_fetchallcomments($a, $uid, $post->object->id);
915 if(link_compare($post->actor->url, $own_id)) {
916 $contactid = $self[0]['id'];
917 $post->actor->displayName = $self[0]['name'];
918 $post->actor->url = $self[0]['url'];
919 $post->actor->image->url = $self[0]['photo'];
921 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
922 dbesc(normalise_link($post->actor->url)),
927 $contactid = $r[0]['id'];
930 $contactid = $orig_post['contact-id'];
933 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
934 dbesc(ACTIVITY_LIKE),
937 dbesc($orig_post['uri'])
941 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
946 $likedata['parent'] = $orig_post['id'];
947 $likedata['verb'] = ACTIVITY_LIKE;
948 $likedata['gravity'] = 3;
949 $likedata['uid'] = $uid;
950 $likedata['wall'] = 0;
951 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
952 $likedata['parent-uri'] = $orig_post["uri"];
953 $likedata['contact-id'] = $contactid;
954 $likedata['app'] = $post->generator->displayName;
955 $likedata['author-name'] = $post->actor->displayName;
956 $likedata['author-link'] = $post->actor->url;
957 $likedata['author-avatar'] = $post->actor->image->url;
959 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
960 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
961 $post_type = t('status');
962 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
963 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
965 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
967 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
968 '<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>';
970 $ret = item_store($likedata);
972 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
975 function pumpio_get_contact($uid, $contact, $no_insert = false) {
977 GlobalContact::update(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
978 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
979 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
980 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
981 $cid = Contact::getIdForURL($contact->url, $uid);
986 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
987 intval($uid), dbesc(normalise_link($contact->url)));
990 // create contact record
991 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
992 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
993 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
994 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
996 dbesc(datetime_convert()),
997 dbesc($contact->url),
998 dbesc(normalise_link($contact->url)),
999 dbesc(str_replace("acct:", "", $contact->id)),
1001 dbesc($contact->id), // What is it for?
1002 dbesc('pump.io ' . $contact->id), // What is it for?
1003 dbesc($contact->displayName),
1004 dbesc($contact->preferredUsername),
1005 dbesc($contact->image->url),
1006 dbesc(NETWORK_PUMPIO),
1007 intval(CONTACT_IS_FRIEND),
1009 dbesc($contact->location->displayName),
1010 dbesc($contact->summary),
1014 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1015 dbesc(normalise_link($contact->url)),
1023 $contact_id = $r[0]['id'];
1025 $g = q("select def_gid from user where uid = %d limit 1",
1029 if($g && intval($g[0]['def_gid'])) {
1030 require_once('include/group.php');
1031 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1034 $contact_id = $r[0]["id"];
1036 /* if (DB_UPDATE_VERSION >= "1177")
1037 q("UPDATE `contact` SET `location` = '%s',
1040 dbesc($contact->location->displayName),
1041 dbesc($contact->summary),
1047 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1049 return($contact_id);
1052 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1054 // Two queries for speed issues
1055 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1056 dbesc($post->object->id),
1061 return drop_item($r[0]["id"], $false);
1063 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1064 dbesc($post->object->id),
1069 return drop_item($r[0]["id"], $false);
1072 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1073 require_once('include/items.php');
1074 require_once('include/html2bbcode.php');
1076 if (($post->verb == "like") || ($post->verb == "favorite"))
1077 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1079 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1080 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1082 if ($post->verb == "delete")
1083 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1085 if ($post->verb != "update") {
1086 // Two queries for speed issues
1087 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1088 dbesc($post->object->id),
1095 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1096 dbesc($post->object->id),
1104 // Only handle these three types
1105 if (!strstr("post|share|update", $post->verb))
1108 $receiptians = array();
1109 if (@is_array($post->cc))
1110 $receiptians = array_merge($receiptians, $post->cc);
1112 if (@is_array($post->to))
1113 $receiptians = array_merge($receiptians, $post->to);
1115 foreach ($receiptians AS $receiver)
1116 if (is_string($receiver->objectType))
1117 if ($receiver->id == "http://activityschema.org/collection/public")
1120 $postarray = array();
1121 $postarray['network'] = NETWORK_PUMPIO;
1122 $postarray['gravity'] = 0;
1123 $postarray['uid'] = $uid;
1124 $postarray['wall'] = 0;
1125 $postarray['uri'] = $post->object->id;
1126 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1128 if ($post->object->objectType != "comment") {
1129 $contact_id = pumpio_get_contact($uid, $post->actor);
1132 $contact_id = $self[0]['id'];
1134 $postarray['parent-uri'] = $post->object->id;
1137 $postarray['private'] = 1;
1138 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1141 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1143 if (link_compare($post->actor->url, $own_id)) {
1144 $contact_id = $self[0]['id'];
1145 $post->actor->displayName = $self[0]['name'];
1146 $post->actor->url = $self[0]['url'];
1147 $post->actor->image->url = $self[0]['photo'];
1148 } elseif ($contact_id == 0) {
1149 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1150 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1151 dbesc(normalise_link($post->actor->url)),
1156 $contact_id = $r[0]['id'];
1158 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1159 dbesc(normalise_link($post->actor->url)),
1164 $contact_id = $r[0]['id'];
1166 $contact_id = $self[0]['id'];
1170 $reply = new stdClass;
1171 $reply->verb = "note";
1172 $reply->cc = $post->cc;
1173 $reply->to = $post->to;
1174 $reply->object = new stdClass;
1175 $reply->object->objectType = $post->object->inReplyTo->objectType;
1176 $reply->object->content = $post->object->inReplyTo->content;
1177 $reply->object->id = $post->object->inReplyTo->id;
1178 $reply->actor = $post->object->inReplyTo->author;
1179 $reply->url = $post->object->inReplyTo->url;
1180 $reply->generator = new stdClass;
1181 $reply->generator->displayName = "pumpio";
1182 $reply->published = $post->object->inReplyTo->published;
1183 $reply->received = $post->object->inReplyTo->updated;
1184 $reply->url = $post->object->inReplyTo->url;
1185 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1187 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1190 if ($post->object->pump_io->proxyURL)
1191 $postarray['extid'] = $post->object->pump_io->proxyURL;
1193 $postarray['contact-id'] = $contact_id;
1194 $postarray['verb'] = ACTIVITY_POST;
1195 $postarray['owner-name'] = $post->actor->displayName;
1196 $postarray['owner-link'] = $post->actor->url;
1197 $postarray['owner-avatar'] = $post->actor->image->url;
1198 $postarray['author-name'] = $post->actor->displayName;
1199 $postarray['author-link'] = $post->actor->url;
1200 $postarray['author-avatar'] = $post->actor->image->url;
1201 $postarray['plink'] = $post->object->url;
1202 $postarray['app'] = $post->generator->displayName;
1203 $postarray['body'] = html2bbcode($post->object->content);
1204 $postarray['object'] = json_encode($post);
1206 if ($post->object->fullImage->url != "")
1207 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1209 if ($post->object->displayName != "")
1210 $postarray['title'] = $post->object->displayName;
1212 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1213 if (isset($post->updated))
1214 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1215 elseif (isset($post->received))
1216 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1218 $postarray['edited'] = $postarray['created'];
1220 if ($post->verb == "share") {
1221 if (!intval(Config::get('system','wall-to-wall_share'))) {
1222 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1223 $share_author = $post->object->author->displayName;
1224 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1225 $share_author = $post->object->author->preferredUsername;
1227 $share_author = $post->object->author->url;
1229 $postarray['body'] = share_header($share_author, $post->object->author->url,
1230 $post->object->author->image->url, "",
1231 datetime_convert('UTC','UTC',$post->object->created),
1232 $post->links->self->href).
1233 $postarray['body']."[/share]";
1236 $postarray['body'] = "[share author='".$share_author.
1237 "' profile='".$post->object->author->url.
1238 "' avatar='".$post->object->author->image->url.
1239 "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1240 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1243 // Let shares look like wall-to-wall posts
1244 $postarray['author-name'] = $post->object->author->displayName;
1245 $postarray['author-link'] = $post->object->author->url;
1246 $postarray['author-avatar'] = $post->object->author->image->url;
1250 if (trim($postarray['body']) == "")
1253 $top_item = item_store($postarray);
1254 $postarray["id"] = $top_item;
1256 if (($top_item == 0) && ($post->verb == "update")) {
1257 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1258 dbesc($postarray["title"]),
1259 dbesc($postarray["body"]),
1260 dbesc($postarray["edited"]),
1261 dbesc($postarray["uri"]),
1266 if ($post->object->objectType == "comment") {
1268 if ($threadcompletion)
1269 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1271 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1278 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1280 if (link_compare($own_id, $postarray['author-link']))
1283 if (!function_exists("check_item_notification")) {
1284 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1285 dbesc($postarray['parent-uri']),
1289 if(count($myconv)) {
1291 foreach($myconv as $conv) {
1292 // now if we find a match, it means we're in this conversation
1294 if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1297 require_once('include/enotify.php');
1299 $conv_parent = $conv['parent'];
1302 'type' => NOTIFY_COMMENT,
1303 'notify_flags' => $user[0]['notify-flags'],
1304 'language' => $user[0]['language'],
1305 'to_name' => $user[0]['username'],
1306 'to_email' => $user[0]['email'],
1307 'uid' => $user[0]['uid'],
1308 'item' => $postarray,
1309 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1310 'source_name' => $postarray['author-name'],
1311 'source_link' => $postarray['author-link'],
1312 'source_photo' => $postarray['author-avatar'],
1313 'verb' => ACTIVITY_POST,
1315 'parent' => $conv_parent,
1318 // only send one notification
1328 function pumpio_fetchinbox(&$a, $uid) {
1330 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1331 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1332 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1333 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1334 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1335 $hostname = PConfig::get($uid, 'pumpio','host');
1336 $username = PConfig::get($uid, "pumpio", "user");
1338 $own_id = "https://".$hostname."/".$username;
1340 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1343 $lastitems = q("SELECT `uri` FROM `thread`
1344 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1345 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1346 ORDER BY `thread`.`commented` DESC LIMIT 10",
1347 dbesc(NETWORK_PUMPIO),
1351 $client = new oauth_client_class;
1352 $client->oauth_version = '1.0a';
1353 $client->authorization_header = true;
1354 $client->url_parameters = false;
1356 $client->client_id = $ckey;
1357 $client->client_secret = $csecret;
1358 $client->access_token = $otoken;
1359 $client->access_token_secret = $osecret;
1361 $last_id = PConfig::get($uid,'pumpio','last_id');
1363 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1366 $url .= '?since='.urlencode($last_id);
1368 if (pumpio_reachable($url))
1369 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1374 $posts = array_reverse($user->items);
1377 foreach ($posts as $post) {
1378 $last_id = $post->id;
1379 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1383 foreach ($lastitems AS $item)
1384 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1386 PConfig::set($uid,'pumpio','last_id', $last_id);
1389 function pumpio_getallusers(&$a, $uid) {
1390 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1391 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1392 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1393 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1394 $hostname = PConfig::get($uid, 'pumpio','host');
1395 $username = PConfig::get($uid, "pumpio", "user");
1397 $client = new oauth_client_class;
1398 $client->oauth_version = '1.0a';
1399 $client->authorization_header = true;
1400 $client->url_parameters = false;
1402 $client->client_id = $ckey;
1403 $client->client_secret = $csecret;
1404 $client->access_token = $otoken;
1405 $client->access_token_secret = $osecret;
1407 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1409 if (pumpio_reachable($url))
1410 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1414 if ($users->totalItems > count($users->items)) {
1415 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1417 if (pumpio_reachable($url))
1418 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1423 if (is_array($users->items)) {
1424 foreach ($users->items AS $user) {
1425 pumpio_get_contact($uid, $user);
1430 function pumpio_queue_hook(&$a,&$b) {
1432 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1433 dbesc(NETWORK_PUMPIO)
1438 require_once('include/queue_fn.php');
1440 foreach($qi as $x) {
1441 if($x['network'] !== NETWORK_PUMPIO)
1444 logger('pumpio_queue: run');
1446 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1447 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1455 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1457 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1458 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1459 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1460 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1462 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1463 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1467 if ($oauth_token && $oauth_token_secret &&
1468 $consumer_key && $consumer_secret) {
1469 $username = $user.'@'.$host;
1471 logger('pumpio_queue: able to post for user '.$username);
1473 $z = unserialize($x['content']);
1475 $client = new oauth_client_class;
1476 $client->oauth_version = '1.0a';
1477 $client->url_parameters = false;
1478 $client->authorization_header = true;
1479 $client->access_token = $oauth_token;
1480 $client->access_token_secret = $oauth_token_secret;
1481 $client->client_id = $consumer_key;
1482 $client->client_secret = $consumer_secret;
1484 if (pumpio_reachable($z['url']))
1485 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1490 $post_id = $user->object->id;
1491 logger('pumpio_queue: send '.$username.': success '.$post_id);
1492 if($post_id && $iscomment) {
1493 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1494 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1499 remove_queue_item($x['id']);
1501 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1503 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1506 logger('pumpio_queue: delayed');
1507 update_queue_time($x['id']);
1512 function pumpio_getreceiver(&$a, $b) {
1514 $receiver = array();
1516 if (!$b["private"]) {
1518 if(! strstr($b['postopts'],'pumpio'))
1521 $public = PConfig::get($b['uid'], "pumpio", "public");
1524 $receiver["to"][] = Array(
1525 "objectType" => "collection",
1526 "id" => "http://activityschema.org/collection/public");
1528 $cids = explode("><", $b["allow_cid"]);
1529 $gids = explode("><", $b["allow_gid"]);
1531 foreach ($cids AS $cid) {
1532 $cid = trim($cid, " <>");
1534 $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",
1537 dbesc(NETWORK_PUMPIO)
1541 $receiver["bcc"][] = Array(
1542 "displayName" => $r[0]["name"],
1543 "objectType" => "person",
1544 "preferredUsername" => $r[0]["nick"],
1545 "url" => $r[0]["url"]);
1548 foreach ($gids AS $gid) {
1549 $gid = trim($gid, " <>");
1551 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1552 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1553 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1556 dbesc(NETWORK_PUMPIO)
1559 foreach ($r AS $row)
1560 $receiver["bcc"][] = Array(
1561 "displayName" => $row["name"],
1562 "objectType" => "person",
1563 "preferredUsername" => $row["nick"],
1564 "url" => $row["url"]);
1568 if ($b["inform"] != "") {
1570 $inform = explode(",", $b["inform"]);
1572 foreach ($inform AS $cid) {
1573 if (substr($cid, 0, 4) != "cid:")
1576 $cid = str_replace("cid:", "", $cid);
1578 $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",
1581 dbesc(NETWORK_PUMPIO)
1585 $receiver["to"][] = Array(
1586 "displayName" => $r[0]["name"],
1587 "objectType" => "person",
1588 "preferredUsername" => $r[0]["nick"],
1589 "url" => $r[0]["url"]);
1597 function pumpio_fetchallcomments(&$a, $uid, $id) {
1598 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1599 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1600 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1601 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1602 $hostname = PConfig::get($uid, 'pumpio','host');
1603 $username = PConfig::get($uid, "pumpio", "user");
1605 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1607 $own_id = "https://".$hostname."/".$username;
1609 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1612 // Fetching the original post
1613 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1621 $url = $r[0]["extid"];
1623 $client = new oauth_client_class;
1624 $client->oauth_version = '1.0a';
1625 $client->authorization_header = true;
1626 $client->url_parameters = false;
1628 $client->client_id = $ckey;
1629 $client->client_secret = $csecret;
1630 $client->access_token = $otoken;
1631 $client->access_token_secret = $osecret;
1633 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1635 if (pumpio_reachable($url))
1636 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1643 if ($item->likes->totalItems != 0) {
1644 foreach ($item->likes->items AS $post) {
1645 $like = new stdClass;
1646 $like->object = new stdClass;
1647 $like->object->id = $item->id;
1648 $like->actor = new stdClass;
1649 $like->actor->displayName = $item->displayName;
1650 $like->actor->preferredUsername = $item->preferredUsername;
1651 $like->actor->url = $item->url;
1652 $like->actor->image = $item->image;
1653 $like->generator = new stdClass;
1654 $like->generator->displayName = "pumpio";
1655 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1659 if ($item->replies->totalItems == 0)
1662 foreach ($item->replies->items AS $item) {
1663 if ($item->id == $id)
1666 // Checking if the comment already exists - Two queries for speed issues
1667 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1675 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1683 $post = new stdClass;
1684 $post->verb = "post";
1685 $post->actor = $item->author;
1686 $post->published = $item->published;
1687 $post->received = $item->updated;
1688 $post->generator = new stdClass;
1689 $post->generator->displayName = "pumpio";
1690 // To-Do: Check for public post
1692 unset($item->author);
1693 unset($item->published);
1694 unset($item->updated);
1696 $post->object = $item;
1698 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1699 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1704 function pumpio_reachable($url) {
1705 $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
1706 return(intval($data['return_code']) != 0);