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;
25 require 'addon/pumpio/oauth/http.php';
26 require 'addon/pumpio/oauth/oauth_client.php';
27 require_once 'include/enotify.php';
28 require_once "mod/share.php";
30 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
32 function pumpio_install() {
33 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
34 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
35 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
36 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
37 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
38 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
39 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
40 Addon::registerHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
43 function pumpio_uninstall() {
44 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
45 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
46 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
47 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
48 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
49 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
50 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
51 Addon::unregisterHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
54 function pumpio_module() {}
56 function pumpio_content(&$a) {
59 notice(L10n::t('Permission denied.') . EOL);
63 require_once("mod/settings.php");
66 if (isset($a->argv[1]))
67 switch ($a->argv[1]) {
69 $o = pumpio_connect($a);
72 $o = print_r($a->argv, true);
76 $o = pumpio_connect($a);
81 function pumpio_check_item_notification($a, &$notification_data) {
82 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
83 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
85 $notification_data["profiles"][] = "https://".$hostname."/".$username;
89 function pumpio_registerclient(&$a, $host) {
91 $url = "https://".$host."/api/client/register";
95 $application_name = Config::get('pumpio', 'application_name');
97 if ($application_name == "")
98 $application_name = $a->get_hostname();
100 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
102 $params["type"] = "client_associate";
103 $params["contacts"] = $adminlist[0];
104 $params["application_type"] = "native";
105 $params["application_name"] = $application_name;
106 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
107 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
109 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
111 $ch = curl_init($url);
112 curl_setopt($ch, CURLOPT_HEADER, false);
113 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
114 curl_setopt($ch, CURLOPT_POST,1);
115 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
116 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
119 $curl_info = curl_getinfo($ch);
121 if ($curl_info["http_code"] == "200") {
122 $values = json_decode($s);
123 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
126 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
131 function pumpio_connect(&$a) {
132 // Start a session. This is necessary to hold on to a few keys the callback script will also need
135 // Define the needed keys
136 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
137 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
138 $hostname = PConfig::get(local_user(), 'pumpio','host');
140 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
141 logger("pumpio_connect: register client");
142 $clientdata = pumpio_registerclient($a, $hostname);
143 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
144 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
146 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
147 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
149 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
152 if (($consumer_key == "") || ($consumer_secret == "")) {
153 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
155 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
159 // The callback URL is the script that gets called after the user authenticates with pumpio
160 $callback_url = $a->get_baseurl()."/pumpio/connect";
162 // Let's begin. First we need a Request Token. The request token is required to send the user
163 // to pumpio's login page.
165 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
166 // Consumer Key and Consumer Secret
167 $client = new oauth_client_class;
169 $client->server = '';
170 $client->oauth_version = '1.0a';
171 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
172 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
173 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
174 $client->url_parameters = false;
175 $client->authorization_header = true;
176 $client->redirect_uri = $callback_url;
177 $client->client_id = $consumer_key;
178 $client->client_secret = $consumer_secret;
180 if (($success = $client->Initialize())) {
181 if (($success = $client->Process())) {
182 if (strlen($client->access_token)) {
183 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
184 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
185 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
188 $success = $client->Finalize($success);
191 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
194 logger("pumpio_connect: authenticated");
195 $o .= L10n::t("You are now authenticated to pumpio.");
196 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
198 logger("pumpio_connect: could not connect");
199 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
205 function pumpio_jot_nets(&$a,&$b) {
209 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
210 if(intval($pumpio_post) == 1) {
211 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
212 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
213 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
214 . L10n::t('Post to pumpio') . '</div>';
219 function pumpio_settings(&$a,&$s) {
224 /* Add our stylesheet to the page so we can make our settings look nice */
226 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
228 /* Get the current state of our config variables */
230 $import_enabled = PConfig::get(local_user(),'pumpio','import');
231 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
233 $enabled = PConfig::get(local_user(),'pumpio','post');
234 $checked = (($enabled) ? ' checked="checked" ' : '');
235 $css = (($enabled) ? '' : '-disabled');
237 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
238 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
240 $public_enabled = PConfig::get(local_user(),'pumpio','public');
241 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
243 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
244 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
246 $servername = PConfig::get(local_user(), "pumpio", "host");
247 $username = PConfig::get(local_user(), "pumpio", "user");
249 /* Add some HTML to the existing form */
251 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
252 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
254 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
255 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
256 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
259 $s .= '<div id="pumpio-username-wrapper">';
260 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
261 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
262 $s .= '</div><div class="clear"></div>';
264 $s .= '<div id="pumpio-servername-wrapper">';
265 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
266 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
267 $s .= '</div><div class="clear"></div>';
269 if (($username != '') && ($servername != '')) {
271 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
272 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
274 $s .= '<div id="pumpio-password-wrapper">';
275 if (($oauth_token == "") || ($oauth_token_secret == "")) {
276 $s .= '<div id="pumpio-authenticate-wrapper">';
277 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
278 $s .= '</div><div class="clear"></div>';
280 $s .= '<div id="pumpio-import-wrapper">';
281 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
282 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
283 $s .= '</div><div class="clear"></div>';
285 $s .= '<div id="pumpio-enable-wrapper">';
286 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
287 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
288 $s .= '</div><div class="clear"></div>';
290 $s .= '<div id="pumpio-bydefault-wrapper">';
291 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
292 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
293 $s .= '</div><div class="clear"></div>';
295 $s .= '<div id="pumpio-public-wrapper">';
296 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
297 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
298 $s .= '</div><div class="clear"></div>';
300 $s .= '<div id="pumpio-mirror-wrapper">';
301 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
302 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
303 $s .= '</div><div class="clear"></div>';
305 $s .= '<div id="pumpio-delete-wrapper">';
306 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
307 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
308 $s .= '</div><div class="clear"></div>';
311 $s .= '</div><div class="clear"></div>';
314 /* provide a submit button */
316 $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>';
320 function pumpio_settings_post(&$a,&$b) {
322 if(x($_POST,'pumpio-submit')) {
323 if(x($_POST,'pumpio_delete')) {
324 PConfig::set(local_user(),'pumpio','consumer_key','');
325 PConfig::set(local_user(),'pumpio','consumer_secret','');
326 PConfig::set(local_user(),'pumpio','oauth_token','');
327 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
328 PConfig::set(local_user(),'pumpio','post',false);
329 PConfig::set(local_user(),'pumpio','import',false);
330 PConfig::set(local_user(),'pumpio','host','');
331 PConfig::set(local_user(),'pumpio','user','');
332 PConfig::set(local_user(),'pumpio','public',false);
333 PConfig::set(local_user(),'pumpio','mirror',false);
334 PConfig::set(local_user(),'pumpio','post_by_default',false);
335 PConfig::set(local_user(),'pumpio','lastdate', 0);
336 PConfig::set(local_user(),'pumpio','last_id', '');
338 // filtering the username if it is filled wrong
339 $user = $_POST['pumpio_user'];
340 if (strstr($user, "@")) {
341 $pos = strpos($user, "@");
343 $user = substr($user, 0, $pos);
346 // Filtering the hostname if someone is entering it with "http"
347 $host = $_POST['pumpio_host'];
349 $host = str_replace(["https://", "http://"], ["", ""], $host);
351 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
352 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
353 PConfig::set(local_user(),'pumpio','host',$host);
354 PConfig::set(local_user(),'pumpio','user',$user);
355 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
356 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
357 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
359 if (!$_POST['pumpio_mirror'])
360 PConfig::delete(local_user(),'pumpio','lastdate');
362 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
367 function pumpio_post_local(&$a, &$b) {
369 if (!local_user() || (local_user() != $b['uid'])) {
373 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
375 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
377 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
381 if (!$pumpio_enable) {
385 if (strlen($b['postopts'])) {
386 $b['postopts'] .= ',';
389 $b['postopts'] .= 'pumpio';
395 function pumpio_send(&$a,&$b) {
397 if (!PConfig::get($b["uid"],'pumpio','import')) {
398 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
402 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
404 if($b['parent'] != $b['id']) {
405 // Looking if its a reply to a pumpio post
406 $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",
407 intval($b["parent"]),
409 dbesc(NETWORK_PUMPIO));
412 logger("pumpio_send: no pumpio post ".$b["parent"]);
421 $receiver = pumpio_getreceiver($a, $b);
423 logger("pumpio_send: receiver ".print_r($receiver, true));
425 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio'))) {
429 // Dont't post if the post doesn't belong to us.
430 // This is a check for forum postings
431 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
432 if ($b['contact-id'] != $self['id']) {
437 if($b['verb'] == ACTIVITY_LIKE) {
439 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
441 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
445 if($b['verb'] == ACTIVITY_DISLIKE)
448 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
449 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
451 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
452 pumpio_action($a, $b["uid"], $b["uri"], "delete");
454 if($b['deleted'] || ($b['created'] !== $b['edited']))
457 // if post comes from pump.io don't send it back
458 if($b['app'] == "pump.io")
462 // Support for native shares
463 // http://<hostname>/api/<type>/shares?id=<the-object-id>
465 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
466 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
467 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
468 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
470 $host = PConfig::get($b['uid'], "pumpio", "host");
471 $user = PConfig::get($b['uid'], "pumpio", "user");
472 $public = PConfig::get($b['uid'], "pumpio", "public");
474 if($oauth_token && $oauth_token_secret) {
475 $title = trim($b['title']);
477 $content = BBCode::convert($b['body'], false, 4);
481 $params["verb"] = "post";
484 $params["object"] = [
485 'objectType' => "note",
486 'content' => $content];
489 $params["object"]["displayName"] = $title;
491 if (count($receiver["to"]))
492 $params["to"] = $receiver["to"];
494 if (count($receiver["bto"]))
495 $params["bto"] = $receiver["bto"];
497 if (count($receiver["cc"]))
498 $params["cc"] = $receiver["cc"];
500 if (count($receiver["bcc"]))
501 $params["bcc"] = $receiver["bcc"];
504 $inReplyTo = ["id" => $orig_post["uri"],
505 "objectType" => "note"];
507 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
508 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
510 $params["object"] = [
511 'objectType' => "comment",
512 'content' => $content,
513 'inReplyTo' => $inReplyTo];
516 $params["object"]["displayName"] = $title;
519 $client = new oauth_client_class;
520 $client->oauth_version = '1.0a';
521 $client->url_parameters = false;
522 $client->authorization_header = true;
523 $client->access_token = $oauth_token;
524 $client->access_token_secret = $oauth_token_secret;
525 $client->client_id = $consumer_key;
526 $client->client_secret = $consumer_secret;
528 $username = $user.'@'.$host;
529 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
531 if (pumpio_reachable($url))
532 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
538 if ($user->generator->displayName)
539 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
541 $post_id = $user->object->id;
542 logger('pumpio_send '.$username.': success '.$post_id);
543 if($post_id && $iscomment) {
544 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
545 Item::update(['extid' => $post_id], ['id' => $b['id']]);
548 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
550 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
552 $a->contact = $r[0]["id"];
554 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
556 Queue::add($a->contact, NETWORK_PUMPIO, $s);
557 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
562 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
564 // Don't do likes and other stuff if you don't import the timeline
565 if (!PConfig::get($uid,'pumpio','import'))
568 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
569 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
570 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
571 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
572 $hostname = PConfig::get($uid, 'pumpio','host');
573 $username = PConfig::get($uid, "pumpio", "user");
575 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
585 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
586 $uri = $orig_post["extid"];
588 $uri = $orig_post["uri"];
590 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
591 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
592 elseif (strstr($uri, "/api/comment/"))
593 $objectType = "comment";
594 elseif (strstr($uri, "/api/note/"))
595 $objectType = "note";
596 elseif (strstr($uri, "/api/image/"))
597 $objectType = "image";
599 $params["verb"] = $action;
600 $params["object"] = ['id' => $uri,
601 "objectType" => $objectType,
602 "content" => $content];
604 $client = new oauth_client_class;
605 $client->oauth_version = '1.0a';
606 $client->authorization_header = true;
607 $client->url_parameters = false;
609 $client->client_id = $ckey;
610 $client->client_secret = $csecret;
611 $client->access_token = $otoken;
612 $client->access_token_secret = $osecret;
614 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
616 if (pumpio_reachable($url))
617 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
622 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
624 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
626 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
628 $a->contact = $r[0]["id"];
630 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
632 Queue::add($a->contact, NETWORK_PUMPIO, $s);
633 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
637 function pumpio_sync(&$a) {
638 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
644 $last = Config::get('pumpio','last_poll');
646 $poll_interval = intval(Config::get('pumpio','poll_interval'));
648 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
651 $next = $last + ($poll_interval * 60);
653 logger('pumpio: poll intervall not reached');
657 logger('pumpio: cron_start');
659 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
662 logger('pumpio: mirroring user '.$rr['uid']);
663 pumpio_fetchtimeline($a, $rr['uid']);
667 $abandon_days = intval(Config::get('system','account_abandon_days'));
668 if ($abandon_days < 1)
671 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
673 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
676 if ($abandon_days != 0) {
677 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
679 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
684 logger('pumpio: importing timeline from user '.$rr['uid']);
685 pumpio_fetchinbox($a, $rr['uid']);
687 // check for new contacts once a day
688 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
689 if($last_contact_check)
690 $next_contact_check = $last_contact_check + 86400;
692 $next_contact_check = 0;
694 if($next_contact_check <= time()) {
695 pumpio_getallusers($a, $rr["uid"]);
696 PConfig::set($rr['uid'],'pumpio','contact_check',time());
701 logger('pumpio: cron_end');
703 Config::set('pumpio','last_poll', time());
706 function pumpio_cron(&$a,$b) {
707 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
710 function pumpio_fetchtimeline(&$a, $uid) {
711 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
712 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
713 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
714 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
715 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
716 $hostname = PConfig::get($uid, 'pumpio','host');
717 $username = PConfig::get($uid, "pumpio", "user");
719 // get the application name for the pump.io app
720 // 1st try personal config, then system config and fallback to the
721 // hostname of the node if neither one is set.
722 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
723 if ($application_name == "")
724 $application_name = Config::get('pumpio', 'application_name');
725 if ($application_name == "")
726 $application_name = $a->get_hostname();
728 $first_time = ($lastdate == "");
730 $client = new oauth_client_class;
731 $client->oauth_version = '1.0a';
732 $client->authorization_header = true;
733 $client->url_parameters = false;
735 $client->client_id = $ckey;
736 $client->client_secret = $csecret;
737 $client->access_token = $otoken;
738 $client->access_token_secret = $osecret;
740 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
742 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
744 $username = $user.'@'.$host;
746 if (pumpio_reachable($url))
747 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
752 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
756 $posts = array_reverse($user->items);
758 $initiallastdate = $lastdate;
762 foreach ($posts as $post) {
763 if ($post->published <= $initiallastdate)
766 if ($lastdate < $post->published)
767 $lastdate = $post->published;
773 if (@is_array($post->cc))
774 $receiptians = array_merge($receiptians, $post->cc);
776 if (@is_array($post->to))
777 $receiptians = array_merge($receiptians, $post->to);
780 foreach ($receiptians AS $receiver)
781 if (is_string($receiver->objectType))
782 if ($receiver->id == "http://activityschema.org/collection/public")
785 if ($public && !stristr($post->generator->displayName, $application_name)) {
786 $_SESSION["authenticated"] = true;
787 $_SESSION["uid"] = $uid;
790 $_REQUEST["type"] = "wall";
791 $_REQUEST["api_source"] = true;
792 $_REQUEST["profile_uid"] = $uid;
793 $_REQUEST["source"] = "pump.io";
795 if (isset($post->object->id)) {
796 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
799 if ($post->object->displayName != "")
800 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
802 $_REQUEST["title"] = "";
804 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
806 // To-Do: Picture has to be cached and stored locally
807 if ($post->object->fullImage->url != "") {
808 if ($post->object->fullImage->pump_io->proxyURL != "")
809 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
811 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
814 logger('pumpio: posting for user '.$uid);
816 require_once('mod/item.php');
819 logger('pumpio: posting done - user '.$uid);
825 PConfig::set($uid,'pumpio','lastdate', $lastdate);
828 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
829 // Searching for the unliked post
830 // Two queries for speed issues
831 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
832 dbesc($post->object->id),
839 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
840 dbesc($post->object->id),
852 if(link_compare($post->actor->url, $own_id)) {
853 $contactid = $self[0]['id'];
855 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
856 dbesc(normalise_link($post->actor->url)),
861 $contactid = $r[0]['id'];
864 $contactid = $orig_post['contact-id'];
867 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
870 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
872 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
875 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
876 require_once('include/items.php');
878 if ($post->object->id == "") {
879 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
883 // Searching for the liked post
884 // Two queries for speed issues
885 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
886 dbesc($post->object->id),
888 dbesc(NETWORK_PUMPIO)
894 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
895 dbesc($post->object->id),
897 dbesc(NETWORK_PUMPIO)
907 if ($threadcompletion)
908 pumpio_fetchallcomments($a, $uid, $post->object->id);
912 if(link_compare($post->actor->url, $own_id)) {
913 $contactid = $self[0]['id'];
914 $post->actor->displayName = $self[0]['name'];
915 $post->actor->url = $self[0]['url'];
916 $post->actor->image->url = $self[0]['photo'];
918 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
919 dbesc(normalise_link($post->actor->url)),
924 $contactid = $r[0]['id'];
927 $contactid = $orig_post['contact-id'];
930 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
931 dbesc(ACTIVITY_LIKE),
934 dbesc($orig_post['uri'])
938 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
943 $likedata['parent'] = $orig_post['id'];
944 $likedata['verb'] = ACTIVITY_LIKE;
945 $likedata['gravity'] = 3;
946 $likedata['uid'] = $uid;
947 $likedata['wall'] = 0;
948 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
949 $likedata['parent-uri'] = $orig_post["uri"];
950 $likedata['contact-id'] = $contactid;
951 $likedata['app'] = $post->generator->displayName;
952 $likedata['author-name'] = $post->actor->displayName;
953 $likedata['author-link'] = $post->actor->url;
954 $likedata['author-avatar'] = $post->actor->image->url;
956 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
957 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
958 $post_type = L10n::t('status');
959 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
960 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
962 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
964 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
965 '<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>';
967 $ret = Item::insert($likedata);
969 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
972 function pumpio_get_contact($uid, $contact, $no_insert = false) {
974 GContact::update(["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
975 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
976 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
977 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)]);
978 $cid = Contact::getIdForURL($contact->url, $uid);
983 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
984 intval($uid), dbesc(normalise_link($contact->url)));
987 // create contact record
988 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
989 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
990 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
991 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
993 dbesc(DateTimeFormat::utcNow()),
994 dbesc($contact->url),
995 dbesc(normalise_link($contact->url)),
996 dbesc(str_replace("acct:", "", $contact->id)),
998 dbesc($contact->id), // What is it for?
999 dbesc('pump.io ' . $contact->id), // What is it for?
1000 dbesc($contact->displayName),
1001 dbesc($contact->preferredUsername),
1002 dbesc($contact->image->url),
1003 dbesc(NETWORK_PUMPIO),
1004 intval(CONTACT_IS_FRIEND),
1006 dbesc($contact->location->displayName),
1007 dbesc($contact->summary),
1011 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1012 dbesc(normalise_link($contact->url)),
1020 $contact_id = $r[0]['id'];
1022 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1024 $contact_id = $r[0]["id"];
1026 /* if (DB_UPDATE_VERSION >= "1177")
1027 q("UPDATE `contact` SET `location` = '%s',
1030 dbesc($contact->location->displayName),
1031 dbesc($contact->summary),
1037 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1039 return($contact_id);
1042 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1044 // Two queries for speed issues
1045 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1046 dbesc($post->object->id),
1051 return Item::deleteById($r[0]["id"]);
1053 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1054 dbesc($post->object->id),
1059 return Item::deleteById($r[0]["id"]);
1062 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1063 require_once('include/items.php');
1065 if (($post->verb == "like") || ($post->verb == "favorite"))
1066 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1068 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1069 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1071 if ($post->verb == "delete")
1072 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1074 if ($post->verb != "update") {
1075 // Two queries for speed issues
1076 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1077 dbesc($post->object->id),
1084 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1085 dbesc($post->object->id),
1093 // Only handle these three types
1094 if (!strstr("post|share|update", $post->verb))
1098 if (@is_array($post->cc))
1099 $receiptians = array_merge($receiptians, $post->cc);
1101 if (@is_array($post->to))
1102 $receiptians = array_merge($receiptians, $post->to);
1104 foreach ($receiptians AS $receiver)
1105 if (is_string($receiver->objectType))
1106 if ($receiver->id == "http://activityschema.org/collection/public")
1110 $postarray['network'] = NETWORK_PUMPIO;
1111 $postarray['gravity'] = 0;
1112 $postarray['uid'] = $uid;
1113 $postarray['wall'] = 0;
1114 $postarray['uri'] = $post->object->id;
1115 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1117 if ($post->object->objectType != "comment") {
1118 $contact_id = pumpio_get_contact($uid, $post->actor);
1121 $contact_id = $self[0]['id'];
1123 $postarray['parent-uri'] = $post->object->id;
1126 $postarray['private'] = 1;
1127 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1130 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1132 if (link_compare($post->actor->url, $own_id)) {
1133 $contact_id = $self[0]['id'];
1134 $post->actor->displayName = $self[0]['name'];
1135 $post->actor->url = $self[0]['url'];
1136 $post->actor->image->url = $self[0]['photo'];
1137 } elseif ($contact_id == 0) {
1138 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1139 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1140 dbesc(normalise_link($post->actor->url)),
1145 $contact_id = $r[0]['id'];
1147 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1148 dbesc(normalise_link($post->actor->url)),
1153 $contact_id = $r[0]['id'];
1155 $contact_id = $self[0]['id'];
1159 $reply = new stdClass;
1160 $reply->verb = "note";
1161 $reply->cc = $post->cc;
1162 $reply->to = $post->to;
1163 $reply->object = new stdClass;
1164 $reply->object->objectType = $post->object->inReplyTo->objectType;
1165 $reply->object->content = $post->object->inReplyTo->content;
1166 $reply->object->id = $post->object->inReplyTo->id;
1167 $reply->actor = $post->object->inReplyTo->author;
1168 $reply->url = $post->object->inReplyTo->url;
1169 $reply->generator = new stdClass;
1170 $reply->generator->displayName = "pumpio";
1171 $reply->published = $post->object->inReplyTo->published;
1172 $reply->received = $post->object->inReplyTo->updated;
1173 $reply->url = $post->object->inReplyTo->url;
1174 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1176 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1179 if ($post->object->pump_io->proxyURL)
1180 $postarray['extid'] = $post->object->pump_io->proxyURL;
1182 $postarray['contact-id'] = $contact_id;
1183 $postarray['verb'] = ACTIVITY_POST;
1184 $postarray['owner-name'] = $post->actor->displayName;
1185 $postarray['owner-link'] = $post->actor->url;
1186 $postarray['owner-avatar'] = $post->actor->image->url;
1187 $postarray['author-name'] = $post->actor->displayName;
1188 $postarray['author-link'] = $post->actor->url;
1189 $postarray['author-avatar'] = $post->actor->image->url;
1190 $postarray['plink'] = $post->object->url;
1191 $postarray['app'] = $post->generator->displayName;
1192 $postarray['body'] = HTML::toBBCode($post->object->content);
1193 $postarray['object'] = json_encode($post);
1195 if ($post->object->fullImage->url != "")
1196 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1198 if ($post->object->displayName != "")
1199 $postarray['title'] = $post->object->displayName;
1201 $postarray['created'] = DateTimeFormat::utc($post->published);
1202 if (isset($post->updated))
1203 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1204 elseif (isset($post->received))
1205 $postarray['edited'] = DateTimeFormat::utc($post->received);
1207 $postarray['edited'] = $postarray['created'];
1209 if ($post->verb == "share") {
1210 if (!intval(Config::get('system','wall-to-wall_share'))) {
1211 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1212 $share_author = $post->object->author->displayName;
1213 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1214 $share_author = $post->object->author->preferredUsername;
1216 $share_author = $post->object->author->url;
1218 $postarray['body'] = share_header($share_author, $post->object->author->url,
1219 $post->object->author->image->url, "",
1220 DateTimeFormat::utc($post->object->created),
1221 $post->links->self->href).
1222 $postarray['body']."[/share]";
1225 $postarray['body'] = "[share author='".$share_author.
1226 "' profile='".$post->object->author->url.
1227 "' avatar='".$post->object->author->image->url.
1228 "' posted='".DateTimeFormat::convert($post->object->created, 'UTC', 'UTC', ).
1229 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1232 // Let shares look like wall-to-wall posts
1233 $postarray['author-name'] = $post->object->author->displayName;
1234 $postarray['author-link'] = $post->object->author->url;
1235 $postarray['author-avatar'] = $post->object->author->image->url;
1239 if (trim($postarray['body']) == "")
1242 $top_item = Item::insert($postarray);
1243 $postarray["id"] = $top_item;
1245 if (($top_item == 0) && ($post->verb == "update")) {
1246 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1247 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1248 Item::update($fields, $condition);
1251 if ($post->object->objectType == "comment") {
1253 if ($threadcompletion)
1254 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1256 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1263 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1265 if (link_compare($own_id, $postarray['author-link']))
1268 if (!function_exists("check_item_notification")) {
1269 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1270 dbesc($postarray['parent-uri']),
1274 if(count($myconv)) {
1276 foreach($myconv as $conv) {
1277 // now if we find a match, it means we're in this conversation
1279 if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1282 require_once('include/enotify.php');
1284 $conv_parent = $conv['parent'];
1287 'type' => NOTIFY_COMMENT,
1288 'notify_flags' => $user[0]['notify-flags'],
1289 'language' => $user[0]['language'],
1290 'to_name' => $user[0]['username'],
1291 'to_email' => $user[0]['email'],
1292 'uid' => $user[0]['uid'],
1293 'item' => $postarray,
1294 'link' => $a->get_baseurl().'/display/'.urlencode(Item::getGuidById($top_item)),
1295 'source_name' => $postarray['author-name'],
1296 'source_link' => $postarray['author-link'],
1297 'source_photo' => $postarray['author-avatar'],
1298 'verb' => ACTIVITY_POST,
1300 'parent' => $conv_parent,
1303 // only send one notification
1313 function pumpio_fetchinbox(&$a, $uid) {
1315 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1316 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1317 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1318 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1319 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1320 $hostname = PConfig::get($uid, 'pumpio','host');
1321 $username = PConfig::get($uid, "pumpio", "user");
1323 $own_id = "https://".$hostname."/".$username;
1325 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1328 $lastitems = q("SELECT `uri` FROM `thread`
1329 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1330 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1331 ORDER BY `thread`.`commented` DESC LIMIT 10",
1332 dbesc(NETWORK_PUMPIO),
1336 $client = new oauth_client_class;
1337 $client->oauth_version = '1.0a';
1338 $client->authorization_header = true;
1339 $client->url_parameters = false;
1341 $client->client_id = $ckey;
1342 $client->client_secret = $csecret;
1343 $client->access_token = $otoken;
1344 $client->access_token_secret = $osecret;
1346 $last_id = PConfig::get($uid,'pumpio','last_id');
1348 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1351 $url .= '?since='.urlencode($last_id);
1353 if (pumpio_reachable($url))
1354 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1359 $posts = array_reverse($user->items);
1362 foreach ($posts as $post) {
1363 $last_id = $post->id;
1364 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1368 foreach ($lastitems AS $item)
1369 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1371 PConfig::set($uid,'pumpio','last_id', $last_id);
1374 function pumpio_getallusers(&$a, $uid) {
1375 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1376 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1377 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1378 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1379 $hostname = PConfig::get($uid, 'pumpio','host');
1380 $username = PConfig::get($uid, "pumpio", "user");
1382 $client = new oauth_client_class;
1383 $client->oauth_version = '1.0a';
1384 $client->authorization_header = true;
1385 $client->url_parameters = false;
1387 $client->client_id = $ckey;
1388 $client->client_secret = $csecret;
1389 $client->access_token = $otoken;
1390 $client->access_token_secret = $osecret;
1392 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1394 if (pumpio_reachable($url))
1395 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1399 if ($users->totalItems > count($users->items)) {
1400 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1402 if (pumpio_reachable($url))
1403 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1408 if (is_array($users->items)) {
1409 foreach ($users->items AS $user) {
1410 pumpio_get_contact($uid, $user);
1415 function pumpio_queue_hook(&$a,&$b) {
1417 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1418 dbesc(NETWORK_PUMPIO)
1423 foreach($qi as $x) {
1424 if($x['network'] !== NETWORK_PUMPIO)
1427 logger('pumpio_queue: run');
1429 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1430 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1438 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1440 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1441 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1442 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1443 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1445 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1446 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1450 if ($oauth_token && $oauth_token_secret &&
1451 $consumer_key && $consumer_secret) {
1452 $username = $user.'@'.$host;
1454 logger('pumpio_queue: able to post for user '.$username);
1456 $z = unserialize($x['content']);
1458 $client = new oauth_client_class;
1459 $client->oauth_version = '1.0a';
1460 $client->url_parameters = false;
1461 $client->authorization_header = true;
1462 $client->access_token = $oauth_token;
1463 $client->access_token_secret = $oauth_token_secret;
1464 $client->client_id = $consumer_key;
1465 $client->client_secret = $consumer_secret;
1467 if (pumpio_reachable($z['url']))
1468 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1473 $post_id = $user->object->id;
1474 logger('pumpio_queue: send '.$username.': success '.$post_id);
1475 if($post_id && $iscomment) {
1476 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1477 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1479 Queue::removeItem($x['id']);
1481 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1483 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1486 logger('pumpio_queue: delayed');
1487 Queue::updateTime($x['id']);
1492 function pumpio_getreceiver(&$a, $b) {
1496 if (!$b["private"]) {
1498 if(! strstr($b['postopts'],'pumpio'))
1501 $public = PConfig::get($b['uid'], "pumpio", "public");
1504 $receiver["to"][] = [
1505 "objectType" => "collection",
1506 "id" => "http://activityschema.org/collection/public"];
1508 $cids = explode("><", $b["allow_cid"]);
1509 $gids = explode("><", $b["allow_gid"]);
1511 foreach ($cids AS $cid) {
1512 $cid = trim($cid, " <>");
1514 $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",
1517 dbesc(NETWORK_PUMPIO)
1521 $receiver["bcc"][] = [
1522 "displayName" => $r[0]["name"],
1523 "objectType" => "person",
1524 "preferredUsername" => $r[0]["nick"],
1525 "url" => $r[0]["url"]];
1528 foreach ($gids AS $gid) {
1529 $gid = trim($gid, " <>");
1531 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1532 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1533 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1535 dbesc(NETWORK_PUMPIO)
1538 foreach ($r AS $row)
1539 $receiver["bcc"][] = [
1540 "displayName" => $row["name"],
1541 "objectType" => "person",
1542 "preferredUsername" => $row["nick"],
1543 "url" => $row["url"]];
1547 if ($b["inform"] != "") {
1549 $inform = explode(",", $b["inform"]);
1551 foreach ($inform AS $cid) {
1552 if (substr($cid, 0, 4) != "cid:")
1555 $cid = str_replace("cid:", "", $cid);
1557 $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",
1560 dbesc(NETWORK_PUMPIO)
1564 $receiver["to"][] = [
1565 "displayName" => $r[0]["name"],
1566 "objectType" => "person",
1567 "preferredUsername" => $r[0]["nick"],
1568 "url" => $r[0]["url"]];
1576 function pumpio_fetchallcomments(&$a, $uid, $id) {
1577 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1578 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1579 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1580 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1581 $hostname = PConfig::get($uid, 'pumpio','host');
1582 $username = PConfig::get($uid, "pumpio", "user");
1584 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1586 $own_id = "https://".$hostname."/".$username;
1588 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1591 // Fetching the original post
1592 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1600 $url = $r[0]["extid"];
1602 $client = new oauth_client_class;
1603 $client->oauth_version = '1.0a';
1604 $client->authorization_header = true;
1605 $client->url_parameters = false;
1607 $client->client_id = $ckey;
1608 $client->client_secret = $csecret;
1609 $client->access_token = $otoken;
1610 $client->access_token_secret = $osecret;
1612 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1614 if (pumpio_reachable($url))
1615 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1622 if ($item->likes->totalItems != 0) {
1623 foreach ($item->likes->items AS $post) {
1624 $like = new stdClass;
1625 $like->object = new stdClass;
1626 $like->object->id = $item->id;
1627 $like->actor = new stdClass;
1628 $like->actor->displayName = $item->displayName;
1629 $like->actor->preferredUsername = $item->preferredUsername;
1630 $like->actor->url = $item->url;
1631 $like->actor->image = $item->image;
1632 $like->generator = new stdClass;
1633 $like->generator->displayName = "pumpio";
1634 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1638 if ($item->replies->totalItems == 0)
1641 foreach ($item->replies->items AS $item) {
1642 if ($item->id == $id)
1645 // Checking if the comment already exists - Two queries for speed issues
1646 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1654 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1662 $post = new stdClass;
1663 $post->verb = "post";
1664 $post->actor = $item->author;
1665 $post->published = $item->published;
1666 $post->received = $item->updated;
1667 $post->generator = new stdClass;
1668 $post->generator->displayName = "pumpio";
1669 // To-Do: Check for public post
1671 unset($item->author);
1672 unset($item->published);
1673 unset($item->updated);
1675 $post->object = $item;
1677 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1678 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1683 function pumpio_reachable($url) {
1684 $data = Network::curl($url, false, $redirects, ['timeout'=>10]);
1685 return(intval($data['return_code']) != 0);