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>
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Addon;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\PConfig;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Contact;
19 use Friendica\Model\GContact;
20 use Friendica\Model\Group;
21 use Friendica\Model\Item;
22 use Friendica\Model\Queue;
23 use Friendica\Model\User;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\Network;
27 require 'addon/pumpio/oauth/http.php';
28 require 'addon/pumpio/oauth/oauth_client.php';
29 require_once 'include/enotify.php';
30 require_once "mod/share.php";
32 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
34 function pumpio_install()
36 Addon::registerHook('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
37 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
38 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
39 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
40 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
41 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
42 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
43 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
44 Addon::registerHook('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
47 function pumpio_uninstall()
49 Addon::unregisterHook('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
50 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
51 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
52 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
53 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
54 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
55 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
56 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
57 Addon::unregisterHook('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
60 function pumpio_module() {}
62 function pumpio_content(App $a)
65 notice(L10n::t('Permission denied.') . EOL);
69 require_once("mod/settings.php");
72 if (isset($a->argv[1])) {
73 switch ($a->argv[1]) {
75 $o = pumpio_connect($a);
78 $o = print_r($a->argv, true);
82 $o = pumpio_connect($a);
87 function pumpio_check_item_notification($a, &$notification_data)
89 $hostname = PConfig::get($notification_data["uid"], 'pumpio', 'host');
90 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
92 $notification_data["profiles"][] = "https://".$hostname."/".$username;
95 function pumpio_registerclient(App $a, $host)
97 $url = "https://".$host."/api/client/register";
101 $application_name = Config::get('pumpio', 'application_name');
103 if ($application_name == "") {
104 $application_name = $a->get_hostname();
107 $adminlist = explode(",", str_replace(" ", "", Config::get('config', 'admin_email')));
109 $params["type"] = "client_associate";
110 $params["contacts"] = $adminlist[0];
111 $params["application_type"] = "native";
112 $params["application_name"] = $application_name;
113 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
114 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
116 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
118 $ch = curl_init($url);
119 curl_setopt($ch, CURLOPT_HEADER, false);
120 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
121 curl_setopt($ch, CURLOPT_POST,1);
122 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
123 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
126 $curl_info = curl_getinfo($ch);
128 if ($curl_info["http_code"] == "200") {
129 $values = json_decode($s);
130 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
133 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
138 function pumpio_connect(App $a)
140 // Start a session. This is necessary to hold on to a few keys the callback script will also need
143 // Define the needed keys
144 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
145 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
146 $hostname = PConfig::get(local_user(), 'pumpio', 'host');
148 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
149 logger("pumpio_connect: register client");
150 $clientdata = pumpio_registerclient($a, $hostname);
151 PConfig::set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
152 PConfig::set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
154 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
155 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
157 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
160 if (($consumer_key == "") || ($consumer_secret == "")) {
161 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
163 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
167 // The callback URL is the script that gets called after the user authenticates with pumpio
168 $callback_url = $a->get_baseurl()."/pumpio/connect";
170 // Let's begin. First we need a Request Token. The request token is required to send the user
171 // to pumpio's login page.
173 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
174 // Consumer Key and Consumer Secret
175 $client = new oauth_client_class;
177 $client->server = '';
178 $client->oauth_version = '1.0a';
179 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
180 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
181 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
182 $client->url_parameters = false;
183 $client->authorization_header = true;
184 $client->redirect_uri = $callback_url;
185 $client->client_id = $consumer_key;
186 $client->client_secret = $consumer_secret;
188 if (($success = $client->Initialize())) {
189 if (($success = $client->Process())) {
190 if (strlen($client->access_token)) {
191 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
192 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
193 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
196 $success = $client->Finalize($success);
199 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
203 logger("pumpio_connect: authenticated");
204 $o .= L10n::t("You are now authenticated to pumpio.");
205 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
207 logger("pumpio_connect: could not connect");
208 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
214 function pumpio_jot_nets(App $a, &$b)
216 if (! local_user()) {
220 $pumpio_post = PConfig::get(local_user(), 'pumpio', 'post');
222 if (intval($pumpio_post) == 1) {
223 $pumpio_defpost = PConfig::get(local_user(), 'pumpio', 'post_by_default');
224 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
225 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
226 . L10n::t('Post to pumpio') . '</div>';
230 function pumpio_settings(App $a, &$s)
236 /* Add our stylesheet to the page so we can make our settings look nice */
238 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
240 /* Get the current state of our config variables */
242 $import_enabled = PConfig::get(local_user(), 'pumpio', 'import');
243 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
245 $enabled = PConfig::get(local_user(), 'pumpio', 'post');
246 $checked = (($enabled) ? ' checked="checked" ' : '');
247 $css = (($enabled) ? '' : '-disabled');
249 $def_enabled = PConfig::get(local_user(), 'pumpio', 'post_by_default');
250 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
252 $public_enabled = PConfig::get(local_user(), 'pumpio', 'public');
253 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
255 $mirror_enabled = PConfig::get(local_user(), 'pumpio', 'mirror');
256 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
258 $servername = PConfig::get(local_user(), "pumpio", "host");
259 $username = PConfig::get(local_user(), "pumpio", "user");
261 /* Add some HTML to the existing form */
263 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" 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>';
266 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
267 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
268 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
271 $s .= '<div id="pumpio-username-wrapper">';
272 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
273 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
274 $s .= '</div><div class="clear"></div>';
276 $s .= '<div id="pumpio-servername-wrapper">';
277 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
278 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
279 $s .= '</div><div class="clear"></div>';
281 if (($username != '') && ($servername != '')) {
282 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
283 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
285 $s .= '<div id="pumpio-password-wrapper">';
286 if (($oauth_token == "") || ($oauth_token_secret == "")) {
287 $s .= '<div id="pumpio-authenticate-wrapper">';
288 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
289 $s .= '</div><div class="clear"></div>';
291 $s .= '<div id="pumpio-import-wrapper">';
292 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
293 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
294 $s .= '</div><div class="clear"></div>';
296 $s .= '<div id="pumpio-enable-wrapper">';
297 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
298 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
299 $s .= '</div><div class="clear"></div>';
301 $s .= '<div id="pumpio-bydefault-wrapper">';
302 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
303 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
304 $s .= '</div><div class="clear"></div>';
306 $s .= '<div id="pumpio-public-wrapper">';
307 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
308 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
309 $s .= '</div><div class="clear"></div>';
311 $s .= '<div id="pumpio-mirror-wrapper">';
312 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
313 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
314 $s .= '</div><div class="clear"></div>';
316 $s .= '<div id="pumpio-delete-wrapper">';
317 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
318 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
319 $s .= '</div><div class="clear"></div>';
322 $s .= '</div><div class="clear"></div>';
325 /* provide a submit button */
327 $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>';
330 function pumpio_settings_post(App $a, array &$b)
332 if (!empty($_POST['pumpio-submit'])) {
333 if (!empty($_POST['pumpio_delete'])) {
334 PConfig::set(local_user(), 'pumpio', 'consumer_key' , '');
335 PConfig::set(local_user(), 'pumpio', 'consumer_secret' , '');
336 PConfig::set(local_user(), 'pumpio', 'oauth_token' , '');
337 PConfig::set(local_user(), 'pumpio', 'oauth_token_secret', '');
338 PConfig::set(local_user(), 'pumpio', 'post' , false);
339 PConfig::set(local_user(), 'pumpio', 'import' , false);
340 PConfig::set(local_user(), 'pumpio', 'host' , '');
341 PConfig::set(local_user(), 'pumpio', 'user' , '');
342 PConfig::set(local_user(), 'pumpio', 'public' , false);
343 PConfig::set(local_user(), 'pumpio', 'mirror' , false);
344 PConfig::set(local_user(), 'pumpio', 'post_by_default' , false);
345 PConfig::set(local_user(), 'pumpio', 'lastdate' , 0);
346 PConfig::set(local_user(), 'pumpio', 'last_id' , '');
348 // filtering the username if it is filled wrong
349 $user = $_POST['pumpio_user'];
350 if (strstr($user, "@")) {
351 $pos = strpos($user, "@");
354 $user = substr($user, 0, $pos);
358 // Filtering the hostname if someone is entering it with "http"
359 $host = $_POST['pumpio_host'];
361 $host = str_replace(["https://", "http://"], ["", ""], $host);
363 PConfig::set(local_user(), 'pumpio', 'post' , intval($_POST['pumpio']));
364 PConfig::set(local_user(), 'pumpio', 'import' , $_POST['pumpio_import']);
365 PConfig::set(local_user(), 'pumpio', 'host' , $host);
366 PConfig::set(local_user(), 'pumpio', 'user' , $user);
367 PConfig::set(local_user(), 'pumpio', 'public' , $_POST['pumpio_public']);
368 PConfig::set(local_user(), 'pumpio', 'mirror' , $_POST['pumpio_mirror']);
369 PConfig::set(local_user(), 'pumpio', 'post_by_default', intval($_POST['pumpio_bydefault']));
371 if (!$_POST['pumpio_mirror']) {
372 PConfig::delete(local_user(), 'pumpio', 'lastdate');
375 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
380 function pumpio_load_config(App $a)
382 $a->loadConfigFile(__DIR__. '/config/pumpio.ini.php');
385 function pumpio_post_local(App $a, array &$b)
387 if (!local_user() || (local_user() != $b['uid'])) {
391 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
393 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
395 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
399 if (!$pumpio_enable) {
403 if (strlen($b['postopts'])) {
404 $b['postopts'] .= ',';
407 $b['postopts'] .= 'pumpio';
410 function pumpio_send(App $a, array &$b)
412 if (!PConfig::get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
416 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
418 if ($b['parent'] != $b['id']) {
419 // Looking if its a reply to a pumpio post
420 $condition = ['id' => $b['parent'], 'network' => NETWORK_PUMPIO];
421 $orig_post = Item::selectFirst([], $condition);
423 if (!DBA::isResult($orig_post)) {
424 logger("pumpio_send: no pumpio post ".$b["parent"]);
432 $receiver = pumpio_getreceiver($a, $b);
434 logger("pumpio_send: receiver ".print_r($receiver, true));
436 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
440 // Dont't post if the post doesn't belong to us.
441 // This is a check for forum postings
442 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
443 if ($b['contact-id'] != $self['id']) {
448 if ($b['verb'] == ACTIVITY_LIKE) {
450 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
452 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
457 if ($b['verb'] == ACTIVITY_DISLIKE) {
461 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
462 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
465 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
466 pumpio_action($a, $b["uid"], $b["uri"], "delete");
469 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
473 // if post comes from pump.io don't send it back
474 if ($b['app'] == "pump.io") {
479 // Support for native shares
480 // http://<hostname>/api/<type>/shares?id=<the-object-id>
482 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
483 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
484 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
485 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
487 $host = PConfig::get($b['uid'], "pumpio", "host");
488 $user = PConfig::get($b['uid'], "pumpio", "user");
489 $public = PConfig::get($b['uid'], "pumpio", "public");
491 if ($oauth_token && $oauth_token_secret) {
492 $title = trim($b['title']);
494 $content = BBCode::convert($b['body'], false, 4);
498 $params["verb"] = "post";
501 $params["object"] = [
502 'objectType' => "note",
503 'content' => $content];
505 if (!empty($title)) {
506 $params["object"]["displayName"] = $title;
509 if (!empty($receiver["to"])) {
510 $params["to"] = $receiver["to"];
513 if (!empty($receiver["bto"])) {
514 $params["bto"] = $receiver["bto"];
517 if (!empty($receiver["cc"])) {
518 $params["cc"] = $receiver["cc"];
521 if (!empty($receiver["bcc"])) {
522 $params["bcc"] = $receiver["bcc"];
525 $inReplyTo = ["id" => $orig_post["uri"],
526 "objectType" => "note"];
528 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
529 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
532 $params["object"] = [
533 'objectType' => "comment",
534 'content' => $content,
535 'inReplyTo' => $inReplyTo];
538 $params["object"]["displayName"] = $title;
542 $client = new oauth_client_class;
543 $client->oauth_version = '1.0a';
544 $client->url_parameters = false;
545 $client->authorization_header = true;
546 $client->access_token = $oauth_token;
547 $client->access_token_secret = $oauth_token_secret;
548 $client->client_id = $consumer_key;
549 $client->client_secret = $consumer_secret;
551 $username = $user.'@'.$host;
552 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
554 if (pumpio_reachable($url)) {
555 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
561 if ($user->generator->displayName) {
562 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
565 $post_id = $user->object->id;
566 logger('pumpio_send '.$username.': success '.$post_id);
567 if ($post_id && $iscomment) {
568 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
569 Item::update(['extid' => $post_id], ['id' => $b['id']]);
572 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
574 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
575 if (DBA::isResult($r)) {
576 $a->contact = $r[0]["id"];
579 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
581 Queue::add($a->contact, NETWORK_PUMPIO, $s);
582 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
587 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
589 // Don't do likes and other stuff if you don't import the timeline
590 if (!PConfig::get($uid, 'pumpio', 'import')) {
594 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
595 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
596 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
597 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
598 $hostname = PConfig::get($uid, 'pumpio', 'host');
599 $username = PConfig::get($uid, "pumpio", "user");
601 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
603 if (!DBA::isResult($orig_post)) {
607 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
608 $uri = $orig_post["extid"];
610 $uri = $orig_post["uri"];
613 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
614 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
615 } elseif (strstr($uri, "/api/comment/")) {
616 $objectType = "comment";
617 } elseif (strstr($uri, "/api/note/")) {
618 $objectType = "note";
619 } elseif (strstr($uri, "/api/image/")) {
620 $objectType = "image";
623 $params["verb"] = $action;
624 $params["object"] = ['id' => $uri,
625 "objectType" => $objectType,
626 "content" => $content];
628 $client = new oauth_client_class;
629 $client->oauth_version = '1.0a';
630 $client->authorization_header = true;
631 $client->url_parameters = false;
633 $client->client_id = $ckey;
634 $client->client_secret = $csecret;
635 $client->access_token = $otoken;
636 $client->access_token_secret = $osecret;
638 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
640 if (pumpio_reachable($url)) {
641 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
647 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
649 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user, true));
651 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
652 if (DBA::isResult($r)) {
653 $a->contact = $r[0]["id"];
656 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
658 Queue::add($a->contact, NETWORK_PUMPIO, $s);
659 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
663 function pumpio_sync(App $a)
665 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
667 if (!DBA::isResult($r)) {
671 $last = Config::get('pumpio', 'last_poll');
673 $poll_interval = intval(Config::get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
676 $next = $last + ($poll_interval * 60);
677 if ($next > time()) {
678 logger('pumpio: poll intervall not reached');
682 logger('pumpio: cron_start');
684 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
685 if (DBA::isResult($r)) {
686 foreach ($r as $rr) {
687 logger('pumpio: mirroring user '.$rr['uid']);
688 pumpio_fetchtimeline($a, $rr['uid']);
692 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
693 if ($abandon_days < 1) {
697 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
699 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
700 if (DBA::isResult($r)) {
701 foreach ($r as $rr) {
702 if ($abandon_days != 0) {
703 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
704 if (!DBA::isResult($user)) {
705 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
710 logger('pumpio: importing timeline from user '.$rr['uid']);
711 pumpio_fetchinbox($a, $rr['uid']);
713 // check for new contacts once a day
714 $last_contact_check = PConfig::get($rr['uid'], 'pumpio', 'contact_check');
715 if ($last_contact_check) {
716 $next_contact_check = $last_contact_check + 86400;
718 $next_contact_check = 0;
721 if ($next_contact_check <= time()) {
722 pumpio_getallusers($a, $rr["uid"]);
723 PConfig::set($rr['uid'], 'pumpio', 'contact_check', time());
728 logger('pumpio: cron_end');
730 Config::set('pumpio', 'last_poll', time());
733 function pumpio_cron(App $a, $b)
735 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
738 function pumpio_fetchtimeline(App $a, $uid)
740 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
741 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
742 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
743 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
744 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
745 $hostname = PConfig::get($uid, 'pumpio', 'host');
746 $username = PConfig::get($uid, "pumpio", "user");
748 // get the application name for the pump.io app
749 // 1st try personal config, then system config and fallback to the
750 // hostname of the node if neither one is set.
751 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
752 if ($application_name == "") {
753 $application_name = Config::get('pumpio', 'application_name');
755 if ($application_name == "") {
756 $application_name = $a->get_hostname();
759 $first_time = ($lastdate == "");
761 $client = new oauth_client_class;
762 $client->oauth_version = '1.0a';
763 $client->authorization_header = true;
764 $client->url_parameters = false;
766 $client->client_id = $ckey;
767 $client->client_secret = $csecret;
768 $client->access_token = $otoken;
769 $client->access_token_secret = $osecret;
771 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
773 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
775 $useraddr = $username.'@'.$hostname;
777 if (pumpio_reachable($url)) {
778 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
784 logger('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
788 $posts = array_reverse($user->items);
790 $initiallastdate = $lastdate;
794 foreach ($posts as $post) {
795 if ($post->published <= $initiallastdate) {
799 if ($lastdate < $post->published) {
800 $lastdate = $post->published;
808 if (@is_array($post->cc)) {
809 $receiptians = array_merge($receiptians, $post->cc);
812 if (@is_array($post->to)) {
813 $receiptians = array_merge($receiptians, $post->to);
817 foreach ($receiptians AS $receiver) {
818 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
823 if ($public && !stristr($post->generator->displayName, $application_name)) {
824 $_SESSION["authenticated"] = true;
825 $_SESSION["uid"] = $uid;
828 $_REQUEST["api_source"] = true;
829 $_REQUEST["profile_uid"] = $uid;
830 $_REQUEST["source"] = "pump.io";
832 if (isset($post->object->id)) {
833 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
836 if ($post->object->displayName != "") {
837 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
839 $_REQUEST["title"] = "";
842 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
844 // To-Do: Picture has to be cached and stored locally
845 if ($post->object->fullImage->url != "") {
846 if ($post->object->fullImage->pump_io->proxyURL != "") {
847 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
849 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
853 logger('pumpio: posting for user '.$uid);
855 require_once('mod/item.php');
858 logger('pumpio: posting done - user '.$uid);
863 if ($lastdate != 0) {
864 PConfig::set($uid, 'pumpio', 'lastdate', $lastdate);
868 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
870 // Searching for the unliked post
871 // Two queries for speed issues
872 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
873 if (!DBA::isResult($orig_post)) {
874 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
875 if (!DBA::isResult($orig_post)) {
882 if (link_compare($post->actor->url, $own_id)) {
883 $contactid = $self[0]['id'];
885 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
886 DBA::escape(normalise_link($post->actor->url)),
890 if (DBA::isResult($r)) {
891 $contactid = $r[0]['id'];
894 if ($contactid == 0) {
895 $contactid = $orig_post['contact-id'];
899 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
901 if (DBA::isResult($r)) {
902 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
904 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
908 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
910 require_once('include/items.php');
912 if (empty($post->object->id)) {
913 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
917 // Searching for the liked post
918 // Two queries for speed issues
919 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
920 if (!DBA::isResult($orig_post)) {
921 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
922 if (!DBA::isResult($orig_post)) {
928 if ($threadcompletion) {
929 pumpio_fetchallcomments($a, $uid, $post->object->id);
934 if (link_compare($post->actor->url, $own_id)) {
935 $contactid = $self[0]['id'];
936 $post->actor->displayName = $self[0]['name'];
937 $post->actor->url = $self[0]['url'];
938 $post->actor->image->url = $self[0]['photo'];
940 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
941 DBA::escape(normalise_link($post->actor->url)),
945 if (DBA::isResult($r)) {
946 $contactid = $r[0]['id'];
949 if ($contactid == 0) {
950 $contactid = $orig_post['contact-id'];
954 $condition = ['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
955 if (DBA::exists('item', $condition)) {
956 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
961 $likedata['parent'] = $orig_post['id'];
962 $likedata['verb'] = ACTIVITY_LIKE;
963 $likedata['gravity'] = GRAVITY_ACTIVITY;
964 $likedata['uid'] = $uid;
965 $likedata['wall'] = 0;
966 $likedata['network'] = NETWORK_PUMPIO;
967 $likedata['uri'] = Item::newURI($uid);
968 $likedata['parent-uri'] = $orig_post["uri"];
969 $likedata['contact-id'] = $contactid;
970 $likedata['app'] = $post->generator->displayName;
971 $likedata['author-name'] = $post->actor->displayName;
972 $likedata['author-link'] = $post->actor->url;
973 if (!empty($post->actor->image)) {
974 $likedata['author-avatar'] = $post->actor->image->url;
977 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
978 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
979 $post_type = L10n::t('status');
980 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
981 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
983 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
985 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
986 '<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>';
988 $ret = Item::insert($likedata);
990 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
993 function pumpio_get_contact($uid, $contact, $no_insert = false)
995 $gcontact = ["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
996 "name" => $contact->displayName, "hide" => true,
997 "nick" => $contact->preferredUsername,
998 "addr" => str_replace("acct:", "", $contact->id)];
1000 if (!empty($contact->location->displayName)) {
1001 $gcontact["location"] = $contact->location->displayName;
1004 if (!empty($contact->summary)) {
1005 $gcontact["about"] = $contact->summary;
1008 if (!empty($contact->image->url)) {
1009 $gcontact["photo"] = $contact->image->url;
1012 GContact::update($gcontact);
1013 $cid = Contact::getIdForURL($contact->url, $uid);
1019 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1020 intval($uid), DBA::escape(normalise_link($contact->url)));
1022 if (!DBA::isResult($r)) {
1023 // create contact record
1024 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1025 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1026 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1027 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1029 DBA::escape(DateTimeFormat::utcNow()),
1030 DBA::escape($contact->url),
1031 DBA::escape(normalise_link($contact->url)),
1032 DBA::escape(str_replace("acct:", "", $contact->id)),
1034 DBA::escape($contact->id), // What is it for?
1035 DBA::escape('pump.io ' . $contact->id), // What is it for?
1036 DBA::escape($contact->displayName),
1037 DBA::escape($contact->preferredUsername),
1038 DBA::escape($contact->image->url),
1039 DBA::escape(NETWORK_PUMPIO),
1040 intval(Contact::FRIEND),
1042 DBA::escape($contact->location->displayName),
1043 DBA::escape($contact->summary),
1047 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1048 DBA::escape(normalise_link($contact->url)),
1052 if (!DBA::isResult($r)) {
1056 $contact_id = $r[0]['id'];
1058 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1060 $contact_id = $r[0]["id"];
1062 /* if (DB_UPDATE_VERSION >= "1177")
1063 q("UPDATE `contact` SET `location` = '%s',
1066 dbesc($contact->location->displayName),
1067 dbesc($contact->summary),
1073 if (!empty($contact->image->url)) {
1074 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1080 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1082 // Two queries for speed issues
1083 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1084 if (DBA::exists('item', $condition)) {
1085 Item::delete($condition);
1089 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1090 if (DBA::exists('item', $condition)) {
1091 Item::delete($condition);
1097 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1099 require_once('include/items.php');
1101 if (($post->verb == "like") || ($post->verb == "favorite")) {
1102 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1105 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1106 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1109 if ($post->verb == "delete") {
1110 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1113 if ($post->verb != "update") {
1114 // Two queries for speed issues
1115 if (DBA::exists('item', ['uri' => $post->object->id, 'uid' => $uid])) {
1118 if (DBA::exists('item', ['extid' => $post->object->id, 'uid' => $uid])) {
1123 // Only handle these three types
1124 if (!strstr("post|share|update", $post->verb)) {
1129 if (@is_array($post->cc)) {
1130 $receiptians = array_merge($receiptians, $post->cc);
1133 if (@is_array($post->to)) {
1134 $receiptians = array_merge($receiptians, $post->to);
1139 foreach ($receiptians AS $receiver) {
1140 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1146 $postarray['network'] = NETWORK_PUMPIO;
1147 $postarray['uid'] = $uid;
1148 $postarray['wall'] = 0;
1149 $postarray['uri'] = $post->object->id;
1150 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1152 if ($post->object->objectType != "comment") {
1153 $contact_id = pumpio_get_contact($uid, $post->actor);
1156 $contact_id = $self[0]['id'];
1159 $postarray['parent-uri'] = $post->object->id;
1162 $postarray['private'] = 1;
1163 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1166 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1168 if (link_compare($post->actor->url, $own_id)) {
1169 $contact_id = $self[0]['id'];
1170 $post->actor->displayName = $self[0]['name'];
1171 $post->actor->url = $self[0]['url'];
1172 $post->actor->image->url = $self[0]['photo'];
1173 } elseif ($contact_id == 0) {
1174 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1175 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1176 DBA::escape(normalise_link($post->actor->url)),
1180 if (DBA::isResult($r)) {
1181 $contact_id = $r[0]['id'];
1183 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1184 DBA::escape(normalise_link($post->actor->url)),
1188 if (DBA::isResult($r)) {
1189 $contact_id = $r[0]['id'];
1191 $contact_id = $self[0]['id'];
1196 $reply = new stdClass;
1197 $reply->verb = "note";
1199 if (isset($post->cc)) {
1200 $reply->cc = $post->cc;
1203 $reply->to = $post->to;
1204 $reply->object = new stdClass;
1205 $reply->object->objectType = $post->object->inReplyTo->objectType;
1206 $reply->object->content = $post->object->inReplyTo->content;
1207 $reply->object->id = $post->object->inReplyTo->id;
1208 $reply->actor = $post->object->inReplyTo->author;
1209 $reply->url = $post->object->inReplyTo->url;
1210 $reply->generator = new stdClass;
1211 $reply->generator->displayName = "pumpio";
1212 $reply->published = $post->object->inReplyTo->published;
1213 $reply->received = $post->object->inReplyTo->updated;
1214 $reply->url = $post->object->inReplyTo->url;
1215 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1217 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1220 if (!empty($post->object->pump_io->proxyURL)) {
1221 $postarray['extid'] = $post->object->pump_io->proxyURL;
1224 $postarray['contact-id'] = $contact_id;
1225 $postarray['verb'] = ACTIVITY_POST;
1226 $postarray['owner-name'] = $post->actor->displayName;
1227 $postarray['owner-link'] = $post->actor->url;
1228 $postarray['author-name'] = $postarray['owner-name'];
1229 $postarray['author-link'] = $postarray['owner-link'];
1230 if (!empty($post->actor->image)) {
1231 $postarray['owner-avatar'] = $post->actor->image->url;
1232 $postarray['author-avatar'] = $postarray['owner-avatar'];
1234 $postarray['plink'] = $post->object->url;
1235 $postarray['app'] = $post->generator->displayName;
1236 $postarray['title'] = '';
1237 $postarray['body'] = HTML::toBBCode($post->object->content);
1238 $postarray['object'] = json_encode($post);
1240 if (!empty($post->object->fullImage->url)) {
1241 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1244 if (!empty($post->object->displayName)) {
1245 $postarray['title'] = $post->object->displayName;
1248 $postarray['created'] = DateTimeFormat::utc($post->published);
1249 if (isset($post->updated)) {
1250 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1251 } elseif (isset($post->received)) {
1252 $postarray['edited'] = DateTimeFormat::utc($post->received);
1254 $postarray['edited'] = $postarray['created'];
1257 if ($post->verb == "share") {
1258 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1259 $share_author = $post->object->author->displayName;
1260 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1261 $share_author = $post->object->author->preferredUsername;
1263 $share_author = $post->object->author->url;
1266 $postarray['body'] = share_header($share_author, $post->object->author->url,
1267 $post->object->author->image->url, "",
1268 DateTimeFormat::utc($post->object->created),
1269 $post->links->self->href).
1270 $postarray['body']."[/share]";
1273 if (trim($postarray['body']) == "") {
1277 $top_item = Item::insert($postarray);
1278 $postarray["id"] = $top_item;
1280 if (($top_item == 0) && ($post->verb == "update")) {
1281 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1282 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1283 Item::update($fields, $condition);
1286 if (($post->object->objectType == "comment") && $threadcompletion) {
1287 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1293 function pumpio_fetchinbox(App $a, $uid)
1295 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1296 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1297 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1298 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1299 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1300 $hostname = PConfig::get($uid, 'pumpio', 'host');
1301 $username = PConfig::get($uid, "pumpio", "user");
1303 $own_id = "https://".$hostname."/".$username;
1305 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1308 $lastitems = q("SELECT `uri` FROM `thread`
1309 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1310 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1311 ORDER BY `thread`.`commented` DESC LIMIT 10",
1312 DBA::escape(NETWORK_PUMPIO),
1316 $client = new oauth_client_class;
1317 $client->oauth_version = '1.0a';
1318 $client->authorization_header = true;
1319 $client->url_parameters = false;
1321 $client->client_id = $ckey;
1322 $client->client_secret = $csecret;
1323 $client->access_token = $otoken;
1324 $client->access_token_secret = $osecret;
1326 $last_id = PConfig::get($uid, 'pumpio', 'last_id');
1328 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1330 if ($last_id != "") {
1331 $url .= '?since='.urlencode($last_id);
1334 if (pumpio_reachable($url)) {
1335 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1345 $posts = array_reverse($user->items);
1347 if (count($posts)) {
1348 foreach ($posts as $post) {
1349 $last_id = $post->id;
1350 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1355 foreach ($lastitems as $item) {
1356 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1359 PConfig::set($uid, 'pumpio', 'last_id', $last_id);
1362 function pumpio_getallusers(App &$a, $uid)
1364 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1365 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1366 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1367 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1368 $hostname = PConfig::get($uid, 'pumpio', 'host');
1369 $username = PConfig::get($uid, "pumpio", "user");
1371 $client = new oauth_client_class;
1372 $client->oauth_version = '1.0a';
1373 $client->authorization_header = true;
1374 $client->url_parameters = false;
1376 $client->client_id = $ckey;
1377 $client->client_secret = $csecret;
1378 $client->access_token = $otoken;
1379 $client->access_token_secret = $osecret;
1381 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1383 if (pumpio_reachable($url)) {
1384 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1389 if ($users->totalItems > count($users->items)) {
1390 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1392 if (pumpio_reachable($url)) {
1393 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1399 if (!empty($users->items)) {
1400 foreach ($users->items as $user) {
1401 pumpio_get_contact($uid, $user);
1406 function pumpio_queue_hook(App $a, array &$b)
1408 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1409 DBA::escape(NETWORK_PUMPIO)
1412 if (!DBA::isResult($qi)) {
1416 foreach ($qi as $x) {
1417 if ($x['network'] !== NETWORK_PUMPIO) {
1421 logger('pumpio_queue: run');
1423 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1424 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1427 if (!DBA::isResult($r)) {
1433 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1435 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1436 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1437 $consumer_key = PConfig::get($userdata['uid'], "pumpio", "consumer_key");
1438 $consumer_secret = PConfig::get($userdata['uid'], "pumpio", "consumer_secret");
1440 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1441 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1445 if ($oauth_token && $oauth_token_secret &&
1446 $consumer_key && $consumer_secret) {
1447 $username = $user.'@'.$host;
1449 logger('pumpio_queue: able to post for user '.$username);
1451 $z = unserialize($x['content']);
1453 $client = new oauth_client_class;
1454 $client->oauth_version = '1.0a';
1455 $client->url_parameters = false;
1456 $client->authorization_header = true;
1457 $client->access_token = $oauth_token;
1458 $client->access_token_secret = $oauth_token_secret;
1459 $client->client_id = $consumer_key;
1460 $client->client_secret = $consumer_secret;
1462 if (pumpio_reachable($z['url'])) {
1463 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1469 $post_id = $user->object->id;
1470 logger('pumpio_queue: send '.$username.': success '.$post_id);
1471 if ($post_id && $iscomment) {
1472 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1473 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1475 Queue::removeItem($x['id']);
1477 logger('pumpio_queue: send '.$username.': '.$z['url'].' general error: ' . print_r($user, true));
1480 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1484 logger('pumpio_queue: delayed');
1485 Queue::updateTime($x['id']);
1490 function pumpio_getreceiver(App $a, array $b)
1494 if (!$b["private"]) {
1495 if (!strstr($b['postopts'], 'pumpio')) {
1499 $public = PConfig::get($b['uid'], "pumpio", "public");
1502 $receiver["to"][] = [
1503 "objectType" => "collection",
1504 "id" => "http://activityschema.org/collection/public"];
1507 $cids = explode("><", $b["allow_cid"]);
1508 $gids = explode("><", $b["allow_gid"]);
1510 foreach ($cids AS $cid) {
1511 $cid = trim($cid, " <>");
1513 $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",
1516 DBA::escape(NETWORK_PUMPIO)
1519 if (DBA::isResult($r)) {
1520 $receiver["bcc"][] = [
1521 "displayName" => $r[0]["name"],
1522 "objectType" => "person",
1523 "preferredUsername" => $r[0]["nick"],
1524 "url" => $r[0]["url"]];
1527 foreach ($gids AS $gid) {
1528 $gid = trim($gid, " <>");
1530 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1531 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1532 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1534 DBA::escape(NETWORK_PUMPIO)
1537 foreach ($r AS $row)
1538 $receiver["bcc"][] = [
1539 "displayName" => $row["name"],
1540 "objectType" => "person",
1541 "preferredUsername" => $row["nick"],
1542 "url" => $row["url"]];
1546 if ($b["inform"] != "") {
1547 $inform = explode(",", $b["inform"]);
1549 foreach ($inform AS $cid) {
1550 if (substr($cid, 0, 4) != "cid:") {
1554 $cid = str_replace("cid:", "", $cid);
1556 $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",
1559 DBA::escape(NETWORK_PUMPIO)
1562 if (DBA::isResult($r)) {
1563 $receiver["to"][] = [
1564 "displayName" => $r[0]["name"],
1565 "objectType" => "person",
1566 "preferredUsername" => $r[0]["nick"],
1567 "url" => $r[0]["url"]];
1575 function pumpio_fetchallcomments(App $a, $uid, $id)
1577 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1578 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1579 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1580 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1581 $hostname = PConfig::get($uid, 'pumpio', 'host');
1582 $username = PConfig::get($uid, "pumpio", "user");
1584 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1586 $own_id = "https://".$hostname."/".$username;
1588 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1591 // Fetching the original post
1592 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1593 $item = Item::selectFirst(['extid'], $condition);
1594 if (!DBA::isResult($item)) {
1598 $url = $item["extid"];
1600 $client = new oauth_client_class;
1601 $client->oauth_version = '1.0a';
1602 $client->authorization_header = true;
1603 $client->url_parameters = false;
1605 $client->client_id = $ckey;
1606 $client->client_secret = $csecret;
1607 $client->access_token = $otoken;
1608 $client->access_token_secret = $osecret;
1610 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1612 if (pumpio_reachable($url)) {
1613 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1622 if ($item->likes->totalItems != 0) {
1623 foreach ($item->likes->items AS $post) {
1624 $like = new stdClass;
1625 $like->object = new stdClass;
1626 $like->object->id = $item->id;
1627 $like->actor = new stdClass;
1628 if (!empty($item->displayName)) {
1629 $like->actor->displayName = $item->displayName;
1631 //$like->actor->preferredUsername = $item->preferredUsername;
1632 //$like->actor->image = $item->image;
1633 $like->actor->url = $item->url;
1634 $like->generator = new stdClass;
1635 $like->generator->displayName = "pumpio";
1636 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1640 if ($item->replies->totalItems == 0) {
1644 foreach ($item->replies->items AS $item) {
1645 if ($item->id == $id) {
1649 // Checking if the comment already exists - Two queries for speed issues
1650 if (DBA::exists('item', ['uri' => $item->id, 'uid' => $uid])) {
1654 if (DBA::exists('item', ['extid' => $item->id, 'uid' => $uid])) {
1658 $post = new stdClass;
1659 $post->verb = "post";
1660 $post->actor = $item->author;
1661 $post->published = $item->published;
1662 $post->received = $item->updated;
1663 $post->generator = new stdClass;
1664 $post->generator->displayName = "pumpio";
1665 // To-Do: Check for public post
1667 unset($item->author);
1668 unset($item->published);
1669 unset($item->updated);
1671 $post->object = $item;
1673 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1674 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1678 function pumpio_reachable($url)
1680 $data = Network::curl($url, false, $redirects, ['timeout'=>10]);
1681 return intval($data['return_code']) != 0;