3 * Name: pump.io Post Connector
4 * Description: Bidirectional (posting, relaying and reading) connector for pump.io.
6 * Author: Michael Vogel <http://pirati.ca/profile/heluecht>
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\Worker;
12 use Friendica\Model\Contact;
13 use Friendica\Model\GContact;
14 use Friendica\Model\Group;
15 use Friendica\Model\User;
16 use Friendica\Model\Item;
18 require 'addon/pumpio/oauth/http.php';
19 require 'addon/pumpio/oauth/oauth_client.php';
20 require_once 'include/enotify.php';
21 require_once "mod/share.php";
23 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
25 function pumpio_install() {
26 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
27 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
28 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
29 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
30 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
31 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
32 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
33 Addon::registerHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
36 function pumpio_uninstall() {
37 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
38 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
39 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
40 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
41 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
42 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
43 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
44 Addon::unregisterHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
47 function pumpio_module() {}
49 function pumpio_content(&$a) {
52 notice( t('Permission denied.') . EOL);
56 require_once("mod/settings.php");
59 if (isset($a->argv[1]))
60 switch ($a->argv[1]) {
62 $o = pumpio_connect($a);
65 $o = print_r($a->argv, true);
69 $o = pumpio_connect($a);
74 function pumpio_check_item_notification($a, &$notification_data) {
75 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
76 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
78 $notification_data["profiles"][] = "https://".$hostname."/".$username;
82 function pumpio_registerclient(&$a, $host) {
84 $url = "https://".$host."/api/client/register";
88 $application_name = Config::get('pumpio', 'application_name');
90 if ($application_name == "")
91 $application_name = $a->get_hostname();
93 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
95 $params["type"] = "client_associate";
96 $params["contacts"] = $adminlist[0];
97 $params["application_type"] = "native";
98 $params["application_name"] = $application_name;
99 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
100 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
102 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
104 $ch = curl_init($url);
105 curl_setopt($ch, CURLOPT_HEADER, false);
106 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
107 curl_setopt($ch, CURLOPT_POST,1);
108 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
109 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
112 $curl_info = curl_getinfo($ch);
114 if ($curl_info["http_code"] == "200") {
115 $values = json_decode($s);
116 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
119 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
124 function pumpio_connect(&$a) {
125 // Start a session. This is necessary to hold on to a few keys the callback script will also need
128 // Define the needed keys
129 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
130 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
131 $hostname = PConfig::get(local_user(), 'pumpio','host');
133 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
134 logger("pumpio_connect: register client");
135 $clientdata = pumpio_registerclient($a, $hostname);
136 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
137 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
139 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
140 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
142 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
145 if (($consumer_key == "") || ($consumer_secret == "")) {
146 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
148 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
152 // The callback URL is the script that gets called after the user authenticates with pumpio
153 $callback_url = $a->get_baseurl()."/pumpio/connect";
155 // Let's begin. First we need a Request Token. The request token is required to send the user
156 // to pumpio's login page.
158 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
159 // Consumer Key and Consumer Secret
160 $client = new oauth_client_class;
162 $client->server = '';
163 $client->oauth_version = '1.0a';
164 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
165 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
166 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
167 $client->url_parameters = false;
168 $client->authorization_header = true;
169 $client->redirect_uri = $callback_url;
170 $client->client_id = $consumer_key;
171 $client->client_secret = $consumer_secret;
173 if (($success = $client->Initialize())) {
174 if (($success = $client->Process())) {
175 if (strlen($client->access_token)) {
176 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
177 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
178 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
181 $success = $client->Finalize($success);
184 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
187 logger("pumpio_connect: authenticated");
188 $o .= t("You are now authenticated to pumpio.");
189 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
191 logger("pumpio_connect: could not connect");
192 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
198 function pumpio_jot_nets(&$a,&$b) {
202 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
203 if(intval($pumpio_post) == 1) {
204 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
205 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
206 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
207 . t('Post to pumpio') . '</div>';
212 function pumpio_settings(&$a,&$s) {
217 /* Add our stylesheet to the page so we can make our settings look nice */
219 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
221 /* Get the current state of our config variables */
223 $import_enabled = PConfig::get(local_user(),'pumpio','import');
224 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
226 $enabled = PConfig::get(local_user(),'pumpio','post');
227 $checked = (($enabled) ? ' checked="checked" ' : '');
228 $css = (($enabled) ? '' : '-disabled');
230 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
231 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
233 $public_enabled = PConfig::get(local_user(),'pumpio','public');
234 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
236 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
237 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
239 $servername = PConfig::get(local_user(), "pumpio", "host");
240 $username = PConfig::get(local_user(), "pumpio", "user");
242 /* Add some HTML to the existing form */
244 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
245 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
247 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
248 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
249 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
252 $s .= '<div id="pumpio-username-wrapper">';
253 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
254 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
255 $s .= '</div><div class="clear"></div>';
257 $s .= '<div id="pumpio-servername-wrapper">';
258 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
259 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
260 $s .= '</div><div class="clear"></div>';
262 if (($username != '') && ($servername != '')) {
264 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
265 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
267 $s .= '<div id="pumpio-password-wrapper">';
268 if (($oauth_token == "") || ($oauth_token_secret == "")) {
269 $s .= '<div id="pumpio-authenticate-wrapper">';
270 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
271 $s .= '</div><div class="clear"></div>';
273 $s .= '<div id="pumpio-import-wrapper">';
274 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
275 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
276 $s .= '</div><div class="clear"></div>';
278 $s .= '<div id="pumpio-enable-wrapper">';
279 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Addon') . '</label>';
280 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
281 $s .= '</div><div class="clear"></div>';
283 $s .= '<div id="pumpio-bydefault-wrapper">';
284 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
285 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
286 $s .= '</div><div class="clear"></div>';
288 $s .= '<div id="pumpio-public-wrapper">';
289 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
290 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
291 $s .= '</div><div class="clear"></div>';
293 $s .= '<div id="pumpio-mirror-wrapper">';
294 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
295 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
296 $s .= '</div><div class="clear"></div>';
298 $s .= '<div id="pumpio-delete-wrapper">';
299 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
300 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
301 $s .= '</div><div class="clear"></div>';
304 $s .= '</div><div class="clear"></div>';
307 /* provide a submit button */
309 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
313 function pumpio_settings_post(&$a,&$b) {
315 if(x($_POST,'pumpio-submit')) {
316 if(x($_POST,'pumpio_delete')) {
317 PConfig::set(local_user(),'pumpio','consumer_key','');
318 PConfig::set(local_user(),'pumpio','consumer_secret','');
319 PConfig::set(local_user(),'pumpio','oauth_token','');
320 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
321 PConfig::set(local_user(),'pumpio','post',false);
322 PConfig::set(local_user(),'pumpio','import',false);
323 PConfig::set(local_user(),'pumpio','host','');
324 PConfig::set(local_user(),'pumpio','user','');
325 PConfig::set(local_user(),'pumpio','public',false);
326 PConfig::set(local_user(),'pumpio','mirror',false);
327 PConfig::set(local_user(),'pumpio','post_by_default',false);
328 PConfig::set(local_user(),'pumpio','lastdate', 0);
329 PConfig::set(local_user(),'pumpio','last_id', '');
331 // filtering the username if it is filled wrong
332 $user = $_POST['pumpio_user'];
333 if (strstr($user, "@")) {
334 $pos = strpos($user, "@");
336 $user = substr($user, 0, $pos);
339 // Filtering the hostname if someone is entering it with "http"
340 $host = $_POST['pumpio_host'];
342 $host = str_replace(["https://", "http://"], ["", ""], $host);
344 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
345 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
346 PConfig::set(local_user(),'pumpio','host',$host);
347 PConfig::set(local_user(),'pumpio','user',$user);
348 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
349 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
350 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
352 if (!$_POST['pumpio_mirror'])
353 PConfig::delete(local_user(),'pumpio','lastdate');
355 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
360 function pumpio_post_local(&$a, &$b) {
362 if (!local_user() || (local_user() != $b['uid'])) {
366 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
368 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
370 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
374 if (!$pumpio_enable) {
378 if (strlen($b['postopts'])) {
379 $b['postopts'] .= ',';
382 $b['postopts'] .= 'pumpio';
388 function pumpio_send(&$a,&$b) {
390 if (!PConfig::get($b["uid"],'pumpio','import')) {
391 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
395 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
397 if($b['parent'] != $b['id']) {
398 // Looking if its a reply to a pumpio post
399 $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",
400 intval($b["parent"]),
402 dbesc(NETWORK_PUMPIO));
405 logger("pumpio_send: no pumpio post ".$b["parent"]);
414 $receiver = pumpio_getreceiver($a, $b);
416 logger("pumpio_send: receiver ".print_r($receiver, true));
418 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio'))) {
422 // Dont't post if the post doesn't belong to us.
423 // This is a check for forum postings
424 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
425 if ($b['contact-id'] != $self['id']) {
430 if($b['verb'] == ACTIVITY_LIKE) {
432 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
434 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
438 if($b['verb'] == ACTIVITY_DISLIKE)
441 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
442 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
444 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
445 pumpio_action($a, $b["uid"], $b["uri"], "delete");
447 if($b['deleted'] || ($b['created'] !== $b['edited']))
450 // if post comes from pump.io don't send it back
451 if($b['app'] == "pump.io")
455 // Support for native shares
456 // http://<hostname>/api/<type>/shares?id=<the-object-id>
458 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
459 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
460 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
461 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
463 $host = PConfig::get($b['uid'], "pumpio", "host");
464 $user = PConfig::get($b['uid'], "pumpio", "user");
465 $public = PConfig::get($b['uid'], "pumpio", "public");
467 if($oauth_token && $oauth_token_secret) {
469 require_once('include/bbcode.php');
471 $title = trim($b['title']);
473 $content = bbcode($b['body'], false, false, 4);
477 $params["verb"] = "post";
480 $params["object"] = [
481 'objectType' => "note",
482 'content' => $content];
485 $params["object"]["displayName"] = $title;
487 if (count($receiver["to"]))
488 $params["to"] = $receiver["to"];
490 if (count($receiver["bto"]))
491 $params["bto"] = $receiver["bto"];
493 if (count($receiver["cc"]))
494 $params["cc"] = $receiver["cc"];
496 if (count($receiver["bcc"]))
497 $params["bcc"] = $receiver["bcc"];
500 $inReplyTo = ["id" => $orig_post["uri"],
501 "objectType" => "note"];
503 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
504 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
506 $params["object"] = [
507 'objectType' => "comment",
508 'content' => $content,
509 'inReplyTo' => $inReplyTo];
512 $params["object"]["displayName"] = $title;
515 $client = new oauth_client_class;
516 $client->oauth_version = '1.0a';
517 $client->url_parameters = false;
518 $client->authorization_header = true;
519 $client->access_token = $oauth_token;
520 $client->access_token_secret = $oauth_token_secret;
521 $client->client_id = $consumer_key;
522 $client->client_secret = $consumer_secret;
524 $username = $user.'@'.$host;
525 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
527 if (pumpio_reachable($url))
528 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
534 if ($user->generator->displayName)
535 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
537 $post_id = $user->object->id;
538 logger('pumpio_send '.$username.': success '.$post_id);
539 if($post_id && $iscomment) {
540 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
541 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
547 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
549 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
551 $a->contact = $r[0]["id"];
553 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
554 require_once('include/queue_fn.php');
555 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
556 notice(t('Pump.io post failed. Queued for retry.').EOL);
562 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
564 // Don't do likes and other stuff if you don't import the timeline
565 if (!PConfig::get($uid,'pumpio','import'))
568 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
569 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
570 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
571 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
572 $hostname = PConfig::get($uid, 'pumpio','host');
573 $username = PConfig::get($uid, "pumpio", "user");
575 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
585 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
586 $uri = $orig_post["extid"];
588 $uri = $orig_post["uri"];
590 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
591 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
592 elseif (strstr($uri, "/api/comment/"))
593 $objectType = "comment";
594 elseif (strstr($uri, "/api/note/"))
595 $objectType = "note";
596 elseif (strstr($uri, "/api/image/"))
597 $objectType = "image";
599 $params["verb"] = $action;
600 $params["object"] = ['id' => $uri,
601 "objectType" => $objectType,
602 "content" => $content];
604 $client = new oauth_client_class;
605 $client->oauth_version = '1.0a';
606 $client->authorization_header = true;
607 $client->url_parameters = false;
609 $client->client_id = $ckey;
610 $client->client_secret = $csecret;
611 $client->access_token = $otoken;
612 $client->access_token_secret = $osecret;
614 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
616 if (pumpio_reachable($url))
617 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
622 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
624 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
626 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
628 $a->contact = $r[0]["id"];
630 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
631 require_once('include/queue_fn.php');
632 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
633 notice(t('Pump.io like failed. Queued for retry.').EOL);
637 function pumpio_sync(&$a) {
638 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
644 $last = Config::get('pumpio','last_poll');
646 $poll_interval = intval(Config::get('pumpio','poll_interval'));
648 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
651 $next = $last + ($poll_interval * 60);
653 logger('pumpio: poll intervall not reached');
657 logger('pumpio: cron_start');
659 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
662 logger('pumpio: mirroring user '.$rr['uid']);
663 pumpio_fetchtimeline($a, $rr['uid']);
667 $abandon_days = intval(Config::get('system','account_abandon_days'));
668 if ($abandon_days < 1)
671 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
673 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
676 if ($abandon_days != 0) {
677 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
679 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
684 logger('pumpio: importing timeline from user '.$rr['uid']);
685 pumpio_fetchinbox($a, $rr['uid']);
687 // check for new contacts once a day
688 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
689 if($last_contact_check)
690 $next_contact_check = $last_contact_check + 86400;
692 $next_contact_check = 0;
694 if($next_contact_check <= time()) {
695 pumpio_getallusers($a, $rr["uid"]);
696 PConfig::set($rr['uid'],'pumpio','contact_check',time());
701 logger('pumpio: cron_end');
703 Config::set('pumpio','last_poll', time());
706 function pumpio_cron(&$a,$b) {
707 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
710 function pumpio_fetchtimeline(&$a, $uid) {
711 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
712 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
713 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
714 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
715 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
716 $hostname = PConfig::get($uid, 'pumpio','host');
717 $username = PConfig::get($uid, "pumpio", "user");
719 // get the application name for the pump.io app
720 // 1st try personal config, then system config and fallback to the
721 // hostname of the node if neither one is set.
722 $application_name = PConfig::get( $uid, 'pumpio', 'application_name');
723 if ($application_name == "")
724 $application_name = Config::get('pumpio', 'application_name');
725 if ($application_name == "")
726 $application_name = $a->get_hostname();
728 $first_time = ($lastdate == "");
730 $client = new oauth_client_class;
731 $client->oauth_version = '1.0a';
732 $client->authorization_header = true;
733 $client->url_parameters = false;
735 $client->client_id = $ckey;
736 $client->client_secret = $csecret;
737 $client->access_token = $otoken;
738 $client->access_token_secret = $osecret;
740 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
742 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
744 $username = $user.'@'.$host;
746 if (pumpio_reachable($url))
747 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
752 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
756 $posts = array_reverse($user->items);
758 $initiallastdate = $lastdate;
762 foreach ($posts as $post) {
763 if ($post->published <= $initiallastdate)
766 if ($lastdate < $post->published)
767 $lastdate = $post->published;
773 if (@is_array($post->cc))
774 $receiptians = array_merge($receiptians, $post->cc);
776 if (@is_array($post->to))
777 $receiptians = array_merge($receiptians, $post->to);
780 foreach ($receiptians AS $receiver)
781 if (is_string($receiver->objectType))
782 if ($receiver->id == "http://activityschema.org/collection/public")
785 if ($public && !stristr($post->generator->displayName, $application_name)) {
786 require_once('include/html2bbcode.php');
788 $_SESSION["authenticated"] = true;
789 $_SESSION["uid"] = $uid;
792 $_REQUEST["type"] = "wall";
793 $_REQUEST["api_source"] = true;
794 $_REQUEST["profile_uid"] = $uid;
795 $_REQUEST["source"] = "pump.io";
797 if (isset($post->object->id)) {
798 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
801 if ($post->object->displayName != "")
802 $_REQUEST["title"] = html2bbcode($post->object->displayName);
804 $_REQUEST["title"] = "";
806 $_REQUEST["body"] = html2bbcode($post->object->content);
808 // To-Do: Picture has to be cached and stored locally
809 if ($post->object->fullImage->url != "") {
810 if ($post->object->fullImage->pump_io->proxyURL != "")
811 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
813 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
816 logger('pumpio: posting for user '.$uid);
818 require_once('mod/item.php');
821 logger('pumpio: posting done - user '.$uid);
827 PConfig::set($uid,'pumpio','lastdate', $lastdate);
830 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
831 // Searching for the unliked post
832 // Two queries for speed issues
833 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
834 dbesc($post->object->id),
841 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
842 dbesc($post->object->id),
854 if(link_compare($post->actor->url, $own_id)) {
855 $contactid = $self[0]['id'];
857 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
858 dbesc(normalise_link($post->actor->url)),
863 $contactid = $r[0]['id'];
866 $contactid = $orig_post['contact-id'];
869 $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'",
870 dbesc(datetime_convert()),
871 dbesc(ACTIVITY_LIKE),
874 dbesc($orig_post['uri'])
878 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
880 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
883 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
884 require_once('include/items.php');
886 if ($post->object->id == "") {
887 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
891 // Searching for the liked post
892 // Two queries for speed issues
893 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
894 dbesc($post->object->id),
896 dbesc(NETWORK_PUMPIO)
902 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
903 dbesc($post->object->id),
905 dbesc(NETWORK_PUMPIO)
915 if ($threadcompletion)
916 pumpio_fetchallcomments($a, $uid, $post->object->id);
920 if(link_compare($post->actor->url, $own_id)) {
921 $contactid = $self[0]['id'];
922 $post->actor->displayName = $self[0]['name'];
923 $post->actor->url = $self[0]['url'];
924 $post->actor->image->url = $self[0]['photo'];
926 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
927 dbesc(normalise_link($post->actor->url)),
932 $contactid = $r[0]['id'];
935 $contactid = $orig_post['contact-id'];
938 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
939 dbesc(ACTIVITY_LIKE),
942 dbesc($orig_post['uri'])
946 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
951 $likedata['parent'] = $orig_post['id'];
952 $likedata['verb'] = ACTIVITY_LIKE;
953 $likedata['gravity'] = 3;
954 $likedata['uid'] = $uid;
955 $likedata['wall'] = 0;
956 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
957 $likedata['parent-uri'] = $orig_post["uri"];
958 $likedata['contact-id'] = $contactid;
959 $likedata['app'] = $post->generator->displayName;
960 $likedata['author-name'] = $post->actor->displayName;
961 $likedata['author-link'] = $post->actor->url;
962 $likedata['author-avatar'] = $post->actor->image->url;
964 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
965 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
966 $post_type = t('status');
967 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
968 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
970 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
972 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
973 '<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>';
975 $ret = item_store($likedata);
977 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
980 function pumpio_get_contact($uid, $contact, $no_insert = false) {
982 GContact::update(["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
983 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
984 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
985 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)]);
986 $cid = Contact::getIdForURL($contact->url, $uid);
991 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
992 intval($uid), dbesc(normalise_link($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 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
999 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %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),
1014 dbesc($contact->location->displayName),
1015 dbesc($contact->summary),
1019 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1020 dbesc(normalise_link($contact->url)),
1028 $contact_id = $r[0]['id'];
1030 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1032 $contact_id = $r[0]["id"];
1034 /* if (DB_UPDATE_VERSION >= "1177")
1035 q("UPDATE `contact` SET `location` = '%s',
1038 dbesc($contact->location->displayName),
1039 dbesc($contact->summary),
1045 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1047 return($contact_id);
1050 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1052 // Two queries for speed issues
1053 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1054 dbesc($post->object->id),
1059 return Item::delete($r[0]["id"]);
1061 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1062 dbesc($post->object->id),
1067 return Item::delete($r[0]["id"]);
1070 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1071 require_once('include/items.php');
1072 require_once('include/html2bbcode.php');
1074 if (($post->verb == "like") || ($post->verb == "favorite"))
1075 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1077 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1078 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1080 if ($post->verb == "delete")
1081 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1083 if ($post->verb != "update") {
1084 // Two queries for speed issues
1085 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1086 dbesc($post->object->id),
1093 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1094 dbesc($post->object->id),
1102 // Only handle these three types
1103 if (!strstr("post|share|update", $post->verb))
1107 if (@is_array($post->cc))
1108 $receiptians = array_merge($receiptians, $post->cc);
1110 if (@is_array($post->to))
1111 $receiptians = array_merge($receiptians, $post->to);
1113 foreach ($receiptians AS $receiver)
1114 if (is_string($receiver->objectType))
1115 if ($receiver->id == "http://activityschema.org/collection/public")
1119 $postarray['network'] = NETWORK_PUMPIO;
1120 $postarray['gravity'] = 0;
1121 $postarray['uid'] = $uid;
1122 $postarray['wall'] = 0;
1123 $postarray['uri'] = $post->object->id;
1124 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1126 if ($post->object->objectType != "comment") {
1127 $contact_id = pumpio_get_contact($uid, $post->actor);
1130 $contact_id = $self[0]['id'];
1132 $postarray['parent-uri'] = $post->object->id;
1135 $postarray['private'] = 1;
1136 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1139 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1141 if (link_compare($post->actor->url, $own_id)) {
1142 $contact_id = $self[0]['id'];
1143 $post->actor->displayName = $self[0]['name'];
1144 $post->actor->url = $self[0]['url'];
1145 $post->actor->image->url = $self[0]['photo'];
1146 } elseif ($contact_id == 0) {
1147 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1148 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1149 dbesc(normalise_link($post->actor->url)),
1154 $contact_id = $r[0]['id'];
1156 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1157 dbesc(normalise_link($post->actor->url)),
1162 $contact_id = $r[0]['id'];
1164 $contact_id = $self[0]['id'];
1168 $reply = new stdClass;
1169 $reply->verb = "note";
1170 $reply->cc = $post->cc;
1171 $reply->to = $post->to;
1172 $reply->object = new stdClass;
1173 $reply->object->objectType = $post->object->inReplyTo->objectType;
1174 $reply->object->content = $post->object->inReplyTo->content;
1175 $reply->object->id = $post->object->inReplyTo->id;
1176 $reply->actor = $post->object->inReplyTo->author;
1177 $reply->url = $post->object->inReplyTo->url;
1178 $reply->generator = new stdClass;
1179 $reply->generator->displayName = "pumpio";
1180 $reply->published = $post->object->inReplyTo->published;
1181 $reply->received = $post->object->inReplyTo->updated;
1182 $reply->url = $post->object->inReplyTo->url;
1183 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1185 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1188 if ($post->object->pump_io->proxyURL)
1189 $postarray['extid'] = $post->object->pump_io->proxyURL;
1191 $postarray['contact-id'] = $contact_id;
1192 $postarray['verb'] = ACTIVITY_POST;
1193 $postarray['owner-name'] = $post->actor->displayName;
1194 $postarray['owner-link'] = $post->actor->url;
1195 $postarray['owner-avatar'] = $post->actor->image->url;
1196 $postarray['author-name'] = $post->actor->displayName;
1197 $postarray['author-link'] = $post->actor->url;
1198 $postarray['author-avatar'] = $post->actor->image->url;
1199 $postarray['plink'] = $post->object->url;
1200 $postarray['app'] = $post->generator->displayName;
1201 $postarray['body'] = html2bbcode($post->object->content);
1202 $postarray['object'] = json_encode($post);
1204 if ($post->object->fullImage->url != "")
1205 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1207 if ($post->object->displayName != "")
1208 $postarray['title'] = $post->object->displayName;
1210 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1211 if (isset($post->updated))
1212 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1213 elseif (isset($post->received))
1214 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1216 $postarray['edited'] = $postarray['created'];
1218 if ($post->verb == "share") {
1219 if (!intval(Config::get('system','wall-to-wall_share'))) {
1220 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1221 $share_author = $post->object->author->displayName;
1222 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1223 $share_author = $post->object->author->preferredUsername;
1225 $share_author = $post->object->author->url;
1227 $postarray['body'] = share_header($share_author, $post->object->author->url,
1228 $post->object->author->image->url, "",
1229 datetime_convert('UTC','UTC',$post->object->created),
1230 $post->links->self->href).
1231 $postarray['body']."[/share]";
1234 $postarray['body'] = "[share author='".$share_author.
1235 "' profile='".$post->object->author->url.
1236 "' avatar='".$post->object->author->image->url.
1237 "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1238 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1241 // Let shares look like wall-to-wall posts
1242 $postarray['author-name'] = $post->object->author->displayName;
1243 $postarray['author-link'] = $post->object->author->url;
1244 $postarray['author-avatar'] = $post->object->author->image->url;
1248 if (trim($postarray['body']) == "")
1251 $top_item = item_store($postarray);
1252 $postarray["id"] = $top_item;
1254 if (($top_item == 0) && ($post->verb == "update")) {
1255 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1256 dbesc($postarray["title"]),
1257 dbesc($postarray["body"]),
1258 dbesc($postarray["edited"]),
1259 dbesc($postarray["uri"]),
1264 if ($post->object->objectType == "comment") {
1266 if ($threadcompletion)
1267 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1269 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1276 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1278 if (link_compare($own_id, $postarray['author-link']))
1281 if (!function_exists("check_item_notification")) {
1282 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1283 dbesc($postarray['parent-uri']),
1287 if(count($myconv)) {
1289 foreach($myconv as $conv) {
1290 // now if we find a match, it means we're in this conversation
1292 if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1295 require_once('include/enotify.php');
1297 $conv_parent = $conv['parent'];
1300 'type' => NOTIFY_COMMENT,
1301 'notify_flags' => $user[0]['notify-flags'],
1302 'language' => $user[0]['language'],
1303 'to_name' => $user[0]['username'],
1304 'to_email' => $user[0]['email'],
1305 'uid' => $user[0]['uid'],
1306 'item' => $postarray,
1307 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1308 'source_name' => $postarray['author-name'],
1309 'source_link' => $postarray['author-link'],
1310 'source_photo' => $postarray['author-avatar'],
1311 'verb' => ACTIVITY_POST,
1313 'parent' => $conv_parent,
1316 // only send one notification
1326 function pumpio_fetchinbox(&$a, $uid) {
1328 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1329 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1330 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1331 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1332 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1333 $hostname = PConfig::get($uid, 'pumpio','host');
1334 $username = PConfig::get($uid, "pumpio", "user");
1336 $own_id = "https://".$hostname."/".$username;
1338 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1341 $lastitems = q("SELECT `uri` FROM `thread`
1342 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1343 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1344 ORDER BY `thread`.`commented` DESC LIMIT 10",
1345 dbesc(NETWORK_PUMPIO),
1349 $client = new oauth_client_class;
1350 $client->oauth_version = '1.0a';
1351 $client->authorization_header = true;
1352 $client->url_parameters = false;
1354 $client->client_id = $ckey;
1355 $client->client_secret = $csecret;
1356 $client->access_token = $otoken;
1357 $client->access_token_secret = $osecret;
1359 $last_id = PConfig::get($uid,'pumpio','last_id');
1361 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1364 $url .= '?since='.urlencode($last_id);
1366 if (pumpio_reachable($url))
1367 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1372 $posts = array_reverse($user->items);
1375 foreach ($posts as $post) {
1376 $last_id = $post->id;
1377 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1381 foreach ($lastitems AS $item)
1382 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1384 PConfig::set($uid,'pumpio','last_id', $last_id);
1387 function pumpio_getallusers(&$a, $uid) {
1388 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1389 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1390 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1391 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1392 $hostname = PConfig::get($uid, 'pumpio','host');
1393 $username = PConfig::get($uid, "pumpio", "user");
1395 $client = new oauth_client_class;
1396 $client->oauth_version = '1.0a';
1397 $client->authorization_header = true;
1398 $client->url_parameters = false;
1400 $client->client_id = $ckey;
1401 $client->client_secret = $csecret;
1402 $client->access_token = $otoken;
1403 $client->access_token_secret = $osecret;
1405 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1407 if (pumpio_reachable($url))
1408 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1412 if ($users->totalItems > count($users->items)) {
1413 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1415 if (pumpio_reachable($url))
1416 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1421 if (is_array($users->items)) {
1422 foreach ($users->items AS $user) {
1423 pumpio_get_contact($uid, $user);
1428 function pumpio_queue_hook(&$a,&$b) {
1430 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1431 dbesc(NETWORK_PUMPIO)
1436 require_once('include/queue_fn.php');
1438 foreach($qi as $x) {
1439 if($x['network'] !== NETWORK_PUMPIO)
1442 logger('pumpio_queue: run');
1444 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1445 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1453 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1455 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1456 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1457 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1458 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1460 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1461 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1465 if ($oauth_token && $oauth_token_secret &&
1466 $consumer_key && $consumer_secret) {
1467 $username = $user.'@'.$host;
1469 logger('pumpio_queue: able to post for user '.$username);
1471 $z = unserialize($x['content']);
1473 $client = new oauth_client_class;
1474 $client->oauth_version = '1.0a';
1475 $client->url_parameters = false;
1476 $client->authorization_header = true;
1477 $client->access_token = $oauth_token;
1478 $client->access_token_secret = $oauth_token_secret;
1479 $client->client_id = $consumer_key;
1480 $client->client_secret = $consumer_secret;
1482 if (pumpio_reachable($z['url']))
1483 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1488 $post_id = $user->object->id;
1489 logger('pumpio_queue: send '.$username.': success '.$post_id);
1490 if($post_id && $iscomment) {
1491 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1492 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1497 remove_queue_item($x['id']);
1499 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1501 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1504 logger('pumpio_queue: delayed');
1505 update_queue_time($x['id']);
1510 function pumpio_getreceiver(&$a, $b) {
1514 if (!$b["private"]) {
1516 if(! strstr($b['postopts'],'pumpio'))
1519 $public = PConfig::get($b['uid'], "pumpio", "public");
1522 $receiver["to"][] = [
1523 "objectType" => "collection",
1524 "id" => "http://activityschema.org/collection/public"];
1526 $cids = explode("><", $b["allow_cid"]);
1527 $gids = explode("><", $b["allow_gid"]);
1529 foreach ($cids AS $cid) {
1530 $cid = trim($cid, " <>");
1532 $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",
1535 dbesc(NETWORK_PUMPIO)
1539 $receiver["bcc"][] = [
1540 "displayName" => $r[0]["name"],
1541 "objectType" => "person",
1542 "preferredUsername" => $r[0]["nick"],
1543 "url" => $r[0]["url"]];
1546 foreach ($gids AS $gid) {
1547 $gid = trim($gid, " <>");
1549 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1550 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1551 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1553 dbesc(NETWORK_PUMPIO)
1556 foreach ($r AS $row)
1557 $receiver["bcc"][] = [
1558 "displayName" => $row["name"],
1559 "objectType" => "person",
1560 "preferredUsername" => $row["nick"],
1561 "url" => $row["url"]];
1565 if ($b["inform"] != "") {
1567 $inform = explode(",", $b["inform"]);
1569 foreach ($inform AS $cid) {
1570 if (substr($cid, 0, 4) != "cid:")
1573 $cid = str_replace("cid:", "", $cid);
1575 $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",
1578 dbesc(NETWORK_PUMPIO)
1582 $receiver["to"][] = [
1583 "displayName" => $r[0]["name"],
1584 "objectType" => "person",
1585 "preferredUsername" => $r[0]["nick"],
1586 "url" => $r[0]["url"]];
1594 function pumpio_fetchallcomments(&$a, $uid, $id) {
1595 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1596 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1597 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1598 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1599 $hostname = PConfig::get($uid, 'pumpio','host');
1600 $username = PConfig::get($uid, "pumpio", "user");
1602 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1604 $own_id = "https://".$hostname."/".$username;
1606 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1609 // Fetching the original post
1610 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1618 $url = $r[0]["extid"];
1620 $client = new oauth_client_class;
1621 $client->oauth_version = '1.0a';
1622 $client->authorization_header = true;
1623 $client->url_parameters = false;
1625 $client->client_id = $ckey;
1626 $client->client_secret = $csecret;
1627 $client->access_token = $otoken;
1628 $client->access_token_secret = $osecret;
1630 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1632 if (pumpio_reachable($url))
1633 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1640 if ($item->likes->totalItems != 0) {
1641 foreach ($item->likes->items AS $post) {
1642 $like = new stdClass;
1643 $like->object = new stdClass;
1644 $like->object->id = $item->id;
1645 $like->actor = new stdClass;
1646 $like->actor->displayName = $item->displayName;
1647 $like->actor->preferredUsername = $item->preferredUsername;
1648 $like->actor->url = $item->url;
1649 $like->actor->image = $item->image;
1650 $like->generator = new stdClass;
1651 $like->generator->displayName = "pumpio";
1652 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1656 if ($item->replies->totalItems == 0)
1659 foreach ($item->replies->items AS $item) {
1660 if ($item->id == $id)
1663 // Checking if the comment already exists - Two queries for speed issues
1664 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1672 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1680 $post = new stdClass;
1681 $post->verb = "post";
1682 $post->actor = $item->author;
1683 $post->published = $item->published;
1684 $post->received = $item->updated;
1685 $post->generator = new stdClass;
1686 $post->generator->displayName = "pumpio";
1687 // To-Do: Check for public post
1689 unset($item->author);
1690 unset($item->published);
1691 unset($item->updated);
1693 $post->object = $item;
1695 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1696 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1701 function pumpio_reachable($url) {
1702 $data = z_fetch_url($url, false, $redirects, ['timeout'=>10]);
1703 return(intval($data['return_code']) != 0);