3 * Name: pump.io Post Connector
4 * Description: Bidirectional (posting, relaying and reading) connector for pump.io.
6 * Author: Michael Vogel <http://pirati.ca/profile/heluecht>
8 require('addon/pumpio/oauth/http.php');
9 require('addon/pumpio/oauth/oauth_client.php');
10 require_once('include/enotify.php');
12 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
14 function pumpio_install() {
15 register_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
16 register_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
17 register_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
18 register_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
19 register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
20 register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
21 register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
22 register_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
25 function pumpio_uninstall() {
26 unregister_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
27 unregister_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
28 unregister_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
29 unregister_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
30 unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
31 unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
32 unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
33 unregister_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
36 function pumpio_module() {}
38 function pumpio_content(&$a) {
41 notice( t('Permission denied.') . EOL);
45 require_once("mod/settings.php");
48 if (isset($a->argv[1]))
49 switch ($a->argv[1]) {
51 $o = pumpio_connect($a);
54 $o = print_r($a->argv, true);
58 $o = pumpio_connect($a);
63 function pumpio_check_item_notification($a, &$notification_data) {
64 $hostname = get_pconfig($notification_data["uid"], 'pumpio','host');
65 $username = get_pconfig($notification_data["uid"], "pumpio", "user");
67 $notification_data["profiles"][] = "https://".$hostname."/".$username;
71 function pumpio_registerclient(&$a, $host) {
73 $url = "https://".$host."/api/client/register";
77 $application_name = get_config('pumpio', 'application_name');
79 if ($application_name == "")
80 $application_name = $a->get_hostname();
82 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
84 $params["type"] = "client_associate";
85 $params["contacts"] = $adminlist[0];
86 $params["application_type"] = "native";
87 $params["application_name"] = $application_name;
88 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
89 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
91 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
93 $ch = curl_init($url);
94 curl_setopt($ch, CURLOPT_HEADER, false);
95 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
96 curl_setopt($ch, CURLOPT_POST,1);
97 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
98 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
101 $curl_info = curl_getinfo($ch);
103 if ($curl_info["http_code"] == "200") {
104 $values = json_decode($s);
105 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
108 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
113 function pumpio_connect(&$a) {
114 // Start a session. This is necessary to hold on to a few keys the callback script will also need
117 // Define the needed keys
118 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
119 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
120 $hostname = get_pconfig(local_user(), 'pumpio','host');
122 if ((($consumer_key == "") OR ($consumer_secret == "")) AND ($hostname != "")) {
123 logger("pumpio_connect: register client");
124 $clientdata = pumpio_registerclient($a, $hostname);
125 set_pconfig(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
126 set_pconfig(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
128 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
129 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
131 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
134 if (($consumer_key == "") OR ($consumer_secret == "")) {
135 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
137 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
141 // The callback URL is the script that gets called after the user authenticates with pumpio
142 $callback_url = $a->get_baseurl()."/pumpio/connect";
144 // Let's begin. First we need a Request Token. The request token is required to send the user
145 // to pumpio's login page.
147 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
148 // Consumer Key and Consumer Secret
149 $client = new oauth_client_class;
151 $client->server = '';
152 $client->oauth_version = '1.0a';
153 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
154 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
155 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
156 $client->url_parameters = false;
157 $client->authorization_header = true;
158 $client->redirect_uri = $callback_url;
159 $client->client_id = $consumer_key;
160 $client->client_secret = $consumer_secret;
162 if (($success = $client->Initialize())) {
163 if (($success = $client->Process())) {
164 if (strlen($client->access_token)) {
165 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
166 set_pconfig(local_user(), "pumpio", "oauth_token", $client->access_token);
167 set_pconfig(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
170 $success = $client->Finalize($success);
173 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
176 logger("pumpio_connect: authenticated");
177 $o .= t("You are now authenticated to pumpio.");
178 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
180 logger("pumpio_connect: could not connect");
181 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
187 function pumpio_jot_nets(&$a,&$b) {
191 $pumpio_post = get_pconfig(local_user(),'pumpio','post');
192 if(intval($pumpio_post) == 1) {
193 $pumpio_defpost = get_pconfig(local_user(),'pumpio','post_by_default');
194 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
195 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
196 . t('Post to pumpio') . '</div>';
201 function pumpio_settings(&$a,&$s) {
206 /* Add our stylesheet to the page so we can make our settings look nice */
208 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
210 /* Get the current state of our config variables */
212 $import_enabled = get_pconfig(local_user(),'pumpio','import');
213 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
215 $enabled = get_pconfig(local_user(),'pumpio','post');
216 $checked = (($enabled) ? ' checked="checked" ' : '');
217 $css = (($enabled) ? '' : '-disabled');
219 $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default');
220 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
222 $public_enabled = get_pconfig(local_user(),'pumpio','public');
223 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
225 $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror');
226 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
228 $servername = get_pconfig(local_user(), "pumpio", "host");
229 $username = get_pconfig(local_user(), "pumpio", "user");
231 /* Add some HTML to the existing form */
233 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
234 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
236 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
237 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
238 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
241 $s .= '<div id="pumpio-username-wrapper">';
242 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
243 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
244 $s .= '</div><div class="clear"></div>';
246 $s .= '<div id="pumpio-servername-wrapper">';
247 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
248 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
249 $s .= '</div><div class="clear"></div>';
251 if (($username != '') AND ($servername != '')) {
253 $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token");
254 $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret");
256 $s .= '<div id="pumpio-password-wrapper">';
257 if (($oauth_token == "") OR ($oauth_token_secret == "")) {
258 $s .= '<div id="pumpio-authenticate-wrapper">';
259 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
260 $s .= '</div><div class="clear"></div>';
262 $s .= '<div id="pumpio-import-wrapper">';
263 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
264 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
265 $s .= '</div><div class="clear"></div>';
267 $s .= '<div id="pumpio-enable-wrapper">';
268 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
269 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
270 $s .= '</div><div class="clear"></div>';
272 $s .= '<div id="pumpio-bydefault-wrapper">';
273 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
274 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
275 $s .= '</div><div class="clear"></div>';
277 $s .= '<div id="pumpio-public-wrapper">';
278 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
279 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
280 $s .= '</div><div class="clear"></div>';
282 $s .= '<div id="pumpio-mirror-wrapper">';
283 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
284 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
285 $s .= '</div><div class="clear"></div>';
287 $s .= '<div id="pumpio-delete-wrapper">';
288 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
289 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
290 $s .= '</div><div class="clear"></div>';
293 $s .= '</div><div class="clear"></div>';
296 /* provide a submit button */
298 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
302 function pumpio_settings_post(&$a,&$b) {
304 if(x($_POST,'pumpio-submit')) {
305 if(x($_POST,'pumpio_delete')) {
306 set_pconfig(local_user(),'pumpio','consumer_key','');
307 set_pconfig(local_user(),'pumpio','consumer_secret','');
308 set_pconfig(local_user(),'pumpio','oauth_token','');
309 set_pconfig(local_user(),'pumpio','oauth_token_secret','');
310 set_pconfig(local_user(),'pumpio','post',false);
311 set_pconfig(local_user(),'pumpio','import',false);
312 set_pconfig(local_user(),'pumpio','host','');
313 set_pconfig(local_user(),'pumpio','user','');
314 set_pconfig(local_user(),'pumpio','public',false);
315 set_pconfig(local_user(),'pumpio','mirror',false);
316 set_pconfig(local_user(),'pumpio','post_by_default',false);
317 set_pconfig(local_user(),'pumpio','lastdate', 0);
318 set_pconfig(local_user(),'pumpio','last_id', '');
320 // filtering the username if it is filled wrong
321 $user = $_POST['pumpio_user'];
322 if (strstr($user, "@")) {
323 $pos = strpos($user, "@");
325 $user = substr($user, 0, $pos);
328 // Filtering the hostname if someone is entering it with "http"
329 $host = $_POST['pumpio_host'];
331 $host = str_replace(array("https://", "http://"), array("", ""), $host);
333 set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
334 set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
335 set_pconfig(local_user(),'pumpio','host',$host);
336 set_pconfig(local_user(),'pumpio','user',$user);
337 set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
338 set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
339 set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
341 if (!$_POST['pumpio_mirror'])
342 del_pconfig(local_user(),'pumpio','lastdate');
344 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
349 function pumpio_post_local(&$a,&$b) {
351 if((! local_user()) || (local_user() != $b['uid']))
354 $pumpio_post = intval(get_pconfig(local_user(),'pumpio','post'));
356 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
358 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
364 if(strlen($b['postopts']))
365 $b['postopts'] .= ',';
367 $b['postopts'] .= 'pumpio';
373 function pumpio_send(&$a,&$b) {
375 if (!get_pconfig($b["uid"],'pumpio','import')) {
376 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
380 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
382 if($b['parent'] != $b['id']) {
383 // Looking if its a reply to a pumpio post
384 $r = q("SELECT item.* FROM item, contact WHERE item.id = %d AND item.uid = %d AND contact.id = `contact-id` AND contact.network='%s'LIMIT 1",
385 intval($b["parent"]),
387 dbesc(NETWORK_PUMPIO));
390 logger("pumpio_send: no pumpio post ".$b["parent"]);
399 $receiver = pumpio_getreceiver($a, $b);
401 logger("pumpio_send: receiver ".print_r($receiver, true));
403 if (!count($receiver) AND ($b['private'] OR !strstr($b['postopts'],'pumpio')))
407 if($b['verb'] == ACTIVITY_LIKE) {
409 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
411 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
415 if($b['verb'] == ACTIVITY_DISLIKE)
418 if (($b['verb'] == ACTIVITY_POST) AND ($b['created'] !== $b['edited']) AND !$b['deleted'])
419 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
421 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
422 pumpio_action($a, $b["uid"], $b["uri"], "delete");
424 if($b['deleted'] || ($b['created'] !== $b['edited']))
427 // if post comes from pump.io don't send it back
428 if($b['app'] == "pump.io")
432 // Support for native shares
433 // http://<hostname>/api/<type>/shares?id=<the-object-id>
435 $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
436 $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
437 $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
438 $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
440 $host = get_pconfig($b['uid'], "pumpio", "host");
441 $user = get_pconfig($b['uid'], "pumpio", "user");
442 $public = get_pconfig($b['uid'], "pumpio", "public");
444 if($oauth_token && $oauth_token_secret) {
446 require_once('include/bbcode.php');
448 $title = trim($b['title']);
450 $content = bbcode($b['body'], false, false, 4);
452 // Enhance the way, videos are displayed
453 $content = preg_replace('/<a href="(https?:\/\/www.youtube.com\/.*?)".*?>(.*?)<\/a>/ism',"\n[url]$1[/url]\n",$content);
454 $content = preg_replace('/<a href="(https?:\/\/youtu.be\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
455 $content = preg_replace('/<a href="(https?:\/\/vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
456 $content = preg_replace('/<a href="(https?:\/\/player.vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
458 $URLSearchString = "^\[\]";
459 $content = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$content);
463 $params["verb"] = "post";
466 $params["object"] = array(
467 'objectType' => "note",
468 'content' => $content);
471 $params["object"]["displayName"] = $title;
473 if (count($receiver["to"]))
474 $params["to"] = $receiver["to"];
476 if (count($receiver["bto"]))
477 $params["bto"] = $receiver["bto"];
479 if (count($receiver["cc"]))
480 $params["cc"] = $receiver["cc"];
482 if (count($receiver["bcc"]))
483 $params["bcc"] = $receiver["bcc"];
486 $inReplyTo = array("id" => $orig_post["uri"],
487 "objectType" => "note");
489 if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
490 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
492 $params["object"] = array(
493 'objectType' => "comment",
494 'content' => $content,
495 'inReplyTo' => $inReplyTo);
498 $params["object"]["displayName"] = $title;
501 $client = new oauth_client_class;
502 $client->oauth_version = '1.0a';
503 $client->url_parameters = false;
504 $client->authorization_header = true;
505 $client->access_token = $oauth_token;
506 $client->access_token_secret = $oauth_token_secret;
507 $client->client_id = $consumer_key;
508 $client->client_secret = $consumer_secret;
510 $username = $user.'@'.$host;
511 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
513 if (pumpio_reachable($url))
514 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
520 if ($user->generator->displayName)
521 set_pconfig($b["uid"], "pumpio", "application_name", $user->generator->displayName);
523 $post_id = $user->object->id;
524 logger('pumpio_send '.$username.': success '.$post_id);
525 if($post_id AND $iscomment) {
526 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
527 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
533 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
535 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
537 $a->contact = $r[0]["id"];
539 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
540 require_once('include/queue_fn.php');
541 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
542 notice(t('Pump.io post failed. Queued for retry.').EOL);
548 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
550 // Don't do likes and other stuff if you don't import the timeline
551 if (!get_pconfig($uid,'pumpio','import'))
554 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
555 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
556 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
557 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
558 $hostname = get_pconfig($uid, 'pumpio','host');
559 $username = get_pconfig($uid, "pumpio", "user");
561 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
571 if ($orig_post["extid"] AND !strstr($orig_post["extid"], "/proxy/"))
572 $uri = $orig_post["extid"];
574 $uri = $orig_post["uri"];
576 if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
577 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
578 elseif (strstr($uri, "/api/comment/"))
579 $objectType = "comment";
580 elseif (strstr($uri, "/api/note/"))
581 $objectType = "note";
582 elseif (strstr($uri, "/api/image/"))
583 $objectType = "image";
585 $params["verb"] = $action;
586 $params["object"] = array('id' => $uri,
587 "objectType" => $objectType,
588 "content" => $content);
590 $client = new oauth_client_class;
591 $client->oauth_version = '1.0a';
592 $client->authorization_header = true;
593 $client->url_parameters = false;
595 $client->client_id = $ckey;
596 $client->client_secret = $csecret;
597 $client->access_token = $otoken;
598 $client->access_token_secret = $osecret;
600 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
602 if (pumpio_reachable($url))
603 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
608 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
610 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
612 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
614 $a->contact = $r[0]["id"];
616 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
617 require_once('include/queue_fn.php');
618 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
619 notice(t('Pump.io like failed. Queued for retry.').EOL);
623 function pumpio_sync(&$a) {
624 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
630 $last = get_config('pumpio','last_poll');
632 $poll_interval = intval(get_config('pumpio','poll_interval'));
634 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
637 $next = $last + ($poll_interval * 60);
639 logger('pumpio: poll intervall not reached');
643 logger('pumpio: cron_start');
645 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
648 logger('pumpio: mirroring user '.$rr['uid']);
649 pumpio_fetchtimeline($a, $rr['uid']);
653 $abandon_days = intval(get_config('system','account_abandon_days'));
654 if ($abandon_days < 1)
657 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
659 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
662 if ($abandon_days != 0) {
663 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
665 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
670 logger('pumpio: importing timeline from user '.$rr['uid']);
671 pumpio_fetchinbox($a, $rr['uid']);
673 // check for new contacts once a day
674 $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check');
675 if($last_contact_check)
676 $next_contact_check = $last_contact_check + 86400;
678 $next_contact_check = 0;
680 if($next_contact_check <= time()) {
681 pumpio_getallusers($a, $rr["uid"]);
682 set_pconfig($rr['uid'],'pumpio','contact_check',time());
687 logger('pumpio: cron_end');
689 set_config('pumpio','last_poll', time());
692 function pumpio_cron(&$a,$b) {
694 proc_run("php","addon/pumpio/pumpio_sync.php");
697 function pumpio_fetchtimeline(&$a, $uid) {
698 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
699 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
700 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
701 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
702 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
703 $hostname = get_pconfig($uid, 'pumpio','host');
704 $username = get_pconfig($uid, "pumpio", "user");
706 // get the application name for the pump.io app
707 // 1st try personal config, then system config and fallback to the
708 // hostname of the node if neither one is set.
709 $application_name = get_pconfig( $uid, 'pumpio', 'application_name');
710 if ($application_name == "")
711 $application_name = get_config('pumpio', 'application_name');
712 if ($application_name == "")
713 $application_name = $a->get_hostname();
715 $first_time = ($lastdate == "");
717 $client = new oauth_client_class;
718 $client->oauth_version = '1.0a';
719 $client->authorization_header = true;
720 $client->url_parameters = false;
722 $client->client_id = $ckey;
723 $client->client_secret = $csecret;
724 $client->access_token = $otoken;
725 $client->access_token_secret = $osecret;
727 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
729 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
731 $username = $user.'@'.$host;
733 if (pumpio_reachable($url))
734 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
739 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
743 $posts = array_reverse($user->items);
745 $initiallastdate = $lastdate;
749 foreach ($posts as $post) {
750 if ($post->published <= $initiallastdate)
753 if ($lastdate < $post->published)
754 $lastdate = $post->published;
759 $receiptians = array();
760 if (@is_array($post->cc))
761 $receiptians = array_merge($receiptians, $post->cc);
763 if (@is_array($post->to))
764 $receiptians = array_merge($receiptians, $post->to);
767 foreach ($receiptians AS $receiver)
768 if (is_string($receiver->objectType))
769 if ($receiver->id == "http://activityschema.org/collection/public")
772 if ($public AND !stristr($post->generator->displayName, $application_name)) {
773 require_once('include/html2bbcode.php');
775 $_SESSION["authenticated"] = true;
776 $_SESSION["uid"] = $uid;
779 $_REQUEST["type"] = "wall";
780 $_REQUEST["api_source"] = true;
781 $_REQUEST["profile_uid"] = $uid;
782 $_REQUEST["source"] = "pump.io";
784 if ($post->object->displayName != "")
785 $_REQUEST["title"] = html2bbcode($post->object->displayName);
787 $_REQUEST["title"] = "";
789 $_REQUEST["body"] = html2bbcode($post->object->content);
791 // To-Do: Picture has to be cached and stored locally
792 if ($post->object->fullImage->url != "") {
793 if ($post->object->fullImage->pump_io->proxyURL != "")
794 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
796 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
799 logger('pumpio: posting for user '.$uid);
801 require_once('mod/item.php');
804 logger('pumpio: posting done - user '.$uid);
810 set_pconfig($uid,'pumpio','lastdate', $lastdate);
813 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
814 // Searching for the unliked post
815 // Two queries for speed issues
816 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
817 dbesc($post->object->id),
824 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
825 dbesc($post->object->id),
837 if(link_compare($post->actor->url, $own_id)) {
838 $contactid = $self[0]['id'];
840 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
841 dbesc($post->actor->url),
846 $contactid = $r[0]['id'];
849 $contactid = $orig_post['contact-id'];
852 $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'",
853 dbesc(datetime_convert()),
854 dbesc(ACTIVITY_LIKE),
857 dbesc($orig_post['uri'])
861 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
863 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
866 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
867 require_once('include/items.php');
869 // Searching for the liked post
870 // Two queries for speed issues
871 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
872 dbesc($post->object->id),
874 dbesc(NETWORK_PUMPIO)
880 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
881 dbesc($post->object->id),
883 dbesc(NETWORK_PUMPIO)
893 if ($threadcompletion)
894 pumpio_fetchallcomments($a, $uid, $post->object->id);
898 if(link_compare($post->actor->url, $own_id)) {
899 $contactid = $self[0]['id'];
900 $post->actor->displayName = $self[0]['name'];
901 $post->actor->url = $self[0]['url'];
902 $post->actor->image->url = $self[0]['photo'];
904 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
905 dbesc($post->actor->url),
910 $contactid = $r[0]['id'];
913 $contactid = $orig_post['contact-id'];
916 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
917 dbesc(ACTIVITY_LIKE),
920 dbesc($orig_post['uri'])
924 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
929 $likedata['parent'] = $orig_post['id'];
930 $likedata['verb'] = ACTIVITY_LIKE;
931 $likedata['gravity'] = 3;
932 $likedata['uid'] = $uid;
933 $likedata['wall'] = 0;
934 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
935 $likedata['parent-uri'] = $orig_post["uri"];
936 $likedata['contact-id'] = $contactid;
937 $likedata['app'] = $post->generator->displayName;
938 $likedata['author-name'] = $post->actor->displayName;
939 $likedata['author-link'] = $post->actor->url;
940 $likedata['author-avatar'] = $post->actor->image->url;
942 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
943 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
944 $post_type = t('status');
945 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
946 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
948 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
950 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
951 '<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>';
953 $ret = item_store($likedata);
955 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
958 function pumpio_get_contact($uid, $contact) {
960 if (function_exists("update_gcontact"))
961 update_gcontact(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
962 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
963 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
964 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
967 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
968 dbesc(normalise_link($contact->url)));
971 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
972 dbesc(normalise_link($contact->url)),
973 dbesc($contact->displayName),
974 dbesc($contact->preferredUsername),
975 dbesc($contact->image->url));
977 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
978 dbesc($contact->displayName),
979 dbesc($contact->preferredUsername),
980 dbesc($contact->image->url),
981 dbesc(normalise_link($contact->url)));
983 if (DB_UPDATE_VERSION >= "1177")
984 q("UPDATE `unique_contacts` SET `location` = '%s', `about` = '%s' WHERE url = '%s'",
985 dbesc($contact->location->displayName),
986 dbesc($contact->summary),
987 dbesc(normalise_link($contact->url)));
990 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
991 intval($uid), dbesc($contact->url));
994 // create contact record
995 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
996 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
997 `writable`, `blocked`, `readonly`, `pending` )
998 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
1000 dbesc(datetime_convert()),
1001 dbesc($contact->url),
1002 dbesc(normalise_link($contact->url)),
1003 dbesc(str_replace("acct:", "", $contact->id)),
1005 dbesc($contact->id), // What is it for?
1006 dbesc('pump.io ' . $contact->id), // What is it for?
1007 dbesc($contact->displayName),
1008 dbesc($contact->preferredUsername),
1009 dbesc($contact->image->url),
1010 dbesc(NETWORK_PUMPIO),
1011 intval(CONTACT_IS_FRIEND),
1016 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
1017 dbesc($contact->url),
1024 $contact_id = $r[0]['id'];
1026 $g = q("select def_gid from user where uid = %d limit 1",
1030 if($g && intval($g[0]['def_gid'])) {
1031 require_once('include/group.php');
1032 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1035 require_once("Photo.php");
1037 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
1039 q("UPDATE `contact` SET `photo` = '%s',
1044 `avatar-date` = '%s'
1050 dbesc(datetime_convert()),
1051 dbesc(datetime_convert()),
1052 dbesc(datetime_convert()),
1056 if (DB_UPDATE_VERSION >= "1177")
1057 q("UPDATE `contact` SET `location` = '%s',
1060 dbesc($contact->location->displayName),
1061 dbesc($contact->summary),
1065 // update profile photos once every two weeks as we have no notification of when they change.
1066 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
1067 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1069 // check that we have all the photos, this has been known to fail on occasion
1071 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1072 require_once("Photo.php");
1074 $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
1076 q("UPDATE `contact` SET `photo` = '%s',
1081 `avatar-date` = '%s',
1089 dbesc(datetime_convert()),
1090 dbesc(datetime_convert()),
1091 dbesc(datetime_convert()),
1092 dbesc($contact->displayName),
1093 dbesc($contact->preferredUsername),
1097 if (DB_UPDATE_VERSION >= "1177")
1098 q("UPDATE `contact` SET `location` = '%s',
1101 dbesc($contact->location->displayName),
1102 dbesc($contact->summary),
1109 return($r[0]["id"]);
1112 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1114 // Two queries for speed issues
1115 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1116 dbesc($post->object->id),
1121 return drop_item($r[0]["id"], $false);
1123 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1124 dbesc($post->object->id),
1129 return drop_item($r[0]["id"], $false);
1132 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1133 require_once('include/items.php');
1134 require_once('include/html2bbcode.php');
1136 if (($post->verb == "like") OR ($post->verb == "favorite"))
1137 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1139 if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
1140 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1142 if ($post->verb == "delete")
1143 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1145 if ($post->verb != "update") {
1146 // Two queries for speed issues
1147 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1148 dbesc($post->object->id),
1155 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1156 dbesc($post->object->id),
1164 // Only handle these three types
1165 if (!strstr("post|share|update", $post->verb))
1168 $receiptians = array();
1169 if (@is_array($post->cc))
1170 $receiptians = array_merge($receiptians, $post->cc);
1172 if (@is_array($post->to))
1173 $receiptians = array_merge($receiptians, $post->to);
1175 foreach ($receiptians AS $receiver)
1176 if (is_string($receiver->objectType))
1177 if ($receiver->id == "http://activityschema.org/collection/public")
1180 $postarray = array();
1181 $postarray['network'] = NETWORK_PUMPIO;
1182 $postarray['gravity'] = 0;
1183 $postarray['uid'] = $uid;
1184 $postarray['wall'] = 0;
1185 $postarray['uri'] = $post->object->id;
1186 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1188 if ($post->object->objectType != "comment") {
1189 $contact_id = pumpio_get_contact($uid, $post->actor);
1192 $contact_id = $self[0]['id'];
1194 $postarray['parent-uri'] = $post->object->id;
1197 $postarray['private'] = 1;
1198 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1203 if(link_compare($post->actor->url, $own_id)) {
1204 $contact_id = $self[0]['id'];
1205 $post->actor->displayName = $self[0]['name'];
1206 $post->actor->url = $self[0]['url'];
1207 $post->actor->image->url = $self[0]['photo'];
1209 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1210 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1211 dbesc($post->actor->url),
1216 $contact_id = $r[0]['id'];
1218 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1219 dbesc($post->actor->url),
1224 $contact_id = $r[0]['id'];
1226 $contact_id = $self[0]['id'];
1230 $reply = new stdClass;
1231 $reply->verb = "note";
1232 $reply->cc = $post->cc;
1233 $reply->to = $post->to;
1234 $reply->object = new stdClass;
1235 $reply->object->objectType = $post->object->inReplyTo->objectType;
1236 $reply->object->content = $post->object->inReplyTo->content;
1237 $reply->object->id = $post->object->inReplyTo->id;
1238 $reply->actor = $post->object->inReplyTo->author;
1239 $reply->url = $post->object->inReplyTo->url;
1240 $reply->generator = new stdClass;
1241 $reply->generator->displayName = "pumpio";
1242 $reply->published = $post->object->inReplyTo->published;
1243 $reply->received = $post->object->inReplyTo->updated;
1244 $reply->url = $post->object->inReplyTo->url;
1245 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1247 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1250 if ($post->object->pump_io->proxyURL)
1251 $postarray['extid'] = $post->object->pump_io->proxyURL;
1253 $postarray['contact-id'] = $contact_id;
1254 $postarray['verb'] = ACTIVITY_POST;
1255 $postarray['owner-name'] = $post->actor->displayName;
1256 $postarray['owner-link'] = $post->actor->url;
1257 $postarray['owner-avatar'] = $post->actor->image->url;
1258 $postarray['author-name'] = $post->actor->displayName;
1259 $postarray['author-link'] = $post->actor->url;
1260 $postarray['author-avatar'] = $post->actor->image->url;
1261 $postarray['plink'] = $post->object->url;
1262 $postarray['app'] = $post->generator->displayName;
1263 $postarray['body'] = html2bbcode($post->object->content);
1265 if ($post->object->fullImage->url != "")
1266 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1268 if ($post->object->displayName != "")
1269 $postarray['title'] = $post->object->displayName;
1271 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1272 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1274 if ($post->verb == "share") {
1275 if (!intval(get_config('system','wall-to-wall_share'))) {
1276 $postarray['body'] = "[share author='".$post->object->author->displayName.
1277 "' profile='".$post->object->author->url.
1278 "' avatar='".$post->object->author->image->url.
1279 "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1280 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1282 // Let shares look like wall-to-wall posts
1283 $postarray['author-name'] = $post->object->author->displayName;
1284 $postarray['author-link'] = $post->object->author->url;
1285 $postarray['author-avatar'] = $post->object->author->image->url;
1289 if (trim($postarray['body']) == "")
1292 $top_item = item_store($postarray);
1293 $postarray["id"] = $top_item;
1295 if (($top_item == 0) AND ($post->verb == "update")) {
1296 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1297 dbesc($postarray["title"]),
1298 dbesc($postarray["body"]),
1299 dbesc($postarray["edited"]),
1300 dbesc($postarray["uri"]),
1305 if ($post->object->objectType == "comment") {
1307 if ($threadcompletion)
1308 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1310 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1317 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1319 if (link_compare($own_id, $postarray['author-link']))
1322 if (!function_exists("check_item_notification")) {
1323 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1324 dbesc($postarray['parent-uri']),
1328 if(count($myconv)) {
1330 foreach($myconv as $conv) {
1331 // now if we find a match, it means we're in this conversation
1333 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_id))
1336 require_once('include/enotify.php');
1338 $conv_parent = $conv['parent'];
1341 'type' => NOTIFY_COMMENT,
1342 'notify_flags' => $user[0]['notify-flags'],
1343 'language' => $user[0]['language'],
1344 'to_name' => $user[0]['username'],
1345 'to_email' => $user[0]['email'],
1346 'uid' => $user[0]['uid'],
1347 'item' => $postarray,
1348 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1349 'source_name' => $postarray['author-name'],
1350 'source_link' => $postarray['author-link'],
1351 'source_photo' => $postarray['author-avatar'],
1352 'verb' => ACTIVITY_POST,
1354 'parent' => $conv_parent,
1357 // only send one notification
1367 function pumpio_fetchinbox(&$a, $uid) {
1369 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1370 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1371 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1372 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1373 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1374 $hostname = get_pconfig($uid, 'pumpio','host');
1375 $username = get_pconfig($uid, "pumpio", "user");
1377 $own_id = "https://".$hostname."/".$username;
1379 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1382 $lastitems = q("SELECT uri FROM `item` WHERE `network` = '%s' AND `uid` = %d AND
1383 `extid` != '' AND `id` = `parent`
1384 ORDER BY `commented` DESC LIMIT 10",
1385 dbesc(NETWORK_PUMPIO),
1389 $client = new oauth_client_class;
1390 $client->oauth_version = '1.0a';
1391 $client->authorization_header = true;
1392 $client->url_parameters = false;
1394 $client->client_id = $ckey;
1395 $client->client_secret = $csecret;
1396 $client->access_token = $otoken;
1397 $client->access_token_secret = $osecret;
1399 $last_id = get_pconfig($uid,'pumpio','last_id');
1401 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1404 $url .= '?since='.urlencode($last_id);
1406 if (pumpio_reachable($url))
1407 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1412 $posts = array_reverse($user->items);
1415 foreach ($posts as $post) {
1416 $last_id = $post->id;
1417 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1421 foreach ($lastitems AS $item)
1422 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1424 set_pconfig($uid,'pumpio','last_id', $last_id);
1427 function pumpio_getallusers(&$a, $uid) {
1428 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1429 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1430 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1431 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1432 $hostname = get_pconfig($uid, 'pumpio','host');
1433 $username = get_pconfig($uid, "pumpio", "user");
1435 $client = new oauth_client_class;
1436 $client->oauth_version = '1.0a';
1437 $client->authorization_header = true;
1438 $client->url_parameters = false;
1440 $client->client_id = $ckey;
1441 $client->client_secret = $csecret;
1442 $client->access_token = $otoken;
1443 $client->access_token_secret = $osecret;
1445 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1447 if (pumpio_reachable($url))
1448 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1452 if ($users->totalItems > count($users->items)) {
1453 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1455 if (pumpio_reachable($url))
1456 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1461 foreach ($users->items AS $user)
1462 pumpio_get_contact($uid, $user);
1465 function pumpio_queue_hook(&$a,&$b) {
1467 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1468 dbesc(NETWORK_PUMPIO)
1473 require_once('include/queue_fn.php');
1475 foreach($qi as $x) {
1476 if($x['network'] !== NETWORK_PUMPIO)
1479 logger('pumpio_queue: run');
1481 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
1482 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1490 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1492 $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token");
1493 $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret");
1494 $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key");
1495 $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret");
1497 $host = get_pconfig($userdata['uid'], "pumpio", "host");
1498 $user = get_pconfig($userdata['uid'], "pumpio", "user");
1502 if ($oauth_token AND $oauth_token_secret AND
1503 $consumer_key AND $consumer_secret) {
1504 $username = $user.'@'.$host;
1506 logger('pumpio_queue: able to post for user '.$username);
1508 $z = unserialize($x['content']);
1510 $client = new oauth_client_class;
1511 $client->oauth_version = '1.0a';
1512 $client->url_parameters = false;
1513 $client->authorization_header = true;
1514 $client->access_token = $oauth_token;
1515 $client->access_token_secret = $oauth_token_secret;
1516 $client->client_id = $consumer_key;
1517 $client->client_secret = $consumer_secret;
1519 if (pumpio_reachable($z['url']))
1520 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1525 $post_id = $user->object->id;
1526 logger('pumpio_queue: send '.$username.': success '.$post_id);
1527 if($post_id AND $iscomment) {
1528 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1529 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1534 remove_queue_item($x['id']);
1536 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1538 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1541 logger('pumpio_queue: delayed');
1542 update_queue_time($x['id']);
1547 function pumpio_getreceiver(&$a, $b) {
1549 $receiver = array();
1551 if (!$b["private"]) {
1553 if(! strstr($b['postopts'],'pumpio'))
1556 $public = get_pconfig($b['uid'], "pumpio", "public");
1559 $receiver["to"][] = Array(
1560 "objectType" => "collection",
1561 "id" => "http://activityschema.org/collection/public");
1563 $cids = explode("><", $b["allow_cid"]);
1564 $gids = explode("><", $b["allow_gid"]);
1566 foreach ($cids AS $cid) {
1567 $cid = trim($cid, " <>");
1569 $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",
1572 dbesc(NETWORK_PUMPIO)
1576 $receiver["bcc"][] = Array(
1577 "displayName" => $r[0]["name"],
1578 "objectType" => "person",
1579 "preferredUsername" => $r[0]["nick"],
1580 "url" => $r[0]["url"]);
1583 foreach ($gids AS $gid) {
1584 $gid = trim($gid, " <>");
1586 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1587 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1588 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1591 dbesc(NETWORK_PUMPIO)
1594 foreach ($r AS $row)
1595 $receiver["bcc"][] = Array(
1596 "displayName" => $row["name"],
1597 "objectType" => "person",
1598 "preferredUsername" => $row["nick"],
1599 "url" => $row["url"]);
1603 if ($b["inform"] != "") {
1605 $inform = explode(",", $b["inform"]);
1607 foreach ($inform AS $cid) {
1608 if (substr($cid, 0, 4) != "cid:")
1611 $cid = str_replace("cid:", "", $cid);
1613 $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",
1616 dbesc(NETWORK_PUMPIO)
1620 $receiver["to"][] = Array(
1621 "displayName" => $r[0]["name"],
1622 "objectType" => "person",
1623 "preferredUsername" => $r[0]["nick"],
1624 "url" => $r[0]["url"]);
1632 function pumpio_fetchallcomments(&$a, $uid, $id) {
1633 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1634 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1635 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1636 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1637 $hostname = get_pconfig($uid, 'pumpio','host');
1638 $username = get_pconfig($uid, "pumpio", "user");
1640 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1642 $own_id = "https://".$hostname."/".$username;
1644 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1647 // Fetching the original post
1648 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1656 $url = $r[0]["extid"];
1658 $client = new oauth_client_class;
1659 $client->oauth_version = '1.0a';
1660 $client->authorization_header = true;
1661 $client->url_parameters = false;
1663 $client->client_id = $ckey;
1664 $client->client_secret = $csecret;
1665 $client->access_token = $otoken;
1666 $client->access_token_secret = $osecret;
1668 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1670 if (pumpio_reachable($url))
1671 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1678 if ($item->likes->totalItems != 0) {
1679 foreach ($item->likes->items AS $post) {
1680 $like = new stdClass;
1681 $like->object = new stdClass;
1682 $like->object->id = $item->id;
1683 $like->actor = new stdClass;
1684 $like->actor->displayName = $item->displayName;
1685 $like->actor->preferredUsername = $item->preferredUsername;
1686 $like->actor->url = $item->url;
1687 $like->actor->image = $item->image;
1688 $like->generator = new stdClass;
1689 $like->generator->displayName = "pumpio";
1690 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1694 if ($item->replies->totalItems == 0)
1697 foreach ($item->replies->items AS $item) {
1698 if ($item->id == $id)
1701 // Checking if the comment already exists - Two queries for speed issues
1702 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1710 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1718 $post = new stdClass;
1719 $post->verb = "post";
1720 $post->actor = $item->author;
1721 $post->published = $item->published;
1722 $post->received = $item->updated;
1723 $post->generator = new stdClass;
1724 $post->generator->displayName = "pumpio";
1725 // To-Do: Check for public post
1727 unset($item->author);
1728 unset($item->published);
1729 unset($item->updated);
1731 $post->object = $item;
1733 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1734 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1739 function pumpio_reachable($url) {
1740 $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
1741 return(intval($data['return_code']) != 0);