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;
24 use Friendica\Database\DBM;
26 require 'addon/pumpio/oauth/http.php';
27 require 'addon/pumpio/oauth/oauth_client.php';
28 require_once 'include/enotify.php';
29 require_once "mod/share.php";
31 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
33 function pumpio_install()
35 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
36 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
37 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
38 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
39 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
40 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
41 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
42 Addon::registerHook('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
45 function pumpio_uninstall()
47 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
48 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
49 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
50 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
51 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
52 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
53 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
54 Addon::unregisterHook('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
57 function pumpio_module() {}
59 function pumpio_content(&$a)
62 notice(L10n::t('Permission denied.') . EOL);
66 require_once("mod/settings.php");
69 if (isset($a->argv[1])) {
70 switch ($a->argv[1]) {
72 $o = pumpio_connect($a);
75 $o = print_r($a->argv, true);
79 $o = pumpio_connect($a);
84 function pumpio_check_item_notification($a, &$notification_data)
86 $hostname = PConfig::get($notification_data["uid"], 'pumpio', 'host');
87 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
89 $notification_data["profiles"][] = "https://".$hostname."/".$username;
92 function pumpio_registerclient(&$a, $host)
94 $url = "https://".$host."/api/client/register";
98 $application_name = Config::get('pumpio', 'application_name');
100 if ($application_name == "") {
101 $application_name = $a->get_hostname();
104 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
106 $params["type"] = "client_associate";
107 $params["contacts"] = $adminlist[0];
108 $params["application_type"] = "native";
109 $params["application_name"] = $application_name;
110 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
111 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
113 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
115 $ch = curl_init($url);
116 curl_setopt($ch, CURLOPT_HEADER, false);
117 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
118 curl_setopt($ch, CURLOPT_POST,1);
119 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
120 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
123 $curl_info = curl_getinfo($ch);
125 if ($curl_info["http_code"] == "200") {
126 $values = json_decode($s);
127 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
130 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
135 function pumpio_connect(&$a)
137 // Start a session. This is necessary to hold on to a few keys the callback script will also need
140 // Define the needed keys
141 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
142 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
143 $hostname = PConfig::get(local_user(), 'pumpio', 'host');
145 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
146 logger("pumpio_connect: register client");
147 $clientdata = pumpio_registerclient($a, $hostname);
148 PConfig::set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
149 PConfig::set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
151 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
152 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
154 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
157 if (($consumer_key == "") || ($consumer_secret == "")) {
158 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
160 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
164 // The callback URL is the script that gets called after the user authenticates with pumpio
165 $callback_url = $a->get_baseurl()."/pumpio/connect";
167 // Let's begin. First we need a Request Token. The request token is required to send the user
168 // to pumpio's login page.
170 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
171 // Consumer Key and Consumer Secret
172 $client = new oauth_client_class;
174 $client->server = '';
175 $client->oauth_version = '1.0a';
176 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
177 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
178 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
179 $client->url_parameters = false;
180 $client->authorization_header = true;
181 $client->redirect_uri = $callback_url;
182 $client->client_id = $consumer_key;
183 $client->client_secret = $consumer_secret;
185 if (($success = $client->Initialize())) {
186 if (($success = $client->Process())) {
187 if (strlen($client->access_token)) {
188 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
189 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
190 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
193 $success = $client->Finalize($success);
196 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
200 logger("pumpio_connect: authenticated");
201 $o .= L10n::t("You are now authenticated to pumpio.");
202 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
204 logger("pumpio_connect: could not connect");
205 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
211 function pumpio_jot_nets(&$a, &$b)
217 $pumpio_post = PConfig::get(local_user(), 'pumpio', 'post');
218 if (intval($pumpio_post) == 1) {
219 $pumpio_defpost = PConfig::get(local_user(), 'pumpio', 'post_by_default');
220 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
221 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
222 . L10n::t('Post to pumpio') . '</div>';
226 function pumpio_settings(&$a, &$s)
232 /* Add our stylesheet to the page so we can make our settings look nice */
234 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
236 /* Get the current state of our config variables */
238 $import_enabled = PConfig::get(local_user(), 'pumpio', 'import');
239 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
241 $enabled = PConfig::get(local_user(), 'pumpio', 'post');
242 $checked = (($enabled) ? ' checked="checked" ' : '');
243 $css = (($enabled) ? '' : '-disabled');
245 $def_enabled = PConfig::get(local_user(), 'pumpio', 'post_by_default');
246 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
248 $public_enabled = PConfig::get(local_user(), 'pumpio', 'public');
249 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
251 $mirror_enabled = PConfig::get(local_user(), 'pumpio', 'mirror');
252 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
254 $servername = PConfig::get(local_user(), "pumpio", "host");
255 $username = PConfig::get(local_user(), "pumpio", "user");
257 /* Add some HTML to the existing form */
259 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
260 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
262 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
263 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
264 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
267 $s .= '<div id="pumpio-username-wrapper">';
268 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
269 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
270 $s .= '</div><div class="clear"></div>';
272 $s .= '<div id="pumpio-servername-wrapper">';
273 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
274 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
275 $s .= '</div><div class="clear"></div>';
277 if (($username != '') && ($servername != '')) {
278 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
279 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
281 $s .= '<div id="pumpio-password-wrapper">';
282 if (($oauth_token == "") || ($oauth_token_secret == "")) {
283 $s .= '<div id="pumpio-authenticate-wrapper">';
284 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
285 $s .= '</div><div class="clear"></div>';
287 $s .= '<div id="pumpio-import-wrapper">';
288 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
289 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
290 $s .= '</div><div class="clear"></div>';
292 $s .= '<div id="pumpio-enable-wrapper">';
293 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
294 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
295 $s .= '</div><div class="clear"></div>';
297 $s .= '<div id="pumpio-bydefault-wrapper">';
298 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
299 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
300 $s .= '</div><div class="clear"></div>';
302 $s .= '<div id="pumpio-public-wrapper">';
303 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
304 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
305 $s .= '</div><div class="clear"></div>';
307 $s .= '<div id="pumpio-mirror-wrapper">';
308 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
309 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
310 $s .= '</div><div class="clear"></div>';
312 $s .= '<div id="pumpio-delete-wrapper">';
313 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
314 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
315 $s .= '</div><div class="clear"></div>';
318 $s .= '</div><div class="clear"></div>';
321 /* provide a submit button */
323 $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>';
326 function pumpio_settings_post(&$a, &$b)
328 if (x($_POST, 'pumpio-submit')) {
329 if (x($_POST, 'pumpio_delete')) {
330 PConfig::set(local_user(), 'pumpio', 'consumer_key', '');
331 PConfig::set(local_user(), 'pumpio', 'consumer_secret', '');
332 PConfig::set(local_user(), 'pumpio', 'oauth_token', '');
333 PConfig::set(local_user(), 'pumpio', 'oauth_token_secret', '');
334 PConfig::set(local_user(), 'pumpio', 'post', false);
335 PConfig::set(local_user(), 'pumpio', 'import', false);
336 PConfig::set(local_user(), 'pumpio', 'host', '');
337 PConfig::set(local_user(), 'pumpio', 'user', '');
338 PConfig::set(local_user(), 'pumpio', 'public', false);
339 PConfig::set(local_user(), 'pumpio', 'mirror', false);
340 PConfig::set(local_user(), 'pumpio', 'post_by_default', false);
341 PConfig::set(local_user(), 'pumpio', 'lastdate', 0);
342 PConfig::set(local_user(), 'pumpio', 'last_id', '');
344 // filtering the username if it is filled wrong
345 $user = $_POST['pumpio_user'];
346 if (strstr($user, "@")) {
347 $pos = strpos($user, "@");
349 $user = substr($user, 0, $pos);
353 // Filtering the hostname if someone is entering it with "http"
354 $host = $_POST['pumpio_host'];
356 $host = str_replace(["https://", "http://"], ["", ""], $host);
358 PConfig::set(local_user(), 'pumpio', 'post',intval($_POST['pumpio']));
359 PConfig::set(local_user(), 'pumpio', 'import', $_POST['pumpio_import']);
360 PConfig::set(local_user(), 'pumpio', 'host', $host);
361 PConfig::set(local_user(), 'pumpio', 'user', $user);
362 PConfig::set(local_user(), 'pumpio', 'public', $_POST['pumpio_public']);
363 PConfig::set(local_user(), 'pumpio', 'mirror', $_POST['pumpio_mirror']);
364 PConfig::set(local_user(), 'pumpio', 'post_by_default',intval($_POST['pumpio_bydefault']));
366 if (!$_POST['pumpio_mirror']) {
367 PConfig::delete(local_user(), 'pumpio', 'lastdate');
370 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
375 function pumpio_post_local(&$a, &$b)
377 if (!local_user() || (local_user() != $b['uid'])) {
381 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
383 $pumpio_enable = (($pumpio_post && x($_REQUEST, 'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
385 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
389 if (!$pumpio_enable) {
393 if (strlen($b['postopts'])) {
394 $b['postopts'] .= ',';
397 $b['postopts'] .= 'pumpio';
400 function pumpio_send(&$a, &$b)
402 if (!PConfig::get($b["uid"], 'pumpio', 'import')) {
403 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
408 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
410 if ($b['parent'] != $b['id']) {
411 // Looking if its a reply to a pumpio post
412 $condition = ['id' => $b['parent'], 'network' => NETWORK_PUMPIO];
413 $orig_post = Item::selectFirst([], $condition);
415 if (!DBM::is_result($orig_post)) {
416 logger("pumpio_send: no pumpio post ".$b["parent"]);
424 $receiver = pumpio_getreceiver($a, $b);
426 logger("pumpio_send: receiver ".print_r($receiver, true));
428 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
432 // Dont't post if the post doesn't belong to us.
433 // This is a check for forum postings
434 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
435 if ($b['contact-id'] != $self['id']) {
440 if ($b['verb'] == ACTIVITY_LIKE) {
442 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
444 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
449 if ($b['verb'] == ACTIVITY_DISLIKE) {
453 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
454 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
457 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
458 pumpio_action($a, $b["uid"], $b["uri"], "delete");
461 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
465 // if post comes from pump.io don't send it back
466 if ($b['app'] == "pump.io") {
471 // Support for native shares
472 // http://<hostname>/api/<type>/shares?id=<the-object-id>
474 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
475 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
476 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
477 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
479 $host = PConfig::get($b['uid'], "pumpio", "host");
480 $user = PConfig::get($b['uid'], "pumpio", "user");
481 $public = PConfig::get($b['uid'], "pumpio", "public");
483 if ($oauth_token && $oauth_token_secret) {
484 $title = trim($b['title']);
486 $content = BBCode::convert($b['body'], false, 4);
490 $params["verb"] = "post";
493 $params["object"] = [
494 'objectType' => "note",
495 'content' => $content];
498 $params["object"]["displayName"] = $title;
501 if (count($receiver["to"])) {
502 $params["to"] = $receiver["to"];
505 if (count($receiver["bto"])) {
506 $params["bto"] = $receiver["bto"];
509 if (count($receiver["cc"])) {
510 $params["cc"] = $receiver["cc"];
513 if (count($receiver["bcc"])) {
514 $params["bcc"] = $receiver["bcc"];
517 $inReplyTo = ["id" => $orig_post["uri"],
518 "objectType" => "note"];
520 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
521 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
524 $params["object"] = [
525 'objectType' => "comment",
526 'content' => $content,
527 'inReplyTo' => $inReplyTo];
530 $params["object"]["displayName"] = $title;
534 $client = new oauth_client_class;
535 $client->oauth_version = '1.0a';
536 $client->url_parameters = false;
537 $client->authorization_header = true;
538 $client->access_token = $oauth_token;
539 $client->access_token_secret = $oauth_token_secret;
540 $client->client_id = $consumer_key;
541 $client->client_secret = $consumer_secret;
543 $username = $user.'@'.$host;
544 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
546 if (pumpio_reachable($url)) {
547 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
553 if ($user->generator->displayName) {
554 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
557 $post_id = $user->object->id;
558 logger('pumpio_send '.$username.': success '.$post_id);
559 if ($post_id && $iscomment) {
560 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
561 Item::update(['extid' => $post_id], ['id' => $b['id']]);
564 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
566 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
567 if (DBM::is_result($r)) {
568 $a->contact = $r[0]["id"];
571 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
573 Queue::add($a->contact, NETWORK_PUMPIO, $s);
574 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
579 function pumpio_action(&$a, $uid, $uri, $action, $content = "")
581 // Don't do likes and other stuff if you don't import the timeline
582 if (!PConfig::get($uid, 'pumpio', 'import')) {
586 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
587 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
588 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
589 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
590 $hostname = PConfig::get($uid, 'pumpio', 'host');
591 $username = PConfig::get($uid, "pumpio", "user");
593 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
595 if (!DBM::is_result($orig_post)) {
599 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
600 $uri = $orig_post["extid"];
602 $uri = $orig_post["uri"];
605 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
606 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
607 } elseif (strstr($uri, "/api/comment/")) {
608 $objectType = "comment";
609 } elseif (strstr($uri, "/api/note/")) {
610 $objectType = "note";
611 } elseif (strstr($uri, "/api/image/")) {
612 $objectType = "image";
615 $params["verb"] = $action;
616 $params["object"] = ['id' => $uri,
617 "objectType" => $objectType,
618 "content" => $content];
620 $client = new oauth_client_class;
621 $client->oauth_version = '1.0a';
622 $client->authorization_header = true;
623 $client->url_parameters = false;
625 $client->client_id = $ckey;
626 $client->client_secret = $csecret;
627 $client->access_token = $otoken;
628 $client->access_token_secret = $osecret;
630 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
632 if (pumpio_reachable($url)) {
633 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
639 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
641 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user, true));
643 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
644 if (DBM::is_result($r)) {
645 $a->contact = $r[0]["id"];
648 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
650 Queue::add($a->contact, NETWORK_PUMPIO, $s);
651 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
655 function pumpio_sync(&$a)
657 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
660 if (!DBM::is_result($r)) {
664 $last = Config::get('pumpio', 'last_poll');
666 $poll_interval = intval(Config::get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
669 $next = $last + ($poll_interval * 60);
670 if ($next > time()) {
671 logger('pumpio: poll intervall not reached');
675 logger('pumpio: cron_start');
677 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
678 if (DBM::is_result($r)) {
679 foreach ($r as $rr) {
680 logger('pumpio: mirroring user '.$rr['uid']);
681 pumpio_fetchtimeline($a, $rr['uid']);
685 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
686 if ($abandon_days < 1) {
690 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
692 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
693 if (DBM::is_result($r)) {
694 foreach ($r as $rr) {
695 if ($abandon_days != 0) {
696 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
697 if (!DBM::is_result($user)) {
698 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
703 logger('pumpio: importing timeline from user '.$rr['uid']);
704 pumpio_fetchinbox($a, $rr['uid']);
706 // check for new contacts once a day
707 $last_contact_check = PConfig::get($rr['uid'], 'pumpio', 'contact_check');
708 if ($last_contact_check) {
709 $next_contact_check = $last_contact_check + 86400;
711 $next_contact_check = 0;
714 if ($next_contact_check <= time()) {
715 pumpio_getallusers($a, $rr["uid"]);
716 PConfig::set($rr['uid'], 'pumpio', 'contact_check', time());
721 logger('pumpio: cron_end');
723 Config::set('pumpio', 'last_poll', time());
726 function pumpio_cron(&$a, $b)
728 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
731 function pumpio_fetchtimeline(&$a, $uid)
733 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
734 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
735 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
736 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
737 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
738 $hostname = PConfig::get($uid, 'pumpio', 'host');
739 $username = PConfig::get($uid, "pumpio", "user");
741 // get the application name for the pump.io app
742 // 1st try personal config, then system config and fallback to the
743 // hostname of the node if neither one is set.
744 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
745 if ($application_name == "") {
746 $application_name = Config::get('pumpio', 'application_name');
748 if ($application_name == "") {
749 $application_name = $a->get_hostname();
752 $first_time = ($lastdate == "");
754 $client = new oauth_client_class;
755 $client->oauth_version = '1.0a';
756 $client->authorization_header = true;
757 $client->url_parameters = false;
759 $client->client_id = $ckey;
760 $client->client_secret = $csecret;
761 $client->access_token = $otoken;
762 $client->access_token_secret = $osecret;
764 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
766 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
768 $username = $user.'@'.$host;
770 if (pumpio_reachable($url)) {
771 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
777 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
781 $posts = array_reverse($user->items);
783 $initiallastdate = $lastdate;
787 foreach ($posts as $post) {
788 if ($post->published <= $initiallastdate) {
792 if ($lastdate < $post->published) {
793 $lastdate = $post->published;
801 if (@is_array($post->cc)) {
802 $receiptians = array_merge($receiptians, $post->cc);
805 if (@is_array($post->to)) {
806 $receiptians = array_merge($receiptians, $post->to);
810 foreach ($receiptians AS $receiver) {
811 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
816 if ($public && !stristr($post->generator->displayName, $application_name)) {
817 $_SESSION["authenticated"] = true;
818 $_SESSION["uid"] = $uid;
821 $_REQUEST["type"] = "wall";
822 $_REQUEST["api_source"] = true;
823 $_REQUEST["profile_uid"] = $uid;
824 $_REQUEST["source"] = "pump.io";
826 if (isset($post->object->id)) {
827 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
830 if ($post->object->displayName != "") {
831 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
833 $_REQUEST["title"] = "";
836 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
838 // To-Do: Picture has to be cached and stored locally
839 if ($post->object->fullImage->url != "") {
840 if ($post->object->fullImage->pump_io->proxyURL != "") {
841 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
843 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
847 logger('pumpio: posting for user '.$uid);
849 require_once('mod/item.php');
852 logger('pumpio: posting done - user '.$uid);
857 if ($lastdate != 0) {
858 PConfig::set($uid, 'pumpio', 'lastdate', $lastdate);
862 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id)
864 // Searching for the unliked post
865 // Two queries for speed issues
866 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
867 if (!DBM::is_result($orig_post)) {
868 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
869 if (!DBM::is_result($orig_post)) {
876 if (link_compare($post->actor->url, $own_id)) {
877 $contactid = $self[0]['id'];
879 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
880 dbesc(normalise_link($post->actor->url)),
884 if (DBM::is_result($r)) {
885 $contactid = $r[0]['id'];
888 if ($contactid == 0) {
889 $contactid = $orig_post['contact-id'];
893 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
895 if (DBM::is_result($r)) {
896 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
898 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
902 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true)
904 require_once('include/items.php');
906 if ($post->object->id == "") {
907 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
911 // Searching for the liked post
912 // Two queries for speed issues
913 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
914 if (!DBM::is_result($orig_post)) {
915 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
916 if (!DBM::is_result($orig_post)) {
922 if ($threadcompletion) {
923 pumpio_fetchallcomments($a, $uid, $post->object->id);
928 if (link_compare($post->actor->url, $own_id)) {
929 $contactid = $self[0]['id'];
930 $post->actor->displayName = $self[0]['name'];
931 $post->actor->url = $self[0]['url'];
932 $post->actor->image->url = $self[0]['photo'];
934 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
935 dbesc(normalise_link($post->actor->url)),
939 if (DBM::is_result($r)) {
940 $contactid = $r[0]['id'];
943 if ($contactid == 0) {
944 $contactid = $orig_post['contact-id'];
948 $condition = ['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
949 if (dba::exists('item', $condition)) {
950 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
955 $likedata['parent'] = $orig_post['id'];
956 $likedata['verb'] = ACTIVITY_LIKE;
957 $likedata['gravity'] = GRAVITY_ACTIVITY;
958 $likedata['uid'] = $uid;
959 $likedata['wall'] = 0;
960 $likedata['uri'] = Item::newURI($uid);
961 $likedata['parent-uri'] = $orig_post["uri"];
962 $likedata['contact-id'] = $contactid;
963 $likedata['app'] = $post->generator->displayName;
964 $likedata['author-name'] = $post->actor->displayName;
965 $likedata['author-link'] = $post->actor->url;
966 $likedata['author-avatar'] = $post->actor->image->url;
968 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
969 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
970 $post_type = L10n::t('status');
971 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
972 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
974 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
976 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
977 '<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>';
979 $ret = Item::insert($likedata);
981 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
984 function pumpio_get_contact($uid, $contact, $no_insert = false)
986 GContact::update(["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
987 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
988 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
989 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)]);
990 $cid = Contact::getIdForURL($contact->url, $uid);
996 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
997 intval($uid), dbesc(normalise_link($contact->url)));
999 if (!DBM::is_result($r)) {
1000 // create contact record
1001 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1002 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1003 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1004 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1006 dbesc(DateTimeFormat::utcNow()),
1007 dbesc($contact->url),
1008 dbesc(normalise_link($contact->url)),
1009 dbesc(str_replace("acct:", "", $contact->id)),
1011 dbesc($contact->id), // What is it for?
1012 dbesc('pump.io ' . $contact->id), // What is it for?
1013 dbesc($contact->displayName),
1014 dbesc($contact->preferredUsername),
1015 dbesc($contact->image->url),
1016 dbesc(NETWORK_PUMPIO),
1017 intval(CONTACT_IS_FRIEND),
1019 dbesc($contact->location->displayName),
1020 dbesc($contact->summary),
1024 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1025 dbesc(normalise_link($contact->url)),
1029 if (!DBM::is_result($r)) {
1033 $contact_id = $r[0]['id'];
1035 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1037 $contact_id = $r[0]["id"];
1039 /* if (DB_UPDATE_VERSION >= "1177")
1040 q("UPDATE `contact` SET `location` = '%s',
1043 dbesc($contact->location->displayName),
1044 dbesc($contact->summary),
1050 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1055 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id)
1057 // Two queries for speed issues
1058 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1059 if (dba::exists('item', $condition)) {
1060 Item::delete($condition);
1064 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1065 if (dba::exists('item', $condition)) {
1066 Item::delete($condition);
1072 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1074 require_once('include/items.php');
1076 if (($post->verb == "like") || ($post->verb == "favorite")) {
1077 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1080 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1081 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1084 if ($post->verb == "delete") {
1085 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1088 if ($post->verb != "update") {
1089 // Two queries for speed issues
1090 if (dba::exists('item', ['uri' => $post->object->id, 'uid' => $uid])) {
1093 if (dba::exists('item', ['extid' => $post->object->id, 'uid' => $uid])) {
1098 // Only handle these three types
1099 if (!strstr("post|share|update", $post->verb)) {
1104 if (@is_array($post->cc)) {
1105 $receiptians = array_merge($receiptians, $post->cc);
1108 if (@is_array($post->to)) {
1109 $receiptians = array_merge($receiptians, $post->to);
1112 foreach ($receiptians AS $receiver) {
1113 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1119 $postarray['network'] = NETWORK_PUMPIO;
1120 $postarray['uid'] = $uid;
1121 $postarray['wall'] = 0;
1122 $postarray['uri'] = $post->object->id;
1123 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1125 if ($post->object->objectType != "comment") {
1126 $contact_id = pumpio_get_contact($uid, $post->actor);
1129 $contact_id = $self[0]['id'];
1132 $postarray['parent-uri'] = $post->object->id;
1135 $postarray['private'] = 1;
1136 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1139 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1141 if (link_compare($post->actor->url, $own_id)) {
1142 $contact_id = $self[0]['id'];
1143 $post->actor->displayName = $self[0]['name'];
1144 $post->actor->url = $self[0]['url'];
1145 $post->actor->image->url = $self[0]['photo'];
1146 } elseif ($contact_id == 0) {
1147 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1148 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1149 dbesc(normalise_link($post->actor->url)),
1153 if (DBM::is_result($r)) {
1154 $contact_id = $r[0]['id'];
1156 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1157 dbesc(normalise_link($post->actor->url)),
1161 if (DBM::is_result($r)) {
1162 $contact_id = $r[0]['id'];
1164 $contact_id = $self[0]['id'];
1169 $reply = new stdClass;
1170 $reply->verb = "note";
1171 $reply->cc = $post->cc;
1172 $reply->to = $post->to;
1173 $reply->object = new stdClass;
1174 $reply->object->objectType = $post->object->inReplyTo->objectType;
1175 $reply->object->content = $post->object->inReplyTo->content;
1176 $reply->object->id = $post->object->inReplyTo->id;
1177 $reply->actor = $post->object->inReplyTo->author;
1178 $reply->url = $post->object->inReplyTo->url;
1179 $reply->generator = new stdClass;
1180 $reply->generator->displayName = "pumpio";
1181 $reply->published = $post->object->inReplyTo->published;
1182 $reply->received = $post->object->inReplyTo->updated;
1183 $reply->url = $post->object->inReplyTo->url;
1184 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1186 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1189 if ($post->object->pump_io->proxyURL) {
1190 $postarray['extid'] = $post->object->pump_io->proxyURL;
1193 $postarray['contact-id'] = $contact_id;
1194 $postarray['verb'] = ACTIVITY_POST;
1195 $postarray['owner-name'] = $post->actor->displayName;
1196 $postarray['owner-link'] = $post->actor->url;
1197 $postarray['owner-avatar'] = $post->actor->image->url;
1198 $postarray['author-name'] = $post->actor->displayName;
1199 $postarray['author-link'] = $post->actor->url;
1200 $postarray['author-avatar'] = $post->actor->image->url;
1201 $postarray['plink'] = $post->object->url;
1202 $postarray['app'] = $post->generator->displayName;
1203 $postarray['body'] = HTML::toBBCode($post->object->content);
1204 $postarray['object'] = json_encode($post);
1206 if ($post->object->fullImage->url != "") {
1207 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1210 if ($post->object->displayName != "") {
1211 $postarray['title'] = $post->object->displayName;
1214 $postarray['created'] = DateTimeFormat::utc($post->published);
1215 if (isset($post->updated)) {
1216 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1217 } elseif (isset($post->received)) {
1218 $postarray['edited'] = DateTimeFormat::utc($post->received);
1220 $postarray['edited'] = $postarray['created'];
1223 if ($post->verb == "share") {
1224 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1225 $share_author = $post->object->author->displayName;
1226 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1227 $share_author = $post->object->author->preferredUsername;
1229 $share_author = $post->object->author->url;
1232 $postarray['body'] = share_header($share_author, $post->object->author->url,
1233 $post->object->author->image->url, "",
1234 DateTimeFormat::utc($post->object->created),
1235 $post->links->self->href).
1236 $postarray['body']."[/share]";
1239 if (trim($postarray['body']) == "") {
1243 $top_item = Item::insert($postarray);
1244 $postarray["id"] = $top_item;
1246 if (($top_item == 0) && ($post->verb == "update")) {
1247 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1248 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1249 Item::update($fields, $condition);
1252 if (($post->object->objectType == "comment") && $threadcompletion) {
1253 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1259 function pumpio_fetchinbox(&$a, $uid)
1261 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1262 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1263 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1264 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1265 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1266 $hostname = PConfig::get($uid, 'pumpio', 'host');
1267 $username = PConfig::get($uid, "pumpio", "user");
1269 $own_id = "https://".$hostname."/".$username;
1271 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1274 $lastitems = q("SELECT `uri` FROM `thread`
1275 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1276 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1277 ORDER BY `thread`.`commented` DESC LIMIT 10",
1278 dbesc(NETWORK_PUMPIO),
1282 $client = new oauth_client_class;
1283 $client->oauth_version = '1.0a';
1284 $client->authorization_header = true;
1285 $client->url_parameters = false;
1287 $client->client_id = $ckey;
1288 $client->client_secret = $csecret;
1289 $client->access_token = $otoken;
1290 $client->access_token_secret = $osecret;
1292 $last_id = PConfig::get($uid, 'pumpio', 'last_id');
1294 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1296 if ($last_id != "") {
1297 $url .= '?since='.urlencode($last_id);
1300 if (pumpio_reachable($url)) {
1301 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1307 $posts = array_reverse($user->items);
1309 if (count($posts)) {
1310 foreach ($posts as $post) {
1311 $last_id = $post->id;
1312 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1317 foreach ($lastitems AS $item) {
1318 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1321 PConfig::set($uid, 'pumpio', 'last_id', $last_id);
1324 function pumpio_getallusers(&$a, $uid)
1326 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1327 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1328 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1329 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1330 $hostname = PConfig::get($uid, 'pumpio', 'host');
1331 $username = PConfig::get($uid, "pumpio", "user");
1333 $client = new oauth_client_class;
1334 $client->oauth_version = '1.0a';
1335 $client->authorization_header = true;
1336 $client->url_parameters = false;
1338 $client->client_id = $ckey;
1339 $client->client_secret = $csecret;
1340 $client->access_token = $otoken;
1341 $client->access_token_secret = $osecret;
1343 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1345 if (pumpio_reachable($url)) {
1346 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1351 if ($users->totalItems > count($users->items)) {
1352 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1354 if (pumpio_reachable($url)) {
1355 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
1361 if (is_array($users->items)) {
1362 foreach ($users->items AS $user) {
1363 pumpio_get_contact($uid, $user);
1368 function pumpio_queue_hook(&$a, &$b)
1370 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1371 dbesc(NETWORK_PUMPIO)
1373 if (!DBM::is_result($qi)) {
1377 foreach ($qi as $x) {
1378 if ($x['network'] !== NETWORK_PUMPIO) {
1382 logger('pumpio_queue: run');
1384 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1385 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1388 if (!DBM::is_result($r)) {
1394 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1396 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1397 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1398 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1399 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1401 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1402 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1406 if ($oauth_token && $oauth_token_secret &&
1407 $consumer_key && $consumer_secret) {
1408 $username = $user.'@'.$host;
1410 logger('pumpio_queue: able to post for user '.$username);
1412 $z = unserialize($x['content']);
1414 $client = new oauth_client_class;
1415 $client->oauth_version = '1.0a';
1416 $client->url_parameters = false;
1417 $client->authorization_header = true;
1418 $client->access_token = $oauth_token;
1419 $client->access_token_secret = $oauth_token_secret;
1420 $client->client_id = $consumer_key;
1421 $client->client_secret = $consumer_secret;
1423 if (pumpio_reachable($z['url'])) {
1424 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1430 $post_id = $user->object->id;
1431 logger('pumpio_queue: send '.$username.': success '.$post_id);
1432 if ($post_id && $iscomment) {
1433 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1434 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1436 Queue::removeItem($x['id']);
1438 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user, true));
1441 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1445 logger('pumpio_queue: delayed');
1446 Queue::updateTime($x['id']);
1451 function pumpio_getreceiver(&$a, $b)
1455 if (!$b["private"]) {
1456 if (!strstr($b['postopts'], 'pumpio')) {
1460 $public = PConfig::get($b['uid'], "pumpio", "public");
1463 $receiver["to"][] = [
1464 "objectType" => "collection",
1465 "id" => "http://activityschema.org/collection/public"];
1468 $cids = explode("><", $b["allow_cid"]);
1469 $gids = explode("><", $b["allow_gid"]);
1471 foreach ($cids AS $cid) {
1472 $cid = trim($cid, " <>");
1474 $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",
1477 dbesc(NETWORK_PUMPIO)
1480 if (DBM::is_result($r)) {
1481 $receiver["bcc"][] = [
1482 "displayName" => $r[0]["name"],
1483 "objectType" => "person",
1484 "preferredUsername" => $r[0]["nick"],
1485 "url" => $r[0]["url"]];
1488 foreach ($gids AS $gid) {
1489 $gid = trim($gid, " <>");
1491 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1492 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1493 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1495 dbesc(NETWORK_PUMPIO)
1498 foreach ($r AS $row)
1499 $receiver["bcc"][] = [
1500 "displayName" => $row["name"],
1501 "objectType" => "person",
1502 "preferredUsername" => $row["nick"],
1503 "url" => $row["url"]];
1507 if ($b["inform"] != "") {
1508 $inform = explode(",", $b["inform"]);
1510 foreach ($inform AS $cid) {
1511 if (substr($cid, 0, 4) != "cid:") {
1515 $cid = str_replace("cid:", "", $cid);
1517 $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",
1520 dbesc(NETWORK_PUMPIO)
1523 if (DBM::is_result($r)) {
1524 $receiver["to"][] = [
1525 "displayName" => $r[0]["name"],
1526 "objectType" => "person",
1527 "preferredUsername" => $r[0]["nick"],
1528 "url" => $r[0]["url"]];
1536 function pumpio_fetchallcomments(&$a, $uid, $id)
1538 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1539 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1540 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1541 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1542 $hostname = PConfig::get($uid, 'pumpio', 'host');
1543 $username = PConfig::get($uid, "pumpio", "user");
1545 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1547 $own_id = "https://".$hostname."/".$username;
1549 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1552 // Fetching the original post
1553 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1554 $item = Item::selectFirst(['extid'], $condition);
1555 if (!DBM::is_result($item)) {
1559 $url = $item["extid"];
1561 $client = new oauth_client_class;
1562 $client->oauth_version = '1.0a';
1563 $client->authorization_header = true;
1564 $client->url_parameters = false;
1566 $client->client_id = $ckey;
1567 $client->client_secret = $csecret;
1568 $client->access_token = $otoken;
1569 $client->access_token_secret = $osecret;
1571 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1573 if (pumpio_reachable($url)) {
1574 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1583 if ($item->likes->totalItems != 0) {
1584 foreach ($item->likes->items AS $post) {
1585 $like = new stdClass;
1586 $like->object = new stdClass;
1587 $like->object->id = $item->id;
1588 $like->actor = new stdClass;
1589 $like->actor->displayName = $item->displayName;
1590 $like->actor->preferredUsername = $item->preferredUsername;
1591 $like->actor->url = $item->url;
1592 $like->actor->image = $item->image;
1593 $like->generator = new stdClass;
1594 $like->generator->displayName = "pumpio";
1595 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1599 if ($item->replies->totalItems == 0) {
1603 foreach ($item->replies->items AS $item) {
1604 if ($item->id == $id) {
1608 // Checking if the comment already exists - Two queries for speed issues
1609 if (dba::exists('item', ['uri' => $item->id, 'uid' => $uid])) {
1613 if (dba::exists('item', ['extid' => $item->id, 'uid' => $uid])) {
1617 $post = new stdClass;
1618 $post->verb = "post";
1619 $post->actor = $item->author;
1620 $post->published = $item->published;
1621 $post->received = $item->updated;
1622 $post->generator = new stdClass;
1623 $post->generator->displayName = "pumpio";
1624 // To-Do: Check for public post
1626 unset($item->author);
1627 unset($item->published);
1628 unset($item->updated);
1630 $post->object = $item;
1632 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1633 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1637 function pumpio_reachable($url)
1639 $data = Network::curl($url, false, $redirects, ['timeout'=>10]);
1640 return intval($data['return_code']) != 0;