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;
17 use Friendica\Model\Queue;
19 require 'addon/pumpio/oauth/http.php';
20 require 'addon/pumpio/oauth/oauth_client.php';
21 require_once 'include/enotify.php';
22 require_once "mod/share.php";
24 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
26 function pumpio_install() {
27 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
28 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
29 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
30 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
31 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
32 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
33 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
34 Addon::registerHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
37 function pumpio_uninstall() {
38 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
39 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
40 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
41 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
42 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
43 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
44 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
45 Addon::unregisterHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
48 function pumpio_module() {}
50 function pumpio_content(&$a) {
53 notice( t('Permission denied.') . EOL);
57 require_once("mod/settings.php");
60 if (isset($a->argv[1]))
61 switch ($a->argv[1]) {
63 $o = pumpio_connect($a);
66 $o = print_r($a->argv, true);
70 $o = pumpio_connect($a);
75 function pumpio_check_item_notification($a, &$notification_data) {
76 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
77 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
79 $notification_data["profiles"][] = "https://".$hostname."/".$username;
83 function pumpio_registerclient(&$a, $host) {
85 $url = "https://".$host."/api/client/register";
89 $application_name = Config::get('pumpio', 'application_name');
91 if ($application_name == "")
92 $application_name = $a->get_hostname();
94 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
96 $params["type"] = "client_associate";
97 $params["contacts"] = $adminlist[0];
98 $params["application_type"] = "native";
99 $params["application_name"] = $application_name;
100 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
101 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
103 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
105 $ch = curl_init($url);
106 curl_setopt($ch, CURLOPT_HEADER, false);
107 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
108 curl_setopt($ch, CURLOPT_POST,1);
109 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
110 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
113 $curl_info = curl_getinfo($ch);
115 if ($curl_info["http_code"] == "200") {
116 $values = json_decode($s);
117 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
120 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
125 function pumpio_connect(&$a) {
126 // Start a session. This is necessary to hold on to a few keys the callback script will also need
129 // Define the needed keys
130 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
131 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
132 $hostname = PConfig::get(local_user(), 'pumpio','host');
134 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
135 logger("pumpio_connect: register client");
136 $clientdata = pumpio_registerclient($a, $hostname);
137 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
138 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
140 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
141 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
143 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
146 if (($consumer_key == "") || ($consumer_secret == "")) {
147 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
149 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
153 // The callback URL is the script that gets called after the user authenticates with pumpio
154 $callback_url = $a->get_baseurl()."/pumpio/connect";
156 // Let's begin. First we need a Request Token. The request token is required to send the user
157 // to pumpio's login page.
159 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
160 // Consumer Key and Consumer Secret
161 $client = new oauth_client_class;
163 $client->server = '';
164 $client->oauth_version = '1.0a';
165 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
166 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
167 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
168 $client->url_parameters = false;
169 $client->authorization_header = true;
170 $client->redirect_uri = $callback_url;
171 $client->client_id = $consumer_key;
172 $client->client_secret = $consumer_secret;
174 if (($success = $client->Initialize())) {
175 if (($success = $client->Process())) {
176 if (strlen($client->access_token)) {
177 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
178 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
179 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
182 $success = $client->Finalize($success);
185 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
188 logger("pumpio_connect: authenticated");
189 $o .= t("You are now authenticated to pumpio.");
190 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
192 logger("pumpio_connect: could not connect");
193 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
199 function pumpio_jot_nets(&$a,&$b) {
203 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
204 if(intval($pumpio_post) == 1) {
205 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
206 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
207 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
208 . t('Post to pumpio') . '</div>';
213 function pumpio_settings(&$a,&$s) {
218 /* Add our stylesheet to the page so we can make our settings look nice */
220 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
222 /* Get the current state of our config variables */
224 $import_enabled = PConfig::get(local_user(),'pumpio','import');
225 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
227 $enabled = PConfig::get(local_user(),'pumpio','post');
228 $checked = (($enabled) ? ' checked="checked" ' : '');
229 $css = (($enabled) ? '' : '-disabled');
231 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
232 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
234 $public_enabled = PConfig::get(local_user(),'pumpio','public');
235 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
237 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
238 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
240 $servername = PConfig::get(local_user(), "pumpio", "host");
241 $username = PConfig::get(local_user(), "pumpio", "user");
243 /* Add some HTML to the existing form */
245 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
246 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
248 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
249 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
250 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
253 $s .= '<div id="pumpio-username-wrapper">';
254 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
255 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
256 $s .= '</div><div class="clear"></div>';
258 $s .= '<div id="pumpio-servername-wrapper">';
259 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
260 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
261 $s .= '</div><div class="clear"></div>';
263 if (($username != '') && ($servername != '')) {
265 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
266 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
268 $s .= '<div id="pumpio-password-wrapper">';
269 if (($oauth_token == "") || ($oauth_token_secret == "")) {
270 $s .= '<div id="pumpio-authenticate-wrapper">';
271 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
272 $s .= '</div><div class="clear"></div>';
274 $s .= '<div id="pumpio-import-wrapper">';
275 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
276 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
277 $s .= '</div><div class="clear"></div>';
279 $s .= '<div id="pumpio-enable-wrapper">';
280 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Addon') . '</label>';
281 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
282 $s .= '</div><div class="clear"></div>';
284 $s .= '<div id="pumpio-bydefault-wrapper">';
285 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
286 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
287 $s .= '</div><div class="clear"></div>';
289 $s .= '<div id="pumpio-public-wrapper">';
290 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
291 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
292 $s .= '</div><div class="clear"></div>';
294 $s .= '<div id="pumpio-mirror-wrapper">';
295 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
296 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
297 $s .= '</div><div class="clear"></div>';
299 $s .= '<div id="pumpio-delete-wrapper">';
300 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
301 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
302 $s .= '</div><div class="clear"></div>';
305 $s .= '</div><div class="clear"></div>';
308 /* provide a submit button */
310 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
314 function pumpio_settings_post(&$a,&$b) {
316 if(x($_POST,'pumpio-submit')) {
317 if(x($_POST,'pumpio_delete')) {
318 PConfig::set(local_user(),'pumpio','consumer_key','');
319 PConfig::set(local_user(),'pumpio','consumer_secret','');
320 PConfig::set(local_user(),'pumpio','oauth_token','');
321 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
322 PConfig::set(local_user(),'pumpio','post',false);
323 PConfig::set(local_user(),'pumpio','import',false);
324 PConfig::set(local_user(),'pumpio','host','');
325 PConfig::set(local_user(),'pumpio','user','');
326 PConfig::set(local_user(),'pumpio','public',false);
327 PConfig::set(local_user(),'pumpio','mirror',false);
328 PConfig::set(local_user(),'pumpio','post_by_default',false);
329 PConfig::set(local_user(),'pumpio','lastdate', 0);
330 PConfig::set(local_user(),'pumpio','last_id', '');
332 // filtering the username if it is filled wrong
333 $user = $_POST['pumpio_user'];
334 if (strstr($user, "@")) {
335 $pos = strpos($user, "@");
337 $user = substr($user, 0, $pos);
340 // Filtering the hostname if someone is entering it with "http"
341 $host = $_POST['pumpio_host'];
343 $host = str_replace(["https://", "http://"], ["", ""], $host);
345 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
346 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
347 PConfig::set(local_user(),'pumpio','host',$host);
348 PConfig::set(local_user(),'pumpio','user',$user);
349 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
350 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
351 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
353 if (!$_POST['pumpio_mirror'])
354 PConfig::delete(local_user(),'pumpio','lastdate');
356 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
361 function pumpio_post_local(&$a, &$b) {
363 if (!local_user() || (local_user() != $b['uid'])) {
367 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
369 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
371 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
375 if (!$pumpio_enable) {
379 if (strlen($b['postopts'])) {
380 $b['postopts'] .= ',';
383 $b['postopts'] .= 'pumpio';
389 function pumpio_send(&$a,&$b) {
391 if (!PConfig::get($b["uid"],'pumpio','import')) {
392 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
396 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
398 if($b['parent'] != $b['id']) {
399 // Looking if its a reply to a pumpio post
400 $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",
401 intval($b["parent"]),
403 dbesc(NETWORK_PUMPIO));
406 logger("pumpio_send: no pumpio post ".$b["parent"]);
415 $receiver = pumpio_getreceiver($a, $b);
417 logger("pumpio_send: receiver ".print_r($receiver, true));
419 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio'))) {
423 // Dont't post if the post doesn't belong to us.
424 // This is a check for forum postings
425 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
426 if ($b['contact-id'] != $self['id']) {
431 if($b['verb'] == ACTIVITY_LIKE) {
433 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
435 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
439 if($b['verb'] == ACTIVITY_DISLIKE)
442 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
443 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
445 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
446 pumpio_action($a, $b["uid"], $b["uri"], "delete");
448 if($b['deleted'] || ($b['created'] !== $b['edited']))
451 // if post comes from pump.io don't send it back
452 if($b['app'] == "pump.io")
456 // Support for native shares
457 // http://<hostname>/api/<type>/shares?id=<the-object-id>
459 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
460 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
461 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
462 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
464 $host = PConfig::get($b['uid'], "pumpio", "host");
465 $user = PConfig::get($b['uid'], "pumpio", "user");
466 $public = PConfig::get($b['uid'], "pumpio", "public");
468 if($oauth_token && $oauth_token_secret) {
470 require_once('include/bbcode.php');
472 $title = trim($b['title']);
474 $content = bbcode($b['body'], false, false, 4);
478 $params["verb"] = "post";
481 $params["object"] = [
482 'objectType' => "note",
483 'content' => $content];
486 $params["object"]["displayName"] = $title;
488 if (count($receiver["to"]))
489 $params["to"] = $receiver["to"];
491 if (count($receiver["bto"]))
492 $params["bto"] = $receiver["bto"];
494 if (count($receiver["cc"]))
495 $params["cc"] = $receiver["cc"];
497 if (count($receiver["bcc"]))
498 $params["bcc"] = $receiver["bcc"];
501 $inReplyTo = ["id" => $orig_post["uri"],
502 "objectType" => "note"];
504 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
505 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
507 $params["object"] = [
508 'objectType' => "comment",
509 'content' => $content,
510 'inReplyTo' => $inReplyTo];
513 $params["object"]["displayName"] = $title;
516 $client = new oauth_client_class;
517 $client->oauth_version = '1.0a';
518 $client->url_parameters = false;
519 $client->authorization_header = true;
520 $client->access_token = $oauth_token;
521 $client->access_token_secret = $oauth_token_secret;
522 $client->client_id = $consumer_key;
523 $client->client_secret = $consumer_secret;
525 $username = $user.'@'.$host;
526 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
528 if (pumpio_reachable($url))
529 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
535 if ($user->generator->displayName)
536 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
538 $post_id = $user->object->id;
539 logger('pumpio_send '.$username.': success '.$post_id);
540 if($post_id && $iscomment) {
541 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
542 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
548 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
550 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
552 $a->contact = $r[0]["id"];
554 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
556 Queue::add($a->contact, NETWORK_PUMPIO, $s);
557 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]);
632 Queue::add($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 foreach($qi as $x) {
1437 if($x['network'] !== NETWORK_PUMPIO)
1440 logger('pumpio_queue: run');
1442 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1443 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1451 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1453 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1454 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1455 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1456 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1458 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1459 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1463 if ($oauth_token && $oauth_token_secret &&
1464 $consumer_key && $consumer_secret) {
1465 $username = $user.'@'.$host;
1467 logger('pumpio_queue: able to post for user '.$username);
1469 $z = unserialize($x['content']);
1471 $client = new oauth_client_class;
1472 $client->oauth_version = '1.0a';
1473 $client->url_parameters = false;
1474 $client->authorization_header = true;
1475 $client->access_token = $oauth_token;
1476 $client->access_token_secret = $oauth_token_secret;
1477 $client->client_id = $consumer_key;
1478 $client->client_secret = $consumer_secret;
1480 if (pumpio_reachable($z['url']))
1481 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1486 $post_id = $user->object->id;
1487 logger('pumpio_queue: send '.$username.': success '.$post_id);
1488 if($post_id && $iscomment) {
1489 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1490 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1495 Queue::removeItem($x['id']);
1497 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1499 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1502 logger('pumpio_queue: delayed');
1503 Queue::updateTime($x['id']);
1508 function pumpio_getreceiver(&$a, $b) {
1512 if (!$b["private"]) {
1514 if(! strstr($b['postopts'],'pumpio'))
1517 $public = PConfig::get($b['uid'], "pumpio", "public");
1520 $receiver["to"][] = [
1521 "objectType" => "collection",
1522 "id" => "http://activityschema.org/collection/public"];
1524 $cids = explode("><", $b["allow_cid"]);
1525 $gids = explode("><", $b["allow_gid"]);
1527 foreach ($cids AS $cid) {
1528 $cid = trim($cid, " <>");
1530 $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",
1533 dbesc(NETWORK_PUMPIO)
1537 $receiver["bcc"][] = [
1538 "displayName" => $r[0]["name"],
1539 "objectType" => "person",
1540 "preferredUsername" => $r[0]["nick"],
1541 "url" => $r[0]["url"]];
1544 foreach ($gids AS $gid) {
1545 $gid = trim($gid, " <>");
1547 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1548 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1549 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1551 dbesc(NETWORK_PUMPIO)
1554 foreach ($r AS $row)
1555 $receiver["bcc"][] = [
1556 "displayName" => $row["name"],
1557 "objectType" => "person",
1558 "preferredUsername" => $row["nick"],
1559 "url" => $row["url"]];
1563 if ($b["inform"] != "") {
1565 $inform = explode(",", $b["inform"]);
1567 foreach ($inform AS $cid) {
1568 if (substr($cid, 0, 4) != "cid:")
1571 $cid = str_replace("cid:", "", $cid);
1573 $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",
1576 dbesc(NETWORK_PUMPIO)
1580 $receiver["to"][] = [
1581 "displayName" => $r[0]["name"],
1582 "objectType" => "person",
1583 "preferredUsername" => $r[0]["nick"],
1584 "url" => $r[0]["url"]];
1592 function pumpio_fetchallcomments(&$a, $uid, $id) {
1593 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1594 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1595 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1596 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1597 $hostname = PConfig::get($uid, 'pumpio','host');
1598 $username = PConfig::get($uid, "pumpio", "user");
1600 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1602 $own_id = "https://".$hostname."/".$username;
1604 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1607 // Fetching the original post
1608 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1616 $url = $r[0]["extid"];
1618 $client = new oauth_client_class;
1619 $client->oauth_version = '1.0a';
1620 $client->authorization_header = true;
1621 $client->url_parameters = false;
1623 $client->client_id = $ckey;
1624 $client->client_secret = $csecret;
1625 $client->access_token = $otoken;
1626 $client->access_token_secret = $osecret;
1628 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1630 if (pumpio_reachable($url))
1631 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1638 if ($item->likes->totalItems != 0) {
1639 foreach ($item->likes->items AS $post) {
1640 $like = new stdClass;
1641 $like->object = new stdClass;
1642 $like->object->id = $item->id;
1643 $like->actor = new stdClass;
1644 $like->actor->displayName = $item->displayName;
1645 $like->actor->preferredUsername = $item->preferredUsername;
1646 $like->actor->url = $item->url;
1647 $like->actor->image = $item->image;
1648 $like->generator = new stdClass;
1649 $like->generator->displayName = "pumpio";
1650 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1654 if ($item->replies->totalItems == 0)
1657 foreach ($item->replies->items AS $item) {
1658 if ($item->id == $id)
1661 // Checking if the comment already exists - Two queries for speed issues
1662 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1670 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1678 $post = new stdClass;
1679 $post->verb = "post";
1680 $post->actor = $item->author;
1681 $post->published = $item->published;
1682 $post->received = $item->updated;
1683 $post->generator = new stdClass;
1684 $post->generator->displayName = "pumpio";
1685 // To-Do: Check for public post
1687 unset($item->author);
1688 unset($item->published);
1689 unset($item->updated);
1691 $post->object = $item;
1693 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1694 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1699 function pumpio_reachable($url) {
1700 $data = z_fetch_url($url, false, $redirects, ['timeout'=>10]);
1701 return(intval($data['return_code']) != 0);