3 * Name: pump.io Post Connector
4 * Description: Bidirectional (posting, relaying and reading) connector for pump.io.
6 * Author: Michael Vogel <http://pirati.ca/profile/heluecht>
8 require('addon/pumpio/oauth/http.php');
9 require('addon/pumpio/oauth/oauth_client.php');
10 require_once('include/enotify.php');
11 require_once('include/socgraph.php');
12 require_once("include/Photo.php");
13 require_once("mod/share.php");
15 use Friendica\Core\Config;
16 use Friendica\Core\PConfig;
18 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
20 function pumpio_install() {
21 register_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
22 register_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
23 register_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
24 register_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
25 register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
26 register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
27 register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
28 register_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
31 function pumpio_uninstall() {
32 unregister_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
33 unregister_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
34 unregister_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
35 unregister_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
36 unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
37 unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
38 unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
39 unregister_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
42 function pumpio_module() {}
44 function pumpio_content(&$a) {
47 notice( t('Permission denied.') . EOL);
51 require_once("mod/settings.php");
54 if (isset($a->argv[1]))
55 switch ($a->argv[1]) {
57 $o = pumpio_connect($a);
60 $o = print_r($a->argv, true);
64 $o = pumpio_connect($a);
69 function pumpio_check_item_notification($a, &$notification_data) {
70 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
71 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
73 $notification_data["profiles"][] = "https://".$hostname."/".$username;
77 function pumpio_registerclient(&$a, $host) {
79 $url = "https://".$host."/api/client/register";
83 $application_name = Config::get('pumpio', 'application_name');
85 if ($application_name == "")
86 $application_name = $a->get_hostname();
88 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
90 $params["type"] = "client_associate";
91 $params["contacts"] = $adminlist[0];
92 $params["application_type"] = "native";
93 $params["application_name"] = $application_name;
94 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
95 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
97 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
99 $ch = curl_init($url);
100 curl_setopt($ch, CURLOPT_HEADER, false);
101 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
102 curl_setopt($ch, CURLOPT_POST,1);
103 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
104 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
107 $curl_info = curl_getinfo($ch);
109 if ($curl_info["http_code"] == "200") {
110 $values = json_decode($s);
111 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
114 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
119 function pumpio_connect(&$a) {
120 // Start a session. This is necessary to hold on to a few keys the callback script will also need
123 // Define the needed keys
124 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
125 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
126 $hostname = PConfig::get(local_user(), 'pumpio','host');
128 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
129 logger("pumpio_connect: register client");
130 $clientdata = pumpio_registerclient($a, $hostname);
131 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
132 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
134 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
135 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
137 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
140 if (($consumer_key == "") || ($consumer_secret == "")) {
141 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
143 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
147 // The callback URL is the script that gets called after the user authenticates with pumpio
148 $callback_url = $a->get_baseurl()."/pumpio/connect";
150 // Let's begin. First we need a Request Token. The request token is required to send the user
151 // to pumpio's login page.
153 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
154 // Consumer Key and Consumer Secret
155 $client = new oauth_client_class;
157 $client->server = '';
158 $client->oauth_version = '1.0a';
159 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
160 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
161 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
162 $client->url_parameters = false;
163 $client->authorization_header = true;
164 $client->redirect_uri = $callback_url;
165 $client->client_id = $consumer_key;
166 $client->client_secret = $consumer_secret;
168 if (($success = $client->Initialize())) {
169 if (($success = $client->Process())) {
170 if (strlen($client->access_token)) {
171 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
172 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
173 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
176 $success = $client->Finalize($success);
179 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
182 logger("pumpio_connect: authenticated");
183 $o .= t("You are now authenticated to pumpio.");
184 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
186 logger("pumpio_connect: could not connect");
187 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
193 function pumpio_jot_nets(&$a,&$b) {
197 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
198 if(intval($pumpio_post) == 1) {
199 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
200 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
201 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
202 . t('Post to pumpio') . '</div>';
207 function pumpio_settings(&$a,&$s) {
212 /* Add our stylesheet to the page so we can make our settings look nice */
214 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
216 /* Get the current state of our config variables */
218 $import_enabled = PConfig::get(local_user(),'pumpio','import');
219 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
221 $enabled = PConfig::get(local_user(),'pumpio','post');
222 $checked = (($enabled) ? ' checked="checked" ' : '');
223 $css = (($enabled) ? '' : '-disabled');
225 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
226 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
228 $public_enabled = PConfig::get(local_user(),'pumpio','public');
229 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
231 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
232 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
234 $servername = PConfig::get(local_user(), "pumpio", "host");
235 $username = PConfig::get(local_user(), "pumpio", "user");
237 /* Add some HTML to the existing form */
239 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
240 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
242 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
243 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
244 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
247 $s .= '<div id="pumpio-username-wrapper">';
248 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
249 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
250 $s .= '</div><div class="clear"></div>';
252 $s .= '<div id="pumpio-servername-wrapper">';
253 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
254 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
255 $s .= '</div><div class="clear"></div>';
257 if (($username != '') && ($servername != '')) {
259 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
260 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
262 $s .= '<div id="pumpio-password-wrapper">';
263 if (($oauth_token == "") || ($oauth_token_secret == "")) {
264 $s .= '<div id="pumpio-authenticate-wrapper">';
265 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
266 $s .= '</div><div class="clear"></div>';
268 $s .= '<div id="pumpio-import-wrapper">';
269 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
270 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
271 $s .= '</div><div class="clear"></div>';
273 $s .= '<div id="pumpio-enable-wrapper">';
274 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
275 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
276 $s .= '</div><div class="clear"></div>';
278 $s .= '<div id="pumpio-bydefault-wrapper">';
279 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
280 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
281 $s .= '</div><div class="clear"></div>';
283 $s .= '<div id="pumpio-public-wrapper">';
284 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
285 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
286 $s .= '</div><div class="clear"></div>';
288 $s .= '<div id="pumpio-mirror-wrapper">';
289 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
290 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
291 $s .= '</div><div class="clear"></div>';
293 $s .= '<div id="pumpio-delete-wrapper">';
294 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
295 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
296 $s .= '</div><div class="clear"></div>';
299 $s .= '</div><div class="clear"></div>';
302 /* provide a submit button */
304 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
308 function pumpio_settings_post(&$a,&$b) {
310 if(x($_POST,'pumpio-submit')) {
311 if(x($_POST,'pumpio_delete')) {
312 PConfig::set(local_user(),'pumpio','consumer_key','');
313 PConfig::set(local_user(),'pumpio','consumer_secret','');
314 PConfig::set(local_user(),'pumpio','oauth_token','');
315 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
316 PConfig::set(local_user(),'pumpio','post',false);
317 PConfig::set(local_user(),'pumpio','import',false);
318 PConfig::set(local_user(),'pumpio','host','');
319 PConfig::set(local_user(),'pumpio','user','');
320 PConfig::set(local_user(),'pumpio','public',false);
321 PConfig::set(local_user(),'pumpio','mirror',false);
322 PConfig::set(local_user(),'pumpio','post_by_default',false);
323 PConfig::set(local_user(),'pumpio','lastdate', 0);
324 PConfig::set(local_user(),'pumpio','last_id', '');
326 // filtering the username if it is filled wrong
327 $user = $_POST['pumpio_user'];
328 if (strstr($user, "@")) {
329 $pos = strpos($user, "@");
331 $user = substr($user, 0, $pos);
334 // Filtering the hostname if someone is entering it with "http"
335 $host = $_POST['pumpio_host'];
337 $host = str_replace(array("https://", "http://"), array("", ""), $host);
339 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
340 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
341 PConfig::set(local_user(),'pumpio','host',$host);
342 PConfig::set(local_user(),'pumpio','user',$user);
343 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
344 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
345 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
347 if (!$_POST['pumpio_mirror'])
348 del_pconfig(local_user(),'pumpio','lastdate');
350 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
355 function pumpio_post_local(&$a, &$b) {
357 if (!local_user() || (local_user() != $b['uid'])) {
361 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
363 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
365 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
369 if (!$pumpio_enable) {
373 if (strlen($b['postopts'])) {
374 $b['postopts'] .= ',';
377 $b['postopts'] .= 'pumpio';
383 function pumpio_send(&$a,&$b) {
385 if (!PConfig::get($b["uid"],'pumpio','import')) {
386 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
390 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
392 if($b['parent'] != $b['id']) {
393 // Looking if its a reply to a pumpio post
394 $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",
395 intval($b["parent"]),
397 dbesc(NETWORK_PUMPIO));
400 logger("pumpio_send: no pumpio post ".$b["parent"]);
409 $receiver = pumpio_getreceiver($a, $b);
411 logger("pumpio_send: receiver ".print_r($receiver, true));
413 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio')))
417 if($b['verb'] == ACTIVITY_LIKE) {
419 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
421 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
425 if($b['verb'] == ACTIVITY_DISLIKE)
428 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
429 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
431 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
432 pumpio_action($a, $b["uid"], $b["uri"], "delete");
434 if($b['deleted'] || ($b['created'] !== $b['edited']))
437 // if post comes from pump.io don't send it back
438 if($b['app'] == "pump.io")
442 // Support for native shares
443 // http://<hostname>/api/<type>/shares?id=<the-object-id>
445 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
446 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
447 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
448 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
450 $host = PConfig::get($b['uid'], "pumpio", "host");
451 $user = PConfig::get($b['uid'], "pumpio", "user");
452 $public = PConfig::get($b['uid'], "pumpio", "public");
454 if($oauth_token && $oauth_token_secret) {
456 require_once('include/bbcode.php');
458 $title = trim($b['title']);
460 $content = bbcode($b['body'], false, false, 4);
464 $params["verb"] = "post";
467 $params["object"] = array(
468 'objectType' => "note",
469 'content' => $content);
472 $params["object"]["displayName"] = $title;
474 if (count($receiver["to"]))
475 $params["to"] = $receiver["to"];
477 if (count($receiver["bto"]))
478 $params["bto"] = $receiver["bto"];
480 if (count($receiver["cc"]))
481 $params["cc"] = $receiver["cc"];
483 if (count($receiver["bcc"]))
484 $params["bcc"] = $receiver["bcc"];
487 $inReplyTo = array("id" => $orig_post["uri"],
488 "objectType" => "note");
490 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
491 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
493 $params["object"] = array(
494 'objectType' => "comment",
495 'content' => $content,
496 'inReplyTo' => $inReplyTo);
499 $params["object"]["displayName"] = $title;
502 $client = new oauth_client_class;
503 $client->oauth_version = '1.0a';
504 $client->url_parameters = false;
505 $client->authorization_header = true;
506 $client->access_token = $oauth_token;
507 $client->access_token_secret = $oauth_token_secret;
508 $client->client_id = $consumer_key;
509 $client->client_secret = $consumer_secret;
511 $username = $user.'@'.$host;
512 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
514 if (pumpio_reachable($url))
515 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
521 if ($user->generator->displayName)
522 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
524 $post_id = $user->object->id;
525 logger('pumpio_send '.$username.': success '.$post_id);
526 if($post_id && $iscomment) {
527 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
528 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
534 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
536 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
538 $a->contact = $r[0]["id"];
540 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
541 require_once('include/queue_fn.php');
542 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
543 notice(t('Pump.io post failed. Queued for retry.').EOL);
549 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
551 // Don't do likes and other stuff if you don't import the timeline
552 if (!PConfig::get($uid,'pumpio','import'))
555 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
556 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
557 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
558 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
559 $hostname = PConfig::get($uid, 'pumpio','host');
560 $username = PConfig::get($uid, "pumpio", "user");
562 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
572 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
573 $uri = $orig_post["extid"];
575 $uri = $orig_post["uri"];
577 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
578 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
579 elseif (strstr($uri, "/api/comment/"))
580 $objectType = "comment";
581 elseif (strstr($uri, "/api/note/"))
582 $objectType = "note";
583 elseif (strstr($uri, "/api/image/"))
584 $objectType = "image";
586 $params["verb"] = $action;
587 $params["object"] = array('id' => $uri,
588 "objectType" => $objectType,
589 "content" => $content);
591 $client = new oauth_client_class;
592 $client->oauth_version = '1.0a';
593 $client->authorization_header = true;
594 $client->url_parameters = false;
596 $client->client_id = $ckey;
597 $client->client_secret = $csecret;
598 $client->access_token = $otoken;
599 $client->access_token_secret = $osecret;
601 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
603 if (pumpio_reachable($url))
604 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
609 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
611 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
613 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
615 $a->contact = $r[0]["id"];
617 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
618 require_once('include/queue_fn.php');
619 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
620 notice(t('Pump.io like failed. Queued for retry.').EOL);
624 function pumpio_sync(&$a) {
625 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
631 $last = Config::get('pumpio','last_poll');
633 $poll_interval = intval(Config::get('pumpio','poll_interval'));
635 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
638 $next = $last + ($poll_interval * 60);
640 logger('pumpio: poll intervall not reached');
644 logger('pumpio: cron_start');
646 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
649 logger('pumpio: mirroring user '.$rr['uid']);
650 pumpio_fetchtimeline($a, $rr['uid']);
654 $abandon_days = intval(Config::get('system','account_abandon_days'));
655 if ($abandon_days < 1)
658 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
660 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
663 if ($abandon_days != 0) {
664 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
666 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
671 logger('pumpio: importing timeline from user '.$rr['uid']);
672 pumpio_fetchinbox($a, $rr['uid']);
674 // check for new contacts once a day
675 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
676 if($last_contact_check)
677 $next_contact_check = $last_contact_check + 86400;
679 $next_contact_check = 0;
681 if($next_contact_check <= time()) {
682 pumpio_getallusers($a, $rr["uid"]);
683 PConfig::set($rr['uid'],'pumpio','contact_check',time());
688 logger('pumpio: cron_end');
690 Config::set('pumpio','last_poll', time());
693 function pumpio_cron(&$a,$b) {
695 proc_run("php","addon/pumpio/pumpio_sync.php");
698 function pumpio_fetchtimeline(&$a, $uid) {
699 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
700 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
701 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
702 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
703 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
704 $hostname = PConfig::get($uid, 'pumpio','host');
705 $username = PConfig::get($uid, "pumpio", "user");
707 // get the application name for the pump.io app
708 // 1st try personal config, then system config and fallback to the
709 // hostname of the node if neither one is set.
710 $application_name = PConfig::get( $uid, 'pumpio', 'application_name');
711 if ($application_name == "")
712 $application_name = Config::get('pumpio', 'application_name');
713 if ($application_name == "")
714 $application_name = $a->get_hostname();
716 $first_time = ($lastdate == "");
718 $client = new oauth_client_class;
719 $client->oauth_version = '1.0a';
720 $client->authorization_header = true;
721 $client->url_parameters = false;
723 $client->client_id = $ckey;
724 $client->client_secret = $csecret;
725 $client->access_token = $otoken;
726 $client->access_token_secret = $osecret;
728 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
730 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
732 $username = $user.'@'.$host;
734 if (pumpio_reachable($url))
735 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
740 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
744 $posts = array_reverse($user->items);
746 $initiallastdate = $lastdate;
750 foreach ($posts as $post) {
751 if ($post->published <= $initiallastdate)
754 if ($lastdate < $post->published)
755 $lastdate = $post->published;
760 $receiptians = array();
761 if (@is_array($post->cc))
762 $receiptians = array_merge($receiptians, $post->cc);
764 if (@is_array($post->to))
765 $receiptians = array_merge($receiptians, $post->to);
768 foreach ($receiptians AS $receiver)
769 if (is_string($receiver->objectType))
770 if ($receiver->id == "http://activityschema.org/collection/public")
773 if ($public && !stristr($post->generator->displayName, $application_name)) {
774 require_once('include/html2bbcode.php');
776 $_SESSION["authenticated"] = true;
777 $_SESSION["uid"] = $uid;
780 $_REQUEST["type"] = "wall";
781 $_REQUEST["api_source"] = true;
782 $_REQUEST["profile_uid"] = $uid;
783 $_REQUEST["source"] = "pump.io";
785 if (isset($post->object->id)) {
786 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
789 if ($post->object->displayName != "")
790 $_REQUEST["title"] = html2bbcode($post->object->displayName);
792 $_REQUEST["title"] = "";
794 $_REQUEST["body"] = html2bbcode($post->object->content);
796 // To-Do: Picture has to be cached and stored locally
797 if ($post->object->fullImage->url != "") {
798 if ($post->object->fullImage->pump_io->proxyURL != "")
799 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
801 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
804 logger('pumpio: posting for user '.$uid);
806 require_once('mod/item.php');
809 logger('pumpio: posting done - user '.$uid);
815 PConfig::set($uid,'pumpio','lastdate', $lastdate);
818 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
819 // Searching for the unliked post
820 // Two queries for speed issues
821 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
822 dbesc($post->object->id),
829 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
830 dbesc($post->object->id),
842 if(link_compare($post->actor->url, $own_id)) {
843 $contactid = $self[0]['id'];
845 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
846 dbesc(normalise_link($post->actor->url)),
851 $contactid = $r[0]['id'];
854 $contactid = $orig_post['contact-id'];
857 $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'",
858 dbesc(datetime_convert()),
859 dbesc(ACTIVITY_LIKE),
862 dbesc($orig_post['uri'])
866 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
868 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
871 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
872 require_once('include/items.php');
874 if ($post->object->id == "") {
875 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
879 // Searching for the liked post
880 // Two queries for speed issues
881 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
882 dbesc($post->object->id),
884 dbesc(NETWORK_PUMPIO)
890 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
891 dbesc($post->object->id),
893 dbesc(NETWORK_PUMPIO)
903 if ($threadcompletion)
904 pumpio_fetchallcomments($a, $uid, $post->object->id);
908 if(link_compare($post->actor->url, $own_id)) {
909 $contactid = $self[0]['id'];
910 $post->actor->displayName = $self[0]['name'];
911 $post->actor->url = $self[0]['url'];
912 $post->actor->image->url = $self[0]['photo'];
914 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
915 dbesc(normalise_link($post->actor->url)),
920 $contactid = $r[0]['id'];
923 $contactid = $orig_post['contact-id'];
926 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
927 dbesc(ACTIVITY_LIKE),
930 dbesc($orig_post['uri'])
934 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
939 $likedata['parent'] = $orig_post['id'];
940 $likedata['verb'] = ACTIVITY_LIKE;
941 $likedata['gravity'] = 3;
942 $likedata['uid'] = $uid;
943 $likedata['wall'] = 0;
944 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
945 $likedata['parent-uri'] = $orig_post["uri"];
946 $likedata['contact-id'] = $contactid;
947 $likedata['app'] = $post->generator->displayName;
948 $likedata['author-name'] = $post->actor->displayName;
949 $likedata['author-link'] = $post->actor->url;
950 $likedata['author-avatar'] = $post->actor->image->url;
952 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
953 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
954 $post_type = t('status');
955 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
956 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
958 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
960 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
961 '<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>';
963 $ret = item_store($likedata);
965 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
968 function pumpio_get_contact($uid, $contact, $no_insert = false) {
970 update_gcontact(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
971 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
972 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
973 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
974 $cid = get_contact($contact->url, $uid);
979 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
980 intval($uid), dbesc(normalise_link($contact->url)));
983 // create contact record
984 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
985 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
986 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
987 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
989 dbesc(datetime_convert()),
990 dbesc($contact->url),
991 dbesc(normalise_link($contact->url)),
992 dbesc(str_replace("acct:", "", $contact->id)),
994 dbesc($contact->id), // What is it for?
995 dbesc('pump.io ' . $contact->id), // What is it for?
996 dbesc($contact->displayName),
997 dbesc($contact->preferredUsername),
998 dbesc($contact->image->url),
999 dbesc(NETWORK_PUMPIO),
1000 intval(CONTACT_IS_FRIEND),
1002 dbesc($contact->location->displayName),
1003 dbesc($contact->summary),
1007 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1008 dbesc(normalise_link($contact->url)),
1016 $contact_id = $r[0]['id'];
1018 $g = q("select def_gid from user where uid = %d limit 1",
1022 if($g && intval($g[0]['def_gid'])) {
1023 require_once('include/group.php');
1024 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1027 $contact_id = $r[0]["id"];
1029 /* if (DB_UPDATE_VERSION >= "1177")
1030 q("UPDATE `contact` SET `location` = '%s',
1033 dbesc($contact->location->displayName),
1034 dbesc($contact->summary),
1040 if (function_exists("update_contact_avatar"))
1041 update_contact_avatar($contact->image->url, $uid, $contact_id);
1043 return($contact_id);
1046 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1048 // Two queries for speed issues
1049 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1050 dbesc($post->object->id),
1055 return drop_item($r[0]["id"], $false);
1057 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1058 dbesc($post->object->id),
1063 return drop_item($r[0]["id"], $false);
1066 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1067 require_once('include/items.php');
1068 require_once('include/html2bbcode.php');
1070 if (($post->verb == "like") || ($post->verb == "favorite"))
1071 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1073 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1074 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1076 if ($post->verb == "delete")
1077 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1079 if ($post->verb != "update") {
1080 // Two queries for speed issues
1081 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1082 dbesc($post->object->id),
1089 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1090 dbesc($post->object->id),
1098 // Only handle these three types
1099 if (!strstr("post|share|update", $post->verb))
1102 $receiptians = array();
1103 if (@is_array($post->cc))
1104 $receiptians = array_merge($receiptians, $post->cc);
1106 if (@is_array($post->to))
1107 $receiptians = array_merge($receiptians, $post->to);
1109 foreach ($receiptians AS $receiver)
1110 if (is_string($receiver->objectType))
1111 if ($receiver->id == "http://activityschema.org/collection/public")
1114 $postarray = array();
1115 $postarray['network'] = NETWORK_PUMPIO;
1116 $postarray['gravity'] = 0;
1117 $postarray['uid'] = $uid;
1118 $postarray['wall'] = 0;
1119 $postarray['uri'] = $post->object->id;
1120 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1122 if ($post->object->objectType != "comment") {
1123 $contact_id = pumpio_get_contact($uid, $post->actor);
1126 $contact_id = $self[0]['id'];
1128 $postarray['parent-uri'] = $post->object->id;
1131 $postarray['private'] = 1;
1132 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1135 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1137 if (link_compare($post->actor->url, $own_id)) {
1138 $contact_id = $self[0]['id'];
1139 $post->actor->displayName = $self[0]['name'];
1140 $post->actor->url = $self[0]['url'];
1141 $post->actor->image->url = $self[0]['photo'];
1142 } elseif ($contact_id == 0) {
1143 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1144 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1145 dbesc(normalise_link($post->actor->url)),
1150 $contact_id = $r[0]['id'];
1152 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1153 dbesc(normalise_link($post->actor->url)),
1158 $contact_id = $r[0]['id'];
1160 $contact_id = $self[0]['id'];
1164 $reply = new stdClass;
1165 $reply->verb = "note";
1166 $reply->cc = $post->cc;
1167 $reply->to = $post->to;
1168 $reply->object = new stdClass;
1169 $reply->object->objectType = $post->object->inReplyTo->objectType;
1170 $reply->object->content = $post->object->inReplyTo->content;
1171 $reply->object->id = $post->object->inReplyTo->id;
1172 $reply->actor = $post->object->inReplyTo->author;
1173 $reply->url = $post->object->inReplyTo->url;
1174 $reply->generator = new stdClass;
1175 $reply->generator->displayName = "pumpio";
1176 $reply->published = $post->object->inReplyTo->published;
1177 $reply->received = $post->object->inReplyTo->updated;
1178 $reply->url = $post->object->inReplyTo->url;
1179 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1181 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1184 if ($post->object->pump_io->proxyURL)
1185 $postarray['extid'] = $post->object->pump_io->proxyURL;
1187 $postarray['contact-id'] = $contact_id;
1188 $postarray['verb'] = ACTIVITY_POST;
1189 $postarray['owner-name'] = $post->actor->displayName;
1190 $postarray['owner-link'] = $post->actor->url;
1191 $postarray['owner-avatar'] = $post->actor->image->url;
1192 $postarray['author-name'] = $post->actor->displayName;
1193 $postarray['author-link'] = $post->actor->url;
1194 $postarray['author-avatar'] = $post->actor->image->url;
1195 $postarray['plink'] = $post->object->url;
1196 $postarray['app'] = $post->generator->displayName;
1197 $postarray['body'] = html2bbcode($post->object->content);
1198 $postarray['object'] = json_encode($post);
1200 if ($post->object->fullImage->url != "")
1201 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1203 if ($post->object->displayName != "")
1204 $postarray['title'] = $post->object->displayName;
1206 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1207 if (isset($post->updated))
1208 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1209 elseif (isset($post->received))
1210 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1212 $postarray['edited'] = $postarray['created'];
1214 if ($post->verb == "share") {
1215 if (!intval(Config::get('system','wall-to-wall_share'))) {
1216 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1217 $share_author = $post->object->author->displayName;
1218 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1219 $share_author = $post->object->author->preferredUsername;
1221 $share_author = $post->object->author->url;
1223 $postarray['body'] = share_header($share_author, $post->object->author->url,
1224 $post->object->author->image->url, "",
1225 datetime_convert('UTC','UTC',$post->object->created),
1226 $post->links->self->href).
1227 $postarray['body']."[/share]";
1230 $postarray['body'] = "[share author='".$share_author.
1231 "' profile='".$post->object->author->url.
1232 "' avatar='".$post->object->author->image->url.
1233 "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1234 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1237 // Let shares look like wall-to-wall posts
1238 $postarray['author-name'] = $post->object->author->displayName;
1239 $postarray['author-link'] = $post->object->author->url;
1240 $postarray['author-avatar'] = $post->object->author->image->url;
1244 if (trim($postarray['body']) == "")
1247 $top_item = item_store($postarray);
1248 $postarray["id"] = $top_item;
1250 if (($top_item == 0) && ($post->verb == "update")) {
1251 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1252 dbesc($postarray["title"]),
1253 dbesc($postarray["body"]),
1254 dbesc($postarray["edited"]),
1255 dbesc($postarray["uri"]),
1260 if ($post->object->objectType == "comment") {
1262 if ($threadcompletion)
1263 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1265 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1272 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1274 if (link_compare($own_id, $postarray['author-link']))
1277 if (!function_exists("check_item_notification")) {
1278 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1279 dbesc($postarray['parent-uri']),
1283 if(count($myconv)) {
1285 foreach($myconv as $conv) {
1286 // now if we find a match, it means we're in this conversation
1288 if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1291 require_once('include/enotify.php');
1293 $conv_parent = $conv['parent'];
1296 'type' => NOTIFY_COMMENT,
1297 'notify_flags' => $user[0]['notify-flags'],
1298 'language' => $user[0]['language'],
1299 'to_name' => $user[0]['username'],
1300 'to_email' => $user[0]['email'],
1301 'uid' => $user[0]['uid'],
1302 'item' => $postarray,
1303 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1304 'source_name' => $postarray['author-name'],
1305 'source_link' => $postarray['author-link'],
1306 'source_photo' => $postarray['author-avatar'],
1307 'verb' => ACTIVITY_POST,
1309 'parent' => $conv_parent,
1312 // only send one notification
1322 function pumpio_fetchinbox(&$a, $uid) {
1324 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1325 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1326 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1327 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1328 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1329 $hostname = PConfig::get($uid, 'pumpio','host');
1330 $username = PConfig::get($uid, "pumpio", "user");
1332 $own_id = "https://".$hostname."/".$username;
1334 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1337 $lastitems = q("SELECT `uri` FROM `thread`
1338 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1339 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1340 ORDER BY `thread`.`commented` DESC LIMIT 10",
1341 dbesc(NETWORK_PUMPIO),
1345 $client = new oauth_client_class;
1346 $client->oauth_version = '1.0a';
1347 $client->authorization_header = true;
1348 $client->url_parameters = false;
1350 $client->client_id = $ckey;
1351 $client->client_secret = $csecret;
1352 $client->access_token = $otoken;
1353 $client->access_token_secret = $osecret;
1355 $last_id = PConfig::get($uid,'pumpio','last_id');
1357 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1360 $url .= '?since='.urlencode($last_id);
1362 if (pumpio_reachable($url))
1363 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1368 $posts = array_reverse($user->items);
1371 foreach ($posts as $post) {
1372 $last_id = $post->id;
1373 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1377 foreach ($lastitems AS $item)
1378 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1380 PConfig::set($uid,'pumpio','last_id', $last_id);
1383 function pumpio_getallusers(&$a, $uid) {
1384 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1385 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1386 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1387 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1388 $hostname = PConfig::get($uid, 'pumpio','host');
1389 $username = PConfig::get($uid, "pumpio", "user");
1391 $client = new oauth_client_class;
1392 $client->oauth_version = '1.0a';
1393 $client->authorization_header = true;
1394 $client->url_parameters = false;
1396 $client->client_id = $ckey;
1397 $client->client_secret = $csecret;
1398 $client->access_token = $otoken;
1399 $client->access_token_secret = $osecret;
1401 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1403 if (pumpio_reachable($url))
1404 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1408 if ($users->totalItems > count($users->items)) {
1409 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1411 if (pumpio_reachable($url))
1412 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1417 if (is_array($users->items)) {
1418 foreach ($users->items AS $user) {
1419 pumpio_get_contact($uid, $user);
1424 function pumpio_queue_hook(&$a,&$b) {
1426 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1427 dbesc(NETWORK_PUMPIO)
1432 require_once('include/queue_fn.php');
1434 foreach($qi as $x) {
1435 if($x['network'] !== NETWORK_PUMPIO)
1438 logger('pumpio_queue: run');
1440 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1441 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1449 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1451 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1452 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1453 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1454 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1456 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1457 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1461 if ($oauth_token && $oauth_token_secret &&
1462 $consumer_key && $consumer_secret) {
1463 $username = $user.'@'.$host;
1465 logger('pumpio_queue: able to post for user '.$username);
1467 $z = unserialize($x['content']);
1469 $client = new oauth_client_class;
1470 $client->oauth_version = '1.0a';
1471 $client->url_parameters = false;
1472 $client->authorization_header = true;
1473 $client->access_token = $oauth_token;
1474 $client->access_token_secret = $oauth_token_secret;
1475 $client->client_id = $consumer_key;
1476 $client->client_secret = $consumer_secret;
1478 if (pumpio_reachable($z['url']))
1479 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1484 $post_id = $user->object->id;
1485 logger('pumpio_queue: send '.$username.': success '.$post_id);
1486 if($post_id && $iscomment) {
1487 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1488 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1493 remove_queue_item($x['id']);
1495 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1497 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1500 logger('pumpio_queue: delayed');
1501 update_queue_time($x['id']);
1506 function pumpio_getreceiver(&$a, $b) {
1508 $receiver = array();
1510 if (!$b["private"]) {
1512 if(! strstr($b['postopts'],'pumpio'))
1515 $public = PConfig::get($b['uid'], "pumpio", "public");
1518 $receiver["to"][] = Array(
1519 "objectType" => "collection",
1520 "id" => "http://activityschema.org/collection/public");
1522 $cids = explode("><", $b["allow_cid"]);
1523 $gids = explode("><", $b["allow_gid"]);
1525 foreach ($cids AS $cid) {
1526 $cid = trim($cid, " <>");
1528 $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",
1531 dbesc(NETWORK_PUMPIO)
1535 $receiver["bcc"][] = Array(
1536 "displayName" => $r[0]["name"],
1537 "objectType" => "person",
1538 "preferredUsername" => $r[0]["nick"],
1539 "url" => $r[0]["url"]);
1542 foreach ($gids AS $gid) {
1543 $gid = trim($gid, " <>");
1545 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1546 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1547 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1550 dbesc(NETWORK_PUMPIO)
1553 foreach ($r AS $row)
1554 $receiver["bcc"][] = Array(
1555 "displayName" => $row["name"],
1556 "objectType" => "person",
1557 "preferredUsername" => $row["nick"],
1558 "url" => $row["url"]);
1562 if ($b["inform"] != "") {
1564 $inform = explode(",", $b["inform"]);
1566 foreach ($inform AS $cid) {
1567 if (substr($cid, 0, 4) != "cid:")
1570 $cid = str_replace("cid:", "", $cid);
1572 $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",
1575 dbesc(NETWORK_PUMPIO)
1579 $receiver["to"][] = Array(
1580 "displayName" => $r[0]["name"],
1581 "objectType" => "person",
1582 "preferredUsername" => $r[0]["nick"],
1583 "url" => $r[0]["url"]);
1591 function pumpio_fetchallcomments(&$a, $uid, $id) {
1592 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1593 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1594 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1595 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1596 $hostname = PConfig::get($uid, 'pumpio','host');
1597 $username = PConfig::get($uid, "pumpio", "user");
1599 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1601 $own_id = "https://".$hostname."/".$username;
1603 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1606 // Fetching the original post
1607 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1615 $url = $r[0]["extid"];
1617 $client = new oauth_client_class;
1618 $client->oauth_version = '1.0a';
1619 $client->authorization_header = true;
1620 $client->url_parameters = false;
1622 $client->client_id = $ckey;
1623 $client->client_secret = $csecret;
1624 $client->access_token = $otoken;
1625 $client->access_token_secret = $osecret;
1627 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1629 if (pumpio_reachable($url))
1630 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1637 if ($item->likes->totalItems != 0) {
1638 foreach ($item->likes->items AS $post) {
1639 $like = new stdClass;
1640 $like->object = new stdClass;
1641 $like->object->id = $item->id;
1642 $like->actor = new stdClass;
1643 $like->actor->displayName = $item->displayName;
1644 $like->actor->preferredUsername = $item->preferredUsername;
1645 $like->actor->url = $item->url;
1646 $like->actor->image = $item->image;
1647 $like->generator = new stdClass;
1648 $like->generator->displayName = "pumpio";
1649 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1653 if ($item->replies->totalItems == 0)
1656 foreach ($item->replies->items AS $item) {
1657 if ($item->id == $id)
1660 // Checking if the comment already exists - Two queries for speed issues
1661 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1669 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1677 $post = new stdClass;
1678 $post->verb = "post";
1679 $post->actor = $item->author;
1680 $post->published = $item->published;
1681 $post->received = $item->updated;
1682 $post->generator = new stdClass;
1683 $post->generator->displayName = "pumpio";
1684 // To-Do: Check for public post
1686 unset($item->author);
1687 unset($item->published);
1688 unset($item->updated);
1690 $post->object = $item;
1692 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1693 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1698 function pumpio_reachable($url) {
1699 $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
1700 return(intval($data['return_code']) != 0);