3 * Name: pump.io Post Connector
4 * Description: Bidirectional (posting, relaying and reading) connector for pump.io.
6 * Author: Michael Vogel <http://pirati.ca/profile/heluecht>
8 use Friendica\Core\Config;
9 use Friendica\Core\PConfig;
10 use Friendica\Core\Worker;
11 use Friendica\Model\Contact;
12 use Friendica\Model\GContact;
13 use Friendica\Model\Group;
14 use Friendica\Model\User;
15 use Friendica\Model\Item;
17 require 'addon/pumpio/oauth/http.php';
18 require 'addon/pumpio/oauth/oauth_client.php';
19 require_once 'include/enotify.php';
20 require_once "mod/share.php";
22 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
24 function pumpio_install() {
25 register_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
26 register_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
27 register_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
28 register_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
29 register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
30 register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
31 register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
32 register_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
35 function pumpio_uninstall() {
36 unregister_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
37 unregister_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
38 unregister_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
39 unregister_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
40 unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
41 unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
42 unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
43 unregister_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
46 function pumpio_module() {}
48 function pumpio_content(&$a) {
51 notice( t('Permission denied.') . EOL);
55 require_once("mod/settings.php");
58 if (isset($a->argv[1]))
59 switch ($a->argv[1]) {
61 $o = pumpio_connect($a);
64 $o = print_r($a->argv, true);
68 $o = pumpio_connect($a);
73 function pumpio_check_item_notification($a, &$notification_data) {
74 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
75 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
77 $notification_data["profiles"][] = "https://".$hostname."/".$username;
81 function pumpio_registerclient(&$a, $host) {
83 $url = "https://".$host."/api/client/register";
87 $application_name = Config::get('pumpio', 'application_name');
89 if ($application_name == "")
90 $application_name = $a->get_hostname();
92 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
94 $params["type"] = "client_associate";
95 $params["contacts"] = $adminlist[0];
96 $params["application_type"] = "native";
97 $params["application_name"] = $application_name;
98 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
99 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
101 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
103 $ch = curl_init($url);
104 curl_setopt($ch, CURLOPT_HEADER, false);
105 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
106 curl_setopt($ch, CURLOPT_POST,1);
107 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
108 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
111 $curl_info = curl_getinfo($ch);
113 if ($curl_info["http_code"] == "200") {
114 $values = json_decode($s);
115 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
118 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
123 function pumpio_connect(&$a) {
124 // Start a session. This is necessary to hold on to a few keys the callback script will also need
127 // Define the needed keys
128 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
129 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
130 $hostname = PConfig::get(local_user(), 'pumpio','host');
132 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
133 logger("pumpio_connect: register client");
134 $clientdata = pumpio_registerclient($a, $hostname);
135 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
136 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
138 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
139 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
141 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
144 if (($consumer_key == "") || ($consumer_secret == "")) {
145 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
147 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
151 // The callback URL is the script that gets called after the user authenticates with pumpio
152 $callback_url = $a->get_baseurl()."/pumpio/connect";
154 // Let's begin. First we need a Request Token. The request token is required to send the user
155 // to pumpio's login page.
157 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
158 // Consumer Key and Consumer Secret
159 $client = new oauth_client_class;
161 $client->server = '';
162 $client->oauth_version = '1.0a';
163 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
164 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
165 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
166 $client->url_parameters = false;
167 $client->authorization_header = true;
168 $client->redirect_uri = $callback_url;
169 $client->client_id = $consumer_key;
170 $client->client_secret = $consumer_secret;
172 if (($success = $client->Initialize())) {
173 if (($success = $client->Process())) {
174 if (strlen($client->access_token)) {
175 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
176 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
177 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
180 $success = $client->Finalize($success);
183 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
186 logger("pumpio_connect: authenticated");
187 $o .= t("You are now authenticated to pumpio.");
188 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
190 logger("pumpio_connect: could not connect");
191 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
197 function pumpio_jot_nets(&$a,&$b) {
201 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
202 if(intval($pumpio_post) == 1) {
203 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
204 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
205 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
206 . t('Post to pumpio') . '</div>';
211 function pumpio_settings(&$a,&$s) {
216 /* Add our stylesheet to the page so we can make our settings look nice */
218 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
220 /* Get the current state of our config variables */
222 $import_enabled = PConfig::get(local_user(),'pumpio','import');
223 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
225 $enabled = PConfig::get(local_user(),'pumpio','post');
226 $checked = (($enabled) ? ' checked="checked" ' : '');
227 $css = (($enabled) ? '' : '-disabled');
229 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
230 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
232 $public_enabled = PConfig::get(local_user(),'pumpio','public');
233 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
235 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
236 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
238 $servername = PConfig::get(local_user(), "pumpio", "host");
239 $username = PConfig::get(local_user(), "pumpio", "user");
241 /* Add some HTML to the existing form */
243 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
244 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
246 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
247 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
248 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
251 $s .= '<div id="pumpio-username-wrapper">';
252 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
253 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
254 $s .= '</div><div class="clear"></div>';
256 $s .= '<div id="pumpio-servername-wrapper">';
257 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
258 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
259 $s .= '</div><div class="clear"></div>';
261 if (($username != '') && ($servername != '')) {
263 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
264 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
266 $s .= '<div id="pumpio-password-wrapper">';
267 if (($oauth_token == "") || ($oauth_token_secret == "")) {
268 $s .= '<div id="pumpio-authenticate-wrapper">';
269 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
270 $s .= '</div><div class="clear"></div>';
272 $s .= '<div id="pumpio-import-wrapper">';
273 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
274 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
275 $s .= '</div><div class="clear"></div>';
277 $s .= '<div id="pumpio-enable-wrapper">';
278 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
279 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
280 $s .= '</div><div class="clear"></div>';
282 $s .= '<div id="pumpio-bydefault-wrapper">';
283 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
284 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
285 $s .= '</div><div class="clear"></div>';
287 $s .= '<div id="pumpio-public-wrapper">';
288 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
289 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
290 $s .= '</div><div class="clear"></div>';
292 $s .= '<div id="pumpio-mirror-wrapper">';
293 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
294 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
295 $s .= '</div><div class="clear"></div>';
297 $s .= '<div id="pumpio-delete-wrapper">';
298 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
299 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
300 $s .= '</div><div class="clear"></div>';
303 $s .= '</div><div class="clear"></div>';
306 /* provide a submit button */
308 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
312 function pumpio_settings_post(&$a,&$b) {
314 if(x($_POST,'pumpio-submit')) {
315 if(x($_POST,'pumpio_delete')) {
316 PConfig::set(local_user(),'pumpio','consumer_key','');
317 PConfig::set(local_user(),'pumpio','consumer_secret','');
318 PConfig::set(local_user(),'pumpio','oauth_token','');
319 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
320 PConfig::set(local_user(),'pumpio','post',false);
321 PConfig::set(local_user(),'pumpio','import',false);
322 PConfig::set(local_user(),'pumpio','host','');
323 PConfig::set(local_user(),'pumpio','user','');
324 PConfig::set(local_user(),'pumpio','public',false);
325 PConfig::set(local_user(),'pumpio','mirror',false);
326 PConfig::set(local_user(),'pumpio','post_by_default',false);
327 PConfig::set(local_user(),'pumpio','lastdate', 0);
328 PConfig::set(local_user(),'pumpio','last_id', '');
330 // filtering the username if it is filled wrong
331 $user = $_POST['pumpio_user'];
332 if (strstr($user, "@")) {
333 $pos = strpos($user, "@");
335 $user = substr($user, 0, $pos);
338 // Filtering the hostname if someone is entering it with "http"
339 $host = $_POST['pumpio_host'];
341 $host = str_replace(["https://", "http://"], ["", ""], $host);
343 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
344 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
345 PConfig::set(local_user(),'pumpio','host',$host);
346 PConfig::set(local_user(),'pumpio','user',$user);
347 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
348 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
349 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
351 if (!$_POST['pumpio_mirror'])
352 PConfig::delete(local_user(),'pumpio','lastdate');
354 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
359 function pumpio_post_local(&$a, &$b) {
361 if (!local_user() || (local_user() != $b['uid'])) {
365 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
367 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
369 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
373 if (!$pumpio_enable) {
377 if (strlen($b['postopts'])) {
378 $b['postopts'] .= ',';
381 $b['postopts'] .= 'pumpio';
387 function pumpio_send(&$a,&$b) {
389 if (!PConfig::get($b["uid"],'pumpio','import')) {
390 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
394 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
396 if($b['parent'] != $b['id']) {
397 // Looking if its a reply to a pumpio post
398 $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",
399 intval($b["parent"]),
401 dbesc(NETWORK_PUMPIO));
404 logger("pumpio_send: no pumpio post ".$b["parent"]);
413 $receiver = pumpio_getreceiver($a, $b);
415 logger("pumpio_send: receiver ".print_r($receiver, true));
417 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio'))) {
421 // Dont't post if the post doesn't belong to us.
422 // This is a check for forum postings
423 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
424 if ($b['contact-id'] != $self['id']) {
429 if($b['verb'] == ACTIVITY_LIKE) {
431 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
433 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
437 if($b['verb'] == ACTIVITY_DISLIKE)
440 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
441 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
443 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
444 pumpio_action($a, $b["uid"], $b["uri"], "delete");
446 if($b['deleted'] || ($b['created'] !== $b['edited']))
449 // if post comes from pump.io don't send it back
450 if($b['app'] == "pump.io")
454 // Support for native shares
455 // http://<hostname>/api/<type>/shares?id=<the-object-id>
457 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
458 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
459 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
460 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
462 $host = PConfig::get($b['uid'], "pumpio", "host");
463 $user = PConfig::get($b['uid'], "pumpio", "user");
464 $public = PConfig::get($b['uid'], "pumpio", "public");
466 if($oauth_token && $oauth_token_secret) {
468 require_once('include/bbcode.php');
470 $title = trim($b['title']);
472 $content = bbcode($b['body'], false, false, 4);
476 $params["verb"] = "post";
479 $params["object"] = [
480 'objectType' => "note",
481 'content' => $content];
484 $params["object"]["displayName"] = $title;
486 if (count($receiver["to"]))
487 $params["to"] = $receiver["to"];
489 if (count($receiver["bto"]))
490 $params["bto"] = $receiver["bto"];
492 if (count($receiver["cc"]))
493 $params["cc"] = $receiver["cc"];
495 if (count($receiver["bcc"]))
496 $params["bcc"] = $receiver["bcc"];
499 $inReplyTo = ["id" => $orig_post["uri"],
500 "objectType" => "note"];
502 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
503 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
505 $params["object"] = [
506 'objectType' => "comment",
507 'content' => $content,
508 'inReplyTo' => $inReplyTo];
511 $params["object"]["displayName"] = $title;
514 $client = new oauth_client_class;
515 $client->oauth_version = '1.0a';
516 $client->url_parameters = false;
517 $client->authorization_header = true;
518 $client->access_token = $oauth_token;
519 $client->access_token_secret = $oauth_token_secret;
520 $client->client_id = $consumer_key;
521 $client->client_secret = $consumer_secret;
523 $username = $user.'@'.$host;
524 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
526 if (pumpio_reachable($url))
527 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
533 if ($user->generator->displayName)
534 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
536 $post_id = $user->object->id;
537 logger('pumpio_send '.$username.': success '.$post_id);
538 if($post_id && $iscomment) {
539 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
540 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
546 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
548 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
550 $a->contact = $r[0]["id"];
552 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
553 require_once('include/queue_fn.php');
554 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
555 notice(t('Pump.io post failed. Queued for retry.').EOL);
561 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
563 // Don't do likes and other stuff if you don't import the timeline
564 if (!PConfig::get($uid,'pumpio','import'))
567 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
568 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
569 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
570 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
571 $hostname = PConfig::get($uid, 'pumpio','host');
572 $username = PConfig::get($uid, "pumpio", "user");
574 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
584 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
585 $uri = $orig_post["extid"];
587 $uri = $orig_post["uri"];
589 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
590 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
591 elseif (strstr($uri, "/api/comment/"))
592 $objectType = "comment";
593 elseif (strstr($uri, "/api/note/"))
594 $objectType = "note";
595 elseif (strstr($uri, "/api/image/"))
596 $objectType = "image";
598 $params["verb"] = $action;
599 $params["object"] = ['id' => $uri,
600 "objectType" => $objectType,
601 "content" => $content];
603 $client = new oauth_client_class;
604 $client->oauth_version = '1.0a';
605 $client->authorization_header = true;
606 $client->url_parameters = false;
608 $client->client_id = $ckey;
609 $client->client_secret = $csecret;
610 $client->access_token = $otoken;
611 $client->access_token_secret = $osecret;
613 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
615 if (pumpio_reachable($url))
616 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
621 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
623 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
625 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
627 $a->contact = $r[0]["id"];
629 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
630 require_once('include/queue_fn.php');
631 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
632 notice(t('Pump.io like failed. Queued for retry.').EOL);
636 function pumpio_sync(&$a) {
637 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
643 $last = Config::get('pumpio','last_poll');
645 $poll_interval = intval(Config::get('pumpio','poll_interval'));
647 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
650 $next = $last + ($poll_interval * 60);
652 logger('pumpio: poll intervall not reached');
656 logger('pumpio: cron_start');
658 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
661 logger('pumpio: mirroring user '.$rr['uid']);
662 pumpio_fetchtimeline($a, $rr['uid']);
666 $abandon_days = intval(Config::get('system','account_abandon_days'));
667 if ($abandon_days < 1)
670 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
672 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
675 if ($abandon_days != 0) {
676 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
678 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
683 logger('pumpio: importing timeline from user '.$rr['uid']);
684 pumpio_fetchinbox($a, $rr['uid']);
686 // check for new contacts once a day
687 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
688 if($last_contact_check)
689 $next_contact_check = $last_contact_check + 86400;
691 $next_contact_check = 0;
693 if($next_contact_check <= time()) {
694 pumpio_getallusers($a, $rr["uid"]);
695 PConfig::set($rr['uid'],'pumpio','contact_check',time());
700 logger('pumpio: cron_end');
702 Config::set('pumpio','last_poll', time());
705 function pumpio_cron(&$a,$b) {
706 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
709 function pumpio_fetchtimeline(&$a, $uid) {
710 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
711 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
712 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
713 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
714 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
715 $hostname = PConfig::get($uid, 'pumpio','host');
716 $username = PConfig::get($uid, "pumpio", "user");
718 // get the application name for the pump.io app
719 // 1st try personal config, then system config and fallback to the
720 // hostname of the node if neither one is set.
721 $application_name = PConfig::get( $uid, 'pumpio', 'application_name');
722 if ($application_name == "")
723 $application_name = Config::get('pumpio', 'application_name');
724 if ($application_name == "")
725 $application_name = $a->get_hostname();
727 $first_time = ($lastdate == "");
729 $client = new oauth_client_class;
730 $client->oauth_version = '1.0a';
731 $client->authorization_header = true;
732 $client->url_parameters = false;
734 $client->client_id = $ckey;
735 $client->client_secret = $csecret;
736 $client->access_token = $otoken;
737 $client->access_token_secret = $osecret;
739 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
741 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
743 $username = $user.'@'.$host;
745 if (pumpio_reachable($url))
746 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
751 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
755 $posts = array_reverse($user->items);
757 $initiallastdate = $lastdate;
761 foreach ($posts as $post) {
762 if ($post->published <= $initiallastdate)
765 if ($lastdate < $post->published)
766 $lastdate = $post->published;
772 if (@is_array($post->cc))
773 $receiptians = array_merge($receiptians, $post->cc);
775 if (@is_array($post->to))
776 $receiptians = array_merge($receiptians, $post->to);
779 foreach ($receiptians AS $receiver)
780 if (is_string($receiver->objectType))
781 if ($receiver->id == "http://activityschema.org/collection/public")
784 if ($public && !stristr($post->generator->displayName, $application_name)) {
785 require_once('include/html2bbcode.php');
787 $_SESSION["authenticated"] = true;
788 $_SESSION["uid"] = $uid;
791 $_REQUEST["type"] = "wall";
792 $_REQUEST["api_source"] = true;
793 $_REQUEST["profile_uid"] = $uid;
794 $_REQUEST["source"] = "pump.io";
796 if (isset($post->object->id)) {
797 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
800 if ($post->object->displayName != "")
801 $_REQUEST["title"] = html2bbcode($post->object->displayName);
803 $_REQUEST["title"] = "";
805 $_REQUEST["body"] = html2bbcode($post->object->content);
807 // To-Do: Picture has to be cached and stored locally
808 if ($post->object->fullImage->url != "") {
809 if ($post->object->fullImage->pump_io->proxyURL != "")
810 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
812 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
815 logger('pumpio: posting for user '.$uid);
817 require_once('mod/item.php');
820 logger('pumpio: posting done - user '.$uid);
826 PConfig::set($uid,'pumpio','lastdate', $lastdate);
829 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
830 // Searching for the unliked post
831 // Two queries for speed issues
832 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
833 dbesc($post->object->id),
840 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
841 dbesc($post->object->id),
853 if(link_compare($post->actor->url, $own_id)) {
854 $contactid = $self[0]['id'];
856 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
857 dbesc(normalise_link($post->actor->url)),
862 $contactid = $r[0]['id'];
865 $contactid = $orig_post['contact-id'];
868 $r = q("UPDATE `item` SET `deleted` = 1, `unseen` = 1, `changed` = '%s' WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s'",
869 dbesc(datetime_convert()),
870 dbesc(ACTIVITY_LIKE),
873 dbesc($orig_post['uri'])
877 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
879 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
882 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
883 require_once('include/items.php');
885 if ($post->object->id == "") {
886 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
890 // Searching for the liked post
891 // Two queries for speed issues
892 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
893 dbesc($post->object->id),
895 dbesc(NETWORK_PUMPIO)
901 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
902 dbesc($post->object->id),
904 dbesc(NETWORK_PUMPIO)
914 if ($threadcompletion)
915 pumpio_fetchallcomments($a, $uid, $post->object->id);
919 if(link_compare($post->actor->url, $own_id)) {
920 $contactid = $self[0]['id'];
921 $post->actor->displayName = $self[0]['name'];
922 $post->actor->url = $self[0]['url'];
923 $post->actor->image->url = $self[0]['photo'];
925 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
926 dbesc(normalise_link($post->actor->url)),
931 $contactid = $r[0]['id'];
934 $contactid = $orig_post['contact-id'];
937 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
938 dbesc(ACTIVITY_LIKE),
941 dbesc($orig_post['uri'])
945 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
950 $likedata['parent'] = $orig_post['id'];
951 $likedata['verb'] = ACTIVITY_LIKE;
952 $likedata['gravity'] = 3;
953 $likedata['uid'] = $uid;
954 $likedata['wall'] = 0;
955 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
956 $likedata['parent-uri'] = $orig_post["uri"];
957 $likedata['contact-id'] = $contactid;
958 $likedata['app'] = $post->generator->displayName;
959 $likedata['author-name'] = $post->actor->displayName;
960 $likedata['author-link'] = $post->actor->url;
961 $likedata['author-avatar'] = $post->actor->image->url;
963 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
964 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
965 $post_type = t('status');
966 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
967 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
969 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
971 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
972 '<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>';
974 $ret = item_store($likedata);
976 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
979 function pumpio_get_contact($uid, $contact, $no_insert = false) {
981 GContact::update(["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
982 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
983 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
984 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)]);
985 $cid = Contact::getIdForURL($contact->url, $uid);
990 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
991 intval($uid), dbesc(normalise_link($contact->url)));
994 // create contact record
995 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
996 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
997 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
998 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1000 dbesc(datetime_convert()),
1001 dbesc($contact->url),
1002 dbesc(normalise_link($contact->url)),
1003 dbesc(str_replace("acct:", "", $contact->id)),
1005 dbesc($contact->id), // What is it for?
1006 dbesc('pump.io ' . $contact->id), // What is it for?
1007 dbesc($contact->displayName),
1008 dbesc($contact->preferredUsername),
1009 dbesc($contact->image->url),
1010 dbesc(NETWORK_PUMPIO),
1011 intval(CONTACT_IS_FRIEND),
1013 dbesc($contact->location->displayName),
1014 dbesc($contact->summary),
1018 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1019 dbesc(normalise_link($contact->url)),
1027 $contact_id = $r[0]['id'];
1029 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1031 $contact_id = $r[0]["id"];
1033 /* if (DB_UPDATE_VERSION >= "1177")
1034 q("UPDATE `contact` SET `location` = '%s',
1037 dbesc($contact->location->displayName),
1038 dbesc($contact->summary),
1044 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1046 return($contact_id);
1049 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1051 // Two queries for speed issues
1052 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1053 dbesc($post->object->id),
1058 return Item::delete($r[0]["id"]);
1060 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1061 dbesc($post->object->id),
1066 return Item::delete($r[0]["id"]);
1069 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1070 require_once('include/items.php');
1071 require_once('include/html2bbcode.php');
1073 if (($post->verb == "like") || ($post->verb == "favorite"))
1074 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1076 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1077 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1079 if ($post->verb == "delete")
1080 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1082 if ($post->verb != "update") {
1083 // Two queries for speed issues
1084 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1085 dbesc($post->object->id),
1092 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1093 dbesc($post->object->id),
1101 // Only handle these three types
1102 if (!strstr("post|share|update", $post->verb))
1106 if (@is_array($post->cc))
1107 $receiptians = array_merge($receiptians, $post->cc);
1109 if (@is_array($post->to))
1110 $receiptians = array_merge($receiptians, $post->to);
1112 foreach ($receiptians AS $receiver)
1113 if (is_string($receiver->objectType))
1114 if ($receiver->id == "http://activityschema.org/collection/public")
1118 $postarray['network'] = NETWORK_PUMPIO;
1119 $postarray['gravity'] = 0;
1120 $postarray['uid'] = $uid;
1121 $postarray['wall'] = 0;
1122 $postarray['uri'] = $post->object->id;
1123 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1125 if ($post->object->objectType != "comment") {
1126 $contact_id = pumpio_get_contact($uid, $post->actor);
1129 $contact_id = $self[0]['id'];
1131 $postarray['parent-uri'] = $post->object->id;
1134 $postarray['private'] = 1;
1135 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1138 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1140 if (link_compare($post->actor->url, $own_id)) {
1141 $contact_id = $self[0]['id'];
1142 $post->actor->displayName = $self[0]['name'];
1143 $post->actor->url = $self[0]['url'];
1144 $post->actor->image->url = $self[0]['photo'];
1145 } elseif ($contact_id == 0) {
1146 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
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 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1156 dbesc(normalise_link($post->actor->url)),
1161 $contact_id = $r[0]['id'];
1163 $contact_id = $self[0]['id'];
1167 $reply = new stdClass;
1168 $reply->verb = "note";
1169 $reply->cc = $post->cc;
1170 $reply->to = $post->to;
1171 $reply->object = new stdClass;
1172 $reply->object->objectType = $post->object->inReplyTo->objectType;
1173 $reply->object->content = $post->object->inReplyTo->content;
1174 $reply->object->id = $post->object->inReplyTo->id;
1175 $reply->actor = $post->object->inReplyTo->author;
1176 $reply->url = $post->object->inReplyTo->url;
1177 $reply->generator = new stdClass;
1178 $reply->generator->displayName = "pumpio";
1179 $reply->published = $post->object->inReplyTo->published;
1180 $reply->received = $post->object->inReplyTo->updated;
1181 $reply->url = $post->object->inReplyTo->url;
1182 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1184 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1187 if ($post->object->pump_io->proxyURL)
1188 $postarray['extid'] = $post->object->pump_io->proxyURL;
1190 $postarray['contact-id'] = $contact_id;
1191 $postarray['verb'] = ACTIVITY_POST;
1192 $postarray['owner-name'] = $post->actor->displayName;
1193 $postarray['owner-link'] = $post->actor->url;
1194 $postarray['owner-avatar'] = $post->actor->image->url;
1195 $postarray['author-name'] = $post->actor->displayName;
1196 $postarray['author-link'] = $post->actor->url;
1197 $postarray['author-avatar'] = $post->actor->image->url;
1198 $postarray['plink'] = $post->object->url;
1199 $postarray['app'] = $post->generator->displayName;
1200 $postarray['body'] = html2bbcode($post->object->content);
1201 $postarray['object'] = json_encode($post);
1203 if ($post->object->fullImage->url != "")
1204 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1206 if ($post->object->displayName != "")
1207 $postarray['title'] = $post->object->displayName;
1209 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1210 if (isset($post->updated))
1211 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1212 elseif (isset($post->received))
1213 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1215 $postarray['edited'] = $postarray['created'];
1217 if ($post->verb == "share") {
1218 if (!intval(Config::get('system','wall-to-wall_share'))) {
1219 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1220 $share_author = $post->object->author->displayName;
1221 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1222 $share_author = $post->object->author->preferredUsername;
1224 $share_author = $post->object->author->url;
1226 $postarray['body'] = share_header($share_author, $post->object->author->url,
1227 $post->object->author->image->url, "",
1228 datetime_convert('UTC','UTC',$post->object->created),
1229 $post->links->self->href).
1230 $postarray['body']."[/share]";
1233 $postarray['body'] = "[share author='".$share_author.
1234 "' profile='".$post->object->author->url.
1235 "' avatar='".$post->object->author->image->url.
1236 "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1237 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1240 // Let shares look like wall-to-wall posts
1241 $postarray['author-name'] = $post->object->author->displayName;
1242 $postarray['author-link'] = $post->object->author->url;
1243 $postarray['author-avatar'] = $post->object->author->image->url;
1247 if (trim($postarray['body']) == "")
1250 $top_item = item_store($postarray);
1251 $postarray["id"] = $top_item;
1253 if (($top_item == 0) && ($post->verb == "update")) {
1254 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1255 dbesc($postarray["title"]),
1256 dbesc($postarray["body"]),
1257 dbesc($postarray["edited"]),
1258 dbesc($postarray["uri"]),
1263 if ($post->object->objectType == "comment") {
1265 if ($threadcompletion)
1266 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1268 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1275 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1277 if (link_compare($own_id, $postarray['author-link']))
1280 if (!function_exists("check_item_notification")) {
1281 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1282 dbesc($postarray['parent-uri']),
1286 if(count($myconv)) {
1288 foreach($myconv as $conv) {
1289 // now if we find a match, it means we're in this conversation
1291 if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1294 require_once('include/enotify.php');
1296 $conv_parent = $conv['parent'];
1299 'type' => NOTIFY_COMMENT,
1300 'notify_flags' => $user[0]['notify-flags'],
1301 'language' => $user[0]['language'],
1302 'to_name' => $user[0]['username'],
1303 'to_email' => $user[0]['email'],
1304 'uid' => $user[0]['uid'],
1305 'item' => $postarray,
1306 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1307 'source_name' => $postarray['author-name'],
1308 'source_link' => $postarray['author-link'],
1309 'source_photo' => $postarray['author-avatar'],
1310 'verb' => ACTIVITY_POST,
1312 'parent' => $conv_parent,
1315 // only send one notification
1325 function pumpio_fetchinbox(&$a, $uid) {
1327 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1328 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1329 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1330 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1331 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1332 $hostname = PConfig::get($uid, 'pumpio','host');
1333 $username = PConfig::get($uid, "pumpio", "user");
1335 $own_id = "https://".$hostname."/".$username;
1337 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1340 $lastitems = q("SELECT `uri` FROM `thread`
1341 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1342 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1343 ORDER BY `thread`.`commented` DESC LIMIT 10",
1344 dbesc(NETWORK_PUMPIO),
1348 $client = new oauth_client_class;
1349 $client->oauth_version = '1.0a';
1350 $client->authorization_header = true;
1351 $client->url_parameters = false;
1353 $client->client_id = $ckey;
1354 $client->client_secret = $csecret;
1355 $client->access_token = $otoken;
1356 $client->access_token_secret = $osecret;
1358 $last_id = PConfig::get($uid,'pumpio','last_id');
1360 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1363 $url .= '?since='.urlencode($last_id);
1365 if (pumpio_reachable($url))
1366 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1371 $posts = array_reverse($user->items);
1374 foreach ($posts as $post) {
1375 $last_id = $post->id;
1376 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1380 foreach ($lastitems AS $item)
1381 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1383 PConfig::set($uid,'pumpio','last_id', $last_id);
1386 function pumpio_getallusers(&$a, $uid) {
1387 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1388 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1389 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1390 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1391 $hostname = PConfig::get($uid, 'pumpio','host');
1392 $username = PConfig::get($uid, "pumpio", "user");
1394 $client = new oauth_client_class;
1395 $client->oauth_version = '1.0a';
1396 $client->authorization_header = true;
1397 $client->url_parameters = false;
1399 $client->client_id = $ckey;
1400 $client->client_secret = $csecret;
1401 $client->access_token = $otoken;
1402 $client->access_token_secret = $osecret;
1404 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1406 if (pumpio_reachable($url))
1407 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1411 if ($users->totalItems > count($users->items)) {
1412 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1414 if (pumpio_reachable($url))
1415 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1420 if (is_array($users->items)) {
1421 foreach ($users->items AS $user) {
1422 pumpio_get_contact($uid, $user);
1427 function pumpio_queue_hook(&$a,&$b) {
1429 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1430 dbesc(NETWORK_PUMPIO)
1435 require_once('include/queue_fn.php');
1437 foreach($qi as $x) {
1438 if($x['network'] !== NETWORK_PUMPIO)
1441 logger('pumpio_queue: run');
1443 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1444 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1452 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1454 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1455 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1456 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1457 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1459 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1460 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1464 if ($oauth_token && $oauth_token_secret &&
1465 $consumer_key && $consumer_secret) {
1466 $username = $user.'@'.$host;
1468 logger('pumpio_queue: able to post for user '.$username);
1470 $z = unserialize($x['content']);
1472 $client = new oauth_client_class;
1473 $client->oauth_version = '1.0a';
1474 $client->url_parameters = false;
1475 $client->authorization_header = true;
1476 $client->access_token = $oauth_token;
1477 $client->access_token_secret = $oauth_token_secret;
1478 $client->client_id = $consumer_key;
1479 $client->client_secret = $consumer_secret;
1481 if (pumpio_reachable($z['url']))
1482 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1487 $post_id = $user->object->id;
1488 logger('pumpio_queue: send '.$username.': success '.$post_id);
1489 if($post_id && $iscomment) {
1490 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1491 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1496 remove_queue_item($x['id']);
1498 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1500 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1503 logger('pumpio_queue: delayed');
1504 update_queue_time($x['id']);
1509 function pumpio_getreceiver(&$a, $b) {
1513 if (!$b["private"]) {
1515 if(! strstr($b['postopts'],'pumpio'))
1518 $public = PConfig::get($b['uid'], "pumpio", "public");
1521 $receiver["to"][] = [
1522 "objectType" => "collection",
1523 "id" => "http://activityschema.org/collection/public"];
1525 $cids = explode("><", $b["allow_cid"]);
1526 $gids = explode("><", $b["allow_gid"]);
1528 foreach ($cids AS $cid) {
1529 $cid = trim($cid, " <>");
1531 $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",
1534 dbesc(NETWORK_PUMPIO)
1538 $receiver["bcc"][] = [
1539 "displayName" => $r[0]["name"],
1540 "objectType" => "person",
1541 "preferredUsername" => $r[0]["nick"],
1542 "url" => $r[0]["url"]];
1545 foreach ($gids AS $gid) {
1546 $gid = trim($gid, " <>");
1548 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1549 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1550 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1552 dbesc(NETWORK_PUMPIO)
1555 foreach ($r AS $row)
1556 $receiver["bcc"][] = [
1557 "displayName" => $row["name"],
1558 "objectType" => "person",
1559 "preferredUsername" => $row["nick"],
1560 "url" => $row["url"]];
1564 if ($b["inform"] != "") {
1566 $inform = explode(",", $b["inform"]);
1568 foreach ($inform AS $cid) {
1569 if (substr($cid, 0, 4) != "cid:")
1572 $cid = str_replace("cid:", "", $cid);
1574 $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",
1577 dbesc(NETWORK_PUMPIO)
1581 $receiver["to"][] = [
1582 "displayName" => $r[0]["name"],
1583 "objectType" => "person",
1584 "preferredUsername" => $r[0]["nick"],
1585 "url" => $r[0]["url"]];
1593 function pumpio_fetchallcomments(&$a, $uid, $id) {
1594 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1595 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1596 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1597 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1598 $hostname = PConfig::get($uid, 'pumpio','host');
1599 $username = PConfig::get($uid, "pumpio", "user");
1601 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1603 $own_id = "https://".$hostname."/".$username;
1605 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1608 // Fetching the original post
1609 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1617 $url = $r[0]["extid"];
1619 $client = new oauth_client_class;
1620 $client->oauth_version = '1.0a';
1621 $client->authorization_header = true;
1622 $client->url_parameters = false;
1624 $client->client_id = $ckey;
1625 $client->client_secret = $csecret;
1626 $client->access_token = $otoken;
1627 $client->access_token_secret = $osecret;
1629 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1631 if (pumpio_reachable($url))
1632 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1639 if ($item->likes->totalItems != 0) {
1640 foreach ($item->likes->items AS $post) {
1641 $like = new stdClass;
1642 $like->object = new stdClass;
1643 $like->object->id = $item->id;
1644 $like->actor = new stdClass;
1645 $like->actor->displayName = $item->displayName;
1646 $like->actor->preferredUsername = $item->preferredUsername;
1647 $like->actor->url = $item->url;
1648 $like->actor->image = $item->image;
1649 $like->generator = new stdClass;
1650 $like->generator->displayName = "pumpio";
1651 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1655 if ($item->replies->totalItems == 0)
1658 foreach ($item->replies->items AS $item) {
1659 if ($item->id == $id)
1662 // Checking if the comment already exists - Two queries for speed issues
1663 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1671 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1679 $post = new stdClass;
1680 $post->verb = "post";
1681 $post->actor = $item->author;
1682 $post->published = $item->published;
1683 $post->received = $item->updated;
1684 $post->generator = new stdClass;
1685 $post->generator->displayName = "pumpio";
1686 // To-Do: Check for public post
1688 unset($item->author);
1689 unset($item->published);
1690 unset($item->updated);
1692 $post->object = $item;
1694 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1695 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1700 function pumpio_reachable($url) {
1701 $data = z_fetch_url($url, false, $redirects, ['timeout'=>10]);
1702 return(intval($data['return_code']) != 0);