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\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\Worker;
13 use Friendica\Model\Contact;
14 use Friendica\Model\GContact;
15 use Friendica\Model\Group;
16 use Friendica\Model\User;
17 use Friendica\Model\Item;
18 use Friendica\Model\Queue;
19 use Friendica\Util\Network;
21 require 'addon/pumpio/oauth/http.php';
22 require 'addon/pumpio/oauth/oauth_client.php';
23 require_once 'include/enotify.php';
24 require_once "mod/share.php";
26 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
28 function pumpio_install() {
29 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
30 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
31 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
32 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
33 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
34 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
35 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
36 Addon::registerHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
39 function pumpio_uninstall() {
40 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
41 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
42 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
43 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
44 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
45 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
46 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
47 Addon::unregisterHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
50 function pumpio_module() {}
52 function pumpio_content(&$a) {
55 notice(L10n::t('Permission denied.') . EOL);
59 require_once("mod/settings.php");
62 if (isset($a->argv[1]))
63 switch ($a->argv[1]) {
65 $o = pumpio_connect($a);
68 $o = print_r($a->argv, true);
72 $o = pumpio_connect($a);
77 function pumpio_check_item_notification($a, &$notification_data) {
78 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
79 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
81 $notification_data["profiles"][] = "https://".$hostname."/".$username;
85 function pumpio_registerclient(&$a, $host) {
87 $url = "https://".$host."/api/client/register";
91 $application_name = Config::get('pumpio', 'application_name');
93 if ($application_name == "")
94 $application_name = $a->get_hostname();
96 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
98 $params["type"] = "client_associate";
99 $params["contacts"] = $adminlist[0];
100 $params["application_type"] = "native";
101 $params["application_name"] = $application_name;
102 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
103 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
105 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
107 $ch = curl_init($url);
108 curl_setopt($ch, CURLOPT_HEADER, false);
109 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
110 curl_setopt($ch, CURLOPT_POST,1);
111 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
112 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
115 $curl_info = curl_getinfo($ch);
117 if ($curl_info["http_code"] == "200") {
118 $values = json_decode($s);
119 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
122 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
127 function pumpio_connect(&$a) {
128 // Start a session. This is necessary to hold on to a few keys the callback script will also need
131 // Define the needed keys
132 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
133 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
134 $hostname = PConfig::get(local_user(), 'pumpio','host');
136 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
137 logger("pumpio_connect: register client");
138 $clientdata = pumpio_registerclient($a, $hostname);
139 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
140 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
142 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
143 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
145 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
148 if (($consumer_key == "") || ($consumer_secret == "")) {
149 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
151 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
155 // The callback URL is the script that gets called after the user authenticates with pumpio
156 $callback_url = $a->get_baseurl()."/pumpio/connect";
158 // Let's begin. First we need a Request Token. The request token is required to send the user
159 // to pumpio's login page.
161 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
162 // Consumer Key and Consumer Secret
163 $client = new oauth_client_class;
165 $client->server = '';
166 $client->oauth_version = '1.0a';
167 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
168 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
169 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
170 $client->url_parameters = false;
171 $client->authorization_header = true;
172 $client->redirect_uri = $callback_url;
173 $client->client_id = $consumer_key;
174 $client->client_secret = $consumer_secret;
176 if (($success = $client->Initialize())) {
177 if (($success = $client->Process())) {
178 if (strlen($client->access_token)) {
179 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
180 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
181 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
184 $success = $client->Finalize($success);
187 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
190 logger("pumpio_connect: authenticated");
191 $o .= L10n::t("You are now authenticated to pumpio.");
192 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
194 logger("pumpio_connect: could not connect");
195 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
201 function pumpio_jot_nets(&$a,&$b) {
205 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
206 if(intval($pumpio_post) == 1) {
207 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
208 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
209 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
210 . L10n::t('Post to pumpio') . '</div>';
215 function pumpio_settings(&$a,&$s) {
220 /* Add our stylesheet to the page so we can make our settings look nice */
222 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
224 /* Get the current state of our config variables */
226 $import_enabled = PConfig::get(local_user(),'pumpio','import');
227 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
229 $enabled = PConfig::get(local_user(),'pumpio','post');
230 $checked = (($enabled) ? ' checked="checked" ' : '');
231 $css = (($enabled) ? '' : '-disabled');
233 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
234 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
236 $public_enabled = PConfig::get(local_user(),'pumpio','public');
237 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
239 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
240 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
242 $servername = PConfig::get(local_user(), "pumpio", "host");
243 $username = PConfig::get(local_user(), "pumpio", "user");
245 /* Add some HTML to the existing form */
247 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
248 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
250 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
251 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
252 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
255 $s .= '<div id="pumpio-username-wrapper">';
256 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
257 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
258 $s .= '</div><div class="clear"></div>';
260 $s .= '<div id="pumpio-servername-wrapper">';
261 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
262 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
263 $s .= '</div><div class="clear"></div>';
265 if (($username != '') && ($servername != '')) {
267 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
268 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
270 $s .= '<div id="pumpio-password-wrapper">';
271 if (($oauth_token == "") || ($oauth_token_secret == "")) {
272 $s .= '<div id="pumpio-authenticate-wrapper">';
273 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
274 $s .= '</div><div class="clear"></div>';
276 $s .= '<div id="pumpio-import-wrapper">';
277 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
278 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
279 $s .= '</div><div class="clear"></div>';
281 $s .= '<div id="pumpio-enable-wrapper">';
282 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
283 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
284 $s .= '</div><div class="clear"></div>';
286 $s .= '<div id="pumpio-bydefault-wrapper">';
287 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
288 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
289 $s .= '</div><div class="clear"></div>';
291 $s .= '<div id="pumpio-public-wrapper">';
292 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
293 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
294 $s .= '</div><div class="clear"></div>';
296 $s .= '<div id="pumpio-mirror-wrapper">';
297 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
298 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
299 $s .= '</div><div class="clear"></div>';
301 $s .= '<div id="pumpio-delete-wrapper">';
302 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
303 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
304 $s .= '</div><div class="clear"></div>';
307 $s .= '</div><div class="clear"></div>';
310 /* provide a submit button */
312 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div></div>';
316 function pumpio_settings_post(&$a,&$b) {
318 if(x($_POST,'pumpio-submit')) {
319 if(x($_POST,'pumpio_delete')) {
320 PConfig::set(local_user(),'pumpio','consumer_key','');
321 PConfig::set(local_user(),'pumpio','consumer_secret','');
322 PConfig::set(local_user(),'pumpio','oauth_token','');
323 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
324 PConfig::set(local_user(),'pumpio','post',false);
325 PConfig::set(local_user(),'pumpio','import',false);
326 PConfig::set(local_user(),'pumpio','host','');
327 PConfig::set(local_user(),'pumpio','user','');
328 PConfig::set(local_user(),'pumpio','public',false);
329 PConfig::set(local_user(),'pumpio','mirror',false);
330 PConfig::set(local_user(),'pumpio','post_by_default',false);
331 PConfig::set(local_user(),'pumpio','lastdate', 0);
332 PConfig::set(local_user(),'pumpio','last_id', '');
334 // filtering the username if it is filled wrong
335 $user = $_POST['pumpio_user'];
336 if (strstr($user, "@")) {
337 $pos = strpos($user, "@");
339 $user = substr($user, 0, $pos);
342 // Filtering the hostname if someone is entering it with "http"
343 $host = $_POST['pumpio_host'];
345 $host = str_replace(["https://", "http://"], ["", ""], $host);
347 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
348 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
349 PConfig::set(local_user(),'pumpio','host',$host);
350 PConfig::set(local_user(),'pumpio','user',$user);
351 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
352 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
353 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
355 if (!$_POST['pumpio_mirror'])
356 PConfig::delete(local_user(),'pumpio','lastdate');
358 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
363 function pumpio_post_local(&$a, &$b) {
365 if (!local_user() || (local_user() != $b['uid'])) {
369 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
371 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
373 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
377 if (!$pumpio_enable) {
381 if (strlen($b['postopts'])) {
382 $b['postopts'] .= ',';
385 $b['postopts'] .= 'pumpio';
391 function pumpio_send(&$a,&$b) {
393 if (!PConfig::get($b["uid"],'pumpio','import')) {
394 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
398 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
400 if($b['parent'] != $b['id']) {
401 // Looking if its a reply to a pumpio post
402 $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",
403 intval($b["parent"]),
405 dbesc(NETWORK_PUMPIO));
408 logger("pumpio_send: no pumpio post ".$b["parent"]);
417 $receiver = pumpio_getreceiver($a, $b);
419 logger("pumpio_send: receiver ".print_r($receiver, true));
421 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio'))) {
425 // Dont't post if the post doesn't belong to us.
426 // This is a check for forum postings
427 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
428 if ($b['contact-id'] != $self['id']) {
433 if($b['verb'] == ACTIVITY_LIKE) {
435 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
437 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
441 if($b['verb'] == ACTIVITY_DISLIKE)
444 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
445 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
447 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
448 pumpio_action($a, $b["uid"], $b["uri"], "delete");
450 if($b['deleted'] || ($b['created'] !== $b['edited']))
453 // if post comes from pump.io don't send it back
454 if($b['app'] == "pump.io")
458 // Support for native shares
459 // http://<hostname>/api/<type>/shares?id=<the-object-id>
461 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
462 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
463 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
464 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
466 $host = PConfig::get($b['uid'], "pumpio", "host");
467 $user = PConfig::get($b['uid'], "pumpio", "user");
468 $public = PConfig::get($b['uid'], "pumpio", "public");
470 if($oauth_token && $oauth_token_secret) {
472 require_once('include/bbcode.php');
474 $title = trim($b['title']);
476 $content = bbcode($b['body'], false, false, 4);
480 $params["verb"] = "post";
483 $params["object"] = [
484 'objectType' => "note",
485 'content' => $content];
488 $params["object"]["displayName"] = $title;
490 if (count($receiver["to"]))
491 $params["to"] = $receiver["to"];
493 if (count($receiver["bto"]))
494 $params["bto"] = $receiver["bto"];
496 if (count($receiver["cc"]))
497 $params["cc"] = $receiver["cc"];
499 if (count($receiver["bcc"]))
500 $params["bcc"] = $receiver["bcc"];
503 $inReplyTo = ["id" => $orig_post["uri"],
504 "objectType" => "note"];
506 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
507 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
509 $params["object"] = [
510 'objectType' => "comment",
511 'content' => $content,
512 'inReplyTo' => $inReplyTo];
515 $params["object"]["displayName"] = $title;
518 $client = new oauth_client_class;
519 $client->oauth_version = '1.0a';
520 $client->url_parameters = false;
521 $client->authorization_header = true;
522 $client->access_token = $oauth_token;
523 $client->access_token_secret = $oauth_token_secret;
524 $client->client_id = $consumer_key;
525 $client->client_secret = $consumer_secret;
527 $username = $user.'@'.$host;
528 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
530 if (pumpio_reachable($url))
531 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
537 if ($user->generator->displayName)
538 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
540 $post_id = $user->object->id;
541 logger('pumpio_send '.$username.': success '.$post_id);
542 if($post_id && $iscomment) {
543 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
544 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
550 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
552 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
554 $a->contact = $r[0]["id"];
556 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
558 Queue::add($a->contact, NETWORK_PUMPIO, $s);
559 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
564 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
566 // Don't do likes and other stuff if you don't import the timeline
567 if (!PConfig::get($uid,'pumpio','import'))
570 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
571 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
572 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
573 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
574 $hostname = PConfig::get($uid, 'pumpio','host');
575 $username = PConfig::get($uid, "pumpio", "user");
577 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
587 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
588 $uri = $orig_post["extid"];
590 $uri = $orig_post["uri"];
592 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
593 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
594 elseif (strstr($uri, "/api/comment/"))
595 $objectType = "comment";
596 elseif (strstr($uri, "/api/note/"))
597 $objectType = "note";
598 elseif (strstr($uri, "/api/image/"))
599 $objectType = "image";
601 $params["verb"] = $action;
602 $params["object"] = ['id' => $uri,
603 "objectType" => $objectType,
604 "content" => $content];
606 $client = new oauth_client_class;
607 $client->oauth_version = '1.0a';
608 $client->authorization_header = true;
609 $client->url_parameters = false;
611 $client->client_id = $ckey;
612 $client->client_secret = $csecret;
613 $client->access_token = $otoken;
614 $client->access_token_secret = $osecret;
616 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
618 if (pumpio_reachable($url))
619 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
624 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
626 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
628 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
630 $a->contact = $r[0]["id"];
632 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
634 Queue::add($a->contact, NETWORK_PUMPIO, $s);
635 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
639 function pumpio_sync(&$a) {
640 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
646 $last = Config::get('pumpio','last_poll');
648 $poll_interval = intval(Config::get('pumpio','poll_interval'));
650 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
653 $next = $last + ($poll_interval * 60);
655 logger('pumpio: poll intervall not reached');
659 logger('pumpio: cron_start');
661 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
664 logger('pumpio: mirroring user '.$rr['uid']);
665 pumpio_fetchtimeline($a, $rr['uid']);
669 $abandon_days = intval(Config::get('system','account_abandon_days'));
670 if ($abandon_days < 1)
673 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
675 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
678 if ($abandon_days != 0) {
679 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
681 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
686 logger('pumpio: importing timeline from user '.$rr['uid']);
687 pumpio_fetchinbox($a, $rr['uid']);
689 // check for new contacts once a day
690 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
691 if($last_contact_check)
692 $next_contact_check = $last_contact_check + 86400;
694 $next_contact_check = 0;
696 if($next_contact_check <= time()) {
697 pumpio_getallusers($a, $rr["uid"]);
698 PConfig::set($rr['uid'],'pumpio','contact_check',time());
703 logger('pumpio: cron_end');
705 Config::set('pumpio','last_poll', time());
708 function pumpio_cron(&$a,$b) {
709 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
712 function pumpio_fetchtimeline(&$a, $uid) {
713 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
714 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
715 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
716 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
717 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
718 $hostname = PConfig::get($uid, 'pumpio','host');
719 $username = PConfig::get($uid, "pumpio", "user");
721 // get the application name for the pump.io app
722 // 1st try personal config, then system config and fallback to the
723 // hostname of the node if neither one is set.
724 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
725 if ($application_name == "")
726 $application_name = Config::get('pumpio', 'application_name');
727 if ($application_name == "")
728 $application_name = $a->get_hostname();
730 $first_time = ($lastdate == "");
732 $client = new oauth_client_class;
733 $client->oauth_version = '1.0a';
734 $client->authorization_header = true;
735 $client->url_parameters = false;
737 $client->client_id = $ckey;
738 $client->client_secret = $csecret;
739 $client->access_token = $otoken;
740 $client->access_token_secret = $osecret;
742 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
744 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
746 $username = $user.'@'.$host;
748 if (pumpio_reachable($url))
749 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
754 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
758 $posts = array_reverse($user->items);
760 $initiallastdate = $lastdate;
764 foreach ($posts as $post) {
765 if ($post->published <= $initiallastdate)
768 if ($lastdate < $post->published)
769 $lastdate = $post->published;
775 if (@is_array($post->cc))
776 $receiptians = array_merge($receiptians, $post->cc);
778 if (@is_array($post->to))
779 $receiptians = array_merge($receiptians, $post->to);
782 foreach ($receiptians AS $receiver)
783 if (is_string($receiver->objectType))
784 if ($receiver->id == "http://activityschema.org/collection/public")
787 if ($public && !stristr($post->generator->displayName, $application_name)) {
788 require_once('include/html2bbcode.php');
790 $_SESSION["authenticated"] = true;
791 $_SESSION["uid"] = $uid;
794 $_REQUEST["type"] = "wall";
795 $_REQUEST["api_source"] = true;
796 $_REQUEST["profile_uid"] = $uid;
797 $_REQUEST["source"] = "pump.io";
799 if (isset($post->object->id)) {
800 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
803 if ($post->object->displayName != "")
804 $_REQUEST["title"] = html2bbcode($post->object->displayName);
806 $_REQUEST["title"] = "";
808 $_REQUEST["body"] = html2bbcode($post->object->content);
810 // To-Do: Picture has to be cached and stored locally
811 if ($post->object->fullImage->url != "") {
812 if ($post->object->fullImage->pump_io->proxyURL != "")
813 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
815 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
818 logger('pumpio: posting for user '.$uid);
820 require_once('mod/item.php');
823 logger('pumpio: posting done - user '.$uid);
829 PConfig::set($uid,'pumpio','lastdate', $lastdate);
832 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
833 // Searching for the unliked post
834 // Two queries for speed issues
835 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
836 dbesc($post->object->id),
843 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
844 dbesc($post->object->id),
856 if(link_compare($post->actor->url, $own_id)) {
857 $contactid = $self[0]['id'];
859 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
860 dbesc(normalise_link($post->actor->url)),
865 $contactid = $r[0]['id'];
868 $contactid = $orig_post['contact-id'];
871 $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'",
872 dbesc(datetime_convert()),
873 dbesc(ACTIVITY_LIKE),
876 dbesc($orig_post['uri'])
880 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
882 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
885 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
886 require_once('include/items.php');
888 if ($post->object->id == "") {
889 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
893 // Searching for the liked post
894 // Two queries for speed issues
895 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
896 dbesc($post->object->id),
898 dbesc(NETWORK_PUMPIO)
904 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
905 dbesc($post->object->id),
907 dbesc(NETWORK_PUMPIO)
917 if ($threadcompletion)
918 pumpio_fetchallcomments($a, $uid, $post->object->id);
922 if(link_compare($post->actor->url, $own_id)) {
923 $contactid = $self[0]['id'];
924 $post->actor->displayName = $self[0]['name'];
925 $post->actor->url = $self[0]['url'];
926 $post->actor->image->url = $self[0]['photo'];
928 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
929 dbesc(normalise_link($post->actor->url)),
934 $contactid = $r[0]['id'];
937 $contactid = $orig_post['contact-id'];
940 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
941 dbesc(ACTIVITY_LIKE),
944 dbesc($orig_post['uri'])
948 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
953 $likedata['parent'] = $orig_post['id'];
954 $likedata['verb'] = ACTIVITY_LIKE;
955 $likedata['gravity'] = 3;
956 $likedata['uid'] = $uid;
957 $likedata['wall'] = 0;
958 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
959 $likedata['parent-uri'] = $orig_post["uri"];
960 $likedata['contact-id'] = $contactid;
961 $likedata['app'] = $post->generator->displayName;
962 $likedata['author-name'] = $post->actor->displayName;
963 $likedata['author-link'] = $post->actor->url;
964 $likedata['author-avatar'] = $post->actor->image->url;
966 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
967 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
968 $post_type = L10n::t('status');
969 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
970 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
972 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
974 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
975 '<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>';
977 $ret = Item::insert($likedata);
979 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
982 function pumpio_get_contact($uid, $contact, $no_insert = false) {
984 GContact::update(["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
985 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
986 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
987 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)]);
988 $cid = Contact::getIdForURL($contact->url, $uid);
993 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
994 intval($uid), dbesc(normalise_link($contact->url)));
997 // create contact record
998 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
999 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1000 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1001 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1003 dbesc(datetime_convert()),
1004 dbesc($contact->url),
1005 dbesc(normalise_link($contact->url)),
1006 dbesc(str_replace("acct:", "", $contact->id)),
1008 dbesc($contact->id), // What is it for?
1009 dbesc('pump.io ' . $contact->id), // What is it for?
1010 dbesc($contact->displayName),
1011 dbesc($contact->preferredUsername),
1012 dbesc($contact->image->url),
1013 dbesc(NETWORK_PUMPIO),
1014 intval(CONTACT_IS_FRIEND),
1016 dbesc($contact->location->displayName),
1017 dbesc($contact->summary),
1021 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1022 dbesc(normalise_link($contact->url)),
1030 $contact_id = $r[0]['id'];
1032 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1034 $contact_id = $r[0]["id"];
1036 /* if (DB_UPDATE_VERSION >= "1177")
1037 q("UPDATE `contact` SET `location` = '%s',
1040 dbesc($contact->location->displayName),
1041 dbesc($contact->summary),
1047 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1049 return($contact_id);
1052 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1054 // Two queries for speed issues
1055 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1056 dbesc($post->object->id),
1061 return Item::delete($r[0]["id"]);
1063 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1064 dbesc($post->object->id),
1069 return Item::delete($r[0]["id"]);
1072 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1073 require_once('include/items.php');
1074 require_once('include/html2bbcode.php');
1076 if (($post->verb == "like") || ($post->verb == "favorite"))
1077 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1079 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1080 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1082 if ($post->verb == "delete")
1083 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1085 if ($post->verb != "update") {
1086 // Two queries for speed issues
1087 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1088 dbesc($post->object->id),
1095 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1096 dbesc($post->object->id),
1104 // Only handle these three types
1105 if (!strstr("post|share|update", $post->verb))
1109 if (@is_array($post->cc))
1110 $receiptians = array_merge($receiptians, $post->cc);
1112 if (@is_array($post->to))
1113 $receiptians = array_merge($receiptians, $post->to);
1115 foreach ($receiptians AS $receiver)
1116 if (is_string($receiver->objectType))
1117 if ($receiver->id == "http://activityschema.org/collection/public")
1121 $postarray['network'] = NETWORK_PUMPIO;
1122 $postarray['gravity'] = 0;
1123 $postarray['uid'] = $uid;
1124 $postarray['wall'] = 0;
1125 $postarray['uri'] = $post->object->id;
1126 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1128 if ($post->object->objectType != "comment") {
1129 $contact_id = pumpio_get_contact($uid, $post->actor);
1132 $contact_id = $self[0]['id'];
1134 $postarray['parent-uri'] = $post->object->id;
1137 $postarray['private'] = 1;
1138 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1141 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1143 if (link_compare($post->actor->url, $own_id)) {
1144 $contact_id = $self[0]['id'];
1145 $post->actor->displayName = $self[0]['name'];
1146 $post->actor->url = $self[0]['url'];
1147 $post->actor->image->url = $self[0]['photo'];
1148 } elseif ($contact_id == 0) {
1149 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1150 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1151 dbesc(normalise_link($post->actor->url)),
1156 $contact_id = $r[0]['id'];
1158 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1159 dbesc(normalise_link($post->actor->url)),
1164 $contact_id = $r[0]['id'];
1166 $contact_id = $self[0]['id'];
1170 $reply = new stdClass;
1171 $reply->verb = "note";
1172 $reply->cc = $post->cc;
1173 $reply->to = $post->to;
1174 $reply->object = new stdClass;
1175 $reply->object->objectType = $post->object->inReplyTo->objectType;
1176 $reply->object->content = $post->object->inReplyTo->content;
1177 $reply->object->id = $post->object->inReplyTo->id;
1178 $reply->actor = $post->object->inReplyTo->author;
1179 $reply->url = $post->object->inReplyTo->url;
1180 $reply->generator = new stdClass;
1181 $reply->generator->displayName = "pumpio";
1182 $reply->published = $post->object->inReplyTo->published;
1183 $reply->received = $post->object->inReplyTo->updated;
1184 $reply->url = $post->object->inReplyTo->url;
1185 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1187 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1190 if ($post->object->pump_io->proxyURL)
1191 $postarray['extid'] = $post->object->pump_io->proxyURL;
1193 $postarray['contact-id'] = $contact_id;
1194 $postarray['verb'] = ACTIVITY_POST;
1195 $postarray['owner-name'] = $post->actor->displayName;
1196 $postarray['owner-link'] = $post->actor->url;
1197 $postarray['owner-avatar'] = $post->actor->image->url;
1198 $postarray['author-name'] = $post->actor->displayName;
1199 $postarray['author-link'] = $post->actor->url;
1200 $postarray['author-avatar'] = $post->actor->image->url;
1201 $postarray['plink'] = $post->object->url;
1202 $postarray['app'] = $post->generator->displayName;
1203 $postarray['body'] = html2bbcode($post->object->content);
1204 $postarray['object'] = json_encode($post);
1206 if ($post->object->fullImage->url != "")
1207 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1209 if ($post->object->displayName != "")
1210 $postarray['title'] = $post->object->displayName;
1212 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1213 if (isset($post->updated))
1214 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1215 elseif (isset($post->received))
1216 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1218 $postarray['edited'] = $postarray['created'];
1220 if ($post->verb == "share") {
1221 if (!intval(Config::get('system','wall-to-wall_share'))) {
1222 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1223 $share_author = $post->object->author->displayName;
1224 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1225 $share_author = $post->object->author->preferredUsername;
1227 $share_author = $post->object->author->url;
1229 $postarray['body'] = share_header($share_author, $post->object->author->url,
1230 $post->object->author->image->url, "",
1231 datetime_convert('UTC','UTC',$post->object->created),
1232 $post->links->self->href).
1233 $postarray['body']."[/share]";
1236 $postarray['body'] = "[share author='".$share_author.
1237 "' profile='".$post->object->author->url.
1238 "' avatar='".$post->object->author->image->url.
1239 "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1240 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1243 // Let shares look like wall-to-wall posts
1244 $postarray['author-name'] = $post->object->author->displayName;
1245 $postarray['author-link'] = $post->object->author->url;
1246 $postarray['author-avatar'] = $post->object->author->image->url;
1250 if (trim($postarray['body']) == "")
1253 $top_item = Item::insert($postarray);
1254 $postarray["id"] = $top_item;
1256 if (($top_item == 0) && ($post->verb == "update")) {
1257 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1258 dbesc($postarray["title"]),
1259 dbesc($postarray["body"]),
1260 dbesc($postarray["edited"]),
1261 dbesc($postarray["uri"]),
1266 if ($post->object->objectType == "comment") {
1268 if ($threadcompletion)
1269 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1271 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1278 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1280 if (link_compare($own_id, $postarray['author-link']))
1283 if (!function_exists("check_item_notification")) {
1284 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1285 dbesc($postarray['parent-uri']),
1289 if(count($myconv)) {
1291 foreach($myconv as $conv) {
1292 // now if we find a match, it means we're in this conversation
1294 if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1297 require_once('include/enotify.php');
1299 $conv_parent = $conv['parent'];
1302 'type' => NOTIFY_COMMENT,
1303 'notify_flags' => $user[0]['notify-flags'],
1304 'language' => $user[0]['language'],
1305 'to_name' => $user[0]['username'],
1306 'to_email' => $user[0]['email'],
1307 'uid' => $user[0]['uid'],
1308 'item' => $postarray,
1309 'link' => $a->get_baseurl().'/display/'.urlencode(Item::getGuidById($top_item)),
1310 'source_name' => $postarray['author-name'],
1311 'source_link' => $postarray['author-link'],
1312 'source_photo' => $postarray['author-avatar'],
1313 'verb' => ACTIVITY_POST,
1315 'parent' => $conv_parent,
1318 // only send one notification
1328 function pumpio_fetchinbox(&$a, $uid) {
1330 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1331 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1332 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1333 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1334 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1335 $hostname = PConfig::get($uid, 'pumpio','host');
1336 $username = PConfig::get($uid, "pumpio", "user");
1338 $own_id = "https://".$hostname."/".$username;
1340 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1343 $lastitems = q("SELECT `uri` FROM `thread`
1344 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1345 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1346 ORDER BY `thread`.`commented` DESC LIMIT 10",
1347 dbesc(NETWORK_PUMPIO),
1351 $client = new oauth_client_class;
1352 $client->oauth_version = '1.0a';
1353 $client->authorization_header = true;
1354 $client->url_parameters = false;
1356 $client->client_id = $ckey;
1357 $client->client_secret = $csecret;
1358 $client->access_token = $otoken;
1359 $client->access_token_secret = $osecret;
1361 $last_id = PConfig::get($uid,'pumpio','last_id');
1363 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1366 $url .= '?since='.urlencode($last_id);
1368 if (pumpio_reachable($url))
1369 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1374 $posts = array_reverse($user->items);
1377 foreach ($posts as $post) {
1378 $last_id = $post->id;
1379 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1383 foreach ($lastitems AS $item)
1384 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1386 PConfig::set($uid,'pumpio','last_id', $last_id);
1389 function pumpio_getallusers(&$a, $uid) {
1390 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1391 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1392 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1393 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1394 $hostname = PConfig::get($uid, 'pumpio','host');
1395 $username = PConfig::get($uid, "pumpio", "user");
1397 $client = new oauth_client_class;
1398 $client->oauth_version = '1.0a';
1399 $client->authorization_header = true;
1400 $client->url_parameters = false;
1402 $client->client_id = $ckey;
1403 $client->client_secret = $csecret;
1404 $client->access_token = $otoken;
1405 $client->access_token_secret = $osecret;
1407 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1409 if (pumpio_reachable($url))
1410 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1414 if ($users->totalItems > count($users->items)) {
1415 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1417 if (pumpio_reachable($url))
1418 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1423 if (is_array($users->items)) {
1424 foreach ($users->items AS $user) {
1425 pumpio_get_contact($uid, $user);
1430 function pumpio_queue_hook(&$a,&$b) {
1432 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1433 dbesc(NETWORK_PUMPIO)
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 Queue::removeItem($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 Queue::updateTime($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 = Network::curl($url, false, $redirects, ['timeout'=>10]);
1703 return(intval($data['return_code']) != 0);