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\Protocol;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Item;
23 use Friendica\Model\Queue;
24 use Friendica\Model\User;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
28 require 'addon/pumpio/oauth/http.php';
29 require 'addon/pumpio/oauth/oauth_client.php';
30 require_once 'include/enotify.php';
31 require_once "mod/share.php";
33 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
35 function pumpio_install()
37 Addon::registerHook('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
38 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
39 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
40 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
41 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
42 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
43 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
44 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
45 Addon::registerHook('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
48 function pumpio_uninstall()
50 Addon::unregisterHook('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
51 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
52 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
53 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
54 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
55 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
56 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
57 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
58 Addon::unregisterHook('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
61 function pumpio_module() {}
63 function pumpio_content(App $a)
66 notice(L10n::t('Permission denied.') . EOL);
70 require_once("mod/settings.php");
73 if (isset($a->argv[1])) {
74 switch ($a->argv[1]) {
76 $o = pumpio_connect($a);
79 $o = print_r($a->argv, true);
83 $o = pumpio_connect($a);
88 function pumpio_check_item_notification($a, &$notification_data)
90 $hostname = PConfig::get($notification_data["uid"], 'pumpio', 'host');
91 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
93 $notification_data["profiles"][] = "https://".$hostname."/".$username;
96 function pumpio_registerclient(App $a, $host)
98 $url = "https://".$host."/api/client/register";
102 $application_name = Config::get('pumpio', 'application_name');
104 if ($application_name == "") {
105 $application_name = $a->get_hostname();
108 $adminlist = explode(",", str_replace(" ", "", Config::get('config', 'admin_email')));
110 $params["type"] = "client_associate";
111 $params["contacts"] = $adminlist[0];
112 $params["application_type"] = "native";
113 $params["application_name"] = $application_name;
114 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
115 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
117 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
119 $ch = curl_init($url);
120 curl_setopt($ch, CURLOPT_HEADER, false);
121 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
122 curl_setopt($ch, CURLOPT_POST,1);
123 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
124 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
127 $curl_info = curl_getinfo($ch);
129 if ($curl_info["http_code"] == "200") {
130 $values = json_decode($s);
131 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
134 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
139 function pumpio_connect(App $a)
141 // Define the needed keys
142 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
143 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
144 $hostname = PConfig::get(local_user(), 'pumpio', 'host');
146 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
147 logger("pumpio_connect: register client");
148 $clientdata = pumpio_registerclient($a, $hostname);
149 PConfig::set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
150 PConfig::set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
152 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
153 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
155 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
158 if (($consumer_key == "") || ($consumer_secret == "")) {
159 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
161 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
165 // The callback URL is the script that gets called after the user authenticates with pumpio
166 $callback_url = $a->get_baseurl()."/pumpio/connect";
168 // Let's begin. First we need a Request Token. The request token is required to send the user
169 // to pumpio's login page.
171 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
172 // Consumer Key and Consumer Secret
173 $client = new oauth_client_class;
175 $client->server = '';
176 $client->oauth_version = '1.0a';
177 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
178 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
179 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
180 $client->url_parameters = false;
181 $client->authorization_header = true;
182 $client->redirect_uri = $callback_url;
183 $client->client_id = $consumer_key;
184 $client->client_secret = $consumer_secret;
186 if (($success = $client->Initialize())) {
187 if (($success = $client->Process())) {
188 if (strlen($client->access_token)) {
189 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
190 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
191 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
194 $success = $client->Finalize($success);
197 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
201 logger("pumpio_connect: authenticated");
202 $o = L10n::t("You are now authenticated to pumpio.");
203 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
205 logger("pumpio_connect: could not connect");
206 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
212 function pumpio_jot_nets(App $a, &$b)
214 if (! local_user()) {
218 $pumpio_post = PConfig::get(local_user(), 'pumpio', 'post');
220 if (intval($pumpio_post) == 1) {
221 $pumpio_defpost = PConfig::get(local_user(), 'pumpio', 'post_by_default');
222 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
223 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
224 . L10n::t('Post to pumpio') . '</div>';
228 function pumpio_settings(App $a, &$s)
234 /* Add our stylesheet to the page so we can make our settings look nice */
236 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
238 /* Get the current state of our config variables */
240 $import_enabled = PConfig::get(local_user(), 'pumpio', 'import');
241 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
243 $enabled = PConfig::get(local_user(), 'pumpio', 'post');
244 $checked = (($enabled) ? ' checked="checked" ' : '');
245 $css = (($enabled) ? '' : '-disabled');
247 $def_enabled = PConfig::get(local_user(), 'pumpio', 'post_by_default');
248 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
250 $public_enabled = PConfig::get(local_user(), 'pumpio', 'public');
251 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
253 $mirror_enabled = PConfig::get(local_user(), 'pumpio', 'mirror');
254 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
256 $servername = PConfig::get(local_user(), "pumpio", "host");
257 $username = PConfig::get(local_user(), "pumpio", "user");
259 /* Add some HTML to the existing form */
261 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
262 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
264 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
265 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
266 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
269 $s .= '<div id="pumpio-username-wrapper">';
270 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
271 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
272 $s .= '</div><div class="clear"></div>';
274 $s .= '<div id="pumpio-servername-wrapper">';
275 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
276 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
277 $s .= '</div><div class="clear"></div>';
279 if (($username != '') && ($servername != '')) {
280 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
281 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
283 $s .= '<div id="pumpio-password-wrapper">';
284 if (($oauth_token == "") || ($oauth_token_secret == "")) {
285 $s .= '<div id="pumpio-authenticate-wrapper">';
286 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
287 $s .= '</div><div class="clear"></div>';
289 $s .= '<div id="pumpio-import-wrapper">';
290 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
291 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
292 $s .= '</div><div class="clear"></div>';
294 $s .= '<div id="pumpio-enable-wrapper">';
295 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
296 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
297 $s .= '</div><div class="clear"></div>';
299 $s .= '<div id="pumpio-bydefault-wrapper">';
300 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
301 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
302 $s .= '</div><div class="clear"></div>';
304 $s .= '<div id="pumpio-public-wrapper">';
305 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
306 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
307 $s .= '</div><div class="clear"></div>';
309 $s .= '<div id="pumpio-mirror-wrapper">';
310 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
311 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
312 $s .= '</div><div class="clear"></div>';
314 $s .= '<div id="pumpio-delete-wrapper">';
315 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
316 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
317 $s .= '</div><div class="clear"></div>';
320 $s .= '</div><div class="clear"></div>';
323 /* provide a submit button */
325 $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>';
328 function pumpio_settings_post(App $a, array &$b)
330 if (!empty($_POST['pumpio-submit'])) {
331 if (!empty($_POST['pumpio_delete'])) {
332 PConfig::set(local_user(), 'pumpio', 'consumer_key' , '');
333 PConfig::set(local_user(), 'pumpio', 'consumer_secret' , '');
334 PConfig::set(local_user(), 'pumpio', 'oauth_token' , '');
335 PConfig::set(local_user(), 'pumpio', 'oauth_token_secret', '');
336 PConfig::set(local_user(), 'pumpio', 'post' , false);
337 PConfig::set(local_user(), 'pumpio', 'import' , false);
338 PConfig::set(local_user(), 'pumpio', 'host' , '');
339 PConfig::set(local_user(), 'pumpio', 'user' , '');
340 PConfig::set(local_user(), 'pumpio', 'public' , false);
341 PConfig::set(local_user(), 'pumpio', 'mirror' , false);
342 PConfig::set(local_user(), 'pumpio', 'post_by_default' , false);
343 PConfig::set(local_user(), 'pumpio', 'lastdate' , 0);
344 PConfig::set(local_user(), 'pumpio', 'last_id' , '');
346 // filtering the username if it is filled wrong
347 $user = $_POST['pumpio_user'];
348 if (strstr($user, "@")) {
349 $pos = strpos($user, "@");
352 $user = substr($user, 0, $pos);
356 // Filtering the hostname if someone is entering it with "http"
357 $host = $_POST['pumpio_host'];
359 $host = str_replace(["https://", "http://"], ["", ""], $host);
361 PConfig::set(local_user(), 'pumpio', 'post' , defaults($_POST, 'pumpio', false));
362 PConfig::set(local_user(), 'pumpio', 'import' , defaults($_POST, 'pumpio_import', false));
363 PConfig::set(local_user(), 'pumpio', 'host' , $host);
364 PConfig::set(local_user(), 'pumpio', 'user' , $user);
365 PConfig::set(local_user(), 'pumpio', 'public' , defaults($_POST, 'pumpio_public', false));
366 PConfig::set(local_user(), 'pumpio', 'mirror' , defaults($_POST, 'pumpio_mirror', false));
367 PConfig::set(local_user(), 'pumpio', 'post_by_default', defaults($_POST, 'pumpio_bydefault', false));
369 if (!empty($_POST['pumpio_mirror'])) {
370 PConfig::delete(local_user(), 'pumpio', 'lastdate');
376 function pumpio_load_config(App $a)
378 $a->loadConfigFile(__DIR__. '/config/pumpio.ini.php');
381 function pumpio_post_local(App $a, array &$b)
383 if (!local_user() || (local_user() != $b['uid'])) {
387 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
389 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
391 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
395 if (!$pumpio_enable) {
399 if (strlen($b['postopts'])) {
400 $b['postopts'] .= ',';
403 $b['postopts'] .= 'pumpio';
406 function pumpio_send(App $a, array &$b)
408 if (!PConfig::get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
412 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
414 if ($b['parent'] != $b['id']) {
415 // Looking if its a reply to a pumpio post
416 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
417 $orig_post = Item::selectFirst([], $condition);
419 if (!DBA::isResult($orig_post)) {
420 logger("pumpio_send: no pumpio post ".$b["parent"]);
428 $receiver = pumpio_getreceiver($a, $b);
430 logger("pumpio_send: receiver ".print_r($receiver, true));
432 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
436 // Dont't post if the post doesn't belong to us.
437 // This is a check for forum postings
438 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
439 if ($b['contact-id'] != $self['id']) {
444 if ($b['verb'] == ACTIVITY_LIKE) {
446 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
448 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
453 if ($b['verb'] == ACTIVITY_DISLIKE) {
457 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
458 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
461 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
462 pumpio_action($a, $b["uid"], $b["uri"], "delete");
465 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
469 // if post comes from pump.io don't send it back
470 if ($b['app'] == "pump.io") {
475 // Support for native shares
476 // http://<hostname>/api/<type>/shares?id=<the-object-id>
478 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
479 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
480 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
481 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
483 $host = PConfig::get($b['uid'], "pumpio", "host");
484 $user = PConfig::get($b['uid'], "pumpio", "user");
485 $public = PConfig::get($b['uid'], "pumpio", "public");
487 if ($oauth_token && $oauth_token_secret) {
488 $title = trim($b['title']);
490 $content = BBCode::convert($b['body'], false, 4);
494 $params["verb"] = "post";
497 $params["object"] = [
498 'objectType' => "note",
499 'content' => $content];
501 if (!empty($title)) {
502 $params["object"]["displayName"] = $title;
505 if (!empty($receiver["to"])) {
506 $params["to"] = $receiver["to"];
509 if (!empty($receiver["bto"])) {
510 $params["bto"] = $receiver["bto"];
513 if (!empty($receiver["cc"])) {
514 $params["cc"] = $receiver["cc"];
517 if (!empty($receiver["bcc"])) {
518 $params["bcc"] = $receiver["bcc"];
521 $inReplyTo = ["id" => $orig_post["uri"],
522 "objectType" => "note"];
524 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
525 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
528 $params["object"] = [
529 'objectType' => "comment",
530 'content' => $content,
531 'inReplyTo' => $inReplyTo];
534 $params["object"]["displayName"] = $title;
538 $client = new oauth_client_class;
539 $client->oauth_version = '1.0a';
540 $client->url_parameters = false;
541 $client->authorization_header = true;
542 $client->access_token = $oauth_token;
543 $client->access_token_secret = $oauth_token_secret;
544 $client->client_id = $consumer_key;
545 $client->client_secret = $consumer_secret;
547 $username = $user.'@'.$host;
548 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
550 if (pumpio_reachable($url)) {
551 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
557 if ($user->generator->displayName) {
558 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
561 $post_id = $user->object->id;
562 logger('pumpio_send '.$username.': success '.$post_id);
563 if ($post_id && $iscomment) {
564 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
565 Item::update(['extid' => $post_id], ['id' => $b['id']]);
568 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
570 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
571 if (DBA::isResult($r)) {
572 $a->contact = $r[0]["id"];
575 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
577 Queue::add($a->contact, Protocol::PUMPIO, $s);
578 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
583 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
585 // Don't do likes and other stuff if you don't import the timeline
586 if (!PConfig::get($uid, 'pumpio', 'import')) {
590 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
591 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
592 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
593 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
594 $hostname = PConfig::get($uid, 'pumpio', 'host');
595 $username = PConfig::get($uid, "pumpio", "user");
597 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
599 if (!DBA::isResult($orig_post)) {
603 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
604 $uri = $orig_post["extid"];
606 $uri = $orig_post["uri"];
609 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
610 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
611 } elseif (strstr($uri, "/api/comment/")) {
612 $objectType = "comment";
613 } elseif (strstr($uri, "/api/note/")) {
614 $objectType = "note";
615 } elseif (strstr($uri, "/api/image/")) {
616 $objectType = "image";
619 $params["verb"] = $action;
620 $params["object"] = ['id' => $uri,
621 "objectType" => $objectType,
622 "content" => $content];
624 $client = new oauth_client_class;
625 $client->oauth_version = '1.0a';
626 $client->authorization_header = true;
627 $client->url_parameters = false;
629 $client->client_id = $ckey;
630 $client->client_secret = $csecret;
631 $client->access_token = $otoken;
632 $client->access_token_secret = $osecret;
634 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
636 if (pumpio_reachable($url)) {
637 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
643 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
645 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user, true));
647 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
648 if (DBA::isResult($r)) {
649 $a->contact = $r[0]["id"];
652 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
654 Queue::add($a->contact, Protocol::PUMPIO, $s);
655 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
659 function pumpio_sync(App $a)
661 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
663 if (!DBA::isResult($r)) {
667 $last = Config::get('pumpio', 'last_poll');
669 $poll_interval = intval(Config::get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
672 $next = $last + ($poll_interval * 60);
673 if ($next > time()) {
674 logger('pumpio: poll intervall not reached');
678 logger('pumpio: cron_start');
680 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
681 if (DBA::isResult($r)) {
682 foreach ($r as $rr) {
683 logger('pumpio: mirroring user '.$rr['uid']);
684 pumpio_fetchtimeline($a, $rr['uid']);
688 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
689 if ($abandon_days < 1) {
693 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
695 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
696 if (DBA::isResult($r)) {
697 foreach ($r as $rr) {
698 if ($abandon_days != 0) {
699 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
700 if (!DBA::isResult($user)) {
701 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
706 logger('pumpio: importing timeline from user '.$rr['uid']);
707 pumpio_fetchinbox($a, $rr['uid']);
709 // check for new contacts once a day
710 $last_contact_check = PConfig::get($rr['uid'], 'pumpio', 'contact_check');
711 if ($last_contact_check) {
712 $next_contact_check = $last_contact_check + 86400;
714 $next_contact_check = 0;
717 if ($next_contact_check <= time()) {
718 pumpio_getallusers($a, $rr["uid"]);
719 PConfig::set($rr['uid'], 'pumpio', 'contact_check', time());
724 logger('pumpio: cron_end');
726 Config::set('pumpio', 'last_poll', time());
729 function pumpio_cron(App $a, $b)
731 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
734 function pumpio_fetchtimeline(App $a, $uid)
736 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
737 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
738 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
739 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
740 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
741 $hostname = PConfig::get($uid, 'pumpio', 'host');
742 $username = PConfig::get($uid, "pumpio", "user");
744 // get the application name for the pump.io app
745 // 1st try personal config, then system config and fallback to the
746 // hostname of the node if neither one is set.
747 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
748 if ($application_name == "") {
749 $application_name = Config::get('pumpio', 'application_name');
751 if ($application_name == "") {
752 $application_name = $a->get_hostname();
755 $first_time = ($lastdate == "");
757 $client = new oauth_client_class;
758 $client->oauth_version = '1.0a';
759 $client->authorization_header = true;
760 $client->url_parameters = false;
762 $client->client_id = $ckey;
763 $client->client_secret = $csecret;
764 $client->access_token = $otoken;
765 $client->access_token_secret = $osecret;
767 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
769 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
771 $useraddr = $username.'@'.$hostname;
773 if (pumpio_reachable($url)) {
774 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
781 logger('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
785 $posts = array_reverse($user->items);
787 $initiallastdate = $lastdate;
791 foreach ($posts as $post) {
792 if ($post->published <= $initiallastdate) {
796 if ($lastdate < $post->published) {
797 $lastdate = $post->published;
805 if (@is_array($post->cc)) {
806 $receiptians = array_merge($receiptians, $post->cc);
809 if (@is_array($post->to)) {
810 $receiptians = array_merge($receiptians, $post->to);
814 foreach ($receiptians AS $receiver) {
815 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
820 if ($public && !stristr($post->generator->displayName, $application_name)) {
821 $_SESSION["authenticated"] = true;
822 $_SESSION["uid"] = $uid;
825 $_REQUEST["api_source"] = true;
826 $_REQUEST["profile_uid"] = $uid;
827 $_REQUEST["source"] = "pump.io";
829 if (isset($post->object->id)) {
830 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
833 if ($post->object->displayName != "") {
834 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
836 $_REQUEST["title"] = "";
839 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
841 // To-Do: Picture has to be cached and stored locally
842 if ($post->object->fullImage->url != "") {
843 if ($post->object->fullImage->pump_io->proxyURL != "") {
844 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
846 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
850 logger('pumpio: posting for user '.$uid);
852 require_once('mod/item.php');
855 logger('pumpio: posting done - user '.$uid);
860 if ($lastdate != 0) {
861 PConfig::set($uid, 'pumpio', 'lastdate', $lastdate);
865 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
867 // Searching for the unliked post
868 // Two queries for speed issues
869 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
870 if (!DBA::isResult($orig_post)) {
871 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
872 if (!DBA::isResult($orig_post)) {
879 if (link_compare($post->actor->url, $own_id)) {
880 $contactid = $self[0]['id'];
882 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
883 DBA::escape(normalise_link($post->actor->url)),
887 if (DBA::isResult($r)) {
888 $contactid = $r[0]['id'];
891 if ($contactid == 0) {
892 $contactid = $orig_post['contact-id'];
896 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
898 if (DBA::isResult($r)) {
899 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
901 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
905 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
907 require_once('include/items.php');
909 if (empty($post->object->id)) {
910 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
914 // Searching for the liked post
915 // Two queries for speed issues
916 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
917 if (!DBA::isResult($orig_post)) {
918 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
919 if (!DBA::isResult($orig_post)) {
925 if ($threadcompletion) {
926 pumpio_fetchallcomments($a, $uid, $post->object->id);
931 if (link_compare($post->actor->url, $own_id)) {
932 $contactid = $self[0]['id'];
933 $post->actor->displayName = $self[0]['name'];
934 $post->actor->url = $self[0]['url'];
935 $post->actor->image->url = $self[0]['photo'];
937 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
938 DBA::escape(normalise_link($post->actor->url)),
942 if (DBA::isResult($r)) {
943 $contactid = $r[0]['id'];
946 if ($contactid == 0) {
947 $contactid = $orig_post['contact-id'];
951 $condition = ['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
952 if (Item::exists($condition)) {
953 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
958 $likedata['parent'] = $orig_post['id'];
959 $likedata['verb'] = ACTIVITY_LIKE;
960 $likedata['gravity'] = GRAVITY_ACTIVITY;
961 $likedata['uid'] = $uid;
962 $likedata['wall'] = 0;
963 $likedata['network'] = Protocol::PUMPIO;
964 $likedata['uri'] = Item::newURI($uid);
965 $likedata['parent-uri'] = $orig_post["uri"];
966 $likedata['contact-id'] = $contactid;
967 $likedata['app'] = $post->generator->displayName;
968 $likedata['author-name'] = $post->actor->displayName;
969 $likedata['author-link'] = $post->actor->url;
970 if (!empty($post->actor->image)) {
971 $likedata['author-avatar'] = $post->actor->image->url;
974 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
975 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
976 $post_type = L10n::t('status');
977 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
978 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
980 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
982 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
983 '<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>';
985 $ret = Item::insert($likedata);
987 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
990 function pumpio_get_contact($uid, $contact, $no_insert = false)
992 $gcontact = ["url" => $contact->url, "network" => Protocol::PUMPIO, "generation" => 2,
993 "name" => $contact->displayName, "hide" => true,
994 "nick" => $contact->preferredUsername,
995 "addr" => str_replace("acct:", "", $contact->id)];
997 if (!empty($contact->location->displayName)) {
998 $gcontact["location"] = $contact->location->displayName;
1001 if (!empty($contact->summary)) {
1002 $gcontact["about"] = $contact->summary;
1005 if (!empty($contact->image->url)) {
1006 $gcontact["photo"] = $contact->image->url;
1009 GContact::update($gcontact);
1010 $cid = Contact::getIdForURL($contact->url, $uid);
1016 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1017 intval($uid), DBA::escape(normalise_link($contact->url)));
1019 if (!DBA::isResult($r)) {
1020 // create contact record
1021 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1022 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1023 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1024 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1026 DBA::escape(DateTimeFormat::utcNow()),
1027 DBA::escape($contact->url),
1028 DBA::escape(normalise_link($contact->url)),
1029 DBA::escape(str_replace("acct:", "", $contact->id)),
1031 DBA::escape($contact->id), // What is it for?
1032 DBA::escape('pump.io ' . $contact->id), // What is it for?
1033 DBA::escape($contact->displayName),
1034 DBA::escape($contact->preferredUsername),
1035 DBA::escape($contact->image->url),
1036 DBA::escape(Protocol::PUMPIO),
1037 intval(Contact::FRIEND),
1039 DBA::escape($contact->location->displayName),
1040 DBA::escape($contact->summary),
1044 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1045 DBA::escape(normalise_link($contact->url)),
1049 if (!DBA::isResult($r)) {
1053 $contact_id = $r[0]['id'];
1055 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1057 $contact_id = $r[0]["id"];
1059 /* if (DB_UPDATE_VERSION >= "1177")
1060 q("UPDATE `contact` SET `location` = '%s',
1063 dbesc($contact->location->displayName),
1064 dbesc($contact->summary),
1070 if (!empty($contact->image->url)) {
1071 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1077 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1079 // Two queries for speed issues
1080 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1081 if (Item::exists($condition)) {
1082 Item::delete($condition);
1086 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1087 if (Item::exists($condition)) {
1088 Item::delete($condition);
1094 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1096 require_once('include/items.php');
1098 if (($post->verb == "like") || ($post->verb == "favorite")) {
1099 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1102 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1103 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1106 if ($post->verb == "delete") {
1107 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1110 if ($post->verb != "update") {
1111 // Two queries for speed issues
1112 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1115 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1120 // Only handle these three types
1121 if (!strstr("post|share|update", $post->verb)) {
1126 if (@is_array($post->cc)) {
1127 $receiptians = array_merge($receiptians, $post->cc);
1130 if (@is_array($post->to)) {
1131 $receiptians = array_merge($receiptians, $post->to);
1136 foreach ($receiptians AS $receiver) {
1137 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1143 $postarray['network'] = Protocol::PUMPIO;
1144 $postarray['uid'] = $uid;
1145 $postarray['wall'] = 0;
1146 $postarray['uri'] = $post->object->id;
1147 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1149 if ($post->object->objectType != "comment") {
1150 $contact_id = pumpio_get_contact($uid, $post->actor);
1153 $contact_id = $self[0]['id'];
1156 $postarray['parent-uri'] = $post->object->id;
1159 $postarray['private'] = 1;
1160 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1163 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1165 if (link_compare($post->actor->url, $own_id)) {
1166 $contact_id = $self[0]['id'];
1167 $post->actor->displayName = $self[0]['name'];
1168 $post->actor->url = $self[0]['url'];
1169 $post->actor->image->url = $self[0]['photo'];
1170 } elseif ($contact_id == 0) {
1171 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1172 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1173 DBA::escape(normalise_link($post->actor->url)),
1177 if (DBA::isResult($r)) {
1178 $contact_id = $r[0]['id'];
1180 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1181 DBA::escape(normalise_link($post->actor->url)),
1185 if (DBA::isResult($r)) {
1186 $contact_id = $r[0]['id'];
1188 $contact_id = $self[0]['id'];
1193 $reply = new stdClass;
1194 $reply->verb = "note";
1196 if (isset($post->cc)) {
1197 $reply->cc = $post->cc;
1200 if (isset($post->to)) {
1201 $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 // When there is no content there is no need to continue
1221 if (empty($post->object->content)) {
1225 if (!empty($post->object->pump_io->proxyURL)) {
1226 $postarray['extid'] = $post->object->pump_io->proxyURL;
1229 $postarray['contact-id'] = $contact_id;
1230 $postarray['verb'] = ACTIVITY_POST;
1231 $postarray['owner-name'] = $post->actor->displayName;
1232 $postarray['owner-link'] = $post->actor->url;
1233 $postarray['author-name'] = $postarray['owner-name'];
1234 $postarray['author-link'] = $postarray['owner-link'];
1235 if (!empty($post->actor->image)) {
1236 $postarray['owner-avatar'] = $post->actor->image->url;
1237 $postarray['author-avatar'] = $postarray['owner-avatar'];
1239 $postarray['plink'] = $post->object->url;
1240 $postarray['app'] = $post->generator->displayName;
1241 $postarray['title'] = '';
1242 $postarray['body'] = HTML::toBBCode($post->object->content);
1243 $postarray['object'] = json_encode($post);
1245 if (!empty($post->object->fullImage->url)) {
1246 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1249 if (!empty($post->object->displayName)) {
1250 $postarray['title'] = $post->object->displayName;
1253 $postarray['created'] = DateTimeFormat::utc($post->published);
1254 if (isset($post->updated)) {
1255 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1256 } elseif (isset($post->received)) {
1257 $postarray['edited'] = DateTimeFormat::utc($post->received);
1259 $postarray['edited'] = $postarray['created'];
1262 if ($post->verb == "share") {
1263 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1264 $share_author = $post->object->author->displayName;
1265 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1266 $share_author = $post->object->author->preferredUsername;
1268 $share_author = $post->object->author->url;
1271 if (isset($post->object->created)) {
1272 $created = DateTimeFormat::utc($post->object->created);
1277 $postarray['body'] = share_header($share_author, $post->object->author->url,
1278 $post->object->author->image->url, "",
1279 $created, $post->links->self->href).
1280 $postarray['body']."[/share]";
1283 if (trim($postarray['body']) == "") {
1287 $top_item = Item::insert($postarray);
1288 $postarray["id"] = $top_item;
1290 if (($top_item == 0) && ($post->verb == "update")) {
1291 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1292 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1293 Item::update($fields, $condition);
1296 if (($post->object->objectType == "comment") && $threadcompletion) {
1297 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1303 function pumpio_fetchinbox(App $a, $uid)
1305 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1306 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1307 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1308 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1309 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1310 $hostname = PConfig::get($uid, 'pumpio', 'host');
1311 $username = PConfig::get($uid, "pumpio", "user");
1313 $own_id = "https://".$hostname."/".$username;
1315 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1318 $lastitems = q("SELECT `uri` FROM `thread`
1319 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1320 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1321 ORDER BY `thread`.`commented` DESC LIMIT 10",
1322 DBA::escape(Protocol::PUMPIO),
1326 $client = new oauth_client_class;
1327 $client->oauth_version = '1.0a';
1328 $client->authorization_header = true;
1329 $client->url_parameters = false;
1331 $client->client_id = $ckey;
1332 $client->client_secret = $csecret;
1333 $client->access_token = $otoken;
1334 $client->access_token_secret = $osecret;
1336 $last_id = PConfig::get($uid, 'pumpio', 'last_id');
1338 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1340 if ($last_id != "") {
1341 $url .= '?since='.urlencode($last_id);
1344 if (pumpio_reachable($url)) {
1345 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1355 $posts = array_reverse($user->items);
1357 if (count($posts)) {
1358 foreach ($posts as $post) {
1359 $last_id = $post->id;
1360 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1365 foreach ($lastitems as $item) {
1366 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1369 PConfig::set($uid, 'pumpio', 'last_id', $last_id);
1372 function pumpio_getallusers(App &$a, $uid)
1374 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1375 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1376 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1377 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1378 $hostname = PConfig::get($uid, 'pumpio', 'host');
1379 $username = PConfig::get($uid, "pumpio", "user");
1381 $client = new oauth_client_class;
1382 $client->oauth_version = '1.0a';
1383 $client->authorization_header = true;
1384 $client->url_parameters = false;
1386 $client->client_id = $ckey;
1387 $client->client_secret = $csecret;
1388 $client->access_token = $otoken;
1389 $client->access_token_secret = $osecret;
1391 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1393 if (pumpio_reachable($url)) {
1394 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1399 if (empty($users)) {
1403 if ($users->totalItems > count($users->items)) {
1404 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1406 if (pumpio_reachable($url)) {
1407 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1413 if (!empty($users->items)) {
1414 foreach ($users->items as $user) {
1415 pumpio_get_contact($uid, $user);
1420 function pumpio_queue_hook(App $a, array &$b)
1422 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1423 DBA::escape(Protocol::PUMPIO)
1426 if (!DBA::isResult($qi)) {
1430 foreach ($qi as $x) {
1431 if ($x['network'] !== Protocol::PUMPIO) {
1435 logger('pumpio_queue: run');
1437 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1438 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1441 if (!DBA::isResult($r)) {
1447 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1449 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1450 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1451 $consumer_key = PConfig::get($userdata['uid'], "pumpio", "consumer_key");
1452 $consumer_secret = PConfig::get($userdata['uid'], "pumpio", "consumer_secret");
1454 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1455 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1459 if ($oauth_token && $oauth_token_secret &&
1460 $consumer_key && $consumer_secret) {
1461 $username = $user.'@'.$host;
1463 logger('pumpio_queue: able to post for user '.$username);
1465 $z = unserialize($x['content']);
1467 $client = new oauth_client_class;
1468 $client->oauth_version = '1.0a';
1469 $client->url_parameters = false;
1470 $client->authorization_header = true;
1471 $client->access_token = $oauth_token;
1472 $client->access_token_secret = $oauth_token_secret;
1473 $client->client_id = $consumer_key;
1474 $client->client_secret = $consumer_secret;
1476 if (pumpio_reachable($z['url'])) {
1477 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1483 $post_id = $user->object->id;
1484 logger('pumpio_queue: send '.$username.': success '.$post_id);
1485 if ($post_id && $iscomment) {
1486 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1487 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1489 Queue::removeItem($x['id']);
1491 logger('pumpio_queue: send '.$username.': '.$z['url'].' general error: ' . print_r($user, true));
1494 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1498 logger('pumpio_queue: delayed');
1499 Queue::updateTime($x['id']);
1504 function pumpio_getreceiver(App $a, array $b)
1508 if (!$b["private"]) {
1509 if (!strstr($b['postopts'], 'pumpio')) {
1513 $public = PConfig::get($b['uid'], "pumpio", "public");
1516 $receiver["to"][] = [
1517 "objectType" => "collection",
1518 "id" => "http://activityschema.org/collection/public"];
1521 $cids = explode("><", $b["allow_cid"]);
1522 $gids = explode("><", $b["allow_gid"]);
1524 foreach ($cids AS $cid) {
1525 $cid = trim($cid, " <>");
1527 $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",
1530 DBA::escape(Protocol::PUMPIO)
1533 if (DBA::isResult($r)) {
1534 $receiver["bcc"][] = [
1535 "displayName" => $r[0]["name"],
1536 "objectType" => "person",
1537 "preferredUsername" => $r[0]["nick"],
1538 "url" => $r[0]["url"]];
1541 foreach ($gids AS $gid) {
1542 $gid = trim($gid, " <>");
1544 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1545 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1546 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1548 DBA::escape(Protocol::PUMPIO)
1551 foreach ($r AS $row)
1552 $receiver["bcc"][] = [
1553 "displayName" => $row["name"],
1554 "objectType" => "person",
1555 "preferredUsername" => $row["nick"],
1556 "url" => $row["url"]];
1560 if ($b["inform"] != "") {
1561 $inform = explode(",", $b["inform"]);
1563 foreach ($inform AS $cid) {
1564 if (substr($cid, 0, 4) != "cid:") {
1568 $cid = str_replace("cid:", "", $cid);
1570 $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",
1573 DBA::escape(Protocol::PUMPIO)
1576 if (DBA::isResult($r)) {
1577 $receiver["to"][] = [
1578 "displayName" => $r[0]["name"],
1579 "objectType" => "person",
1580 "preferredUsername" => $r[0]["nick"],
1581 "url" => $r[0]["url"]];
1589 function pumpio_fetchallcomments(App $a, $uid, $id)
1591 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1592 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1593 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1594 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1595 $hostname = PConfig::get($uid, 'pumpio', 'host');
1596 $username = PConfig::get($uid, "pumpio", "user");
1598 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1600 $own_id = "https://".$hostname."/".$username;
1602 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1605 // Fetching the original post
1606 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1607 $item = Item::selectFirst(['extid'], $condition);
1608 if (!DBA::isResult($item)) {
1612 $url = $item["extid"];
1614 $client = new oauth_client_class;
1615 $client->oauth_version = '1.0a';
1616 $client->authorization_header = true;
1617 $client->url_parameters = false;
1619 $client->client_id = $ckey;
1620 $client->client_secret = $csecret;
1621 $client->access_token = $otoken;
1622 $client->access_token_secret = $osecret;
1624 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1626 if (pumpio_reachable($url)) {
1627 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1636 if ($item->likes->totalItems != 0) {
1637 foreach ($item->likes->items AS $post) {
1638 $like = new stdClass;
1639 $like->object = new stdClass;
1640 $like->object->id = $item->id;
1641 $like->actor = new stdClass;
1642 if (!empty($item->displayName)) {
1643 $like->actor->displayName = $item->displayName;
1645 //$like->actor->preferredUsername = $item->preferredUsername;
1646 //$like->actor->image = $item->image;
1647 $like->actor->url = $item->url;
1648 $like->generator = new stdClass;
1649 $like->generator->displayName = "pumpio";
1650 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1654 if ($item->replies->totalItems == 0) {
1658 foreach ($item->replies->items AS $item) {
1659 if ($item->id == $id) {
1663 // Checking if the comment already exists - Two queries for speed issues
1664 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1668 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1672 $post = new stdClass;
1673 $post->verb = "post";
1674 $post->actor = $item->author;
1675 $post->published = $item->published;
1676 $post->received = $item->updated;
1677 $post->generator = new stdClass;
1678 $post->generator->displayName = "pumpio";
1679 // To-Do: Check for public post
1681 unset($item->author);
1682 unset($item->published);
1683 unset($item->updated);
1685 $post->object = $item;
1687 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1688 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1692 function pumpio_reachable($url)
1694 $data = Network::curl($url, false, $redirects, ['timeout'=>10]);
1695 return intval($data['return_code']) != 0;