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>
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Content\Text\HTML;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\Worker;
16 use Friendica\Model\Contact;
17 use Friendica\Model\GContact;
18 use Friendica\Model\Group;
19 use Friendica\Model\Item;
20 use Friendica\Model\Queue;
21 use Friendica\Model\User;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Network;
24 use Friendica\Database\DBM;
26 require 'addon/pumpio/oauth/http.php';
27 require 'addon/pumpio/oauth/oauth_client.php';
28 require_once 'include/enotify.php';
29 require_once "mod/share.php";
31 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
33 function pumpio_install() {
34 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
35 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
36 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
37 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
38 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
39 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
40 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
41 Addon::registerHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
44 function pumpio_uninstall() {
45 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
46 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
47 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
48 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
49 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
50 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
51 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
52 Addon::unregisterHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
55 function pumpio_module() {}
57 function pumpio_content(&$a) {
60 notice(L10n::t('Permission denied.') . EOL);
64 require_once("mod/settings.php");
67 if (isset($a->argv[1]))
68 switch ($a->argv[1]) {
70 $o = pumpio_connect($a);
73 $o = print_r($a->argv, true);
77 $o = pumpio_connect($a);
82 function pumpio_check_item_notification($a, &$notification_data) {
83 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
84 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
86 $notification_data["profiles"][] = "https://".$hostname."/".$username;
90 function pumpio_registerclient(&$a, $host) {
92 $url = "https://".$host."/api/client/register";
96 $application_name = Config::get('pumpio', 'application_name');
98 if ($application_name == "")
99 $application_name = $a->get_hostname();
101 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
103 $params["type"] = "client_associate";
104 $params["contacts"] = $adminlist[0];
105 $params["application_type"] = "native";
106 $params["application_name"] = $application_name;
107 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
108 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
110 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
112 $ch = curl_init($url);
113 curl_setopt($ch, CURLOPT_HEADER, false);
114 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
115 curl_setopt($ch, CURLOPT_POST,1);
116 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
117 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
120 $curl_info = curl_getinfo($ch);
122 if ($curl_info["http_code"] == "200") {
123 $values = json_decode($s);
124 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
127 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
132 function pumpio_connect(&$a) {
133 // Start a session. This is necessary to hold on to a few keys the callback script will also need
136 // Define the needed keys
137 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
138 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
139 $hostname = PConfig::get(local_user(), 'pumpio','host');
141 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
142 logger("pumpio_connect: register client");
143 $clientdata = pumpio_registerclient($a, $hostname);
144 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
145 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
147 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
148 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
150 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
153 if (($consumer_key == "") || ($consumer_secret == "")) {
154 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
156 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
160 // The callback URL is the script that gets called after the user authenticates with pumpio
161 $callback_url = $a->get_baseurl()."/pumpio/connect";
163 // Let's begin. First we need a Request Token. The request token is required to send the user
164 // to pumpio's login page.
166 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
167 // Consumer Key and Consumer Secret
168 $client = new oauth_client_class;
170 $client->server = '';
171 $client->oauth_version = '1.0a';
172 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
173 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
174 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
175 $client->url_parameters = false;
176 $client->authorization_header = true;
177 $client->redirect_uri = $callback_url;
178 $client->client_id = $consumer_key;
179 $client->client_secret = $consumer_secret;
181 if (($success = $client->Initialize())) {
182 if (($success = $client->Process())) {
183 if (strlen($client->access_token)) {
184 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
185 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
186 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
189 $success = $client->Finalize($success);
192 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
195 logger("pumpio_connect: authenticated");
196 $o .= L10n::t("You are now authenticated to pumpio.");
197 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
199 logger("pumpio_connect: could not connect");
200 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
206 function pumpio_jot_nets(&$a,&$b) {
210 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
211 if (intval($pumpio_post) == 1) {
212 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
213 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
214 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
215 . L10n::t('Post to pumpio') . '</div>';
220 function pumpio_settings(&$a,&$s) {
225 /* Add our stylesheet to the page so we can make our settings look nice */
227 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
229 /* Get the current state of our config variables */
231 $import_enabled = PConfig::get(local_user(),'pumpio','import');
232 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
234 $enabled = PConfig::get(local_user(),'pumpio','post');
235 $checked = (($enabled) ? ' checked="checked" ' : '');
236 $css = (($enabled) ? '' : '-disabled');
238 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
239 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
241 $public_enabled = PConfig::get(local_user(),'pumpio','public');
242 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
244 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
245 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
247 $servername = PConfig::get(local_user(), "pumpio", "host");
248 $username = PConfig::get(local_user(), "pumpio", "user");
250 /* Add some HTML to the existing form */
252 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
253 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
255 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
256 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
257 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
260 $s .= '<div id="pumpio-username-wrapper">';
261 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
262 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
263 $s .= '</div><div class="clear"></div>';
265 $s .= '<div id="pumpio-servername-wrapper">';
266 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
267 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
268 $s .= '</div><div class="clear"></div>';
270 if (($username != '') && ($servername != '')) {
272 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
273 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
275 $s .= '<div id="pumpio-password-wrapper">';
276 if (($oauth_token == "") || ($oauth_token_secret == "")) {
277 $s .= '<div id="pumpio-authenticate-wrapper">';
278 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
279 $s .= '</div><div class="clear"></div>';
281 $s .= '<div id="pumpio-import-wrapper">';
282 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
283 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
284 $s .= '</div><div class="clear"></div>';
286 $s .= '<div id="pumpio-enable-wrapper">';
287 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
288 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
289 $s .= '</div><div class="clear"></div>';
291 $s .= '<div id="pumpio-bydefault-wrapper">';
292 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
293 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
294 $s .= '</div><div class="clear"></div>';
296 $s .= '<div id="pumpio-public-wrapper">';
297 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
298 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
299 $s .= '</div><div class="clear"></div>';
301 $s .= '<div id="pumpio-mirror-wrapper">';
302 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
303 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
304 $s .= '</div><div class="clear"></div>';
306 $s .= '<div id="pumpio-delete-wrapper">';
307 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
308 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
309 $s .= '</div><div class="clear"></div>';
312 $s .= '</div><div class="clear"></div>';
315 /* provide a submit button */
317 $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>';
321 function pumpio_settings_post(&$a,&$b) {
323 if (x($_POST,'pumpio-submit')) {
324 if (x($_POST,'pumpio_delete')) {
325 PConfig::set(local_user(),'pumpio','consumer_key','');
326 PConfig::set(local_user(),'pumpio','consumer_secret','');
327 PConfig::set(local_user(),'pumpio','oauth_token','');
328 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
329 PConfig::set(local_user(),'pumpio','post',false);
330 PConfig::set(local_user(),'pumpio','import',false);
331 PConfig::set(local_user(),'pumpio','host','');
332 PConfig::set(local_user(),'pumpio','user','');
333 PConfig::set(local_user(),'pumpio','public',false);
334 PConfig::set(local_user(),'pumpio','mirror',false);
335 PConfig::set(local_user(),'pumpio','post_by_default',false);
336 PConfig::set(local_user(),'pumpio','lastdate', 0);
337 PConfig::set(local_user(),'pumpio','last_id', '');
339 // filtering the username if it is filled wrong
340 $user = $_POST['pumpio_user'];
341 if (strstr($user, "@")) {
342 $pos = strpos($user, "@");
344 $user = substr($user, 0, $pos);
347 // Filtering the hostname if someone is entering it with "http"
348 $host = $_POST['pumpio_host'];
350 $host = str_replace(["https://", "http://"], ["", ""], $host);
352 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
353 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
354 PConfig::set(local_user(),'pumpio','host',$host);
355 PConfig::set(local_user(),'pumpio','user',$user);
356 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
357 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
358 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
360 if (!$_POST['pumpio_mirror'])
361 PConfig::delete(local_user(),'pumpio','lastdate');
363 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
368 function pumpio_post_local(&$a, &$b) {
370 if (!local_user() || (local_user() != $b['uid'])) {
374 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
376 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
378 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
382 if (!$pumpio_enable) {
386 if (strlen($b['postopts'])) {
387 $b['postopts'] .= ',';
390 $b['postopts'] .= 'pumpio';
396 function pumpio_send(&$a,&$b) {
398 if (!PConfig::get($b["uid"],'pumpio','import')) {
399 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
403 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
405 if ($b['parent'] != $b['id']) {
406 // Looking if its a reply to a pumpio post
407 $condition = ['id' => $b['parent'], 'network' => NETWORK_PUMPIO];
408 $orig_post = Item::selectFirst([], $condition);
410 if (!DBM::is_result($orig_post)) {
411 logger("pumpio_send: no pumpio post ".$b["parent"]);
419 $receiver = pumpio_getreceiver($a, $b);
421 logger("pumpio_send: receiver ".print_r($receiver, true));
423 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio'))) {
427 // Dont't post if the post doesn't belong to us.
428 // This is a check for forum postings
429 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
430 if ($b['contact-id'] != $self['id']) {
435 if ($b['verb'] == ACTIVITY_LIKE) {
437 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
439 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
443 if ($b['verb'] == ACTIVITY_DISLIKE)
446 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
447 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
449 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
450 pumpio_action($a, $b["uid"], $b["uri"], "delete");
452 if ($b['deleted'] || ($b['created'] !== $b['edited']))
455 // if post comes from pump.io don't send it back
456 if ($b['app'] == "pump.io")
460 // Support for native shares
461 // http://<hostname>/api/<type>/shares?id=<the-object-id>
463 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
464 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
465 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
466 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
468 $host = PConfig::get($b['uid'], "pumpio", "host");
469 $user = PConfig::get($b['uid'], "pumpio", "user");
470 $public = PConfig::get($b['uid'], "pumpio", "public");
472 if ($oauth_token && $oauth_token_secret) {
473 $title = trim($b['title']);
475 $content = BBCode::convert($b['body'], false, 4);
479 $params["verb"] = "post";
482 $params["object"] = [
483 'objectType' => "note",
484 'content' => $content];
487 $params["object"]["displayName"] = $title;
489 if (count($receiver["to"]))
490 $params["to"] = $receiver["to"];
492 if (count($receiver["bto"]))
493 $params["bto"] = $receiver["bto"];
495 if (count($receiver["cc"]))
496 $params["cc"] = $receiver["cc"];
498 if (count($receiver["bcc"]))
499 $params["bcc"] = $receiver["bcc"];
502 $inReplyTo = ["id" => $orig_post["uri"],
503 "objectType" => "note"];
505 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
506 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
508 $params["object"] = [
509 'objectType' => "comment",
510 'content' => $content,
511 'inReplyTo' => $inReplyTo];
514 $params["object"]["displayName"] = $title;
517 $client = new oauth_client_class;
518 $client->oauth_version = '1.0a';
519 $client->url_parameters = false;
520 $client->authorization_header = true;
521 $client->access_token = $oauth_token;
522 $client->access_token_secret = $oauth_token_secret;
523 $client->client_id = $consumer_key;
524 $client->client_secret = $consumer_secret;
526 $username = $user.'@'.$host;
527 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
529 if (pumpio_reachable($url))
530 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
536 if ($user->generator->displayName)
537 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
539 $post_id = $user->object->id;
540 logger('pumpio_send '.$username.': success '.$post_id);
541 if ($post_id && $iscomment) {
542 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
543 Item::update(['extid' => $post_id], ['id' => $b['id']]);
546 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
548 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
549 if (DBM::is_result($r))
550 $a->contact = $r[0]["id"];
552 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
554 Queue::add($a->contact, NETWORK_PUMPIO, $s);
555 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
560 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
562 // Don't do likes and other stuff if you don't import the timeline
563 if (!PConfig::get($uid,'pumpio','import'))
566 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
567 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
568 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
569 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
570 $hostname = PConfig::get($uid, 'pumpio','host');
571 $username = PConfig::get($uid, "pumpio", "user");
573 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
575 if (!DBM::is_result($orig_post)) {
579 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
580 $uri = $orig_post["extid"];
582 $uri = $orig_post["uri"];
584 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
585 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
586 elseif (strstr($uri, "/api/comment/"))
587 $objectType = "comment";
588 elseif (strstr($uri, "/api/note/"))
589 $objectType = "note";
590 elseif (strstr($uri, "/api/image/"))
591 $objectType = "image";
593 $params["verb"] = $action;
594 $params["object"] = ['id' => $uri,
595 "objectType" => $objectType,
596 "content" => $content];
598 $client = new oauth_client_class;
599 $client->oauth_version = '1.0a';
600 $client->authorization_header = true;
601 $client->url_parameters = false;
603 $client->client_id = $ckey;
604 $client->client_secret = $csecret;
605 $client->access_token = $otoken;
606 $client->access_token_secret = $osecret;
608 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
610 if (pumpio_reachable($url))
611 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
616 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
618 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
620 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
621 if (DBM::is_result($r))
622 $a->contact = $r[0]["id"];
624 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
626 Queue::add($a->contact, NETWORK_PUMPIO, $s);
627 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
631 function pumpio_sync(&$a) {
632 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
635 if (!DBM::is_result($r))
638 $last = Config::get('pumpio','last_poll');
640 $poll_interval = intval(Config::get('pumpio','poll_interval'));
642 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
645 $next = $last + ($poll_interval * 60);
646 if ($next > time()) {
647 logger('pumpio: poll intervall not reached');
651 logger('pumpio: cron_start');
653 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
654 if (DBM::is_result($r)) {
656 logger('pumpio: mirroring user '.$rr['uid']);
657 pumpio_fetchtimeline($a, $rr['uid']);
661 $abandon_days = intval(Config::get('system','account_abandon_days'));
662 if ($abandon_days < 1)
665 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
667 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
668 if (DBM::is_result($r)) {
670 if ($abandon_days != 0) {
671 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
672 if (!DBM::is_result($user)) {
673 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
678 logger('pumpio: importing timeline from user '.$rr['uid']);
679 pumpio_fetchinbox($a, $rr['uid']);
681 // check for new contacts once a day
682 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
683 if ($last_contact_check)
684 $next_contact_check = $last_contact_check + 86400;
686 $next_contact_check = 0;
688 if ($next_contact_check <= time()) {
689 pumpio_getallusers($a, $rr["uid"]);
690 PConfig::set($rr['uid'],'pumpio','contact_check',time());
695 logger('pumpio: cron_end');
697 Config::set('pumpio','last_poll', time());
700 function pumpio_cron(&$a,$b) {
701 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
704 function pumpio_fetchtimeline(&$a, $uid) {
705 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
706 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
707 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
708 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
709 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
710 $hostname = PConfig::get($uid, 'pumpio','host');
711 $username = PConfig::get($uid, "pumpio", "user");
713 // get the application name for the pump.io app
714 // 1st try personal config, then system config and fallback to the
715 // hostname of the node if neither one is set.
716 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
717 if ($application_name == "")
718 $application_name = Config::get('pumpio', 'application_name');
719 if ($application_name == "")
720 $application_name = $a->get_hostname();
722 $first_time = ($lastdate == "");
724 $client = new oauth_client_class;
725 $client->oauth_version = '1.0a';
726 $client->authorization_header = true;
727 $client->url_parameters = false;
729 $client->client_id = $ckey;
730 $client->client_secret = $csecret;
731 $client->access_token = $otoken;
732 $client->access_token_secret = $osecret;
734 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
736 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
738 $username = $user.'@'.$host;
740 if (pumpio_reachable($url))
741 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
746 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
750 $posts = array_reverse($user->items);
752 $initiallastdate = $lastdate;
756 foreach ($posts as $post) {
757 if ($post->published <= $initiallastdate)
760 if ($lastdate < $post->published)
761 $lastdate = $post->published;
767 if (@is_array($post->cc))
768 $receiptians = array_merge($receiptians, $post->cc);
770 if (@is_array($post->to))
771 $receiptians = array_merge($receiptians, $post->to);
774 foreach ($receiptians AS $receiver)
775 if (is_string($receiver->objectType))
776 if ($receiver->id == "http://activityschema.org/collection/public")
779 if ($public && !stristr($post->generator->displayName, $application_name)) {
780 $_SESSION["authenticated"] = true;
781 $_SESSION["uid"] = $uid;
784 $_REQUEST["type"] = "wall";
785 $_REQUEST["api_source"] = true;
786 $_REQUEST["profile_uid"] = $uid;
787 $_REQUEST["source"] = "pump.io";
789 if (isset($post->object->id)) {
790 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
793 if ($post->object->displayName != "")
794 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
796 $_REQUEST["title"] = "";
798 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
800 // To-Do: Picture has to be cached and stored locally
801 if ($post->object->fullImage->url != "") {
802 if ($post->object->fullImage->pump_io->proxyURL != "")
803 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
805 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
808 logger('pumpio: posting for user '.$uid);
810 require_once('mod/item.php');
813 logger('pumpio: posting done - user '.$uid);
819 PConfig::set($uid,'pumpio','lastdate', $lastdate);
822 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
823 // Searching for the unliked post
824 // Two queries for speed issues
825 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
826 if (!DBM::is_result($orig_post)) {
827 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
828 if (!DBM::is_result($orig_post)) {
835 if (link_compare($post->actor->url, $own_id)) {
836 $contactid = $self[0]['id'];
838 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
839 dbesc(normalise_link($post->actor->url)),
843 if (DBM::is_result($r))
844 $contactid = $r[0]['id'];
847 $contactid = $orig_post['contact-id'];
850 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
852 if (DBM::is_result($r))
853 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
855 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
858 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
859 require_once('include/items.php');
861 if ($post->object->id == "") {
862 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
866 // Searching for the liked post
867 // Two queries for speed issues
868 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
869 if (!DBM::is_result($orig_post)) {
870 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
871 if (!DBM::is_result($orig_post)) {
877 if ($threadcompletion)
878 pumpio_fetchallcomments($a, $uid, $post->object->id);
882 if (link_compare($post->actor->url, $own_id)) {
883 $contactid = $self[0]['id'];
884 $post->actor->displayName = $self[0]['name'];
885 $post->actor->url = $self[0]['url'];
886 $post->actor->image->url = $self[0]['photo'];
888 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
889 dbesc(normalise_link($post->actor->url)),
893 if (DBM::is_result($r))
894 $contactid = $r[0]['id'];
897 $contactid = $orig_post['contact-id'];
900 $condition = ['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
901 if (dba::exists('item', $condition)) {
902 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
907 $likedata['parent'] = $orig_post['id'];
908 $likedata['verb'] = ACTIVITY_LIKE;
909 $likedata['gravity'] = 3;
910 $likedata['uid'] = $uid;
911 $likedata['wall'] = 0;
912 $likedata['uri'] = Item::newURI($uid);
913 $likedata['parent-uri'] = $orig_post["uri"];
914 $likedata['contact-id'] = $contactid;
915 $likedata['app'] = $post->generator->displayName;
916 $likedata['author-name'] = $post->actor->displayName;
917 $likedata['author-link'] = $post->actor->url;
918 $likedata['author-avatar'] = $post->actor->image->url;
920 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
921 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
922 $post_type = L10n::t('status');
923 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
924 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
926 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
928 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
929 '<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>';
931 $ret = Item::insert($likedata);
933 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
936 function pumpio_get_contact($uid, $contact, $no_insert = false) {
938 GContact::update(["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
939 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
940 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
941 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)]);
942 $cid = Contact::getIdForURL($contact->url, $uid);
947 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
948 intval($uid), dbesc(normalise_link($contact->url)));
950 if (!DBM::is_result($r)) {
951 // create contact record
952 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
953 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
954 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
955 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
957 dbesc(DateTimeFormat::utcNow()),
958 dbesc($contact->url),
959 dbesc(normalise_link($contact->url)),
960 dbesc(str_replace("acct:", "", $contact->id)),
962 dbesc($contact->id), // What is it for?
963 dbesc('pump.io ' . $contact->id), // What is it for?
964 dbesc($contact->displayName),
965 dbesc($contact->preferredUsername),
966 dbesc($contact->image->url),
967 dbesc(NETWORK_PUMPIO),
968 intval(CONTACT_IS_FRIEND),
970 dbesc($contact->location->displayName),
971 dbesc($contact->summary),
975 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
976 dbesc(normalise_link($contact->url)),
980 if (!DBM::is_result($r)) {
984 $contact_id = $r[0]['id'];
986 Group::addMember(User::getDefaultGroup($uid), $contact_id);
988 $contact_id = $r[0]["id"];
990 /* if (DB_UPDATE_VERSION >= "1177")
991 q("UPDATE `contact` SET `location` = '%s',
994 dbesc($contact->location->displayName),
995 dbesc($contact->summary),
1001 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1003 return($contact_id);
1006 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1008 // Two queries for speed issues
1009 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1010 if (dba::exists('item', $condition)) {
1011 Item::delete($condition);
1015 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1016 if (dba::exists('item', $condition)) {
1017 Item::delete($condition);
1023 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1024 require_once('include/items.php');
1026 if (($post->verb == "like") || ($post->verb == "favorite"))
1027 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1029 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1030 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1032 if ($post->verb == "delete")
1033 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1035 if ($post->verb != "update") {
1036 // Two queries for speed issues
1037 if (dba::exists('item', ['uri' => $post->object->id, 'uid' => $uid])) {
1040 if (dba::exists('item', ['extid' => $post->object->id, 'uid' => $uid])) {
1045 // Only handle these three types
1046 if (!strstr("post|share|update", $post->verb))
1050 if (@is_array($post->cc))
1051 $receiptians = array_merge($receiptians, $post->cc);
1053 if (@is_array($post->to))
1054 $receiptians = array_merge($receiptians, $post->to);
1056 foreach ($receiptians AS $receiver)
1057 if (is_string($receiver->objectType))
1058 if ($receiver->id == "http://activityschema.org/collection/public")
1062 $postarray['network'] = NETWORK_PUMPIO;
1063 $postarray['gravity'] = 0;
1064 $postarray['uid'] = $uid;
1065 $postarray['wall'] = 0;
1066 $postarray['uri'] = $post->object->id;
1067 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1069 if ($post->object->objectType != "comment") {
1070 $contact_id = pumpio_get_contact($uid, $post->actor);
1073 $contact_id = $self[0]['id'];
1075 $postarray['parent-uri'] = $post->object->id;
1078 $postarray['private'] = 1;
1079 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1082 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1084 if (link_compare($post->actor->url, $own_id)) {
1085 $contact_id = $self[0]['id'];
1086 $post->actor->displayName = $self[0]['name'];
1087 $post->actor->url = $self[0]['url'];
1088 $post->actor->image->url = $self[0]['photo'];
1089 } elseif ($contact_id == 0) {
1090 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1091 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1092 dbesc(normalise_link($post->actor->url)),
1096 if (DBM::is_result($r))
1097 $contact_id = $r[0]['id'];
1099 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1100 dbesc(normalise_link($post->actor->url)),
1104 if (DBM::is_result($r))
1105 $contact_id = $r[0]['id'];
1107 $contact_id = $self[0]['id'];
1111 $reply = new stdClass;
1112 $reply->verb = "note";
1113 $reply->cc = $post->cc;
1114 $reply->to = $post->to;
1115 $reply->object = new stdClass;
1116 $reply->object->objectType = $post->object->inReplyTo->objectType;
1117 $reply->object->content = $post->object->inReplyTo->content;
1118 $reply->object->id = $post->object->inReplyTo->id;
1119 $reply->actor = $post->object->inReplyTo->author;
1120 $reply->url = $post->object->inReplyTo->url;
1121 $reply->generator = new stdClass;
1122 $reply->generator->displayName = "pumpio";
1123 $reply->published = $post->object->inReplyTo->published;
1124 $reply->received = $post->object->inReplyTo->updated;
1125 $reply->url = $post->object->inReplyTo->url;
1126 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1128 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1131 if ($post->object->pump_io->proxyURL)
1132 $postarray['extid'] = $post->object->pump_io->proxyURL;
1134 $postarray['contact-id'] = $contact_id;
1135 $postarray['verb'] = ACTIVITY_POST;
1136 $postarray['owner-name'] = $post->actor->displayName;
1137 $postarray['owner-link'] = $post->actor->url;
1138 $postarray['owner-avatar'] = $post->actor->image->url;
1139 $postarray['author-name'] = $post->actor->displayName;
1140 $postarray['author-link'] = $post->actor->url;
1141 $postarray['author-avatar'] = $post->actor->image->url;
1142 $postarray['plink'] = $post->object->url;
1143 $postarray['app'] = $post->generator->displayName;
1144 $postarray['body'] = HTML::toBBCode($post->object->content);
1145 $postarray['object'] = json_encode($post);
1147 if ($post->object->fullImage->url != "")
1148 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1150 if ($post->object->displayName != "")
1151 $postarray['title'] = $post->object->displayName;
1153 $postarray['created'] = DateTimeFormat::utc($post->published);
1154 if (isset($post->updated))
1155 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1156 elseif (isset($post->received))
1157 $postarray['edited'] = DateTimeFormat::utc($post->received);
1159 $postarray['edited'] = $postarray['created'];
1161 if ($post->verb == "share") {
1162 if (!intval(Config::get('system','wall-to-wall_share'))) {
1163 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1164 $share_author = $post->object->author->displayName;
1165 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1166 $share_author = $post->object->author->preferredUsername;
1168 $share_author = $post->object->author->url;
1170 $postarray['body'] = share_header($share_author, $post->object->author->url,
1171 $post->object->author->image->url, "",
1172 DateTimeFormat::utc($post->object->created),
1173 $post->links->self->href).
1174 $postarray['body']."[/share]";
1176 // Let shares look like wall-to-wall posts
1177 $postarray['author-name'] = $post->object->author->displayName;
1178 $postarray['author-link'] = $post->object->author->url;
1179 $postarray['author-avatar'] = $post->object->author->image->url;
1183 if (trim($postarray['body']) == "")
1186 $top_item = Item::insert($postarray);
1187 $postarray["id"] = $top_item;
1189 if (($top_item == 0) && ($post->verb == "update")) {
1190 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1191 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1192 Item::update($fields, $condition);
1195 if ($post->object->objectType == "comment") {
1197 if ($threadcompletion)
1198 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1204 function pumpio_fetchinbox(&$a, $uid) {
1206 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1207 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1208 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1209 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1210 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1211 $hostname = PConfig::get($uid, 'pumpio','host');
1212 $username = PConfig::get($uid, "pumpio", "user");
1214 $own_id = "https://".$hostname."/".$username;
1216 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1219 $lastitems = q("SELECT `uri` FROM `thread`
1220 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1221 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1222 ORDER BY `thread`.`commented` DESC LIMIT 10",
1223 dbesc(NETWORK_PUMPIO),
1227 $client = new oauth_client_class;
1228 $client->oauth_version = '1.0a';
1229 $client->authorization_header = true;
1230 $client->url_parameters = false;
1232 $client->client_id = $ckey;
1233 $client->client_secret = $csecret;
1234 $client->access_token = $otoken;
1235 $client->access_token_secret = $osecret;
1237 $last_id = PConfig::get($uid,'pumpio','last_id');
1239 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1242 $url .= '?since='.urlencode($last_id);
1244 if (pumpio_reachable($url))
1245 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1250 $posts = array_reverse($user->items);
1253 foreach ($posts as $post) {
1254 $last_id = $post->id;
1255 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1259 foreach ($lastitems AS $item)
1260 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1262 PConfig::set($uid,'pumpio','last_id', $last_id);
1265 function pumpio_getallusers(&$a, $uid) {
1266 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1267 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1268 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1269 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1270 $hostname = PConfig::get($uid, 'pumpio','host');
1271 $username = PConfig::get($uid, "pumpio", "user");
1273 $client = new oauth_client_class;
1274 $client->oauth_version = '1.0a';
1275 $client->authorization_header = true;
1276 $client->url_parameters = false;
1278 $client->client_id = $ckey;
1279 $client->client_secret = $csecret;
1280 $client->access_token = $otoken;
1281 $client->access_token_secret = $osecret;
1283 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1285 if (pumpio_reachable($url))
1286 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1290 if ($users->totalItems > count($users->items)) {
1291 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1293 if (pumpio_reachable($url))
1294 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1299 if (is_array($users->items)) {
1300 foreach ($users->items AS $user) {
1301 pumpio_get_contact($uid, $user);
1306 function pumpio_queue_hook(&$a,&$b) {
1308 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1309 dbesc(NETWORK_PUMPIO)
1311 if (!DBM::is_result($qi))
1314 foreach($qi as $x) {
1315 if ($x['network'] !== NETWORK_PUMPIO)
1318 logger('pumpio_queue: run');
1320 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1321 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1324 if (!DBM::is_result($r))
1329 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1331 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1332 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1333 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1334 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1336 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1337 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1341 if ($oauth_token && $oauth_token_secret &&
1342 $consumer_key && $consumer_secret) {
1343 $username = $user.'@'.$host;
1345 logger('pumpio_queue: able to post for user '.$username);
1347 $z = unserialize($x['content']);
1349 $client = new oauth_client_class;
1350 $client->oauth_version = '1.0a';
1351 $client->url_parameters = false;
1352 $client->authorization_header = true;
1353 $client->access_token = $oauth_token;
1354 $client->access_token_secret = $oauth_token_secret;
1355 $client->client_id = $consumer_key;
1356 $client->client_secret = $consumer_secret;
1358 if (pumpio_reachable($z['url']))
1359 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1364 $post_id = $user->object->id;
1365 logger('pumpio_queue: send '.$username.': success '.$post_id);
1366 if ($post_id && $iscomment) {
1367 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1368 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1370 Queue::removeItem($x['id']);
1372 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1374 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1377 logger('pumpio_queue: delayed');
1378 Queue::updateTime($x['id']);
1383 function pumpio_getreceiver(&$a, $b) {
1387 if (!$b["private"]) {
1389 if (!strstr($b['postopts'],'pumpio'))
1392 $public = PConfig::get($b['uid'], "pumpio", "public");
1395 $receiver["to"][] = [
1396 "objectType" => "collection",
1397 "id" => "http://activityschema.org/collection/public"];
1399 $cids = explode("><", $b["allow_cid"]);
1400 $gids = explode("><", $b["allow_gid"]);
1402 foreach ($cids AS $cid) {
1403 $cid = trim($cid, " <>");
1405 $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",
1408 dbesc(NETWORK_PUMPIO)
1411 if (DBM::is_result($r)) {
1412 $receiver["bcc"][] = [
1413 "displayName" => $r[0]["name"],
1414 "objectType" => "person",
1415 "preferredUsername" => $r[0]["nick"],
1416 "url" => $r[0]["url"]];
1419 foreach ($gids AS $gid) {
1420 $gid = trim($gid, " <>");
1422 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1423 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1424 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1426 dbesc(NETWORK_PUMPIO)
1429 foreach ($r AS $row)
1430 $receiver["bcc"][] = [
1431 "displayName" => $row["name"],
1432 "objectType" => "person",
1433 "preferredUsername" => $row["nick"],
1434 "url" => $row["url"]];
1438 if ($b["inform"] != "") {
1440 $inform = explode(",", $b["inform"]);
1442 foreach ($inform AS $cid) {
1443 if (substr($cid, 0, 4) != "cid:")
1446 $cid = str_replace("cid:", "", $cid);
1448 $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",
1451 dbesc(NETWORK_PUMPIO)
1454 if (DBM::is_result($r)) {
1455 $receiver["to"][] = [
1456 "displayName" => $r[0]["name"],
1457 "objectType" => "person",
1458 "preferredUsername" => $r[0]["nick"],
1459 "url" => $r[0]["url"]];
1467 function pumpio_fetchallcomments(&$a, $uid, $id) {
1468 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1469 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1470 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1471 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1472 $hostname = PConfig::get($uid, 'pumpio','host');
1473 $username = PConfig::get($uid, "pumpio", "user");
1475 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1477 $own_id = "https://".$hostname."/".$username;
1479 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1482 // Fetching the original post
1483 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1484 $item = Item::selectFirst(['extid'], $condition);
1485 if (!DBM::is_result($item)) {
1489 $url = $item["extid"];
1491 $client = new oauth_client_class;
1492 $client->oauth_version = '1.0a';
1493 $client->authorization_header = true;
1494 $client->url_parameters = false;
1496 $client->client_id = $ckey;
1497 $client->client_secret = $csecret;
1498 $client->access_token = $otoken;
1499 $client->access_token_secret = $osecret;
1501 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1503 if (pumpio_reachable($url))
1504 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1511 if ($item->likes->totalItems != 0) {
1512 foreach ($item->likes->items AS $post) {
1513 $like = new stdClass;
1514 $like->object = new stdClass;
1515 $like->object->id = $item->id;
1516 $like->actor = new stdClass;
1517 $like->actor->displayName = $item->displayName;
1518 $like->actor->preferredUsername = $item->preferredUsername;
1519 $like->actor->url = $item->url;
1520 $like->actor->image = $item->image;
1521 $like->generator = new stdClass;
1522 $like->generator->displayName = "pumpio";
1523 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1527 if ($item->replies->totalItems == 0)
1530 foreach ($item->replies->items AS $item) {
1531 if ($item->id == $id)
1534 // Checking if the comment already exists - Two queries for speed issues
1535 if (dba::exists('item', ['uri' => $item->id, 'uid' => $uid])) {
1539 if (dba::exists('item', ['extid' => $item->id, 'uid' => $uid])) {
1543 $post = new stdClass;
1544 $post->verb = "post";
1545 $post->actor = $item->author;
1546 $post->published = $item->published;
1547 $post->received = $item->updated;
1548 $post->generator = new stdClass;
1549 $post->generator->displayName = "pumpio";
1550 // To-Do: Check for public post
1552 unset($item->author);
1553 unset($item->published);
1554 unset($item->updated);
1556 $post->object = $item;
1558 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1559 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1564 function pumpio_reachable($url) {
1565 $data = Network::curl($url, false, $redirects, ['timeout'=>10]);
1566 return(intval($data['return_code']) != 0);