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\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\Worker;
14 use Friendica\Model\Contact;
15 use Friendica\Model\GContact;
16 use Friendica\Model\Group;
17 use Friendica\Model\Item;
18 use Friendica\Model\Queue;
19 use Friendica\Model\User;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Network;
23 require 'addon/pumpio/oauth/http.php';
24 require 'addon/pumpio/oauth/oauth_client.php';
25 require_once 'include/enotify.php';
26 require_once "mod/share.php";
28 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
30 function pumpio_install() {
31 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
32 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
33 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
34 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
35 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
36 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
37 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
38 Addon::registerHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
41 function pumpio_uninstall() {
42 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
43 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
44 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
45 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
46 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
47 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
48 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
49 Addon::unregisterHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
52 function pumpio_module() {}
54 function pumpio_content(&$a) {
57 notice(L10n::t('Permission denied.') . EOL);
61 require_once("mod/settings.php");
64 if (isset($a->argv[1]))
65 switch ($a->argv[1]) {
67 $o = pumpio_connect($a);
70 $o = print_r($a->argv, true);
74 $o = pumpio_connect($a);
79 function pumpio_check_item_notification($a, &$notification_data) {
80 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
81 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
83 $notification_data["profiles"][] = "https://".$hostname."/".$username;
87 function pumpio_registerclient(&$a, $host) {
89 $url = "https://".$host."/api/client/register";
93 $application_name = Config::get('pumpio', 'application_name');
95 if ($application_name == "")
96 $application_name = $a->get_hostname();
98 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
100 $params["type"] = "client_associate";
101 $params["contacts"] = $adminlist[0];
102 $params["application_type"] = "native";
103 $params["application_name"] = $application_name;
104 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
105 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
107 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
109 $ch = curl_init($url);
110 curl_setopt($ch, CURLOPT_HEADER, false);
111 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
112 curl_setopt($ch, CURLOPT_POST,1);
113 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
114 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
117 $curl_info = curl_getinfo($ch);
119 if ($curl_info["http_code"] == "200") {
120 $values = json_decode($s);
121 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
124 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
129 function pumpio_connect(&$a) {
130 // Start a session. This is necessary to hold on to a few keys the callback script will also need
133 // Define the needed keys
134 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
135 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
136 $hostname = PConfig::get(local_user(), 'pumpio','host');
138 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
139 logger("pumpio_connect: register client");
140 $clientdata = pumpio_registerclient($a, $hostname);
141 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
142 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
144 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
145 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
147 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
150 if (($consumer_key == "") || ($consumer_secret == "")) {
151 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
153 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
157 // The callback URL is the script that gets called after the user authenticates with pumpio
158 $callback_url = $a->get_baseurl()."/pumpio/connect";
160 // Let's begin. First we need a Request Token. The request token is required to send the user
161 // to pumpio's login page.
163 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
164 // Consumer Key and Consumer Secret
165 $client = new oauth_client_class;
167 $client->server = '';
168 $client->oauth_version = '1.0a';
169 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
170 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
171 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
172 $client->url_parameters = false;
173 $client->authorization_header = true;
174 $client->redirect_uri = $callback_url;
175 $client->client_id = $consumer_key;
176 $client->client_secret = $consumer_secret;
178 if (($success = $client->Initialize())) {
179 if (($success = $client->Process())) {
180 if (strlen($client->access_token)) {
181 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
182 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
183 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
186 $success = $client->Finalize($success);
189 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
192 logger("pumpio_connect: authenticated");
193 $o .= L10n::t("You are now authenticated to pumpio.");
194 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
196 logger("pumpio_connect: could not connect");
197 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
203 function pumpio_jot_nets(&$a,&$b) {
207 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
208 if(intval($pumpio_post) == 1) {
209 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
210 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
211 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
212 . L10n::t('Post to pumpio') . '</div>';
217 function pumpio_settings(&$a,&$s) {
222 /* Add our stylesheet to the page so we can make our settings look nice */
224 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
226 /* Get the current state of our config variables */
228 $import_enabled = PConfig::get(local_user(),'pumpio','import');
229 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
231 $enabled = PConfig::get(local_user(),'pumpio','post');
232 $checked = (($enabled) ? ' checked="checked" ' : '');
233 $css = (($enabled) ? '' : '-disabled');
235 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
236 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
238 $public_enabled = PConfig::get(local_user(),'pumpio','public');
239 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
241 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
242 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
244 $servername = PConfig::get(local_user(), "pumpio", "host");
245 $username = PConfig::get(local_user(), "pumpio", "user");
247 /* Add some HTML to the existing form */
249 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
250 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
252 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
253 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
254 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
257 $s .= '<div id="pumpio-username-wrapper">';
258 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
259 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
260 $s .= '</div><div class="clear"></div>';
262 $s .= '<div id="pumpio-servername-wrapper">';
263 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
264 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
265 $s .= '</div><div class="clear"></div>';
267 if (($username != '') && ($servername != '')) {
269 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
270 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
272 $s .= '<div id="pumpio-password-wrapper">';
273 if (($oauth_token == "") || ($oauth_token_secret == "")) {
274 $s .= '<div id="pumpio-authenticate-wrapper">';
275 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
276 $s .= '</div><div class="clear"></div>';
278 $s .= '<div id="pumpio-import-wrapper">';
279 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
280 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
281 $s .= '</div><div class="clear"></div>';
283 $s .= '<div id="pumpio-enable-wrapper">';
284 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
285 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
286 $s .= '</div><div class="clear"></div>';
288 $s .= '<div id="pumpio-bydefault-wrapper">';
289 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
290 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
291 $s .= '</div><div class="clear"></div>';
293 $s .= '<div id="pumpio-public-wrapper">';
294 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
295 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
296 $s .= '</div><div class="clear"></div>';
298 $s .= '<div id="pumpio-mirror-wrapper">';
299 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
300 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
301 $s .= '</div><div class="clear"></div>';
303 $s .= '<div id="pumpio-delete-wrapper">';
304 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
305 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
306 $s .= '</div><div class="clear"></div>';
309 $s .= '</div><div class="clear"></div>';
312 /* provide a submit button */
314 $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>';
318 function pumpio_settings_post(&$a,&$b) {
320 if(x($_POST,'pumpio-submit')) {
321 if(x($_POST,'pumpio_delete')) {
322 PConfig::set(local_user(),'pumpio','consumer_key','');
323 PConfig::set(local_user(),'pumpio','consumer_secret','');
324 PConfig::set(local_user(),'pumpio','oauth_token','');
325 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
326 PConfig::set(local_user(),'pumpio','post',false);
327 PConfig::set(local_user(),'pumpio','import',false);
328 PConfig::set(local_user(),'pumpio','host','');
329 PConfig::set(local_user(),'pumpio','user','');
330 PConfig::set(local_user(),'pumpio','public',false);
331 PConfig::set(local_user(),'pumpio','mirror',false);
332 PConfig::set(local_user(),'pumpio','post_by_default',false);
333 PConfig::set(local_user(),'pumpio','lastdate', 0);
334 PConfig::set(local_user(),'pumpio','last_id', '');
336 // filtering the username if it is filled wrong
337 $user = $_POST['pumpio_user'];
338 if (strstr($user, "@")) {
339 $pos = strpos($user, "@");
341 $user = substr($user, 0, $pos);
344 // Filtering the hostname if someone is entering it with "http"
345 $host = $_POST['pumpio_host'];
347 $host = str_replace(["https://", "http://"], ["", ""], $host);
349 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
350 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
351 PConfig::set(local_user(),'pumpio','host',$host);
352 PConfig::set(local_user(),'pumpio','user',$user);
353 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
354 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
355 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
357 if (!$_POST['pumpio_mirror'])
358 PConfig::delete(local_user(),'pumpio','lastdate');
360 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
365 function pumpio_post_local(&$a, &$b) {
367 if (!local_user() || (local_user() != $b['uid'])) {
371 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
373 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
375 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
379 if (!$pumpio_enable) {
383 if (strlen($b['postopts'])) {
384 $b['postopts'] .= ',';
387 $b['postopts'] .= 'pumpio';
393 function pumpio_send(&$a,&$b) {
395 if (!PConfig::get($b["uid"],'pumpio','import')) {
396 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
400 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
402 if($b['parent'] != $b['id']) {
403 // Looking if its a reply to a pumpio post
404 $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",
405 intval($b["parent"]),
407 dbesc(NETWORK_PUMPIO));
410 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) {
474 require_once('include/bbcode.php');
476 $title = trim($b['title']);
478 $content = bbcode($b['body'], false, false, 4);
482 $params["verb"] = "post";
485 $params["object"] = [
486 'objectType' => "note",
487 'content' => $content];
490 $params["object"]["displayName"] = $title;
492 if (count($receiver["to"]))
493 $params["to"] = $receiver["to"];
495 if (count($receiver["bto"]))
496 $params["bto"] = $receiver["bto"];
498 if (count($receiver["cc"]))
499 $params["cc"] = $receiver["cc"];
501 if (count($receiver["bcc"]))
502 $params["bcc"] = $receiver["bcc"];
505 $inReplyTo = ["id" => $orig_post["uri"],
506 "objectType" => "note"];
508 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
509 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
511 $params["object"] = [
512 'objectType' => "comment",
513 'content' => $content,
514 'inReplyTo' => $inReplyTo];
517 $params["object"]["displayName"] = $title;
520 $client = new oauth_client_class;
521 $client->oauth_version = '1.0a';
522 $client->url_parameters = false;
523 $client->authorization_header = true;
524 $client->access_token = $oauth_token;
525 $client->access_token_secret = $oauth_token_secret;
526 $client->client_id = $consumer_key;
527 $client->client_secret = $consumer_secret;
529 $username = $user.'@'.$host;
530 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
532 if (pumpio_reachable($url))
533 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
539 if ($user->generator->displayName)
540 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
542 $post_id = $user->object->id;
543 logger('pumpio_send '.$username.': success '.$post_id);
544 if($post_id && $iscomment) {
545 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
546 Item::update(['extid' => $post_id], ['id' => $b['id']]);
549 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
551 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
553 $a->contact = $r[0]["id"];
555 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
557 Queue::add($a->contact, NETWORK_PUMPIO, $s);
558 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
563 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
565 // Don't do likes and other stuff if you don't import the timeline
566 if (!PConfig::get($uid,'pumpio','import'))
569 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
570 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
571 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
572 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
573 $hostname = PConfig::get($uid, 'pumpio','host');
574 $username = PConfig::get($uid, "pumpio", "user");
576 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
586 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
587 $uri = $orig_post["extid"];
589 $uri = $orig_post["uri"];
591 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
592 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
593 elseif (strstr($uri, "/api/comment/"))
594 $objectType = "comment";
595 elseif (strstr($uri, "/api/note/"))
596 $objectType = "note";
597 elseif (strstr($uri, "/api/image/"))
598 $objectType = "image";
600 $params["verb"] = $action;
601 $params["object"] = ['id' => $uri,
602 "objectType" => $objectType,
603 "content" => $content];
605 $client = new oauth_client_class;
606 $client->oauth_version = '1.0a';
607 $client->authorization_header = true;
608 $client->url_parameters = false;
610 $client->client_id = $ckey;
611 $client->client_secret = $csecret;
612 $client->access_token = $otoken;
613 $client->access_token_secret = $osecret;
615 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
617 if (pumpio_reachable($url))
618 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
623 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
625 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
627 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
629 $a->contact = $r[0]["id"];
631 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
633 Queue::add($a->contact, NETWORK_PUMPIO, $s);
634 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
638 function pumpio_sync(&$a) {
639 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
645 $last = Config::get('pumpio','last_poll');
647 $poll_interval = intval(Config::get('pumpio','poll_interval'));
649 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
652 $next = $last + ($poll_interval * 60);
654 logger('pumpio: poll intervall not reached');
658 logger('pumpio: cron_start');
660 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
663 logger('pumpio: mirroring user '.$rr['uid']);
664 pumpio_fetchtimeline($a, $rr['uid']);
668 $abandon_days = intval(Config::get('system','account_abandon_days'));
669 if ($abandon_days < 1)
672 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
674 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
677 if ($abandon_days != 0) {
678 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
680 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
685 logger('pumpio: importing timeline from user '.$rr['uid']);
686 pumpio_fetchinbox($a, $rr['uid']);
688 // check for new contacts once a day
689 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
690 if($last_contact_check)
691 $next_contact_check = $last_contact_check + 86400;
693 $next_contact_check = 0;
695 if($next_contact_check <= time()) {
696 pumpio_getallusers($a, $rr["uid"]);
697 PConfig::set($rr['uid'],'pumpio','contact_check',time());
702 logger('pumpio: cron_end');
704 Config::set('pumpio','last_poll', time());
707 function pumpio_cron(&$a,$b) {
708 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
711 function pumpio_fetchtimeline(&$a, $uid) {
712 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
713 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
714 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
715 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
716 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
717 $hostname = PConfig::get($uid, 'pumpio','host');
718 $username = PConfig::get($uid, "pumpio", "user");
720 // get the application name for the pump.io app
721 // 1st try personal config, then system config and fallback to the
722 // hostname of the node if neither one is set.
723 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
724 if ($application_name == "")
725 $application_name = Config::get('pumpio', 'application_name');
726 if ($application_name == "")
727 $application_name = $a->get_hostname();
729 $first_time = ($lastdate == "");
731 $client = new oauth_client_class;
732 $client->oauth_version = '1.0a';
733 $client->authorization_header = true;
734 $client->url_parameters = false;
736 $client->client_id = $ckey;
737 $client->client_secret = $csecret;
738 $client->access_token = $otoken;
739 $client->access_token_secret = $osecret;
741 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
743 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
745 $username = $user.'@'.$host;
747 if (pumpio_reachable($url))
748 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
753 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
757 $posts = array_reverse($user->items);
759 $initiallastdate = $lastdate;
763 foreach ($posts as $post) {
764 if ($post->published <= $initiallastdate)
767 if ($lastdate < $post->published)
768 $lastdate = $post->published;
774 if (@is_array($post->cc))
775 $receiptians = array_merge($receiptians, $post->cc);
777 if (@is_array($post->to))
778 $receiptians = array_merge($receiptians, $post->to);
781 foreach ($receiptians AS $receiver)
782 if (is_string($receiver->objectType))
783 if ($receiver->id == "http://activityschema.org/collection/public")
786 if ($public && !stristr($post->generator->displayName, $application_name)) {
787 require_once('include/html2bbcode.php');
789 $_SESSION["authenticated"] = true;
790 $_SESSION["uid"] = $uid;
793 $_REQUEST["type"] = "wall";
794 $_REQUEST["api_source"] = true;
795 $_REQUEST["profile_uid"] = $uid;
796 $_REQUEST["source"] = "pump.io";
798 if (isset($post->object->id)) {
799 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
802 if ($post->object->displayName != "")
803 $_REQUEST["title"] = html2bbcode($post->object->displayName);
805 $_REQUEST["title"] = "";
807 $_REQUEST["body"] = html2bbcode($post->object->content);
809 // To-Do: Picture has to be cached and stored locally
810 if ($post->object->fullImage->url != "") {
811 if ($post->object->fullImage->pump_io->proxyURL != "")
812 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
814 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
817 logger('pumpio: posting for user '.$uid);
819 require_once('mod/item.php');
822 logger('pumpio: posting done - user '.$uid);
828 PConfig::set($uid,'pumpio','lastdate', $lastdate);
831 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
832 // Searching for the unliked post
833 // Two queries for speed issues
834 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
835 dbesc($post->object->id),
842 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
843 dbesc($post->object->id),
855 if(link_compare($post->actor->url, $own_id)) {
856 $contactid = $self[0]['id'];
858 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
859 dbesc(normalise_link($post->actor->url)),
864 $contactid = $r[0]['id'];
867 $contactid = $orig_post['contact-id'];
870 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
873 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
875 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
878 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
879 require_once('include/items.php');
881 if ($post->object->id == "") {
882 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
886 // Searching for the liked post
887 // Two queries for speed issues
888 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
889 dbesc($post->object->id),
891 dbesc(NETWORK_PUMPIO)
897 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
898 dbesc($post->object->id),
900 dbesc(NETWORK_PUMPIO)
910 if ($threadcompletion)
911 pumpio_fetchallcomments($a, $uid, $post->object->id);
915 if(link_compare($post->actor->url, $own_id)) {
916 $contactid = $self[0]['id'];
917 $post->actor->displayName = $self[0]['name'];
918 $post->actor->url = $self[0]['url'];
919 $post->actor->image->url = $self[0]['photo'];
921 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
922 dbesc(normalise_link($post->actor->url)),
927 $contactid = $r[0]['id'];
930 $contactid = $orig_post['contact-id'];
933 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
934 dbesc(ACTIVITY_LIKE),
937 dbesc($orig_post['uri'])
941 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
946 $likedata['parent'] = $orig_post['id'];
947 $likedata['verb'] = ACTIVITY_LIKE;
948 $likedata['gravity'] = 3;
949 $likedata['uid'] = $uid;
950 $likedata['wall'] = 0;
951 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
952 $likedata['parent-uri'] = $orig_post["uri"];
953 $likedata['contact-id'] = $contactid;
954 $likedata['app'] = $post->generator->displayName;
955 $likedata['author-name'] = $post->actor->displayName;
956 $likedata['author-link'] = $post->actor->url;
957 $likedata['author-avatar'] = $post->actor->image->url;
959 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
960 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
961 $post_type = L10n::t('status');
962 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
963 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
965 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
967 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
968 '<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>';
970 $ret = Item::insert($likedata);
972 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
975 function pumpio_get_contact($uid, $contact, $no_insert = false) {
977 GContact::update(["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
978 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
979 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
980 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)]);
981 $cid = Contact::getIdForURL($contact->url, $uid);
986 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
987 intval($uid), dbesc(normalise_link($contact->url)));
990 // create contact record
991 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
992 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
993 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
994 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
996 dbesc(DateTimeFormat::utcNow()),
997 dbesc($contact->url),
998 dbesc(normalise_link($contact->url)),
999 dbesc(str_replace("acct:", "", $contact->id)),
1001 dbesc($contact->id), // What is it for?
1002 dbesc('pump.io ' . $contact->id), // What is it for?
1003 dbesc($contact->displayName),
1004 dbesc($contact->preferredUsername),
1005 dbesc($contact->image->url),
1006 dbesc(NETWORK_PUMPIO),
1007 intval(CONTACT_IS_FRIEND),
1009 dbesc($contact->location->displayName),
1010 dbesc($contact->summary),
1014 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1015 dbesc(normalise_link($contact->url)),
1023 $contact_id = $r[0]['id'];
1025 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1027 $contact_id = $r[0]["id"];
1029 /* if (DB_UPDATE_VERSION >= "1177")
1030 q("UPDATE `contact` SET `location` = '%s',
1033 dbesc($contact->location->displayName),
1034 dbesc($contact->summary),
1040 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1042 return($contact_id);
1045 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1047 // Two queries for speed issues
1048 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1049 dbesc($post->object->id),
1054 return Item::deleteById($r[0]["id"]);
1056 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1057 dbesc($post->object->id),
1062 return Item::deleteById($r[0]["id"]);
1065 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1066 require_once('include/items.php');
1067 require_once('include/html2bbcode.php');
1069 if (($post->verb == "like") || ($post->verb == "favorite"))
1070 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1072 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1073 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1075 if ($post->verb == "delete")
1076 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1078 if ($post->verb != "update") {
1079 // Two queries for speed issues
1080 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1081 dbesc($post->object->id),
1088 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1089 dbesc($post->object->id),
1097 // Only handle these three types
1098 if (!strstr("post|share|update", $post->verb))
1102 if (@is_array($post->cc))
1103 $receiptians = array_merge($receiptians, $post->cc);
1105 if (@is_array($post->to))
1106 $receiptians = array_merge($receiptians, $post->to);
1108 foreach ($receiptians AS $receiver)
1109 if (is_string($receiver->objectType))
1110 if ($receiver->id == "http://activityschema.org/collection/public")
1114 $postarray['network'] = NETWORK_PUMPIO;
1115 $postarray['gravity'] = 0;
1116 $postarray['uid'] = $uid;
1117 $postarray['wall'] = 0;
1118 $postarray['uri'] = $post->object->id;
1119 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1121 if ($post->object->objectType != "comment") {
1122 $contact_id = pumpio_get_contact($uid, $post->actor);
1125 $contact_id = $self[0]['id'];
1127 $postarray['parent-uri'] = $post->object->id;
1130 $postarray['private'] = 1;
1131 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1134 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1136 if (link_compare($post->actor->url, $own_id)) {
1137 $contact_id = $self[0]['id'];
1138 $post->actor->displayName = $self[0]['name'];
1139 $post->actor->url = $self[0]['url'];
1140 $post->actor->image->url = $self[0]['photo'];
1141 } elseif ($contact_id == 0) {
1142 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1143 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1144 dbesc(normalise_link($post->actor->url)),
1149 $contact_id = $r[0]['id'];
1151 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1152 dbesc(normalise_link($post->actor->url)),
1157 $contact_id = $r[0]['id'];
1159 $contact_id = $self[0]['id'];
1163 $reply = new stdClass;
1164 $reply->verb = "note";
1165 $reply->cc = $post->cc;
1166 $reply->to = $post->to;
1167 $reply->object = new stdClass;
1168 $reply->object->objectType = $post->object->inReplyTo->objectType;
1169 $reply->object->content = $post->object->inReplyTo->content;
1170 $reply->object->id = $post->object->inReplyTo->id;
1171 $reply->actor = $post->object->inReplyTo->author;
1172 $reply->url = $post->object->inReplyTo->url;
1173 $reply->generator = new stdClass;
1174 $reply->generator->displayName = "pumpio";
1175 $reply->published = $post->object->inReplyTo->published;
1176 $reply->received = $post->object->inReplyTo->updated;
1177 $reply->url = $post->object->inReplyTo->url;
1178 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1180 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1183 if ($post->object->pump_io->proxyURL)
1184 $postarray['extid'] = $post->object->pump_io->proxyURL;
1186 $postarray['contact-id'] = $contact_id;
1187 $postarray['verb'] = ACTIVITY_POST;
1188 $postarray['owner-name'] = $post->actor->displayName;
1189 $postarray['owner-link'] = $post->actor->url;
1190 $postarray['owner-avatar'] = $post->actor->image->url;
1191 $postarray['author-name'] = $post->actor->displayName;
1192 $postarray['author-link'] = $post->actor->url;
1193 $postarray['author-avatar'] = $post->actor->image->url;
1194 $postarray['plink'] = $post->object->url;
1195 $postarray['app'] = $post->generator->displayName;
1196 $postarray['body'] = html2bbcode($post->object->content);
1197 $postarray['object'] = json_encode($post);
1199 if ($post->object->fullImage->url != "")
1200 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1202 if ($post->object->displayName != "")
1203 $postarray['title'] = $post->object->displayName;
1205 $postarray['created'] = DateTimeFormat::utc($post->published);
1206 if (isset($post->updated))
1207 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1208 elseif (isset($post->received))
1209 $postarray['edited'] = DateTimeFormat::utc($post->received);
1211 $postarray['edited'] = $postarray['created'];
1213 if ($post->verb == "share") {
1214 if (!intval(Config::get('system','wall-to-wall_share'))) {
1215 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1216 $share_author = $post->object->author->displayName;
1217 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1218 $share_author = $post->object->author->preferredUsername;
1220 $share_author = $post->object->author->url;
1222 $postarray['body'] = share_header($share_author, $post->object->author->url,
1223 $post->object->author->image->url, "",
1224 DateTimeFormat::utc($post->object->created),
1225 $post->links->self->href).
1226 $postarray['body']."[/share]";
1229 $postarray['body'] = "[share author='".$share_author.
1230 "' profile='".$post->object->author->url.
1231 "' avatar='".$post->object->author->image->url.
1232 "' posted='".DateTimeFormat::convert($post->object->created, 'UTC', 'UTC', ).
1233 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1236 // Let shares look like wall-to-wall posts
1237 $postarray['author-name'] = $post->object->author->displayName;
1238 $postarray['author-link'] = $post->object->author->url;
1239 $postarray['author-avatar'] = $post->object->author->image->url;
1243 if (trim($postarray['body']) == "")
1246 $top_item = Item::insert($postarray);
1247 $postarray["id"] = $top_item;
1249 if (($top_item == 0) && ($post->verb == "update")) {
1250 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1251 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1252 Item::update($fields, $condition);
1255 if ($post->object->objectType == "comment") {
1257 if ($threadcompletion)
1258 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1260 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1267 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1269 if (link_compare($own_id, $postarray['author-link']))
1272 if (!function_exists("check_item_notification")) {
1273 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1274 dbesc($postarray['parent-uri']),
1278 if(count($myconv)) {
1280 foreach($myconv as $conv) {
1281 // now if we find a match, it means we're in this conversation
1283 if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1286 require_once('include/enotify.php');
1288 $conv_parent = $conv['parent'];
1291 'type' => NOTIFY_COMMENT,
1292 'notify_flags' => $user[0]['notify-flags'],
1293 'language' => $user[0]['language'],
1294 'to_name' => $user[0]['username'],
1295 'to_email' => $user[0]['email'],
1296 'uid' => $user[0]['uid'],
1297 'item' => $postarray,
1298 'link' => $a->get_baseurl().'/display/'.urlencode(Item::getGuidById($top_item)),
1299 'source_name' => $postarray['author-name'],
1300 'source_link' => $postarray['author-link'],
1301 'source_photo' => $postarray['author-avatar'],
1302 'verb' => ACTIVITY_POST,
1304 'parent' => $conv_parent,
1307 // only send one notification
1317 function pumpio_fetchinbox(&$a, $uid) {
1319 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1320 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1321 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1322 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1323 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1324 $hostname = PConfig::get($uid, 'pumpio','host');
1325 $username = PConfig::get($uid, "pumpio", "user");
1327 $own_id = "https://".$hostname."/".$username;
1329 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1332 $lastitems = q("SELECT `uri` FROM `thread`
1333 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1334 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1335 ORDER BY `thread`.`commented` DESC LIMIT 10",
1336 dbesc(NETWORK_PUMPIO),
1340 $client = new oauth_client_class;
1341 $client->oauth_version = '1.0a';
1342 $client->authorization_header = true;
1343 $client->url_parameters = false;
1345 $client->client_id = $ckey;
1346 $client->client_secret = $csecret;
1347 $client->access_token = $otoken;
1348 $client->access_token_secret = $osecret;
1350 $last_id = PConfig::get($uid,'pumpio','last_id');
1352 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1355 $url .= '?since='.urlencode($last_id);
1357 if (pumpio_reachable($url))
1358 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1363 $posts = array_reverse($user->items);
1366 foreach ($posts as $post) {
1367 $last_id = $post->id;
1368 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1372 foreach ($lastitems AS $item)
1373 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1375 PConfig::set($uid,'pumpio','last_id', $last_id);
1378 function pumpio_getallusers(&$a, $uid) {
1379 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1380 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1381 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1382 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1383 $hostname = PConfig::get($uid, 'pumpio','host');
1384 $username = PConfig::get($uid, "pumpio", "user");
1386 $client = new oauth_client_class;
1387 $client->oauth_version = '1.0a';
1388 $client->authorization_header = true;
1389 $client->url_parameters = false;
1391 $client->client_id = $ckey;
1392 $client->client_secret = $csecret;
1393 $client->access_token = $otoken;
1394 $client->access_token_secret = $osecret;
1396 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1398 if (pumpio_reachable($url))
1399 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1403 if ($users->totalItems > count($users->items)) {
1404 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1406 if (pumpio_reachable($url))
1407 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1412 if (is_array($users->items)) {
1413 foreach ($users->items AS $user) {
1414 pumpio_get_contact($uid, $user);
1419 function pumpio_queue_hook(&$a,&$b) {
1421 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1422 dbesc(NETWORK_PUMPIO)
1427 foreach($qi as $x) {
1428 if($x['network'] !== NETWORK_PUMPIO)
1431 logger('pumpio_queue: run');
1433 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1434 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1442 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1444 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1445 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1446 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1447 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1449 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1450 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1454 if ($oauth_token && $oauth_token_secret &&
1455 $consumer_key && $consumer_secret) {
1456 $username = $user.'@'.$host;
1458 logger('pumpio_queue: able to post for user '.$username);
1460 $z = unserialize($x['content']);
1462 $client = new oauth_client_class;
1463 $client->oauth_version = '1.0a';
1464 $client->url_parameters = false;
1465 $client->authorization_header = true;
1466 $client->access_token = $oauth_token;
1467 $client->access_token_secret = $oauth_token_secret;
1468 $client->client_id = $consumer_key;
1469 $client->client_secret = $consumer_secret;
1471 if (pumpio_reachable($z['url']))
1472 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1477 $post_id = $user->object->id;
1478 logger('pumpio_queue: send '.$username.': success '.$post_id);
1479 if($post_id && $iscomment) {
1480 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1481 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1483 Queue::removeItem($x['id']);
1485 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1487 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1490 logger('pumpio_queue: delayed');
1491 Queue::updateTime($x['id']);
1496 function pumpio_getreceiver(&$a, $b) {
1500 if (!$b["private"]) {
1502 if(! strstr($b['postopts'],'pumpio'))
1505 $public = PConfig::get($b['uid'], "pumpio", "public");
1508 $receiver["to"][] = [
1509 "objectType" => "collection",
1510 "id" => "http://activityschema.org/collection/public"];
1512 $cids = explode("><", $b["allow_cid"]);
1513 $gids = explode("><", $b["allow_gid"]);
1515 foreach ($cids AS $cid) {
1516 $cid = trim($cid, " <>");
1518 $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",
1521 dbesc(NETWORK_PUMPIO)
1525 $receiver["bcc"][] = [
1526 "displayName" => $r[0]["name"],
1527 "objectType" => "person",
1528 "preferredUsername" => $r[0]["nick"],
1529 "url" => $r[0]["url"]];
1532 foreach ($gids AS $gid) {
1533 $gid = trim($gid, " <>");
1535 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1536 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1537 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1539 dbesc(NETWORK_PUMPIO)
1542 foreach ($r AS $row)
1543 $receiver["bcc"][] = [
1544 "displayName" => $row["name"],
1545 "objectType" => "person",
1546 "preferredUsername" => $row["nick"],
1547 "url" => $row["url"]];
1551 if ($b["inform"] != "") {
1553 $inform = explode(",", $b["inform"]);
1555 foreach ($inform AS $cid) {
1556 if (substr($cid, 0, 4) != "cid:")
1559 $cid = str_replace("cid:", "", $cid);
1561 $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",
1564 dbesc(NETWORK_PUMPIO)
1568 $receiver["to"][] = [
1569 "displayName" => $r[0]["name"],
1570 "objectType" => "person",
1571 "preferredUsername" => $r[0]["nick"],
1572 "url" => $r[0]["url"]];
1580 function pumpio_fetchallcomments(&$a, $uid, $id) {
1581 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1582 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1583 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1584 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1585 $hostname = PConfig::get($uid, 'pumpio','host');
1586 $username = PConfig::get($uid, "pumpio", "user");
1588 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1590 $own_id = "https://".$hostname."/".$username;
1592 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1595 // Fetching the original post
1596 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1604 $url = $r[0]["extid"];
1606 $client = new oauth_client_class;
1607 $client->oauth_version = '1.0a';
1608 $client->authorization_header = true;
1609 $client->url_parameters = false;
1611 $client->client_id = $ckey;
1612 $client->client_secret = $csecret;
1613 $client->access_token = $otoken;
1614 $client->access_token_secret = $osecret;
1616 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1618 if (pumpio_reachable($url))
1619 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1626 if ($item->likes->totalItems != 0) {
1627 foreach ($item->likes->items AS $post) {
1628 $like = new stdClass;
1629 $like->object = new stdClass;
1630 $like->object->id = $item->id;
1631 $like->actor = new stdClass;
1632 $like->actor->displayName = $item->displayName;
1633 $like->actor->preferredUsername = $item->preferredUsername;
1634 $like->actor->url = $item->url;
1635 $like->actor->image = $item->image;
1636 $like->generator = new stdClass;
1637 $like->generator->displayName = "pumpio";
1638 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1642 if ($item->replies->totalItems == 0)
1645 foreach ($item->replies->items AS $item) {
1646 if ($item->id == $id)
1649 // Checking if the comment already exists - Two queries for speed issues
1650 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1658 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1666 $post = new stdClass;
1667 $post->verb = "post";
1668 $post->actor = $item->author;
1669 $post->published = $item->published;
1670 $post->received = $item->updated;
1671 $post->generator = new stdClass;
1672 $post->generator->displayName = "pumpio";
1673 // To-Do: Check for public post
1675 unset($item->author);
1676 unset($item->published);
1677 unset($item->updated);
1679 $post->object = $item;
1681 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1682 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1687 function pumpio_reachable($url) {
1688 $data = Network::curl($url, false, $redirects, ['timeout'=>10]);
1689 return(intval($data['return_code']) != 0);