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