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\Core\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\Worker;
15 use Friendica\Model\Contact;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Group;
18 use Friendica\Model\Item;
19 use Friendica\Model\Queue;
20 use Friendica\Model\User;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
24 require 'addon/pumpio/oauth/http.php';
25 require 'addon/pumpio/oauth/oauth_client.php';
26 require_once 'include/enotify.php';
27 require_once "mod/share.php";
29 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
31 function pumpio_install() {
32 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
33 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
34 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
35 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
36 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
37 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
38 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
39 Addon::registerHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
42 function pumpio_uninstall() {
43 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
44 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
45 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
46 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
47 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
48 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
49 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
50 Addon::unregisterHook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
53 function pumpio_module() {}
55 function pumpio_content(&$a) {
58 notice(L10n::t('Permission denied.') . EOL);
62 require_once("mod/settings.php");
65 if (isset($a->argv[1]))
66 switch ($a->argv[1]) {
68 $o = pumpio_connect($a);
71 $o = print_r($a->argv, true);
75 $o = pumpio_connect($a);
80 function pumpio_check_item_notification($a, &$notification_data) {
81 $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
82 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
84 $notification_data["profiles"][] = "https://".$hostname."/".$username;
88 function pumpio_registerclient(&$a, $host) {
90 $url = "https://".$host."/api/client/register";
94 $application_name = Config::get('pumpio', 'application_name');
96 if ($application_name == "")
97 $application_name = $a->get_hostname();
99 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
101 $params["type"] = "client_associate";
102 $params["contacts"] = $adminlist[0];
103 $params["application_type"] = "native";
104 $params["application_name"] = $application_name;
105 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
106 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
108 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
110 $ch = curl_init($url);
111 curl_setopt($ch, CURLOPT_HEADER, false);
112 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
113 curl_setopt($ch, CURLOPT_POST,1);
114 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
115 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
118 $curl_info = curl_getinfo($ch);
120 if ($curl_info["http_code"] == "200") {
121 $values = json_decode($s);
122 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
125 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
130 function pumpio_connect(&$a) {
131 // Start a session. This is necessary to hold on to a few keys the callback script will also need
134 // Define the needed keys
135 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
136 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
137 $hostname = PConfig::get(local_user(), 'pumpio','host');
139 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
140 logger("pumpio_connect: register client");
141 $clientdata = pumpio_registerclient($a, $hostname);
142 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
143 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
145 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
146 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
148 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
151 if (($consumer_key == "") || ($consumer_secret == "")) {
152 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
154 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
158 // The callback URL is the script that gets called after the user authenticates with pumpio
159 $callback_url = $a->get_baseurl()."/pumpio/connect";
161 // Let's begin. First we need a Request Token. The request token is required to send the user
162 // to pumpio's login page.
164 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
165 // Consumer Key and Consumer Secret
166 $client = new oauth_client_class;
168 $client->server = '';
169 $client->oauth_version = '1.0a';
170 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
171 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
172 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
173 $client->url_parameters = false;
174 $client->authorization_header = true;
175 $client->redirect_uri = $callback_url;
176 $client->client_id = $consumer_key;
177 $client->client_secret = $consumer_secret;
179 if (($success = $client->Initialize())) {
180 if (($success = $client->Process())) {
181 if (strlen($client->access_token)) {
182 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
183 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
184 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
187 $success = $client->Finalize($success);
190 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
193 logger("pumpio_connect: authenticated");
194 $o .= L10n::t("You are now authenticated to pumpio.");
195 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
197 logger("pumpio_connect: could not connect");
198 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
204 function pumpio_jot_nets(&$a,&$b) {
208 $pumpio_post = PConfig::get(local_user(),'pumpio','post');
209 if(intval($pumpio_post) == 1) {
210 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
211 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
212 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
213 . L10n::t('Post to pumpio') . '</div>';
218 function pumpio_settings(&$a,&$s) {
223 /* Add our stylesheet to the page so we can make our settings look nice */
225 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
227 /* Get the current state of our config variables */
229 $import_enabled = PConfig::get(local_user(),'pumpio','import');
230 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
232 $enabled = PConfig::get(local_user(),'pumpio','post');
233 $checked = (($enabled) ? ' checked="checked" ' : '');
234 $css = (($enabled) ? '' : '-disabled');
236 $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
237 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
239 $public_enabled = PConfig::get(local_user(),'pumpio','public');
240 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
242 $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
243 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
245 $servername = PConfig::get(local_user(), "pumpio", "host");
246 $username = PConfig::get(local_user(), "pumpio", "user");
248 /* Add some HTML to the existing form */
250 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
251 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
253 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
254 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
255 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
258 $s .= '<div id="pumpio-username-wrapper">';
259 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
260 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
261 $s .= '</div><div class="clear"></div>';
263 $s .= '<div id="pumpio-servername-wrapper">';
264 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
265 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
266 $s .= '</div><div class="clear"></div>';
268 if (($username != '') && ($servername != '')) {
270 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
271 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
273 $s .= '<div id="pumpio-password-wrapper">';
274 if (($oauth_token == "") || ($oauth_token_secret == "")) {
275 $s .= '<div id="pumpio-authenticate-wrapper">';
276 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
277 $s .= '</div><div class="clear"></div>';
279 $s .= '<div id="pumpio-import-wrapper">';
280 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
281 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
282 $s .= '</div><div class="clear"></div>';
284 $s .= '<div id="pumpio-enable-wrapper">';
285 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
286 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
287 $s .= '</div><div class="clear"></div>';
289 $s .= '<div id="pumpio-bydefault-wrapper">';
290 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
291 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
292 $s .= '</div><div class="clear"></div>';
294 $s .= '<div id="pumpio-public-wrapper">';
295 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
296 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
297 $s .= '</div><div class="clear"></div>';
299 $s .= '<div id="pumpio-mirror-wrapper">';
300 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
301 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
302 $s .= '</div><div class="clear"></div>';
304 $s .= '<div id="pumpio-delete-wrapper">';
305 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
306 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
307 $s .= '</div><div class="clear"></div>';
310 $s .= '</div><div class="clear"></div>';
313 /* provide a submit button */
315 $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>';
319 function pumpio_settings_post(&$a,&$b) {
321 if(x($_POST,'pumpio-submit')) {
322 if(x($_POST,'pumpio_delete')) {
323 PConfig::set(local_user(),'pumpio','consumer_key','');
324 PConfig::set(local_user(),'pumpio','consumer_secret','');
325 PConfig::set(local_user(),'pumpio','oauth_token','');
326 PConfig::set(local_user(),'pumpio','oauth_token_secret','');
327 PConfig::set(local_user(),'pumpio','post',false);
328 PConfig::set(local_user(),'pumpio','import',false);
329 PConfig::set(local_user(),'pumpio','host','');
330 PConfig::set(local_user(),'pumpio','user','');
331 PConfig::set(local_user(),'pumpio','public',false);
332 PConfig::set(local_user(),'pumpio','mirror',false);
333 PConfig::set(local_user(),'pumpio','post_by_default',false);
334 PConfig::set(local_user(),'pumpio','lastdate', 0);
335 PConfig::set(local_user(),'pumpio','last_id', '');
337 // filtering the username if it is filled wrong
338 $user = $_POST['pumpio_user'];
339 if (strstr($user, "@")) {
340 $pos = strpos($user, "@");
342 $user = substr($user, 0, $pos);
345 // Filtering the hostname if someone is entering it with "http"
346 $host = $_POST['pumpio_host'];
348 $host = str_replace(["https://", "http://"], ["", ""], $host);
350 PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
351 PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
352 PConfig::set(local_user(),'pumpio','host',$host);
353 PConfig::set(local_user(),'pumpio','user',$user);
354 PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
355 PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
356 PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
358 if (!$_POST['pumpio_mirror'])
359 PConfig::delete(local_user(),'pumpio','lastdate');
361 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
366 function pumpio_post_local(&$a, &$b) {
368 if (!local_user() || (local_user() != $b['uid'])) {
372 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
374 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
376 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
380 if (!$pumpio_enable) {
384 if (strlen($b['postopts'])) {
385 $b['postopts'] .= ',';
388 $b['postopts'] .= 'pumpio';
394 function pumpio_send(&$a,&$b) {
396 if (!PConfig::get($b["uid"],'pumpio','import')) {
397 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
401 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
403 if($b['parent'] != $b['id']) {
404 // Looking if its a reply to a pumpio post
405 $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",
406 intval($b["parent"]),
408 dbesc(NETWORK_PUMPIO));
411 logger("pumpio_send: no pumpio post ".$b["parent"]);
420 $receiver = pumpio_getreceiver($a, $b);
422 logger("pumpio_send: receiver ".print_r($receiver, true));
424 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio'))) {
428 // Dont't post if the post doesn't belong to us.
429 // This is a check for forum postings
430 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
431 if ($b['contact-id'] != $self['id']) {
436 if($b['verb'] == ACTIVITY_LIKE) {
438 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
440 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
444 if($b['verb'] == ACTIVITY_DISLIKE)
447 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
448 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
450 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
451 pumpio_action($a, $b["uid"], $b["uri"], "delete");
453 if($b['deleted'] || ($b['created'] !== $b['edited']))
456 // if post comes from pump.io don't send it back
457 if($b['app'] == "pump.io")
461 // Support for native shares
462 // http://<hostname>/api/<type>/shares?id=<the-object-id>
464 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
465 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
466 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
467 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
469 $host = PConfig::get($b['uid'], "pumpio", "host");
470 $user = PConfig::get($b['uid'], "pumpio", "user");
471 $public = PConfig::get($b['uid'], "pumpio", "public");
473 if($oauth_token && $oauth_token_secret) {
474 $title = trim($b['title']);
476 $content = BBCode::convert($b['body'], false, 4);
480 $params["verb"] = "post";
483 $params["object"] = [
484 'objectType' => "note",
485 'content' => $content];
488 $params["object"]["displayName"] = $title;
490 if (count($receiver["to"]))
491 $params["to"] = $receiver["to"];
493 if (count($receiver["bto"]))
494 $params["bto"] = $receiver["bto"];
496 if (count($receiver["cc"]))
497 $params["cc"] = $receiver["cc"];
499 if (count($receiver["bcc"]))
500 $params["bcc"] = $receiver["bcc"];
503 $inReplyTo = ["id" => $orig_post["uri"],
504 "objectType" => "note"];
506 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
507 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
509 $params["object"] = [
510 'objectType' => "comment",
511 'content' => $content,
512 'inReplyTo' => $inReplyTo];
515 $params["object"]["displayName"] = $title;
518 $client = new oauth_client_class;
519 $client->oauth_version = '1.0a';
520 $client->url_parameters = false;
521 $client->authorization_header = true;
522 $client->access_token = $oauth_token;
523 $client->access_token_secret = $oauth_token_secret;
524 $client->client_id = $consumer_key;
525 $client->client_secret = $consumer_secret;
527 $username = $user.'@'.$host;
528 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
530 if (pumpio_reachable($url))
531 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
537 if ($user->generator->displayName)
538 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
540 $post_id = $user->object->id;
541 logger('pumpio_send '.$username.': success '.$post_id);
542 if($post_id && $iscomment) {
543 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
544 Item::update(['extid' => $post_id], ['id' => $b['id']]);
547 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
549 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
551 $a->contact = $r[0]["id"];
553 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
555 Queue::add($a->contact, NETWORK_PUMPIO, $s);
556 notice(L10n::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]);
631 Queue::add($a->contact, NETWORK_PUMPIO, $s);
632 notice(L10n::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(DateTimeFormat::MYSQL, 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 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
871 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
873 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
876 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
877 require_once('include/items.php');
879 if ($post->object->id == "") {
880 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
884 // Searching for the liked post
885 // Two queries for speed issues
886 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
887 dbesc($post->object->id),
889 dbesc(NETWORK_PUMPIO)
895 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
896 dbesc($post->object->id),
898 dbesc(NETWORK_PUMPIO)
908 if ($threadcompletion)
909 pumpio_fetchallcomments($a, $uid, $post->object->id);
913 if(link_compare($post->actor->url, $own_id)) {
914 $contactid = $self[0]['id'];
915 $post->actor->displayName = $self[0]['name'];
916 $post->actor->url = $self[0]['url'];
917 $post->actor->image->url = $self[0]['photo'];
919 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
920 dbesc(normalise_link($post->actor->url)),
925 $contactid = $r[0]['id'];
928 $contactid = $orig_post['contact-id'];
931 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
932 dbesc(ACTIVITY_LIKE),
935 dbesc($orig_post['uri'])
939 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
944 $likedata['parent'] = $orig_post['id'];
945 $likedata['verb'] = ACTIVITY_LIKE;
946 $likedata['gravity'] = 3;
947 $likedata['uid'] = $uid;
948 $likedata['wall'] = 0;
949 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
950 $likedata['parent-uri'] = $orig_post["uri"];
951 $likedata['contact-id'] = $contactid;
952 $likedata['app'] = $post->generator->displayName;
953 $likedata['author-name'] = $post->actor->displayName;
954 $likedata['author-link'] = $post->actor->url;
955 $likedata['author-avatar'] = $post->actor->image->url;
957 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
958 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
959 $post_type = L10n::t('status');
960 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
961 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
963 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
965 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
966 '<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>';
968 $ret = Item::insert($likedata);
970 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
973 function pumpio_get_contact($uid, $contact, $no_insert = false) {
975 GContact::update(["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
976 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
977 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
978 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)]);
979 $cid = Contact::getIdForURL($contact->url, $uid);
984 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
985 intval($uid), dbesc(normalise_link($contact->url)));
988 // create contact record
989 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
990 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
991 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
992 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
994 dbesc(DateTimeFormat::utcNow()),
995 dbesc($contact->url),
996 dbesc(normalise_link($contact->url)),
997 dbesc(str_replace("acct:", "", $contact->id)),
999 dbesc($contact->id), // What is it for?
1000 dbesc('pump.io ' . $contact->id), // What is it for?
1001 dbesc($contact->displayName),
1002 dbesc($contact->preferredUsername),
1003 dbesc($contact->image->url),
1004 dbesc(NETWORK_PUMPIO),
1005 intval(CONTACT_IS_FRIEND),
1007 dbesc($contact->location->displayName),
1008 dbesc($contact->summary),
1012 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1013 dbesc(normalise_link($contact->url)),
1021 $contact_id = $r[0]['id'];
1023 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1025 $contact_id = $r[0]["id"];
1027 /* if (DB_UPDATE_VERSION >= "1177")
1028 q("UPDATE `contact` SET `location` = '%s',
1031 dbesc($contact->location->displayName),
1032 dbesc($contact->summary),
1038 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1040 return($contact_id);
1043 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1045 // Two queries for speed issues
1046 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1047 dbesc($post->object->id),
1052 return Item::deleteById($r[0]["id"]);
1054 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1055 dbesc($post->object->id),
1060 return Item::deleteById($r[0]["id"]);
1063 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1064 require_once('include/items.php');
1065 require_once('include/html2bbcode.php');
1067 if (($post->verb == "like") || ($post->verb == "favorite"))
1068 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1070 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1071 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1073 if ($post->verb == "delete")
1074 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1076 if ($post->verb != "update") {
1077 // Two queries for speed issues
1078 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1079 dbesc($post->object->id),
1086 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1087 dbesc($post->object->id),
1095 // Only handle these three types
1096 if (!strstr("post|share|update", $post->verb))
1100 if (@is_array($post->cc))
1101 $receiptians = array_merge($receiptians, $post->cc);
1103 if (@is_array($post->to))
1104 $receiptians = array_merge($receiptians, $post->to);
1106 foreach ($receiptians AS $receiver)
1107 if (is_string($receiver->objectType))
1108 if ($receiver->id == "http://activityschema.org/collection/public")
1112 $postarray['network'] = NETWORK_PUMPIO;
1113 $postarray['gravity'] = 0;
1114 $postarray['uid'] = $uid;
1115 $postarray['wall'] = 0;
1116 $postarray['uri'] = $post->object->id;
1117 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1119 if ($post->object->objectType != "comment") {
1120 $contact_id = pumpio_get_contact($uid, $post->actor);
1123 $contact_id = $self[0]['id'];
1125 $postarray['parent-uri'] = $post->object->id;
1128 $postarray['private'] = 1;
1129 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1132 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1134 if (link_compare($post->actor->url, $own_id)) {
1135 $contact_id = $self[0]['id'];
1136 $post->actor->displayName = $self[0]['name'];
1137 $post->actor->url = $self[0]['url'];
1138 $post->actor->image->url = $self[0]['photo'];
1139 } elseif ($contact_id == 0) {
1140 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1141 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1142 dbesc(normalise_link($post->actor->url)),
1147 $contact_id = $r[0]['id'];
1149 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1150 dbesc(normalise_link($post->actor->url)),
1155 $contact_id = $r[0]['id'];
1157 $contact_id = $self[0]['id'];
1161 $reply = new stdClass;
1162 $reply->verb = "note";
1163 $reply->cc = $post->cc;
1164 $reply->to = $post->to;
1165 $reply->object = new stdClass;
1166 $reply->object->objectType = $post->object->inReplyTo->objectType;
1167 $reply->object->content = $post->object->inReplyTo->content;
1168 $reply->object->id = $post->object->inReplyTo->id;
1169 $reply->actor = $post->object->inReplyTo->author;
1170 $reply->url = $post->object->inReplyTo->url;
1171 $reply->generator = new stdClass;
1172 $reply->generator->displayName = "pumpio";
1173 $reply->published = $post->object->inReplyTo->published;
1174 $reply->received = $post->object->inReplyTo->updated;
1175 $reply->url = $post->object->inReplyTo->url;
1176 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1178 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1181 if ($post->object->pump_io->proxyURL)
1182 $postarray['extid'] = $post->object->pump_io->proxyURL;
1184 $postarray['contact-id'] = $contact_id;
1185 $postarray['verb'] = ACTIVITY_POST;
1186 $postarray['owner-name'] = $post->actor->displayName;
1187 $postarray['owner-link'] = $post->actor->url;
1188 $postarray['owner-avatar'] = $post->actor->image->url;
1189 $postarray['author-name'] = $post->actor->displayName;
1190 $postarray['author-link'] = $post->actor->url;
1191 $postarray['author-avatar'] = $post->actor->image->url;
1192 $postarray['plink'] = $post->object->url;
1193 $postarray['app'] = $post->generator->displayName;
1194 $postarray['body'] = html2bbcode($post->object->content);
1195 $postarray['object'] = json_encode($post);
1197 if ($post->object->fullImage->url != "")
1198 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1200 if ($post->object->displayName != "")
1201 $postarray['title'] = $post->object->displayName;
1203 $postarray['created'] = DateTimeFormat::utc($post->published);
1204 if (isset($post->updated))
1205 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1206 elseif (isset($post->received))
1207 $postarray['edited'] = DateTimeFormat::utc($post->received);
1209 $postarray['edited'] = $postarray['created'];
1211 if ($post->verb == "share") {
1212 if (!intval(Config::get('system','wall-to-wall_share'))) {
1213 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1214 $share_author = $post->object->author->displayName;
1215 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1216 $share_author = $post->object->author->preferredUsername;
1218 $share_author = $post->object->author->url;
1220 $postarray['body'] = share_header($share_author, $post->object->author->url,
1221 $post->object->author->image->url, "",
1222 DateTimeFormat::utc($post->object->created),
1223 $post->links->self->href).
1224 $postarray['body']."[/share]";
1227 $postarray['body'] = "[share author='".$share_author.
1228 "' profile='".$post->object->author->url.
1229 "' avatar='".$post->object->author->image->url.
1230 "' posted='".DateTimeFormat::convert($post->object->created, 'UTC', 'UTC', ).
1231 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1234 // Let shares look like wall-to-wall posts
1235 $postarray['author-name'] = $post->object->author->displayName;
1236 $postarray['author-link'] = $post->object->author->url;
1237 $postarray['author-avatar'] = $post->object->author->image->url;
1241 if (trim($postarray['body']) == "")
1244 $top_item = Item::insert($postarray);
1245 $postarray["id"] = $top_item;
1247 if (($top_item == 0) && ($post->verb == "update")) {
1248 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1249 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1250 Item::update($fields, $condition);
1253 if ($post->object->objectType == "comment") {
1255 if ($threadcompletion)
1256 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1258 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1265 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1267 if (link_compare($own_id, $postarray['author-link']))
1270 if (!function_exists("check_item_notification")) {
1271 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1272 dbesc($postarray['parent-uri']),
1276 if(count($myconv)) {
1278 foreach($myconv as $conv) {
1279 // now if we find a match, it means we're in this conversation
1281 if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1284 require_once('include/enotify.php');
1286 $conv_parent = $conv['parent'];
1289 'type' => NOTIFY_COMMENT,
1290 'notify_flags' => $user[0]['notify-flags'],
1291 'language' => $user[0]['language'],
1292 'to_name' => $user[0]['username'],
1293 'to_email' => $user[0]['email'],
1294 'uid' => $user[0]['uid'],
1295 'item' => $postarray,
1296 'link' => $a->get_baseurl().'/display/'.urlencode(Item::getGuidById($top_item)),
1297 'source_name' => $postarray['author-name'],
1298 'source_link' => $postarray['author-link'],
1299 'source_photo' => $postarray['author-avatar'],
1300 'verb' => ACTIVITY_POST,
1302 'parent' => $conv_parent,
1305 // only send one notification
1315 function pumpio_fetchinbox(&$a, $uid) {
1317 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1318 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1319 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1320 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1321 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1322 $hostname = PConfig::get($uid, 'pumpio','host');
1323 $username = PConfig::get($uid, "pumpio", "user");
1325 $own_id = "https://".$hostname."/".$username;
1327 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1330 $lastitems = q("SELECT `uri` FROM `thread`
1331 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1332 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1333 ORDER BY `thread`.`commented` DESC LIMIT 10",
1334 dbesc(NETWORK_PUMPIO),
1338 $client = new oauth_client_class;
1339 $client->oauth_version = '1.0a';
1340 $client->authorization_header = true;
1341 $client->url_parameters = false;
1343 $client->client_id = $ckey;
1344 $client->client_secret = $csecret;
1345 $client->access_token = $otoken;
1346 $client->access_token_secret = $osecret;
1348 $last_id = PConfig::get($uid,'pumpio','last_id');
1350 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1353 $url .= '?since='.urlencode($last_id);
1355 if (pumpio_reachable($url))
1356 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1361 $posts = array_reverse($user->items);
1364 foreach ($posts as $post) {
1365 $last_id = $post->id;
1366 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1370 foreach ($lastitems AS $item)
1371 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1373 PConfig::set($uid,'pumpio','last_id', $last_id);
1376 function pumpio_getallusers(&$a, $uid) {
1377 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1378 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1379 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1380 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1381 $hostname = PConfig::get($uid, 'pumpio','host');
1382 $username = PConfig::get($uid, "pumpio", "user");
1384 $client = new oauth_client_class;
1385 $client->oauth_version = '1.0a';
1386 $client->authorization_header = true;
1387 $client->url_parameters = false;
1389 $client->client_id = $ckey;
1390 $client->client_secret = $csecret;
1391 $client->access_token = $otoken;
1392 $client->access_token_secret = $osecret;
1394 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1396 if (pumpio_reachable($url))
1397 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1401 if ($users->totalItems > count($users->items)) {
1402 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1404 if (pumpio_reachable($url))
1405 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1410 if (is_array($users->items)) {
1411 foreach ($users->items AS $user) {
1412 pumpio_get_contact($uid, $user);
1417 function pumpio_queue_hook(&$a,&$b) {
1419 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1420 dbesc(NETWORK_PUMPIO)
1425 foreach($qi as $x) {
1426 if($x['network'] !== NETWORK_PUMPIO)
1429 logger('pumpio_queue: run');
1431 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1432 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1440 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1442 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1443 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1444 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1445 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1447 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1448 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1452 if ($oauth_token && $oauth_token_secret &&
1453 $consumer_key && $consumer_secret) {
1454 $username = $user.'@'.$host;
1456 logger('pumpio_queue: able to post for user '.$username);
1458 $z = unserialize($x['content']);
1460 $client = new oauth_client_class;
1461 $client->oauth_version = '1.0a';
1462 $client->url_parameters = false;
1463 $client->authorization_header = true;
1464 $client->access_token = $oauth_token;
1465 $client->access_token_secret = $oauth_token_secret;
1466 $client->client_id = $consumer_key;
1467 $client->client_secret = $consumer_secret;
1469 if (pumpio_reachable($z['url']))
1470 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1475 $post_id = $user->object->id;
1476 logger('pumpio_queue: send '.$username.': success '.$post_id);
1477 if($post_id && $iscomment) {
1478 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1479 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1481 Queue::removeItem($x['id']);
1483 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1485 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1488 logger('pumpio_queue: delayed');
1489 Queue::updateTime($x['id']);
1494 function pumpio_getreceiver(&$a, $b) {
1498 if (!$b["private"]) {
1500 if(! strstr($b['postopts'],'pumpio'))
1503 $public = PConfig::get($b['uid'], "pumpio", "public");
1506 $receiver["to"][] = [
1507 "objectType" => "collection",
1508 "id" => "http://activityschema.org/collection/public"];
1510 $cids = explode("><", $b["allow_cid"]);
1511 $gids = explode("><", $b["allow_gid"]);
1513 foreach ($cids AS $cid) {
1514 $cid = trim($cid, " <>");
1516 $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",
1519 dbesc(NETWORK_PUMPIO)
1523 $receiver["bcc"][] = [
1524 "displayName" => $r[0]["name"],
1525 "objectType" => "person",
1526 "preferredUsername" => $r[0]["nick"],
1527 "url" => $r[0]["url"]];
1530 foreach ($gids AS $gid) {
1531 $gid = trim($gid, " <>");
1533 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1534 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1535 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1537 dbesc(NETWORK_PUMPIO)
1540 foreach ($r AS $row)
1541 $receiver["bcc"][] = [
1542 "displayName" => $row["name"],
1543 "objectType" => "person",
1544 "preferredUsername" => $row["nick"],
1545 "url" => $row["url"]];
1549 if ($b["inform"] != "") {
1551 $inform = explode(",", $b["inform"]);
1553 foreach ($inform AS $cid) {
1554 if (substr($cid, 0, 4) != "cid:")
1557 $cid = str_replace("cid:", "", $cid);
1559 $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",
1562 dbesc(NETWORK_PUMPIO)
1566 $receiver["to"][] = [
1567 "displayName" => $r[0]["name"],
1568 "objectType" => "person",
1569 "preferredUsername" => $r[0]["nick"],
1570 "url" => $r[0]["url"]];
1578 function pumpio_fetchallcomments(&$a, $uid, $id) {
1579 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1580 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1581 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1582 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1583 $hostname = PConfig::get($uid, 'pumpio','host');
1584 $username = PConfig::get($uid, "pumpio", "user");
1586 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1588 $own_id = "https://".$hostname."/".$username;
1590 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1593 // Fetching the original post
1594 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1602 $url = $r[0]["extid"];
1604 $client = new oauth_client_class;
1605 $client->oauth_version = '1.0a';
1606 $client->authorization_header = true;
1607 $client->url_parameters = false;
1609 $client->client_id = $ckey;
1610 $client->client_secret = $csecret;
1611 $client->access_token = $otoken;
1612 $client->access_token_secret = $osecret;
1614 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1616 if (pumpio_reachable($url))
1617 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1624 if ($item->likes->totalItems != 0) {
1625 foreach ($item->likes->items AS $post) {
1626 $like = new stdClass;
1627 $like->object = new stdClass;
1628 $like->object->id = $item->id;
1629 $like->actor = new stdClass;
1630 $like->actor->displayName = $item->displayName;
1631 $like->actor->preferredUsername = $item->preferredUsername;
1632 $like->actor->url = $item->url;
1633 $like->actor->image = $item->image;
1634 $like->generator = new stdClass;
1635 $like->generator->displayName = "pumpio";
1636 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1640 if ($item->replies->totalItems == 0)
1643 foreach ($item->replies->items AS $item) {
1644 if ($item->id == $id)
1647 // Checking if the comment already exists - Two queries for speed issues
1648 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1656 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1664 $post = new stdClass;
1665 $post->verb = "post";
1666 $post->actor = $item->author;
1667 $post->published = $item->published;
1668 $post->received = $item->updated;
1669 $post->generator = new stdClass;
1670 $post->generator->displayName = "pumpio";
1671 // To-Do: Check for public post
1673 unset($item->author);
1674 unset($item->published);
1675 unset($item->updated);
1677 $post->object = $item;
1679 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1680 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1685 function pumpio_reachable($url) {
1686 $data = Network::curl($url, false, $redirects, ['timeout'=>10]);
1687 return(intval($data['return_code']) != 0);