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 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
17 function pumpio_install() {
18 register_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
19 register_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
20 register_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
21 register_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
22 register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
23 register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
24 register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
25 register_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
28 function pumpio_uninstall() {
29 unregister_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
30 unregister_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
31 unregister_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
32 unregister_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
33 unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
34 unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
35 unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
36 unregister_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
39 function pumpio_module() {}
41 function pumpio_content(&$a) {
44 notice( t('Permission denied.') . EOL);
48 require_once("mod/settings.php");
51 if (isset($a->argv[1]))
52 switch ($a->argv[1]) {
54 $o = pumpio_connect($a);
57 $o = print_r($a->argv, true);
61 $o = pumpio_connect($a);
66 function pumpio_check_item_notification($a, &$notification_data) {
67 $hostname = get_pconfig($notification_data["uid"], 'pumpio','host');
68 $username = get_pconfig($notification_data["uid"], "pumpio", "user");
70 $notification_data["profiles"][] = "https://".$hostname."/".$username;
74 function pumpio_registerclient(&$a, $host) {
76 $url = "https://".$host."/api/client/register";
80 $application_name = get_config('pumpio', 'application_name');
82 if ($application_name == "")
83 $application_name = $a->get_hostname();
85 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
87 $params["type"] = "client_associate";
88 $params["contacts"] = $adminlist[0];
89 $params["application_type"] = "native";
90 $params["application_name"] = $application_name;
91 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
92 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
94 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
96 $ch = curl_init($url);
97 curl_setopt($ch, CURLOPT_HEADER, false);
98 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
99 curl_setopt($ch, CURLOPT_POST,1);
100 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
101 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
104 $curl_info = curl_getinfo($ch);
106 if ($curl_info["http_code"] == "200") {
107 $values = json_decode($s);
108 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
111 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
116 function pumpio_connect(&$a) {
117 // Start a session. This is necessary to hold on to a few keys the callback script will also need
120 // Define the needed keys
121 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
122 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
123 $hostname = get_pconfig(local_user(), 'pumpio','host');
125 if ((($consumer_key == "") OR ($consumer_secret == "")) AND ($hostname != "")) {
126 logger("pumpio_connect: register client");
127 $clientdata = pumpio_registerclient($a, $hostname);
128 set_pconfig(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
129 set_pconfig(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
131 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
132 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
134 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
137 if (($consumer_key == "") OR ($consumer_secret == "")) {
138 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
140 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
144 // The callback URL is the script that gets called after the user authenticates with pumpio
145 $callback_url = $a->get_baseurl()."/pumpio/connect";
147 // Let's begin. First we need a Request Token. The request token is required to send the user
148 // to pumpio's login page.
150 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
151 // Consumer Key and Consumer Secret
152 $client = new oauth_client_class;
154 $client->server = '';
155 $client->oauth_version = '1.0a';
156 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
157 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
158 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
159 $client->url_parameters = false;
160 $client->authorization_header = true;
161 $client->redirect_uri = $callback_url;
162 $client->client_id = $consumer_key;
163 $client->client_secret = $consumer_secret;
165 if (($success = $client->Initialize())) {
166 if (($success = $client->Process())) {
167 if (strlen($client->access_token)) {
168 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
169 set_pconfig(local_user(), "pumpio", "oauth_token", $client->access_token);
170 set_pconfig(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
173 $success = $client->Finalize($success);
176 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
179 logger("pumpio_connect: authenticated");
180 $o .= t("You are now authenticated to pumpio.");
181 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
183 logger("pumpio_connect: could not connect");
184 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
190 function pumpio_jot_nets(&$a,&$b) {
194 $pumpio_post = get_pconfig(local_user(),'pumpio','post');
195 if(intval($pumpio_post) == 1) {
196 $pumpio_defpost = get_pconfig(local_user(),'pumpio','post_by_default');
197 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
198 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
199 . t('Post to pumpio') . '</div>';
204 function pumpio_settings(&$a,&$s) {
209 /* Add our stylesheet to the page so we can make our settings look nice */
211 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
213 /* Get the current state of our config variables */
215 $import_enabled = get_pconfig(local_user(),'pumpio','import');
216 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
218 $enabled = get_pconfig(local_user(),'pumpio','post');
219 $checked = (($enabled) ? ' checked="checked" ' : '');
220 $css = (($enabled) ? '' : '-disabled');
222 $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default');
223 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
225 $public_enabled = get_pconfig(local_user(),'pumpio','public');
226 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
228 $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror');
229 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
231 $servername = get_pconfig(local_user(), "pumpio", "host");
232 $username = get_pconfig(local_user(), "pumpio", "user");
234 /* Add some HTML to the existing form */
236 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
237 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
239 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
240 $s .= '<span class="fakelink" 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>';
244 $s .= '<div id="pumpio-username-wrapper">';
245 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
246 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
247 $s .= '</div><div class="clear"></div>';
249 $s .= '<div id="pumpio-servername-wrapper">';
250 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
251 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
252 $s .= '</div><div class="clear"></div>';
254 if (($username != '') AND ($servername != '')) {
256 $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token");
257 $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret");
259 $s .= '<div id="pumpio-password-wrapper">';
260 if (($oauth_token == "") OR ($oauth_token_secret == "")) {
261 $s .= '<div id="pumpio-authenticate-wrapper">';
262 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
263 $s .= '</div><div class="clear"></div>';
265 $s .= '<div id="pumpio-import-wrapper">';
266 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
267 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
268 $s .= '</div><div class="clear"></div>';
270 $s .= '<div id="pumpio-enable-wrapper">';
271 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
272 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
273 $s .= '</div><div class="clear"></div>';
275 $s .= '<div id="pumpio-bydefault-wrapper">';
276 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
277 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
278 $s .= '</div><div class="clear"></div>';
280 $s .= '<div id="pumpio-public-wrapper">';
281 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
282 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
283 $s .= '</div><div class="clear"></div>';
285 $s .= '<div id="pumpio-mirror-wrapper">';
286 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
287 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
288 $s .= '</div><div class="clear"></div>';
290 $s .= '<div id="pumpio-delete-wrapper">';
291 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
292 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
293 $s .= '</div><div class="clear"></div>';
296 $s .= '</div><div class="clear"></div>';
299 /* provide a submit button */
301 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
305 function pumpio_settings_post(&$a,&$b) {
307 if(x($_POST,'pumpio-submit')) {
308 if(x($_POST,'pumpio_delete')) {
309 set_pconfig(local_user(),'pumpio','consumer_key','');
310 set_pconfig(local_user(),'pumpio','consumer_secret','');
311 set_pconfig(local_user(),'pumpio','oauth_token','');
312 set_pconfig(local_user(),'pumpio','oauth_token_secret','');
313 set_pconfig(local_user(),'pumpio','post',false);
314 set_pconfig(local_user(),'pumpio','import',false);
315 set_pconfig(local_user(),'pumpio','host','');
316 set_pconfig(local_user(),'pumpio','user','');
317 set_pconfig(local_user(),'pumpio','public',false);
318 set_pconfig(local_user(),'pumpio','mirror',false);
319 set_pconfig(local_user(),'pumpio','post_by_default',false);
320 set_pconfig(local_user(),'pumpio','lastdate', 0);
321 set_pconfig(local_user(),'pumpio','last_id', '');
323 // filtering the username if it is filled wrong
324 $user = $_POST['pumpio_user'];
325 if (strstr($user, "@")) {
326 $pos = strpos($user, "@");
328 $user = substr($user, 0, $pos);
331 // Filtering the hostname if someone is entering it with "http"
332 $host = $_POST['pumpio_host'];
334 $host = str_replace(array("https://", "http://"), array("", ""), $host);
336 set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
337 set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
338 set_pconfig(local_user(),'pumpio','host',$host);
339 set_pconfig(local_user(),'pumpio','user',$user);
340 set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
341 set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
342 set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
344 if (!$_POST['pumpio_mirror'])
345 del_pconfig(local_user(),'pumpio','lastdate');
347 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
352 function pumpio_post_local(&$a,&$b) {
354 if((! local_user()) || (local_user() != $b['uid']))
357 $pumpio_post = intval(get_pconfig(local_user(),'pumpio','post'));
359 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
361 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
367 if(strlen($b['postopts']))
368 $b['postopts'] .= ',';
370 $b['postopts'] .= 'pumpio';
376 function pumpio_send(&$a,&$b) {
378 if (!get_pconfig($b["uid"],'pumpio','import')) {
379 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
383 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
385 if($b['parent'] != $b['id']) {
386 // Looking if its a reply to a pumpio post
387 $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",
388 intval($b["parent"]),
390 dbesc(NETWORK_PUMPIO));
393 logger("pumpio_send: no pumpio post ".$b["parent"]);
402 $receiver = pumpio_getreceiver($a, $b);
404 logger("pumpio_send: receiver ".print_r($receiver, true));
406 if (!count($receiver) AND ($b['private'] OR !strstr($b['postopts'],'pumpio')))
410 if($b['verb'] == ACTIVITY_LIKE) {
412 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
414 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
418 if($b['verb'] == ACTIVITY_DISLIKE)
421 if (($b['verb'] == ACTIVITY_POST) AND ($b['created'] !== $b['edited']) AND !$b['deleted'])
422 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
424 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
425 pumpio_action($a, $b["uid"], $b["uri"], "delete");
427 if($b['deleted'] || ($b['created'] !== $b['edited']))
430 // if post comes from pump.io don't send it back
431 if($b['app'] == "pump.io")
435 // Support for native shares
436 // http://<hostname>/api/<type>/shares?id=<the-object-id>
438 $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
439 $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
440 $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
441 $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
443 $host = get_pconfig($b['uid'], "pumpio", "host");
444 $user = get_pconfig($b['uid'], "pumpio", "user");
445 $public = get_pconfig($b['uid'], "pumpio", "public");
447 if($oauth_token && $oauth_token_secret) {
449 require_once('include/bbcode.php');
451 $title = trim($b['title']);
453 $content = bbcode($b['body'], false, false, 4);
457 $params["verb"] = "post";
460 $params["object"] = array(
461 'objectType' => "note",
462 'content' => $content);
465 $params["object"]["displayName"] = $title;
467 if (count($receiver["to"]))
468 $params["to"] = $receiver["to"];
470 if (count($receiver["bto"]))
471 $params["bto"] = $receiver["bto"];
473 if (count($receiver["cc"]))
474 $params["cc"] = $receiver["cc"];
476 if (count($receiver["bcc"]))
477 $params["bcc"] = $receiver["bcc"];
480 $inReplyTo = array("id" => $orig_post["uri"],
481 "objectType" => "note");
483 if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
484 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
486 $params["object"] = array(
487 'objectType' => "comment",
488 'content' => $content,
489 'inReplyTo' => $inReplyTo);
492 $params["object"]["displayName"] = $title;
495 $client = new oauth_client_class;
496 $client->oauth_version = '1.0a';
497 $client->url_parameters = false;
498 $client->authorization_header = true;
499 $client->access_token = $oauth_token;
500 $client->access_token_secret = $oauth_token_secret;
501 $client->client_id = $consumer_key;
502 $client->client_secret = $consumer_secret;
504 $username = $user.'@'.$host;
505 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
507 if (pumpio_reachable($url))
508 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
514 if ($user->generator->displayName)
515 set_pconfig($b["uid"], "pumpio", "application_name", $user->generator->displayName);
517 $post_id = $user->object->id;
518 logger('pumpio_send '.$username.': success '.$post_id);
519 if($post_id AND $iscomment) {
520 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
521 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
527 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
529 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
531 $a->contact = $r[0]["id"];
533 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
534 require_once('include/queue_fn.php');
535 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
536 notice(t('Pump.io post failed. Queued for retry.').EOL);
542 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
544 // Don't do likes and other stuff if you don't import the timeline
545 if (!get_pconfig($uid,'pumpio','import'))
548 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
549 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
550 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
551 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
552 $hostname = get_pconfig($uid, 'pumpio','host');
553 $username = get_pconfig($uid, "pumpio", "user");
555 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
565 if ($orig_post["extid"] AND !strstr($orig_post["extid"], "/proxy/"))
566 $uri = $orig_post["extid"];
568 $uri = $orig_post["uri"];
570 if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
571 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
572 elseif (strstr($uri, "/api/comment/"))
573 $objectType = "comment";
574 elseif (strstr($uri, "/api/note/"))
575 $objectType = "note";
576 elseif (strstr($uri, "/api/image/"))
577 $objectType = "image";
579 $params["verb"] = $action;
580 $params["object"] = array('id' => $uri,
581 "objectType" => $objectType,
582 "content" => $content);
584 $client = new oauth_client_class;
585 $client->oauth_version = '1.0a';
586 $client->authorization_header = true;
587 $client->url_parameters = false;
589 $client->client_id = $ckey;
590 $client->client_secret = $csecret;
591 $client->access_token = $otoken;
592 $client->access_token_secret = $osecret;
594 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
596 if (pumpio_reachable($url))
597 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
602 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
604 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
606 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
608 $a->contact = $r[0]["id"];
610 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
611 require_once('include/queue_fn.php');
612 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
613 notice(t('Pump.io like failed. Queued for retry.').EOL);
617 function pumpio_sync(&$a) {
618 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
624 $last = get_config('pumpio','last_poll');
626 $poll_interval = intval(get_config('pumpio','poll_interval'));
628 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
631 $next = $last + ($poll_interval * 60);
633 logger('pumpio: poll intervall not reached');
637 logger('pumpio: cron_start');
639 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
642 logger('pumpio: mirroring user '.$rr['uid']);
643 pumpio_fetchtimeline($a, $rr['uid']);
647 $abandon_days = intval(get_config('system','account_abandon_days'));
648 if ($abandon_days < 1)
651 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
653 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
656 if ($abandon_days != 0) {
657 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
659 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
664 logger('pumpio: importing timeline from user '.$rr['uid']);
665 pumpio_fetchinbox($a, $rr['uid']);
667 // check for new contacts once a day
668 $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check');
669 if($last_contact_check)
670 $next_contact_check = $last_contact_check + 86400;
672 $next_contact_check = 0;
674 if($next_contact_check <= time()) {
675 pumpio_getallusers($a, $rr["uid"]);
676 set_pconfig($rr['uid'],'pumpio','contact_check',time());
681 logger('pumpio: cron_end');
683 set_config('pumpio','last_poll', time());
686 function pumpio_cron(&$a,$b) {
688 proc_run("php","addon/pumpio/pumpio_sync.php");
691 function pumpio_fetchtimeline(&$a, $uid) {
692 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
693 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
694 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
695 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
696 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
697 $hostname = get_pconfig($uid, 'pumpio','host');
698 $username = get_pconfig($uid, "pumpio", "user");
700 // get the application name for the pump.io app
701 // 1st try personal config, then system config and fallback to the
702 // hostname of the node if neither one is set.
703 $application_name = get_pconfig( $uid, 'pumpio', 'application_name');
704 if ($application_name == "")
705 $application_name = get_config('pumpio', 'application_name');
706 if ($application_name == "")
707 $application_name = $a->get_hostname();
709 $first_time = ($lastdate == "");
711 $client = new oauth_client_class;
712 $client->oauth_version = '1.0a';
713 $client->authorization_header = true;
714 $client->url_parameters = false;
716 $client->client_id = $ckey;
717 $client->client_secret = $csecret;
718 $client->access_token = $otoken;
719 $client->access_token_secret = $osecret;
721 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
723 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
725 $username = $user.'@'.$host;
727 if (pumpio_reachable($url))
728 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
733 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
737 $posts = array_reverse($user->items);
739 $initiallastdate = $lastdate;
743 foreach ($posts as $post) {
744 if ($post->published <= $initiallastdate)
747 if ($lastdate < $post->published)
748 $lastdate = $post->published;
753 $receiptians = array();
754 if (@is_array($post->cc))
755 $receiptians = array_merge($receiptians, $post->cc);
757 if (@is_array($post->to))
758 $receiptians = array_merge($receiptians, $post->to);
761 foreach ($receiptians AS $receiver)
762 if (is_string($receiver->objectType))
763 if ($receiver->id == "http://activityschema.org/collection/public")
766 if ($public AND !stristr($post->generator->displayName, $application_name)) {
767 require_once('include/html2bbcode.php');
769 $_SESSION["authenticated"] = true;
770 $_SESSION["uid"] = $uid;
773 $_REQUEST["type"] = "wall";
774 $_REQUEST["api_source"] = true;
775 $_REQUEST["profile_uid"] = $uid;
776 $_REQUEST["source"] = "pump.io";
778 if ($post->object->displayName != "")
779 $_REQUEST["title"] = html2bbcode($post->object->displayName);
781 $_REQUEST["title"] = "";
783 $_REQUEST["body"] = html2bbcode($post->object->content);
785 // To-Do: Picture has to be cached and stored locally
786 if ($post->object->fullImage->url != "") {
787 if ($post->object->fullImage->pump_io->proxyURL != "")
788 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
790 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
793 logger('pumpio: posting for user '.$uid);
795 require_once('mod/item.php');
798 logger('pumpio: posting done - user '.$uid);
804 set_pconfig($uid,'pumpio','lastdate', $lastdate);
807 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
808 // Searching for the unliked post
809 // Two queries for speed issues
810 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
811 dbesc($post->object->id),
818 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
819 dbesc($post->object->id),
831 if(link_compare($post->actor->url, $own_id)) {
832 $contactid = $self[0]['id'];
834 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
835 dbesc($post->actor->url),
840 $contactid = $r[0]['id'];
843 $contactid = $orig_post['contact-id'];
846 $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'",
847 dbesc(datetime_convert()),
848 dbesc(ACTIVITY_LIKE),
851 dbesc($orig_post['uri'])
855 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
857 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
860 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
861 require_once('include/items.php');
863 // Searching for the liked post
864 // Two queries for speed issues
865 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
866 dbesc($post->object->id),
868 dbesc(NETWORK_PUMPIO)
874 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
875 dbesc($post->object->id),
877 dbesc(NETWORK_PUMPIO)
887 if ($threadcompletion)
888 pumpio_fetchallcomments($a, $uid, $post->object->id);
892 if(link_compare($post->actor->url, $own_id)) {
893 $contactid = $self[0]['id'];
894 $post->actor->displayName = $self[0]['name'];
895 $post->actor->url = $self[0]['url'];
896 $post->actor->image->url = $self[0]['photo'];
898 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
899 dbesc($post->actor->url),
904 $contactid = $r[0]['id'];
907 $contactid = $orig_post['contact-id'];
910 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
911 dbesc(ACTIVITY_LIKE),
914 dbesc($orig_post['uri'])
918 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
923 $likedata['parent'] = $orig_post['id'];
924 $likedata['verb'] = ACTIVITY_LIKE;
925 $likedata['gravity'] = 3;
926 $likedata['uid'] = $uid;
927 $likedata['wall'] = 0;
928 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
929 $likedata['parent-uri'] = $orig_post["uri"];
930 $likedata['contact-id'] = $contactid;
931 $likedata['app'] = $post->generator->displayName;
932 $likedata['author-name'] = $post->actor->displayName;
933 $likedata['author-link'] = $post->actor->url;
934 $likedata['author-avatar'] = $post->actor->image->url;
936 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
937 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
938 $post_type = t('status');
939 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
940 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
942 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
944 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
945 '<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>';
947 $ret = item_store($likedata);
949 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
952 function pumpio_get_contact($uid, $contact, $no_insert = false) {
954 if (function_exists("update_gcontact")) {
955 update_gcontact(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
956 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
957 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
958 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
960 $cid = get_contact($contact->url, $uid);
963 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
964 dbesc(normalise_link($contact->url)));
967 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
968 dbesc(normalise_link($contact->url)),
969 dbesc($contact->displayName),
970 dbesc($contact->preferredUsername),
971 dbesc($contact->image->url));
973 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
974 dbesc($contact->displayName),
975 dbesc($contact->preferredUsername),
976 dbesc($contact->image->url),
977 dbesc(normalise_link($contact->url)));
979 if (DB_UPDATE_VERSION >= "1177")
980 q("UPDATE `unique_contacts` SET `location` = '%s', `about` = '%s' WHERE url = '%s'",
981 dbesc($contact->location->displayName),
982 dbesc($contact->summary),
983 dbesc(normalise_link($contact->url)));
991 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
992 intval($uid), dbesc($contact->url));
995 // create contact record
996 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
997 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
998 `writable`, `blocked`, `readonly`, `pending` )
999 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
1001 dbesc(datetime_convert()),
1002 dbesc($contact->url),
1003 dbesc(normalise_link($contact->url)),
1004 dbesc(str_replace("acct:", "", $contact->id)),
1006 dbesc($contact->id), // What is it for?
1007 dbesc('pump.io ' . $contact->id), // What is it for?
1008 dbesc($contact->displayName),
1009 dbesc($contact->preferredUsername),
1010 dbesc($contact->image->url),
1011 dbesc(NETWORK_PUMPIO),
1012 intval(CONTACT_IS_FRIEND),
1017 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
1018 dbesc($contact->url),
1025 $contact_id = $r[0]['id'];
1027 $g = q("select def_gid from user where uid = %d limit 1",
1031 if($g && intval($g[0]['def_gid'])) {
1032 require_once('include/group.php');
1033 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1036 if (DB_UPDATE_VERSION >= "1177")
1037 q("UPDATE `contact` SET `location` = '%s',
1040 dbesc($contact->location->displayName),
1041 dbesc($contact->summary),
1045 $contact_id = $r[0]["id"];
1047 /* if (DB_UPDATE_VERSION >= "1177")
1048 q("UPDATE `contact` SET `location` = '%s',
1051 dbesc($contact->location->displayName),
1052 dbesc($contact->summary),
1058 if (function_exists("update_contact_avatar"))
1059 update_contact_avatar($contact->image->url, $uid, $contact_id);
1061 return($contact_id);
1064 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1066 // Two queries for speed issues
1067 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1068 dbesc($post->object->id),
1073 return drop_item($r[0]["id"], $false);
1075 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1076 dbesc($post->object->id),
1081 return drop_item($r[0]["id"], $false);
1084 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1085 require_once('include/items.php');
1086 require_once('include/html2bbcode.php');
1088 if (($post->verb == "like") OR ($post->verb == "favorite"))
1089 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1091 if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
1092 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1094 if ($post->verb == "delete")
1095 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1097 if ($post->verb != "update") {
1098 // Two queries for speed issues
1099 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1100 dbesc($post->object->id),
1107 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1108 dbesc($post->object->id),
1116 // Only handle these three types
1117 if (!strstr("post|share|update", $post->verb))
1120 $receiptians = array();
1121 if (@is_array($post->cc))
1122 $receiptians = array_merge($receiptians, $post->cc);
1124 if (@is_array($post->to))
1125 $receiptians = array_merge($receiptians, $post->to);
1127 foreach ($receiptians AS $receiver)
1128 if (is_string($receiver->objectType))
1129 if ($receiver->id == "http://activityschema.org/collection/public")
1132 $postarray = array();
1133 $postarray['network'] = NETWORK_PUMPIO;
1134 $postarray['gravity'] = 0;
1135 $postarray['uid'] = $uid;
1136 $postarray['wall'] = 0;
1137 $postarray['uri'] = $post->object->id;
1138 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1140 if ($post->object->objectType != "comment") {
1141 $contact_id = pumpio_get_contact($uid, $post->actor);
1144 $contact_id = $self[0]['id'];
1146 $postarray['parent-uri'] = $post->object->id;
1149 $postarray['private'] = 1;
1150 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1153 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1155 if (link_compare($post->actor->url, $own_id)) {
1156 $contact_id = $self[0]['id'];
1157 $post->actor->displayName = $self[0]['name'];
1158 $post->actor->url = $self[0]['url'];
1159 $post->actor->image->url = $self[0]['photo'];
1160 } elseif ($contact_id == 0) {
1161 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1162 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1163 dbesc($post->actor->url),
1168 $contact_id = $r[0]['id'];
1170 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1171 dbesc($post->actor->url),
1176 $contact_id = $r[0]['id'];
1178 $contact_id = $self[0]['id'];
1182 $reply = new stdClass;
1183 $reply->verb = "note";
1184 $reply->cc = $post->cc;
1185 $reply->to = $post->to;
1186 $reply->object = new stdClass;
1187 $reply->object->objectType = $post->object->inReplyTo->objectType;
1188 $reply->object->content = $post->object->inReplyTo->content;
1189 $reply->object->id = $post->object->inReplyTo->id;
1190 $reply->actor = $post->object->inReplyTo->author;
1191 $reply->url = $post->object->inReplyTo->url;
1192 $reply->generator = new stdClass;
1193 $reply->generator->displayName = "pumpio";
1194 $reply->published = $post->object->inReplyTo->published;
1195 $reply->received = $post->object->inReplyTo->updated;
1196 $reply->url = $post->object->inReplyTo->url;
1197 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1199 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1202 if ($post->object->pump_io->proxyURL)
1203 $postarray['extid'] = $post->object->pump_io->proxyURL;
1205 $postarray['contact-id'] = $contact_id;
1206 $postarray['verb'] = ACTIVITY_POST;
1207 $postarray['owner-name'] = $post->actor->displayName;
1208 $postarray['owner-link'] = $post->actor->url;
1209 $postarray['owner-avatar'] = $post->actor->image->url;
1210 $postarray['author-name'] = $post->actor->displayName;
1211 $postarray['author-link'] = $post->actor->url;
1212 $postarray['author-avatar'] = $post->actor->image->url;
1213 $postarray['plink'] = $post->object->url;
1214 $postarray['app'] = $post->generator->displayName;
1215 $postarray['body'] = html2bbcode($post->object->content);
1216 $postarray['object'] = json_encode($post);
1218 if ($post->object->fullImage->url != "")
1219 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1221 if ($post->object->displayName != "")
1222 $postarray['title'] = $post->object->displayName;
1224 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1225 if (isset($post->updated))
1226 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1227 elseif (isset($post->received))
1228 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1230 $postarray['edited'] = $postarray['created'];
1232 if ($post->verb == "share") {
1233 if (!intval(get_config('system','wall-to-wall_share'))) {
1234 if (isset($post->object->author->displayName) AND ($post->object->author->displayName != ""))
1235 $share_author = $post->object->author->displayName;
1236 elseif (isset($post->object->author->preferredUsername) AND ($post->object->author->preferredUsername != ""))
1237 $share_author = $post->object->author->preferredUsername;
1239 $share_author = $post->object->author->url;
1241 $postarray['body'] = share_header($share_author, $post->object->author->url,
1242 $post->object->author->image->url, "",
1243 datetime_convert('UTC','UTC',$post->object->created),
1244 $post->links->self->href).
1245 $postarray['body']."[/share]";
1248 $postarray['body'] = "[share author='".$share_author.
1249 "' profile='".$post->object->author->url.
1250 "' avatar='".$post->object->author->image->url.
1251 "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1252 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1255 // Let shares look like wall-to-wall posts
1256 $postarray['author-name'] = $post->object->author->displayName;
1257 $postarray['author-link'] = $post->object->author->url;
1258 $postarray['author-avatar'] = $post->object->author->image->url;
1262 if (trim($postarray['body']) == "")
1265 $top_item = item_store($postarray);
1266 $postarray["id"] = $top_item;
1268 if (($top_item == 0) AND ($post->verb == "update")) {
1269 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1270 dbesc($postarray["title"]),
1271 dbesc($postarray["body"]),
1272 dbesc($postarray["edited"]),
1273 dbesc($postarray["uri"]),
1278 if ($post->object->objectType == "comment") {
1280 if ($threadcompletion)
1281 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1283 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1290 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1292 if (link_compare($own_id, $postarray['author-link']))
1295 if (!function_exists("check_item_notification")) {
1296 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1297 dbesc($postarray['parent-uri']),
1301 if(count($myconv)) {
1303 foreach($myconv as $conv) {
1304 // now if we find a match, it means we're in this conversation
1306 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_id))
1309 require_once('include/enotify.php');
1311 $conv_parent = $conv['parent'];
1314 'type' => NOTIFY_COMMENT,
1315 'notify_flags' => $user[0]['notify-flags'],
1316 'language' => $user[0]['language'],
1317 'to_name' => $user[0]['username'],
1318 'to_email' => $user[0]['email'],
1319 'uid' => $user[0]['uid'],
1320 'item' => $postarray,
1321 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1322 'source_name' => $postarray['author-name'],
1323 'source_link' => $postarray['author-link'],
1324 'source_photo' => $postarray['author-avatar'],
1325 'verb' => ACTIVITY_POST,
1327 'parent' => $conv_parent,
1330 // only send one notification
1340 function pumpio_fetchinbox(&$a, $uid) {
1342 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1343 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1344 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1345 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1346 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1347 $hostname = get_pconfig($uid, 'pumpio','host');
1348 $username = get_pconfig($uid, "pumpio", "user");
1350 $own_id = "https://".$hostname."/".$username;
1352 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1355 $lastitems = q("SELECT uri FROM `item` WHERE `network` = '%s' AND `uid` = %d AND
1356 `extid` != '' AND `id` = `parent`
1357 ORDER BY `commented` DESC LIMIT 10",
1358 dbesc(NETWORK_PUMPIO),
1362 $client = new oauth_client_class;
1363 $client->oauth_version = '1.0a';
1364 $client->authorization_header = true;
1365 $client->url_parameters = false;
1367 $client->client_id = $ckey;
1368 $client->client_secret = $csecret;
1369 $client->access_token = $otoken;
1370 $client->access_token_secret = $osecret;
1372 $last_id = get_pconfig($uid,'pumpio','last_id');
1374 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1377 $url .= '?since='.urlencode($last_id);
1379 if (pumpio_reachable($url))
1380 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1385 $posts = array_reverse($user->items);
1388 foreach ($posts as $post) {
1389 $last_id = $post->id;
1390 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1394 foreach ($lastitems AS $item)
1395 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1397 set_pconfig($uid,'pumpio','last_id', $last_id);
1400 function pumpio_getallusers(&$a, $uid) {
1401 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1402 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1403 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1404 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1405 $hostname = get_pconfig($uid, 'pumpio','host');
1406 $username = get_pconfig($uid, "pumpio", "user");
1408 $client = new oauth_client_class;
1409 $client->oauth_version = '1.0a';
1410 $client->authorization_header = true;
1411 $client->url_parameters = false;
1413 $client->client_id = $ckey;
1414 $client->client_secret = $csecret;
1415 $client->access_token = $otoken;
1416 $client->access_token_secret = $osecret;
1418 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1420 if (pumpio_reachable($url))
1421 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1425 if ($users->totalItems > count($users->items)) {
1426 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1428 if (pumpio_reachable($url))
1429 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1434 foreach ($users->items AS $user)
1435 pumpio_get_contact($uid, $user);
1438 function pumpio_queue_hook(&$a,&$b) {
1440 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1441 dbesc(NETWORK_PUMPIO)
1446 require_once('include/queue_fn.php');
1448 foreach($qi as $x) {
1449 if($x['network'] !== NETWORK_PUMPIO)
1452 logger('pumpio_queue: run');
1454 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
1455 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1463 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1465 $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token");
1466 $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret");
1467 $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key");
1468 $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret");
1470 $host = get_pconfig($userdata['uid'], "pumpio", "host");
1471 $user = get_pconfig($userdata['uid'], "pumpio", "user");
1475 if ($oauth_token AND $oauth_token_secret AND
1476 $consumer_key AND $consumer_secret) {
1477 $username = $user.'@'.$host;
1479 logger('pumpio_queue: able to post for user '.$username);
1481 $z = unserialize($x['content']);
1483 $client = new oauth_client_class;
1484 $client->oauth_version = '1.0a';
1485 $client->url_parameters = false;
1486 $client->authorization_header = true;
1487 $client->access_token = $oauth_token;
1488 $client->access_token_secret = $oauth_token_secret;
1489 $client->client_id = $consumer_key;
1490 $client->client_secret = $consumer_secret;
1492 if (pumpio_reachable($z['url']))
1493 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1498 $post_id = $user->object->id;
1499 logger('pumpio_queue: send '.$username.': success '.$post_id);
1500 if($post_id AND $iscomment) {
1501 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1502 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1507 remove_queue_item($x['id']);
1509 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1511 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1514 logger('pumpio_queue: delayed');
1515 update_queue_time($x['id']);
1520 function pumpio_getreceiver(&$a, $b) {
1522 $receiver = array();
1524 if (!$b["private"]) {
1526 if(! strstr($b['postopts'],'pumpio'))
1529 $public = get_pconfig($b['uid'], "pumpio", "public");
1532 $receiver["to"][] = Array(
1533 "objectType" => "collection",
1534 "id" => "http://activityschema.org/collection/public");
1536 $cids = explode("><", $b["allow_cid"]);
1537 $gids = explode("><", $b["allow_gid"]);
1539 foreach ($cids AS $cid) {
1540 $cid = trim($cid, " <>");
1542 $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",
1545 dbesc(NETWORK_PUMPIO)
1549 $receiver["bcc"][] = Array(
1550 "displayName" => $r[0]["name"],
1551 "objectType" => "person",
1552 "preferredUsername" => $r[0]["nick"],
1553 "url" => $r[0]["url"]);
1556 foreach ($gids AS $gid) {
1557 $gid = trim($gid, " <>");
1559 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1560 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1561 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1564 dbesc(NETWORK_PUMPIO)
1567 foreach ($r AS $row)
1568 $receiver["bcc"][] = Array(
1569 "displayName" => $row["name"],
1570 "objectType" => "person",
1571 "preferredUsername" => $row["nick"],
1572 "url" => $row["url"]);
1576 if ($b["inform"] != "") {
1578 $inform = explode(",", $b["inform"]);
1580 foreach ($inform AS $cid) {
1581 if (substr($cid, 0, 4) != "cid:")
1584 $cid = str_replace("cid:", "", $cid);
1586 $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",
1589 dbesc(NETWORK_PUMPIO)
1593 $receiver["to"][] = Array(
1594 "displayName" => $r[0]["name"],
1595 "objectType" => "person",
1596 "preferredUsername" => $r[0]["nick"],
1597 "url" => $r[0]["url"]);
1605 function pumpio_fetchallcomments(&$a, $uid, $id) {
1606 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1607 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1608 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1609 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1610 $hostname = get_pconfig($uid, 'pumpio','host');
1611 $username = get_pconfig($uid, "pumpio", "user");
1613 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1615 $own_id = "https://".$hostname."/".$username;
1617 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1620 // Fetching the original post
1621 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1629 $url = $r[0]["extid"];
1631 $client = new oauth_client_class;
1632 $client->oauth_version = '1.0a';
1633 $client->authorization_header = true;
1634 $client->url_parameters = false;
1636 $client->client_id = $ckey;
1637 $client->client_secret = $csecret;
1638 $client->access_token = $otoken;
1639 $client->access_token_secret = $osecret;
1641 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1643 if (pumpio_reachable($url))
1644 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1651 if ($item->likes->totalItems != 0) {
1652 foreach ($item->likes->items AS $post) {
1653 $like = new stdClass;
1654 $like->object = new stdClass;
1655 $like->object->id = $item->id;
1656 $like->actor = new stdClass;
1657 $like->actor->displayName = $item->displayName;
1658 $like->actor->preferredUsername = $item->preferredUsername;
1659 $like->actor->url = $item->url;
1660 $like->actor->image = $item->image;
1661 $like->generator = new stdClass;
1662 $like->generator->displayName = "pumpio";
1663 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1667 if ($item->replies->totalItems == 0)
1670 foreach ($item->replies->items AS $item) {
1671 if ($item->id == $id)
1674 // Checking if the comment already exists - Two queries for speed issues
1675 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1683 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1691 $post = new stdClass;
1692 $post->verb = "post";
1693 $post->actor = $item->author;
1694 $post->published = $item->published;
1695 $post->received = $item->updated;
1696 $post->generator = new stdClass;
1697 $post->generator->displayName = "pumpio";
1698 // To-Do: Check for public post
1700 unset($item->author);
1701 unset($item->published);
1702 unset($item->updated);
1704 $post->object = $item;
1706 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1707 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1712 function pumpio_reachable($url) {
1713 $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
1714 return(intval($data['return_code']) != 0);