3 * Name: pump.io Post Connector
4 * Description: Post to 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');
11 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
13 function pumpio_install() {
14 register_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
15 register_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
16 register_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
17 register_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
18 register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
19 register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
20 register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
23 function pumpio_uninstall() {
24 unregister_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
25 unregister_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
26 unregister_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
27 unregister_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
28 unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
29 unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
30 unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
33 function pumpio_module() {}
35 function pumpio_content(&$a) {
38 notice( t('Permission denied.') . EOL);
42 if (isset($a->argv[1]))
43 switch ($a->argv[1]) {
45 $o = pumpio_connect($a);
48 $o = print_r($a->argv, true);
52 $o = pumpio_connect($a);
57 function pumpio_registerclient($a, $host) {
59 $url = "https://".$host."/api/client/register";
63 $application_name = get_config('pumpio', 'application_name');
65 if ($application_name == "")
66 $application_name = $a->get_hostname();
68 $params["type"] = "client_associate";
69 $params["contacts"] = $a->config['admin_email'];
70 $params["application_type"] = "native";
71 $params["application_name"] = $application_name;
72 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
73 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
75 $ch = curl_init($url);
76 curl_setopt($ch, CURLOPT_HEADER, false);
77 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
78 curl_setopt($ch, CURLOPT_POST,1);
79 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
80 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
83 $curl_info = curl_getinfo($ch);
85 if ($curl_info["http_code"] == "200") {
86 $values = json_decode($s);
92 function pumpio_connect($a) {
93 // Start a session. This is necessary to hold on to a few keys the callback script will also need
96 // Define the needed keys
97 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
98 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
99 $hostname = get_pconfig(local_user(), 'pumpio','host');
101 if ((($consumer_key == "") OR ($consumer_secret == "")) AND ($hostname != "")) {
102 $clientdata = pumpio_registerclient($a, $hostname);
103 set_pconfig(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
104 set_pconfig(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
106 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
107 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
110 if (($consumer_key == "") OR ($consumer_secret == ""))
113 // The callback URL is the script that gets called after the user authenticates with pumpio
114 $callback_url = $a->get_baseurl()."/pumpio/connect";
116 // Let's begin. First we need a Request Token. The request token is required to send the user
117 // to pumpio's login page.
119 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
120 // Consumer Key and Consumer Secret
121 $client = new oauth_client_class;
123 $client->server = '';
124 $client->oauth_version = '1.0a';
125 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
126 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
127 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
128 $client->url_parameters = false;
129 $client->authorization_header = true;
130 $client->redirect_uri = $callback_url;
131 $client->client_id = $consumer_key;
132 $client->client_secret = $consumer_secret;
134 if (($success = $client->Initialize())) {
135 if (($success = $client->Process())) {
136 if (strlen($client->access_token)) {
137 set_pconfig(local_user(), "pumpio", "oauth_token", $client->access_token);
138 set_pconfig(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
141 $success = $client->Finalize($success);
144 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
147 $o .= t("You are now authenticated to pumpio.");
148 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
154 function pumpio_jot_nets(&$a,&$b) {
158 $pumpio_post = get_pconfig(local_user(),'pumpio','post');
159 if(intval($pumpio_post) == 1) {
160 $pumpio_defpost = get_pconfig(local_user(),'pumpio','post_by_default');
161 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
162 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
163 . t('Post to pumpio') . '</div>';
168 function pumpio_settings(&$a,&$s) {
173 /* Add our stylesheet to the page so we can make our settings look nice */
175 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
177 /* Get the current state of our config variables */
179 $import_enabled = get_pconfig(local_user(),'pumpio','import');
180 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
182 $enabled = get_pconfig(local_user(),'pumpio','post');
183 $checked = (($enabled) ? ' checked="checked" ' : '');
185 $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default');
186 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
188 $public_enabled = get_pconfig(local_user(),'pumpio','public');
189 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
191 $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror');
192 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
194 $servername = get_pconfig(local_user(), "pumpio", "host");
195 $username = get_pconfig(local_user(), "pumpio", "user");
197 /* Add some HTML to the existing form */
199 $s .= '<div class="settings-block">';
200 $s .= '<h3>' . t('Pump.io Post Settings') . '</h3>';
202 $s .= '<div id="pumpio-username-wrapper">';
203 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
204 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
205 $s .= '</div><div class="clear"></div>';
207 $s .= '<div id="pumpio-servername-wrapper">';
208 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
209 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
210 $s .= '</div><div class="clear"></div>';
212 if (($username != '') AND ($servername != '')) {
214 $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token");
215 $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret");
217 $s .= '<div id="pumpio-password-wrapper">';
218 if (($oauth_token == "") OR ($oauth_token_secret == "")) {
219 $s .= '<div id="pumpio-authenticate-wrapper">';
220 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
221 $s .= '</div><div class="clear"></div>';
223 //$s .= t("You are not authenticated to pumpio");
225 $s .= '<div id="pumpio-import-wrapper">';
226 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
227 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
228 $s .= '</div><div class="clear"></div>';
230 $s .= '<div id="pumpio-enable-wrapper">';
231 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
232 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
233 $s .= '</div><div class="clear"></div>';
235 $s .= '<div id="pumpio-bydefault-wrapper">';
236 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
237 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
238 $s .= '</div><div class="clear"></div>';
240 $s .= '<div id="pumpio-public-wrapper">';
241 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
242 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
243 $s .= '</div><div class="clear"></div>';
245 $s .= '<div id="pumpio-mirror-wrapper">';
246 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
247 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
248 $s .= '</div><div class="clear"></div>';
250 $s .= '<div id="pumpio-delete-wrapper">';
251 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
252 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
253 $s .= '</div><div class="clear"></div>';
255 //$s .= '<div id="pumpio-authenticate-wrapper">';
256 //$s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Reauthenticate your pump.io connection").'</a>';
257 //$s .= '</div><div class="clear"></div>';
261 $s .= '</div><div class="clear"></div>';
264 /* provide a submit button */
266 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
271 function pumpio_settings_post(&$a,&$b) {
273 if(x($_POST,'pumpio-submit')) {
274 if(x($_POST,'pumpio_delete')) {
275 set_pconfig(local_user(),'pumpio','consumer_key','');
276 set_pconfig(local_user(),'pumpio','consumer_secret','');
277 set_pconfig(local_user(),'pumpio','host','');
278 set_pconfig(local_user(),'pumpio','oauth_token','');
279 set_pconfig(local_user(),'pumpio','oauth_token_secret','');
280 set_pconfig(local_user(),'pumpio','post',false);
281 set_pconfig(local_user(),'pumpio','post_by_default',false);
282 set_pconfig(local_user(),'pumpio','user','');
284 // filtering the username if it is filled wrong
285 $user = $_POST['pumpio_user'];
286 if (strstr($user, "@")) {
287 $pos = strpos($user, "@");
289 $user = substr($user, 0, $pos);
292 // Filtering the hostname if someone is entering it with "http"
293 $host = $_POST['pumpio_host'];
295 $host = str_replace(array("https://", "http://"), array("", ""), $host);
297 set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
298 set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
299 set_pconfig(local_user(),'pumpio','host',$host);
300 set_pconfig(local_user(),'pumpio','user',$user);
301 set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
302 set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
303 set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
308 function pumpio_post_local(&$a,&$b) {
310 // This can probably be changed to allow editing by pointing to a different API endpoint
315 if((! local_user()) || (local_user() != $b['uid']))
318 if($b['private'] || $b['parent'])
321 $pumpio_post = intval(get_pconfig(local_user(),'pumpio','post'));
323 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
325 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
331 if(strlen($b['postopts']))
332 $b['postopts'] .= ',';
334 $b['postopts'] .= 'pumpio';
340 function pumpio_send(&$a,&$b) {
341 if($b['deleted'] || ($b['created'] !== $b['edited']))
344 if($b['parent'] != $b['id']) {
345 // Looking if its a reply to a pumpio post
346 $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",
347 intval($b["parent"]),
349 dbesc(NETWORK_PUMPIO));
360 if(! strstr($b['postopts'],'pumpio'))
367 // if post comes from pump.io don't send it back
368 if($b['app'] == "pump.io")
371 $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
372 $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
373 $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
374 $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
376 $host = get_pconfig($b['uid'], "pumpio", "host");
377 $user = get_pconfig($b['uid'], "pumpio", "user");
378 $public = get_pconfig($b['uid'], "pumpio", "public");
380 if($oauth_token && $oauth_token_secret) {
382 require_once('include/bbcode.php');
384 $title = trim($b['title']);
387 $title = "<h4>".$title."</h4>";
389 $content = bbcode($b['body'], false, false);
391 // Enhance the way, videos are displayed
392 $content = preg_replace('/<a.*?href="(https?:\/\/www.youtube.com\/.*?)".*?>(.*?)<\/a>/ism',"\n[url]$1[/url]\n",$content);
393 $content = preg_replace('/<a.*?href="(https?:\/\/youtu.be\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
394 $content = preg_replace('/<a.*?href="(https?:\/\/vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
395 $content = preg_replace('/<a.*?href="(https?:\/\/player.vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
397 $URLSearchString = "^\[\]";
398 $content = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$content);
402 $params["verb"] = "post";
405 $params["object"] = array(
406 'objectType' => "note",
407 'content' => $title.$content);
410 $params["to"] = array(Array(
411 "objectType" => "collection",
412 "id" => "http://activityschema.org/collection/public"));
414 $inReplyTo = array("id" => $orig_post["uri"],
415 "objectType" => "note");
417 $params["object"] = array(
418 'objectType' => "comment",
419 'content' => $title.$content,
420 'inReplyTo' => $inReplyTo);
423 $client = new oauth_client_class;
424 $client->oauth_version = '1.0a';
425 $client->url_parameters = false;
426 $client->authorization_header = true;
427 $client->access_token = $oauth_token;
428 $client->access_token_secret = $oauth_token_secret;
429 $client->client_id = $consumer_key;
430 $client->client_secret = $consumer_secret;
432 $username = $user.'@'.$host;
433 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
435 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
439 $post_id = $user->object->id;
440 logger('pumpio_send '.$username.': success '.$post_id);
441 if($post_id AND $iscomment) {
442 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
443 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
449 logger('pumpio_send '.$username.': general error: ' . print_r($user,true));
451 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
453 $a->contact = $r[0]["id"];
455 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
456 require_once('include/queue_fn.php');
457 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
458 notice(t('Pump.io post failed. Queued for retry.').EOL);
464 function pumpio_cron($a,$b) {
465 $last = get_config('pumpio','last_poll');
467 $poll_interval = intval(get_config('pumpio','poll_interval'));
469 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
472 $next = $last + ($poll_interval * 60);
474 logger('pumpio: poll intervall not reached');
478 logger('pumpio: cron_start');
480 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
483 logger('pumpio: mirroring user '.$rr['uid']);
484 pumpio_fetchtimeline($a, $rr['uid']);
488 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
491 logger('pumpio: importing timeline from user '.$rr['uid']);
492 pumpio_fetchinbox($a, $rr['uid']);
497 //pumpio_getallusers($a, $uid);
499 logger('pumpio: cron_end');
501 set_config('pumpio','last_poll', time());
504 function pumpio_fetchtimeline($a, $uid) {
505 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
506 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
507 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
508 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
509 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
510 $hostname = get_pconfig($uid, 'pumpio','host');
511 $username = get_pconfig($uid, "pumpio", "user");
513 $application_name = get_config('pumpio', 'application_name');
515 if ($application_name == "")
516 $application_name = $a->get_hostname();
518 $first_time = ($lastdate == "");
520 $client = new oauth_client_class;
521 $client->oauth_version = '1.0a';
522 $client->authorization_header = true;
523 $client->url_parameters = false;
525 $client->client_id = $ckey;
526 $client->client_secret = $csecret;
527 $client->access_token = $otoken;
528 $client->access_token_secret = $osecret;
530 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
532 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
534 $username = $user.'@'.$host;
536 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
539 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
543 $posts = array_reverse($user->items);
545 $initiallastdate = $lastdate;
549 foreach ($posts as $post) {
550 if ($post->generator->published <= $initiallastdate)
553 if ($lastdate < $post->generator->published)
554 $lastdate = $post->generator->published;
559 $receiptians = array();
560 if (@is_array($post->cc))
561 $receiptians = array_merge($receiptians, $post->cc);
563 if (@is_array($post->to))
564 $receiptians = array_merge($receiptians, $post->to);
567 foreach ($receiptians AS $receiver)
568 if (is_string($receiver->objectType))
569 if ($receiver->id == "http://activityschema.org/collection/public")
572 if ($public AND !strstr($post->generator->displayName, $application_name)) {
573 require_once('include/html2bbcode.php');
575 $_SESSION["authenticated"] = true;
576 $_SESSION["uid"] = $uid;
579 $_REQUEST["type"] = "wall";
580 $_REQUEST["api_source"] = true;
581 $_REQUEST["profile_uid"] = $uid;
582 $_REQUEST["source"] = "pump.io";
584 if ($post->object->displayName != "")
585 $_REQUEST["title"] = html2bbcode($post->object->displayName);
587 $_REQUEST["title"] = "";
589 $_REQUEST["body"] = html2bbcode($post->object->content);
591 if ($post->object->fullImage->url != "")
592 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
594 logger('pumpio: posting for user '.$uid);
596 require_once('mod/item.php');
597 //print_r($_REQUEST);
599 logger('pumpio: posting done - user '.$uid);
604 //$lastdate = '2013-05-16T20:22:12Z';
607 set_pconfig($uid,'pumpio','lastdate', $lastdate);
610 function pumpio_dolike(&$a, $uid, $self, $post) {
613 // If we posted the like locally, it will be found with our url, not the FB url.
615 $second_url = (($likes->id == $fb_id) ? $self[0]['url'] : 'http://facebook.com/profile.php?id=' . $likes->id);
617 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
618 AND ( `author-link` = '%s' OR `author-link` = '%s' ) LIMIT 1",
619 dbesc($orig_post['uri']),
621 dbesc(ACTIVITY_LIKE),
622 dbesc('http://facebook.com/profile.php?id=' . $likes->id),
631 $own_id = "123455678";
633 // Two queries for speed issues
634 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
635 dbesc($post->object->id),
642 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
643 dbesc($post->object->id),
653 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `author-link` = '%s' AND parent = %d LIMIT 1",
654 dbesc(ACTIVITY_LIKE),
656 dbesc($post->actor->url),
657 intval($orig_post['id'])
664 $likedata['parent'] = $orig_post['id'];
665 $likedata['verb'] = ACTIVITY_LIKE;
666 $likedata['gravity'] = 3;
667 $likedata['uid'] = $uid;
668 $likedata['wall'] = 0;
669 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
670 $likedata['parent-uri'] = $orig_post["uri"];
672 if($likes->id == $own_id)
673 $likedata['contact-id'] = $self[0]['id'];
675 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
676 dbesc($post->actor->url),
681 $likedata['contact-id'] = $r[0]['id'];
683 if(! x($likedata,'contact-id'))
684 $likedata['contact-id'] = $orig_post['contact-id'];
686 $likedata['app'] = $post->generator->displayName;
687 $likedata['verb'] = ACTIVITY_LIKE;
688 $likedata['author-name'] = $post->actor->displayName;
689 $likedata['author-link'] = $post->actor->url;
690 $likedata['author-avatar'] = $post->actor->image->url;
692 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
693 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
694 $post_type = t('status');
695 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
696 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
698 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
700 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
701 '<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>';
703 item_store($likedata);
706 function pumpio_get_contact($uid, $contact) {
708 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
709 intval($uid), dbesc($contact->url));
712 // create contact record
713 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
714 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
715 `writable`, `blocked`, `readonly`, `pending` )
716 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
718 dbesc(datetime_convert()),
719 dbesc($contact->url),
720 dbesc(normalise_link($contact->url)),
721 dbesc(str_replace("acct:", "", $contact->id)),
723 dbesc($contact->id), // To-Do?
724 dbesc('pump.io ' . $contact->id), // To-Do?
725 dbesc($contact->displayName),
726 dbesc($contact->preferredUsername),
727 dbesc($contact->image->url),
728 dbesc(NETWORK_PUMPIO),
729 intval(CONTACT_IS_FRIEND),
734 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
735 dbesc($contact->url),
742 $contact_id = $r[0]['id'];
744 $g = q("select def_gid from user where uid = %d limit 1",
748 if($g && intval($g[0]['def_gid'])) {
749 require_once('include/group.php');
750 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
753 require_once("Photo.php");
755 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
757 q("UPDATE `contact` SET `photo` = '%s',
763 WHERE `id` = %d LIMIT 1
768 dbesc(datetime_convert()),
769 dbesc(datetime_convert()),
770 dbesc(datetime_convert()),
774 // update profile photos once every two weeks as we have no notification of when they change.
776 $update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
778 // check that we have all the photos, this has been known to fail on occasion
780 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
781 require_once("Photo.php");
783 $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
785 q("UPDATE `contact` SET `photo` = '%s',
791 WHERE `id` = %d LIMIT 1
796 dbesc(datetime_convert()),
797 dbesc(datetime_convert()),
798 dbesc(datetime_convert()),
808 function pumpio_dodelete(&$a, $client, $uid, $self, $post) {
810 // Two queries for speed issues
811 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
812 dbesc($post->object->id),
817 drop_item($r[0]["id"], $false);
821 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
822 dbesc($post->object->id),
827 drop_item($r[0]["id"], $false);
832 function pumpio_dopost(&$a, $client, $uid, $self, $post) {
833 require_once('include/items.php');
835 if ($post->verb == "like") {
836 pumpio_dolike(&$a, $uid, $self, $post);
840 if ($post->verb == "delete") {
841 pumpio_dodelete(&$a, $uid, $self, $post);
845 // Only handle these three types
846 if (!strstr("post|share|update", $post->verb))
849 if ($post->verb != "update") {
850 // Two queries for speed issues
851 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
852 dbesc($post->object->id),
859 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
860 dbesc($post->object->id),
868 $receiptians = array();
869 if (@is_array($post->cc))
870 $receiptians = array_merge($receiptians, $post->cc);
872 if (@is_array($post->to))
873 $receiptians = array_merge($receiptians, $post->to);
875 foreach ($receiptians AS $receiver)
876 if (is_string($receiver->objectType))
877 if ($receiver->id == "http://activityschema.org/collection/public")
880 $contact_id = pumpio_get_contact($uid, $post->actor);
883 $contact_id = $self[0]['id'];
885 $postarray = array();
886 $postarray['gravity'] = 0;
887 $postarray['uid'] = $uid;
888 $postarray['wall'] = 0;
889 $postarray['uri'] = $post->object->id;
891 if ($post->object->objectType != "comment") {
892 $postarray['parent-uri'] = $post->object->id;
894 //echo($post->object->inReplyTo->url."\n");
895 //print_r($post->object->inReplyTo);
896 //echo $post->object->inReplyTo->likes->url."\n";
897 //$replies = $post->object->inReplyTo->replies->url;
898 //$replies = $post->object->likes->pump_io->proxyURL;
899 //$replies = $post->object->replies->pump_io->proxyURL;
902 //$replies = $post->object->replies->pump_io->proxyURL;
904 if ($replies != "") {
905 $success = $client->CallAPI($replies, 'GET', array(), array('FailOnAccessError'=>true), $replydata);
911 $reply->verb = "note";
912 $reply->cc = $post->cc;
913 $reply->to = $post->to;
914 $reply->object->objectType = $post->object->inReplyTo->objectType;
915 $reply->object->content = $post->object->inReplyTo->content;
916 $reply->object->id = $post->object->inReplyTo->id;
917 $reply->actor = $post->object->inReplyTo->author;
918 $reply->url = $post->object->inReplyTo->url;
919 $reply->generator->displayName = "pumpio";
920 $reply->published = $post->object->inReplyTo->published;
921 $reply->received = $post->object->inReplyTo->updated;
922 $reply->url = $post->object->inReplyTo->url;
923 pumpio_dopost(&$a, $client, $uid, $self, $reply);
925 $postarray['parent-uri'] = $post->object->inReplyTo->id;
928 $postarray['contact-id'] = $contact_id;
929 $postarray['verb'] = ACTIVITY_POST;
930 $postarray['owner-name'] = $post->actor->displayName;
931 $postarray['owner-link'] = $post->actor->url;
932 $postarray['owner-avatar'] = $post->actor->image->url;
933 $postarray['author-name'] = $post->actor->displayName;
934 $postarray['author-link'] = $post->actor->url;
935 $postarray['author-avatar'] = $post->actor->image->url;
936 $postarray['plink'] = $post->object->url;
937 $postarray['app'] = $post->generator->displayName;
938 $postarray['body'] = html2bbcode($post->object->content);
940 if ($post->object->fullImage->url != "")
941 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
943 if ($post->object->displayName != "")
944 $postarray['title'] = $post->object->displayName;
946 //$postarray['location'] = ""
947 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
948 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
950 $postarray['private'] = 1;
951 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
954 if ($post->verb == "share") {
955 $postarray['body'] = "[share author='".$post->object->author->displayName.
956 "' profile='".$post->object->author->url.
957 "' avatar='".$post->object->author->image->url.
958 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
961 if (trim($postarray['body']) == "")
964 $top_item = item_store($postarray);
966 if (($top_item == 0) AND ($post->verb == "update")) {
967 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
968 dbesc($postarray["title"]),
969 dbesc($postarray["body"]),
970 dbesc($postarray["edited"]),
971 dbesc($postarray["uri"]),
976 if ($post->object->objectType == "comment") {
978 $hostname = get_pconfig($uid, 'pumpio','host');
979 $username = get_pconfig($uid, "pumpio", "user");
981 $foreign_url = "https://".$hostname."/".$username;
983 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
990 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
992 if (link_compare($foreign_url, $postarray['author-link']))
995 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
996 dbesc($postarray['parent-uri']),
1000 if(count($myconv)) {
1002 foreach($myconv as $conv) {
1003 // now if we find a match, it means we're in this conversation
1005 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$foreign_url))
1008 require_once('include/enotify.php');
1010 $conv_parent = $conv['parent'];
1013 'type' => NOTIFY_COMMENT,
1014 'notify_flags' => $user[0]['notify-flags'],
1015 'language' => $user[0]['language'],
1016 'to_name' => $user[0]['username'],
1017 'to_email' => $user[0]['email'],
1018 'uid' => $user[0]['uid'],
1019 'item' => $postarray,
1020 'link' => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1021 'source_name' => $postarray['author-name'],
1022 'source_link' => $postarray['author-link'],
1023 'source_photo' => $postarray['author-avatar'],
1024 'verb' => ACTIVITY_POST,
1026 'parent' => $conv_parent,
1029 // only send one notification
1036 function pumpio_fetchinbox($a, $uid) {
1038 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1039 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1040 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1041 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1042 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1043 $hostname = get_pconfig($uid, 'pumpio','host');
1044 $username = get_pconfig($uid, "pumpio", "user");
1046 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1049 $client = new oauth_client_class;
1050 $client->oauth_version = '1.0a';
1051 $client->authorization_header = true;
1052 $client->url_parameters = false;
1054 $client->client_id = $ckey;
1055 $client->client_secret = $csecret;
1056 $client->access_token = $otoken;
1057 $client->access_token_secret = $osecret;
1059 $last_id = get_pconfig($uid,'pumpio','last_id');
1061 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1064 $url .= '?since='.urlencode($last_id);
1066 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1067 $posts = array_reverse($user->items);
1070 foreach ($posts as $post) {
1071 $last_id = $post->id;
1072 pumpio_dopost(&$a, $client, $uid, $self, $post);
1075 set_pconfig($uid,'pumpio','last_id', $last_id);
1078 function pumpio_getallusers($a, $uid) {
1079 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1080 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1081 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1082 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1083 $hostname = get_pconfig($uid, 'pumpio','host');
1084 $username = get_pconfig($uid, "pumpio", "user");
1086 $client = new oauth_client_class;
1087 $client->oauth_version = '1.0a';
1088 $client->authorization_header = true;
1089 $client->url_parameters = false;
1091 $client->client_id = $ckey;
1092 $client->client_secret = $csecret;
1093 $client->access_token = $otoken;
1094 $client->access_token_secret = $osecret;
1096 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1098 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1100 if ($users->totalItems > count($users->items)) {
1101 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1103 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1106 foreach ($users->items AS $user)
1107 echo pumpio_get_contact($uid, $user)."\n";
1110 function pumpio_queue_hook(&$a,&$b) {
1112 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1113 dbesc(NETWORK_PUMPIO)
1118 require_once('include/queue_fn.php');
1120 foreach($qi as $x) {
1121 if($x['network'] !== NETWORK_PUMPIO)
1124 logger('pumpio_queue: run '.print_r($x, true));
1126 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
1127 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1135 $oauth_token = get_pconfig($user['uid'], "pumpio", "oauth_token");
1136 $oauth_token_secret = get_pconfig($user['uid'], "pumpio", "oauth_token_secret");
1137 $consumer_key = get_pconfig($user['uid'], "pumpio","consumer_key");
1138 $consumer_secret = get_pconfig($user['uid'], "pumpio","consumer_secret");
1140 $host = get_pconfig($user['uid'], "pumpio", "host");
1141 $user = get_pconfig($user['uid'], "pumpio", "user");
1145 if ($oauth_token AND $oauth_token_secret AND
1146 $consumer_key AND $consumer_secret) {
1147 $username = $user.'@'.$host;
1149 logger('pumpio_queue: able to post for user '.$username);
1151 $z = unserialize($x['content']);
1153 $client = new oauth_client_class;
1154 $client->oauth_version = '1.0a';
1155 $client->url_parameters = false;
1156 $client->authorization_header = true;
1157 $client->access_token = $oauth_token;
1158 $client->access_token_secret = $oauth_token_secret;
1159 $client->client_id = $consumer_key;
1160 $client->client_secret = $consumer_secret;
1162 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1165 $post_id = $user->object->id;
1166 logger('pumpio_queue: send '.$username.': success '.$post_id);
1167 if($post_id AND $iscomment) {
1168 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1169 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
1174 remove_queue_item($x['id']);
1176 logger('pumpio_queue: send '.$username.': general error: ' . print_r($user,true));
1178 logger("pumpio_queue: Error getting tokens for user ".$user['uid']);
1181 logger('pumpio_queue: delayed');
1182 update_queue_time($x['id']);
1197 - Threads completion
1198 - refresh after post