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\Logger;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Contact;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Item;
24 use Friendica\Model\Queue;
25 use Friendica\Model\User;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
30 require 'addon/pumpio/oauth/http.php';
31 require 'addon/pumpio/oauth/oauth_client.php';
32 require_once 'include/enotify.php';
33 require_once "mod/share.php";
35 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
37 function pumpio_install()
39 Addon::registerHook('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
40 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
41 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
42 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
43 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
44 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
45 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
46 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
47 Addon::registerHook('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
50 function pumpio_uninstall()
52 Addon::unregisterHook('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
53 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
54 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
55 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
56 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
57 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
58 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
59 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
60 Addon::unregisterHook('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
63 function pumpio_module() {}
65 function pumpio_content(App $a)
68 notice(L10n::t('Permission denied.') . EOL);
72 require_once("mod/settings.php");
75 if (isset($a->argv[1])) {
76 switch ($a->argv[1]) {
78 $o = pumpio_connect($a);
81 $o = print_r($a->argv, true);
85 $o = pumpio_connect($a);
90 function pumpio_check_item_notification($a, &$notification_data)
92 $hostname = PConfig::get($notification_data["uid"], 'pumpio', 'host');
93 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
95 $notification_data["profiles"][] = "https://".$hostname."/".$username;
98 function pumpio_registerclient(App $a, $host)
100 $url = "https://".$host."/api/client/register";
104 $application_name = Config::get('pumpio', 'application_name');
106 if ($application_name == "") {
107 $application_name = $a->getHostName();
110 $adminlist = explode(",", str_replace(" ", "", Config::get('config', 'admin_email')));
112 $params["type"] = "client_associate";
113 $params["contacts"] = $adminlist[0];
114 $params["application_type"] = "native";
115 $params["application_name"] = $application_name;
116 $params["logo_url"] = $a->getBaseURL()."/images/friendica-256.png";
117 $params["redirect_uris"] = $a->getBaseURL()."/pumpio/connect";
119 Logger::log("pumpio_registerclient: ".$url." parameters ".print_r($params, true), Logger::DEBUG);
121 $ch = curl_init($url);
122 curl_setopt($ch, CURLOPT_HEADER, false);
123 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
124 curl_setopt($ch, CURLOPT_POST,1);
125 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
126 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
129 $curl_info = curl_getinfo($ch);
131 if ($curl_info["http_code"] == "200") {
132 $values = json_decode($s);
133 Logger::log("pumpio_registerclient: success ".print_r($values, true), Logger::DEBUG);
136 Logger::log("pumpio_registerclient: failed: ".print_r($curl_info, true), Logger::DEBUG);
141 function pumpio_connect(App $a)
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::log("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::log("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, Logger::DEBUG);
160 if (($consumer_key == "") || ($consumer_secret == "")) {
161 Logger::log("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->getBaseURL()."/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::log("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::log("pumpio_connect: authenticated");
204 $o = L10n::t("You are now authenticated to pumpio.");
205 $o .= '<br /><a href="'.$a->getBaseURL().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
207 Logger::log("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->getBaseURL() . '/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->getBaseURL().'/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' , defaults($_POST, 'pumpio', false));
364 PConfig::set(local_user(), 'pumpio', 'import' , defaults($_POST, 'pumpio_import', false));
365 PConfig::set(local_user(), 'pumpio', 'host' , $host);
366 PConfig::set(local_user(), 'pumpio', 'user' , $user);
367 PConfig::set(local_user(), 'pumpio', 'public' , defaults($_POST, 'pumpio_public', false));
368 PConfig::set(local_user(), 'pumpio', 'mirror' , defaults($_POST, 'pumpio_mirror', false));
369 PConfig::set(local_user(), 'pumpio', 'post_by_default', defaults($_POST, 'pumpio_bydefault', false));
371 if (!empty($_POST['pumpio_mirror'])) {
372 PConfig::delete(local_user(), 'pumpio', 'lastdate');
378 function pumpio_load_config(App $a)
380 $a->loadConfigFile(__DIR__. '/config/pumpio.ini.php');
383 function pumpio_post_local(App $a, array &$b)
385 if (!local_user() || (local_user() != $b['uid'])) {
389 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
391 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
393 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
397 if (!$pumpio_enable) {
401 if (strlen($b['postopts'])) {
402 $b['postopts'] .= ',';
405 $b['postopts'] .= 'pumpio';
408 function pumpio_send(App $a, array &$b)
410 if (!PConfig::get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
414 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
416 if ($b['parent'] != $b['id']) {
417 // Looking if its a reply to a pumpio post
418 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
419 $orig_post = Item::selectFirst([], $condition);
421 if (!DBA::isResult($orig_post)) {
422 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
430 $receiver = pumpio_getreceiver($a, $b);
432 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
434 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
438 // Dont't post if the post doesn't belong to us.
439 // This is a check for forum postings
440 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
441 if ($b['contact-id'] != $self['id']) {
446 if ($b['verb'] == ACTIVITY_LIKE) {
448 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
450 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
455 if ($b['verb'] == ACTIVITY_DISLIKE) {
459 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
460 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
463 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
464 pumpio_action($a, $b["uid"], $b["uri"], "delete");
467 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
471 // if post comes from pump.io don't send it back
472 if ($b['app'] == "pump.io") {
477 // Support for native shares
478 // http://<hostname>/api/<type>/shares?id=<the-object-id>
480 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
481 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
482 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
483 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
485 $host = PConfig::get($b['uid'], "pumpio", "host");
486 $user = PConfig::get($b['uid'], "pumpio", "user");
487 $public = PConfig::get($b['uid'], "pumpio", "public");
489 if ($oauth_token && $oauth_token_secret) {
490 $title = trim($b['title']);
492 $content = BBCode::convert($b['body'], false, 4);
496 $params["verb"] = "post";
499 $params["object"] = [
500 'objectType' => "note",
501 'content' => $content];
503 if (!empty($title)) {
504 $params["object"]["displayName"] = $title;
507 if (!empty($receiver["to"])) {
508 $params["to"] = $receiver["to"];
511 if (!empty($receiver["bto"])) {
512 $params["bto"] = $receiver["bto"];
515 if (!empty($receiver["cc"])) {
516 $params["cc"] = $receiver["cc"];
519 if (!empty($receiver["bcc"])) {
520 $params["bcc"] = $receiver["bcc"];
523 $inReplyTo = ["id" => $orig_post["uri"],
524 "objectType" => "note"];
526 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
527 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
530 $params["object"] = [
531 'objectType' => "comment",
532 'content' => $content,
533 'inReplyTo' => $inReplyTo];
536 $params["object"]["displayName"] = $title;
540 $client = new oauth_client_class;
541 $client->oauth_version = '1.0a';
542 $client->url_parameters = false;
543 $client->authorization_header = true;
544 $client->access_token = $oauth_token;
545 $client->access_token_secret = $oauth_token_secret;
546 $client->client_id = $consumer_key;
547 $client->client_secret = $consumer_secret;
549 $username = $user.'@'.$host;
550 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
552 if (pumpio_reachable($url)) {
553 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
559 if ($user->generator->displayName) {
560 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
563 $post_id = $user->object->id;
564 Logger::log('pumpio_send '.$username.': success '.$post_id);
565 if ($post_id && $iscomment) {
566 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
567 Item::update(['extid' => $post_id], ['id' => $b['id']]);
570 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
572 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
573 if (DBA::isResult($r)) {
574 $a->contact = $r[0]["id"];
577 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
579 Queue::add($a->contact, Protocol::PUMPIO, $s);
580 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
585 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
587 // Don't do likes and other stuff if you don't import the timeline
588 if (!PConfig::get($uid, 'pumpio', 'import')) {
592 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
593 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
594 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
595 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
596 $hostname = PConfig::get($uid, 'pumpio', 'host');
597 $username = PConfig::get($uid, "pumpio", "user");
599 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
601 if (!DBA::isResult($orig_post)) {
605 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
606 $uri = $orig_post["extid"];
608 $uri = $orig_post["uri"];
611 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
612 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
613 } elseif (strstr($uri, "/api/comment/")) {
614 $objectType = "comment";
615 } elseif (strstr($uri, "/api/note/")) {
616 $objectType = "note";
617 } elseif (strstr($uri, "/api/image/")) {
618 $objectType = "image";
621 $params["verb"] = $action;
622 $params["object"] = ['id' => $uri,
623 "objectType" => $objectType,
624 "content" => $content];
626 $client = new oauth_client_class;
627 $client->oauth_version = '1.0a';
628 $client->authorization_header = true;
629 $client->url_parameters = false;
631 $client->client_id = $ckey;
632 $client->client_secret = $csecret;
633 $client->access_token = $otoken;
634 $client->access_token_secret = $osecret;
636 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
638 if (pumpio_reachable($url)) {
639 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
645 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
647 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user, true));
649 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $uid);
650 if (DBA::isResult($r)) {
651 $a->contact = $r[0]["id"];
654 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
656 Queue::add($a->contact, Protocol::PUMPIO, $s);
657 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
661 function pumpio_sync(App $a)
663 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
665 if (!DBA::isResult($r)) {
669 $last = Config::get('pumpio', 'last_poll');
671 $poll_interval = intval(Config::get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
674 $next = $last + ($poll_interval * 60);
675 if ($next > time()) {
676 Logger::log('pumpio: poll intervall not reached');
680 Logger::log('pumpio: cron_start');
682 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
683 if (DBA::isResult($r)) {
684 foreach ($r as $rr) {
685 Logger::log('pumpio: mirroring user '.$rr['uid']);
686 pumpio_fetchtimeline($a, $rr['uid']);
690 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
691 if ($abandon_days < 1) {
695 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
697 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
698 if (DBA::isResult($r)) {
699 foreach ($r as $rr) {
700 if ($abandon_days != 0) {
701 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
702 if (!DBA::isResult($user)) {
703 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
708 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
709 pumpio_fetchinbox($a, $rr['uid']);
711 // check for new contacts once a day
712 $last_contact_check = PConfig::get($rr['uid'], 'pumpio', 'contact_check');
713 if ($last_contact_check) {
714 $next_contact_check = $last_contact_check + 86400;
716 $next_contact_check = 0;
719 if ($next_contact_check <= time()) {
720 pumpio_getallusers($a, $rr["uid"]);
721 PConfig::set($rr['uid'], 'pumpio', 'contact_check', time());
726 Logger::log('pumpio: cron_end');
728 Config::set('pumpio', 'last_poll', time());
731 function pumpio_cron(App $a, $b)
733 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
736 function pumpio_fetchtimeline(App $a, $uid)
738 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
739 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
740 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
741 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
742 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
743 $hostname = PConfig::get($uid, 'pumpio', 'host');
744 $username = PConfig::get($uid, "pumpio", "user");
746 // get the application name for the pump.io app
747 // 1st try personal config, then system config and fallback to the
748 // hostname of the node if neither one is set.
749 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
750 if ($application_name == "") {
751 $application_name = Config::get('pumpio', 'application_name');
753 if ($application_name == "") {
754 $application_name = $a->getHostName();
757 $first_time = ($lastdate == "");
759 $client = new oauth_client_class;
760 $client->oauth_version = '1.0a';
761 $client->authorization_header = true;
762 $client->url_parameters = false;
764 $client->client_id = $ckey;
765 $client->client_secret = $csecret;
766 $client->access_token = $otoken;
767 $client->access_token_secret = $osecret;
769 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
771 Logger::log('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
773 $useraddr = $username.'@'.$hostname;
775 if (pumpio_reachable($url)) {
776 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
783 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
787 $posts = array_reverse($user->items);
789 $initiallastdate = $lastdate;
793 foreach ($posts as $post) {
794 if ($post->published <= $initiallastdate) {
798 if ($lastdate < $post->published) {
799 $lastdate = $post->published;
807 if (@is_array($post->cc)) {
808 $receiptians = array_merge($receiptians, $post->cc);
811 if (@is_array($post->to)) {
812 $receiptians = array_merge($receiptians, $post->to);
816 foreach ($receiptians AS $receiver) {
817 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
822 if ($public && !stristr($post->generator->displayName, $application_name)) {
823 $_SESSION["authenticated"] = true;
824 $_SESSION["uid"] = $uid;
827 $_REQUEST["api_source"] = true;
828 $_REQUEST["profile_uid"] = $uid;
829 $_REQUEST["source"] = "pump.io";
831 if (isset($post->object->id)) {
832 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
835 if ($post->object->displayName != "") {
836 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
838 $_REQUEST["title"] = "";
841 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
843 // To-Do: Picture has to be cached and stored locally
844 if ($post->object->fullImage->url != "") {
845 if ($post->object->fullImage->pump_io->proxyURL != "") {
846 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
848 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
852 Logger::log('pumpio: posting for user '.$uid);
854 require_once('mod/item.php');
857 Logger::log('pumpio: posting done - user '.$uid);
862 if ($lastdate != 0) {
863 PConfig::set($uid, 'pumpio', 'lastdate', $lastdate);
867 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
869 // Searching for the unliked post
870 // Two queries for speed issues
871 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
872 if (!DBA::isResult($orig_post)) {
873 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
874 if (!DBA::isResult($orig_post)) {
881 if (link_compare($post->actor->url, $own_id)) {
882 $contactid = $self[0]['id'];
884 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
885 DBA::escape(normalise_link($post->actor->url)),
889 if (DBA::isResult($r)) {
890 $contactid = $r[0]['id'];
893 if ($contactid == 0) {
894 $contactid = $orig_post['contact-id'];
898 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
900 if (DBA::isResult($r)) {
901 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
903 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
907 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
909 require_once('include/items.php');
911 if (empty($post->object->id)) {
912 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
916 // Searching for the liked post
917 // Two queries for speed issues
918 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
919 if (!DBA::isResult($orig_post)) {
920 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
921 if (!DBA::isResult($orig_post)) {
927 if ($threadcompletion) {
928 pumpio_fetchallcomments($a, $uid, $post->object->id);
933 if (link_compare($post->actor->url, $own_id)) {
934 $contactid = $self[0]['id'];
935 $post->actor->displayName = $self[0]['name'];
936 $post->actor->url = $self[0]['url'];
937 $post->actor->image->url = $self[0]['photo'];
939 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
940 DBA::escape(normalise_link($post->actor->url)),
944 if (DBA::isResult($r)) {
945 $contactid = $r[0]['id'];
948 if ($contactid == 0) {
949 $contactid = $orig_post['contact-id'];
953 $condition = ['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
954 if (Item::exists($condition)) {
955 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
960 $likedata['parent'] = $orig_post['id'];
961 $likedata['verb'] = ACTIVITY_LIKE;
962 $likedata['gravity'] = GRAVITY_ACTIVITY;
963 $likedata['uid'] = $uid;
964 $likedata['wall'] = 0;
965 $likedata['network'] = Protocol::PUMPIO;
966 $likedata['uri'] = Item::newURI($uid);
967 $likedata['parent-uri'] = $orig_post["uri"];
968 $likedata['contact-id'] = $contactid;
969 $likedata['app'] = $post->generator->displayName;
970 $likedata['author-name'] = $post->actor->displayName;
971 $likedata['author-link'] = $post->actor->url;
972 if (!empty($post->actor->image)) {
973 $likedata['author-avatar'] = $post->actor->image->url;
976 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
977 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
978 $post_type = L10n::t('status');
979 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
980 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
982 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
984 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
985 '<id>' . $orig_post['uri'] . '</id><link>' . Strings::escape('<link rel="alternate" type="text/html" href="' . Strings::escape($orig_post['plink']) . '" />') . '</link><title>' . $orig_post['title'] . '</title><content>' . $orig_post['body'] . '</content></object>';
987 $ret = Item::insert($likedata);
989 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
992 function pumpio_get_contact($uid, $contact, $no_insert = false)
994 $gcontact = ["url" => $contact->url, "network" => Protocol::PUMPIO, "generation" => 2,
995 "name" => $contact->displayName, "hide" => true,
996 "nick" => $contact->preferredUsername,
997 "addr" => str_replace("acct:", "", $contact->id)];
999 if (!empty($contact->location->displayName)) {
1000 $gcontact["location"] = $contact->location->displayName;
1003 if (!empty($contact->summary)) {
1004 $gcontact["about"] = $contact->summary;
1007 if (!empty($contact->image->url)) {
1008 $gcontact["photo"] = $contact->image->url;
1011 GContact::update($gcontact);
1012 $cid = Contact::getIdForURL($contact->url, $uid);
1018 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1019 intval($uid), DBA::escape(normalise_link($contact->url)));
1021 if (!DBA::isResult($r)) {
1022 // create contact record
1023 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1024 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1025 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1026 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1028 DBA::escape(DateTimeFormat::utcNow()),
1029 DBA::escape($contact->url),
1030 DBA::escape(normalise_link($contact->url)),
1031 DBA::escape(str_replace("acct:", "", $contact->id)),
1033 DBA::escape($contact->id), // What is it for?
1034 DBA::escape('pump.io ' . $contact->id), // What is it for?
1035 DBA::escape($contact->displayName),
1036 DBA::escape($contact->preferredUsername),
1037 DBA::escape($contact->image->url),
1038 DBA::escape(Protocol::PUMPIO),
1039 intval(Contact::FRIEND),
1041 DBA::escape($contact->location->displayName),
1042 DBA::escape($contact->summary),
1046 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1047 DBA::escape(normalise_link($contact->url)),
1051 if (!DBA::isResult($r)) {
1055 $contact_id = $r[0]['id'];
1057 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1059 $contact_id = $r[0]["id"];
1061 /* if (DB_UPDATE_VERSION >= "1177")
1062 q("UPDATE `contact` SET `location` = '%s',
1065 dbesc($contact->location->displayName),
1066 dbesc($contact->summary),
1072 if (!empty($contact->image->url)) {
1073 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1079 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1081 // Two queries for speed issues
1082 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1083 if (Item::exists($condition)) {
1084 Item::delete($condition);
1088 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1089 if (Item::exists($condition)) {
1090 Item::delete($condition);
1096 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1098 require_once('include/items.php');
1100 if (($post->verb == "like") || ($post->verb == "favorite")) {
1101 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1104 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1105 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1108 if ($post->verb == "delete") {
1109 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1112 if ($post->verb != "update") {
1113 // Two queries for speed issues
1114 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1117 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1122 // Only handle these three types
1123 if (!strstr("post|share|update", $post->verb)) {
1128 if (@is_array($post->cc)) {
1129 $receiptians = array_merge($receiptians, $post->cc);
1132 if (@is_array($post->to)) {
1133 $receiptians = array_merge($receiptians, $post->to);
1138 foreach ($receiptians AS $receiver) {
1139 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1145 $postarray['network'] = Protocol::PUMPIO;
1146 $postarray['uid'] = $uid;
1147 $postarray['wall'] = 0;
1148 $postarray['uri'] = $post->object->id;
1149 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1151 if ($post->object->objectType != "comment") {
1152 $contact_id = pumpio_get_contact($uid, $post->actor);
1155 $contact_id = $self[0]['id'];
1158 $postarray['parent-uri'] = $post->object->id;
1161 $postarray['private'] = 1;
1162 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1165 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1167 if (link_compare($post->actor->url, $own_id)) {
1168 $contact_id = $self[0]['id'];
1169 $post->actor->displayName = $self[0]['name'];
1170 $post->actor->url = $self[0]['url'];
1171 $post->actor->image->url = $self[0]['photo'];
1172 } elseif ($contact_id == 0) {
1173 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1174 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1175 DBA::escape(normalise_link($post->actor->url)),
1179 if (DBA::isResult($r)) {
1180 $contact_id = $r[0]['id'];
1182 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1183 DBA::escape(normalise_link($post->actor->url)),
1187 if (DBA::isResult($r)) {
1188 $contact_id = $r[0]['id'];
1190 $contact_id = $self[0]['id'];
1195 $reply = new stdClass;
1196 $reply->verb = "note";
1198 if (isset($post->cc)) {
1199 $reply->cc = $post->cc;
1202 if (isset($post->to)) {
1203 $reply->to = $post->to;
1206 $reply->object = new stdClass;
1207 $reply->object->objectType = $post->object->inReplyTo->objectType;
1208 $reply->object->content = $post->object->inReplyTo->content;
1209 $reply->object->id = $post->object->inReplyTo->id;
1210 $reply->actor = $post->object->inReplyTo->author;
1211 $reply->url = $post->object->inReplyTo->url;
1212 $reply->generator = new stdClass;
1213 $reply->generator->displayName = "pumpio";
1214 $reply->published = $post->object->inReplyTo->published;
1215 $reply->received = $post->object->inReplyTo->updated;
1216 $reply->url = $post->object->inReplyTo->url;
1217 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1219 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1222 // When there is no content there is no need to continue
1223 if (empty($post->object->content)) {
1227 if (!empty($post->object->pump_io->proxyURL)) {
1228 $postarray['extid'] = $post->object->pump_io->proxyURL;
1231 $postarray['contact-id'] = $contact_id;
1232 $postarray['verb'] = ACTIVITY_POST;
1233 $postarray['owner-name'] = $post->actor->displayName;
1234 $postarray['owner-link'] = $post->actor->url;
1235 $postarray['author-name'] = $postarray['owner-name'];
1236 $postarray['author-link'] = $postarray['owner-link'];
1237 if (!empty($post->actor->image)) {
1238 $postarray['owner-avatar'] = $post->actor->image->url;
1239 $postarray['author-avatar'] = $postarray['owner-avatar'];
1241 $postarray['plink'] = $post->object->url;
1242 $postarray['app'] = $post->generator->displayName;
1243 $postarray['title'] = '';
1244 $postarray['body'] = HTML::toBBCode($post->object->content);
1245 $postarray['object'] = json_encode($post);
1247 if (!empty($post->object->fullImage->url)) {
1248 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1251 if (!empty($post->object->displayName)) {
1252 $postarray['title'] = $post->object->displayName;
1255 $postarray['created'] = DateTimeFormat::utc($post->published);
1256 if (isset($post->updated)) {
1257 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1258 } elseif (isset($post->received)) {
1259 $postarray['edited'] = DateTimeFormat::utc($post->received);
1261 $postarray['edited'] = $postarray['created'];
1264 if ($post->verb == "share") {
1265 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1266 $share_author = $post->object->author->displayName;
1267 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1268 $share_author = $post->object->author->preferredUsername;
1270 $share_author = $post->object->author->url;
1273 if (isset($post->object->created)) {
1274 $created = DateTimeFormat::utc($post->object->created);
1279 $postarray['body'] = share_header($share_author, $post->object->author->url,
1280 $post->object->author->image->url, "",
1281 $created, $post->links->self->href).
1282 $postarray['body']."[/share]";
1285 if (trim($postarray['body']) == "") {
1289 $top_item = Item::insert($postarray);
1290 $postarray["id"] = $top_item;
1292 if (($top_item == 0) && ($post->verb == "update")) {
1293 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1294 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1295 Item::update($fields, $condition);
1298 if (($post->object->objectType == "comment") && $threadcompletion) {
1299 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1305 function pumpio_fetchinbox(App $a, $uid)
1307 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1308 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1309 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1310 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1311 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1312 $hostname = PConfig::get($uid, 'pumpio', 'host');
1313 $username = PConfig::get($uid, "pumpio", "user");
1315 $own_id = "https://".$hostname."/".$username;
1317 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1320 $lastitems = q("SELECT `uri` FROM `thread`
1321 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1322 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1323 ORDER BY `thread`.`commented` DESC LIMIT 10",
1324 DBA::escape(Protocol::PUMPIO),
1328 $client = new oauth_client_class;
1329 $client->oauth_version = '1.0a';
1330 $client->authorization_header = true;
1331 $client->url_parameters = false;
1333 $client->client_id = $ckey;
1334 $client->client_secret = $csecret;
1335 $client->access_token = $otoken;
1336 $client->access_token_secret = $osecret;
1338 $last_id = PConfig::get($uid, 'pumpio', 'last_id');
1340 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1342 if ($last_id != "") {
1343 $url .= '?since='.urlencode($last_id);
1346 if (pumpio_reachable($url)) {
1347 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1357 $posts = array_reverse($user->items);
1359 if (count($posts)) {
1360 foreach ($posts as $post) {
1361 $last_id = $post->id;
1362 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1367 foreach ($lastitems as $item) {
1368 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1371 PConfig::set($uid, 'pumpio', 'last_id', $last_id);
1374 function pumpio_getallusers(App &$a, $uid)
1376 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1377 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1378 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1379 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1380 $hostname = PConfig::get($uid, 'pumpio', 'host');
1381 $username = PConfig::get($uid, "pumpio", "user");
1383 $client = new oauth_client_class;
1384 $client->oauth_version = '1.0a';
1385 $client->authorization_header = true;
1386 $client->url_parameters = false;
1388 $client->client_id = $ckey;
1389 $client->client_secret = $csecret;
1390 $client->access_token = $otoken;
1391 $client->access_token_secret = $osecret;
1393 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1395 if (pumpio_reachable($url)) {
1396 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1401 if (empty($users)) {
1405 if ($users->totalItems > count($users->items)) {
1406 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1408 if (pumpio_reachable($url)) {
1409 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1415 if (!empty($users->items)) {
1416 foreach ($users->items as $user) {
1417 pumpio_get_contact($uid, $user);
1422 function pumpio_queue_hook(App $a, array &$b)
1424 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1425 DBA::escape(Protocol::PUMPIO)
1428 if (!DBA::isResult($qi)) {
1432 foreach ($qi as $x) {
1433 if ($x['network'] !== Protocol::PUMPIO) {
1437 Logger::log('pumpio_queue: run');
1439 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1440 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1443 if (!DBA::isResult($r)) {
1449 //Logger::log('pumpio_queue: fetching userdata '.print_r($userdata, true));
1451 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1452 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1453 $consumer_key = PConfig::get($userdata['uid'], "pumpio", "consumer_key");
1454 $consumer_secret = PConfig::get($userdata['uid'], "pumpio", "consumer_secret");
1456 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1457 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1461 if ($oauth_token && $oauth_token_secret &&
1462 $consumer_key && $consumer_secret) {
1463 $username = $user.'@'.$host;
1465 Logger::log('pumpio_queue: able to post for user '.$username);
1467 $z = unserialize($x['content']);
1469 $client = new oauth_client_class;
1470 $client->oauth_version = '1.0a';
1471 $client->url_parameters = false;
1472 $client->authorization_header = true;
1473 $client->access_token = $oauth_token;
1474 $client->access_token_secret = $oauth_token_secret;
1475 $client->client_id = $consumer_key;
1476 $client->client_secret = $consumer_secret;
1478 if (pumpio_reachable($z['url'])) {
1479 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1485 $post_id = $user->object->id;
1486 Logger::log('pumpio_queue: send '.$username.': success '.$post_id);
1487 if ($post_id && $iscomment) {
1488 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1489 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1491 Queue::removeItem($x['id']);
1493 Logger::log('pumpio_queue: send '.$username.': '.$z['url'].' general error: ' . print_r($user, true));
1496 Logger::log("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1500 Logger::log('pumpio_queue: delayed');
1501 Queue::updateTime($x['id']);
1506 function pumpio_getreceiver(App $a, array $b)
1510 if (!$b["private"]) {
1511 if (!strstr($b['postopts'], 'pumpio')) {
1515 $public = PConfig::get($b['uid'], "pumpio", "public");
1518 $receiver["to"][] = [
1519 "objectType" => "collection",
1520 "id" => "http://activityschema.org/collection/public"];
1523 $cids = explode("><", $b["allow_cid"]);
1524 $gids = explode("><", $b["allow_gid"]);
1526 foreach ($cids AS $cid) {
1527 $cid = trim($cid, " <>");
1529 $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",
1532 DBA::escape(Protocol::PUMPIO)
1535 if (DBA::isResult($r)) {
1536 $receiver["bcc"][] = [
1537 "displayName" => $r[0]["name"],
1538 "objectType" => "person",
1539 "preferredUsername" => $r[0]["nick"],
1540 "url" => $r[0]["url"]];
1543 foreach ($gids AS $gid) {
1544 $gid = trim($gid, " <>");
1546 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1547 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1548 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1550 DBA::escape(Protocol::PUMPIO)
1553 foreach ($r AS $row)
1554 $receiver["bcc"][] = [
1555 "displayName" => $row["name"],
1556 "objectType" => "person",
1557 "preferredUsername" => $row["nick"],
1558 "url" => $row["url"]];
1562 if ($b["inform"] != "") {
1563 $inform = explode(",", $b["inform"]);
1565 foreach ($inform AS $cid) {
1566 if (substr($cid, 0, 4) != "cid:") {
1570 $cid = str_replace("cid:", "", $cid);
1572 $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",
1575 DBA::escape(Protocol::PUMPIO)
1578 if (DBA::isResult($r)) {
1579 $receiver["to"][] = [
1580 "displayName" => $r[0]["name"],
1581 "objectType" => "person",
1582 "preferredUsername" => $r[0]["nick"],
1583 "url" => $r[0]["url"]];
1591 function pumpio_fetchallcomments(App $a, $uid, $id)
1593 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1594 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1595 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1596 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1597 $hostname = PConfig::get($uid, 'pumpio', 'host');
1598 $username = PConfig::get($uid, "pumpio", "user");
1600 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1602 $own_id = "https://".$hostname."/".$username;
1604 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1607 // Fetching the original post
1608 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1609 $item = Item::selectFirst(['extid'], $condition);
1610 if (!DBA::isResult($item)) {
1614 $url = $item["extid"];
1616 $client = new oauth_client_class;
1617 $client->oauth_version = '1.0a';
1618 $client->authorization_header = true;
1619 $client->url_parameters = false;
1621 $client->client_id = $ckey;
1622 $client->client_secret = $csecret;
1623 $client->access_token = $otoken;
1624 $client->access_token_secret = $osecret;
1626 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1628 if (pumpio_reachable($url)) {
1629 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1638 if ($item->likes->totalItems != 0) {
1639 foreach ($item->likes->items AS $post) {
1640 $like = new stdClass;
1641 $like->object = new stdClass;
1642 $like->object->id = $item->id;
1643 $like->actor = new stdClass;
1644 if (!empty($item->displayName)) {
1645 $like->actor->displayName = $item->displayName;
1647 //$like->actor->preferredUsername = $item->preferredUsername;
1648 //$like->actor->image = $item->image;
1649 $like->actor->url = $item->url;
1650 $like->generator = new stdClass;
1651 $like->generator->displayName = "pumpio";
1652 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1656 if ($item->replies->totalItems == 0) {
1660 foreach ($item->replies->items AS $item) {
1661 if ($item->id == $id) {
1665 // Checking if the comment already exists - Two queries for speed issues
1666 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1670 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1674 $post = new stdClass;
1675 $post->verb = "post";
1676 $post->actor = $item->author;
1677 $post->published = $item->published;
1678 $post->received = $item->updated;
1679 $post->generator = new stdClass;
1680 $post->generator->displayName = "pumpio";
1681 // To-Do: Check for public post
1683 unset($item->author);
1684 unset($item->published);
1685 unset($item->updated);
1687 $post->object = $item;
1689 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1690 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1694 function pumpio_reachable($url)
1696 return Network::curl($url, false, $redirects, ['timeout'=>10])->isSuccess();