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\Hook;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBA;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Group;
20 use Friendica\Model\Item;
21 use Friendica\Model\Post;
22 use Friendica\Model\User;
23 use Friendica\Network\HTTPClientOptions;
24 use Friendica\Protocol\Activity;
25 use Friendica\Protocol\ActivityNamespace;
26 use Friendica\Util\ConfigFileLoader;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Strings;
29 use Friendica\Util\XML;
31 require 'addon/pumpio/oauth/http.php';
32 require 'addon/pumpio/oauth/oauth_client.php';
33 require_once "mod/share.php";
35 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
37 function pumpio_install()
39 Hook::register('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
40 Hook::register('hook_fork', 'addon/pumpio/pumpio.php', 'hook_fork');
41 Hook::register('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
42 Hook::register('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
43 Hook::register('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
44 Hook::register('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
45 Hook::register('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
46 Hook::register('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
47 Hook::register('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
50 function pumpio_module() {}
52 function pumpio_content(App $a)
55 notice(DI::l10n()->t('Permission denied.') . EOL);
59 require_once("mod/settings.php");
62 if (isset(DI::args()->getArgv()[1])) {
63 switch (DI::args()->getArgv()[1]) {
65 $o = pumpio_connect($a);
68 $o = print_r(DI::args()->getArgv(), true);
72 $o = pumpio_connect($a);
77 function pumpio_check_item_notification($a, &$notification_data)
79 $hostname = DI::pConfig()->get($notification_data["uid"], 'pumpio', 'host');
80 $username = DI::pConfig()->get($notification_data["uid"], "pumpio", "user");
82 $notification_data["profiles"][] = "https://".$hostname."/".$username;
85 function pumpio_registerclient(App $a, $host)
87 $url = "https://".$host."/api/client/register";
91 $application_name = DI::config()->get('pumpio', 'application_name');
93 if ($application_name == "") {
94 $application_name = DI::baseUrl()->getHostname();
97 $adminlist = explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email')));
99 $params["type"] = "client_associate";
100 $params["contacts"] = $adminlist[0];
101 $params["application_type"] = "native";
102 $params["application_name"] = $application_name;
103 $params["logo_url"] = DI::baseUrl()->get()."/images/friendica-256.png";
104 $params["redirect_uris"] = DI::baseUrl()->get()."/pumpio/connect";
106 Logger::log("pumpio_registerclient: ".$url." parameters ".print_r($params, true), Logger::DEBUG);
108 $ch = curl_init($url);
109 curl_setopt($ch, CURLOPT_HEADER, false);
110 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
111 curl_setopt($ch, CURLOPT_POST,1);
112 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
113 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
116 $curl_info = curl_getinfo($ch);
118 if ($curl_info["http_code"] == "200") {
119 $values = json_decode($s);
120 Logger::log("pumpio_registerclient: success ".print_r($values, true), Logger::DEBUG);
123 Logger::log("pumpio_registerclient: failed: ".print_r($curl_info, true), Logger::DEBUG);
128 function pumpio_connect(App $a)
130 // Define the needed keys
131 $consumer_key = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_key');
132 $consumer_secret = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_secret');
133 $hostname = DI::pConfig()->get(local_user(), 'pumpio', 'host');
135 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
136 Logger::log("pumpio_connect: register client");
137 $clientdata = pumpio_registerclient($a, $hostname);
138 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
139 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
141 $consumer_key = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_key');
142 $consumer_secret = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_secret');
144 Logger::log("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, Logger::DEBUG);
147 if (($consumer_key == "") || ($consumer_secret == "")) {
148 Logger::log("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
150 return DI::l10n()->t("Unable to register the client at the pump.io server '%s'.", $hostname);
153 // The callback URL is the script that gets called after the user authenticates with pumpio
154 $callback_url = DI::baseUrl()->get()."/pumpio/connect";
156 // Let's begin. First we need a Request Token. The request token is required to send the user
157 // to pumpio's login page.
159 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
160 // Consumer Key and Consumer Secret
161 $client = new oauth_client_class;
163 $client->server = '';
164 $client->oauth_version = '1.0a';
165 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
166 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
167 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
168 $client->url_parameters = false;
169 $client->authorization_header = true;
170 $client->redirect_uri = $callback_url;
171 $client->client_id = $consumer_key;
172 $client->client_secret = $consumer_secret;
174 if (($success = $client->Initialize())) {
175 if (($success = $client->Process())) {
176 if (strlen($client->access_token)) {
177 Logger::log("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, Logger::DEBUG);
178 DI::pConfig()->set(local_user(), "pumpio", "oauth_token", $client->access_token);
179 DI::pConfig()->set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
182 $success = $client->Finalize($success);
185 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
189 Logger::log("pumpio_connect: authenticated");
190 $o = DI::l10n()->t("You are now authenticated to pumpio.");
191 $o .= '<br /><a href="'.DI::baseUrl()->get().'/settings/connectors">'.DI::l10n()->t("return to the connector page").'</a>';
193 Logger::log("pumpio_connect: could not connect");
194 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
200 function pumpio_jot_nets(App $a, array &$jotnets_fields)
202 if (! local_user()) {
206 if (DI::pConfig()->get(local_user(), 'pumpio', 'post')) {
207 $jotnets_fields[] = [
208 'type' => 'checkbox',
211 DI::l10n()->t('Post to pumpio'),
212 DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default')
218 function pumpio_settings(App $a, &$s)
224 /* Add our stylesheet to the page so we can make our settings look nice */
226 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
228 /* Get the current state of our config variables */
230 $import_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'import');
231 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
233 $enabled = DI::pConfig()->get(local_user(), 'pumpio', 'post');
234 $checked = (($enabled) ? ' checked="checked" ' : '');
235 $css = (($enabled) ? '' : '-disabled');
237 $def_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default');
238 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
240 $public_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'public');
241 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
243 $mirror_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'mirror');
244 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
246 $servername = DI::pConfig()->get(local_user(), "pumpio", "host");
247 $username = DI::pConfig()->get(local_user(), "pumpio", "user");
249 /* Add some HTML to the existing form */
251 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
252 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. DI::l10n()->t('Pump.io Import/Export/Mirror').'</h3>';
254 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
255 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
256 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. DI::l10n()->t('Pump.io Import/Export/Mirror').'</h3>';
259 $s .= '<div id="pumpio-username-wrapper">';
260 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.DI::l10n()->t('pump.io username (without the servername)').'</label>';
261 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
262 $s .= '</div><div class="clear"></div>';
264 $s .= '<div id="pumpio-servername-wrapper">';
265 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.DI::l10n()->t('pump.io servername (without "http://" or "https://" )').'</label>';
266 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
267 $s .= '</div><div class="clear"></div>';
269 if (($username != '') && ($servername != '')) {
270 $oauth_token = DI::pConfig()->get(local_user(), "pumpio", "oauth_token");
271 $oauth_token_secret = DI::pConfig()->get(local_user(), "pumpio", "oauth_token_secret");
273 $s .= '<div id="pumpio-password-wrapper">';
274 if (($oauth_token == "") || ($oauth_token_secret == "")) {
275 $s .= '<div id="pumpio-authenticate-wrapper">';
276 $s .= '<a href="'.DI::baseUrl()->get().'/pumpio/connect">'.DI::l10n()->t("Authenticate your pump.io connection").'</a>';
277 $s .= '</div><div class="clear"></div>';
279 $s .= '<div id="pumpio-import-wrapper">';
280 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . DI::l10n()->t('Import the remote timeline') . '</label>';
281 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
282 $s .= '</div><div class="clear"></div>';
284 $s .= '<div id="pumpio-enable-wrapper">';
285 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . DI::l10n()->t('Enable pump.io Post Addon') . '</label>';
286 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
287 $s .= '</div><div class="clear"></div>';
289 $s .= '<div id="pumpio-bydefault-wrapper">';
290 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . DI::l10n()->t('Post to pump.io by default') . '</label>';
291 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
292 $s .= '</div><div class="clear"></div>';
294 $s .= '<div id="pumpio-public-wrapper">';
295 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . DI::l10n()->t('Should posts be public?') . '</label>';
296 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
297 $s .= '</div><div class="clear"></div>';
299 $s .= '<div id="pumpio-mirror-wrapper">';
300 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . DI::l10n()->t('Mirror all public posts') . '</label>';
301 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
302 $s .= '</div><div class="clear"></div>';
304 $s .= '<div id="pumpio-delete-wrapper">';
305 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . DI::l10n()->t('Check to delete this preset') . '</label>';
306 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
307 $s .= '</div><div class="clear"></div>';
310 $s .= '</div><div class="clear"></div>';
313 /* provide a submit button */
315 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div></div>';
318 function pumpio_settings_post(App $a, array &$b)
320 if (!empty($_POST['pumpio-submit'])) {
321 if (!empty($_POST['pumpio_delete'])) {
322 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_key' , '');
323 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_secret' , '');
324 DI::pConfig()->set(local_user(), 'pumpio', 'oauth_token' , '');
325 DI::pConfig()->set(local_user(), 'pumpio', 'oauth_token_secret', '');
326 DI::pConfig()->set(local_user(), 'pumpio', 'post' , false);
327 DI::pConfig()->set(local_user(), 'pumpio', 'import' , false);
328 DI::pConfig()->set(local_user(), 'pumpio', 'host' , '');
329 DI::pConfig()->set(local_user(), 'pumpio', 'user' , '');
330 DI::pConfig()->set(local_user(), 'pumpio', 'public' , false);
331 DI::pConfig()->set(local_user(), 'pumpio', 'mirror' , false);
332 DI::pConfig()->set(local_user(), 'pumpio', 'post_by_default' , false);
333 DI::pConfig()->set(local_user(), 'pumpio', 'lastdate' , 0);
334 DI::pConfig()->set(local_user(), 'pumpio', 'last_id' , '');
336 // filtering the username if it is filled wrong
337 $user = $_POST['pumpio_user'];
338 if (strstr($user, "@")) {
339 $pos = strpos($user, "@");
342 $user = substr($user, 0, $pos);
346 // Filtering the hostname if someone is entering it with "http"
347 $host = $_POST['pumpio_host'];
349 $host = str_replace(["https://", "http://"], ["", ""], $host);
351 DI::pConfig()->set(local_user(), 'pumpio', 'post' , $_POST['pumpio'] ?? false);
352 DI::pConfig()->set(local_user(), 'pumpio', 'import' , $_POST['pumpio_import'] ?? false);
353 DI::pConfig()->set(local_user(), 'pumpio', 'host' , $host);
354 DI::pConfig()->set(local_user(), 'pumpio', 'user' , $user);
355 DI::pConfig()->set(local_user(), 'pumpio', 'public' , $_POST['pumpio_public'] ?? false);
356 DI::pConfig()->set(local_user(), 'pumpio', 'mirror' , $_POST['pumpio_mirror'] ?? false);
357 DI::pConfig()->set(local_user(), 'pumpio', 'post_by_default', $_POST['pumpio_bydefault'] ?? false);
359 if (!empty($_POST['pumpio_mirror'])) {
360 DI::pConfig()->delete(local_user(), 'pumpio', 'lastdate');
366 function pumpio_load_config(App $a, ConfigFileLoader $loader)
368 $a->getConfigCache()->load($loader->loadAddonConfig('pumpio'));
371 function pumpio_hook_fork(App $a, array &$b)
373 if ($b['name'] != 'notifier_normal') {
379 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
380 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
381 $b['execute'] = false;
385 // if post comes from pump.io don't send it back
386 if ($post['app'] == "pump.io") {
387 $b['execute'] = false;
391 if (DI::pConfig()->get($post['uid'], 'pumpio', 'import')) {
392 // Don't fork if it isn't a reply to a pump.io post
393 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::PUMPIO])) {
394 Logger::log('No pump.io parent found for item ' . $post['id']);
395 $b['execute'] = false;
399 // Comments are never exported when we don't import the pumpio timeline
400 if (!strstr($post['postopts'], 'pumpio') || ($post['parent'] != $post['id']) || $post['private']) {
401 $b['execute'] = false;
407 function pumpio_post_local(App $a, array &$b)
409 if (!local_user() || (local_user() != $b['uid'])) {
413 $pumpio_post = intval(DI::pConfig()->get(local_user(), 'pumpio', 'post'));
415 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
417 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default'))) {
421 if (!$pumpio_enable) {
425 if (strlen($b['postopts'])) {
426 $b['postopts'] .= ',';
429 $b['postopts'] .= 'pumpio';
432 function pumpio_send(App $a, array &$b)
434 if (!DI::pConfig()->get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
438 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
440 $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], $b['body']);
442 if ($b['parent'] != $b['id']) {
443 // Looking if its a reply to a pumpio post
444 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
445 $orig_post = Post::selectFirst([], $condition);
447 if (!DBA::isResult($orig_post)) {
448 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
456 $receiver = pumpio_getreceiver($a, $b);
458 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
460 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
464 // Dont't post if the post doesn't belong to us.
465 // This is a check for forum postings
466 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
467 if ($b['contact-id'] != $self['id']) {
472 if ($b['verb'] == Activity::LIKE) {
474 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
476 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
481 if ($b['verb'] == Activity::DISLIKE) {
485 if (($b['verb'] == Activity::POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
486 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
489 if (($b['verb'] == Activity::POST) && $b['deleted']) {
490 pumpio_action($a, $b["uid"], $b["uri"], "delete");
493 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
497 // if post comes from pump.io don't send it back
498 if ($b['app'] == "pump.io") {
503 // Support for native shares
504 // http://<hostname>/api/<type>/shares?id=<the-object-id>
506 $oauth_token = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token");
507 $oauth_token_secret = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token_secret");
508 $consumer_key = DI::pConfig()->get($b['uid'], "pumpio","consumer_key");
509 $consumer_secret = DI::pConfig()->get($b['uid'], "pumpio","consumer_secret");
511 $host = DI::pConfig()->get($b['uid'], "pumpio", "host");
512 $user = DI::pConfig()->get($b['uid'], "pumpio", "user");
513 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
515 if ($oauth_token && $oauth_token_secret) {
516 $title = trim($b['title']);
518 $content = BBCode::convertForUriId($b['uri-id'], $b['body'], BBCode::CONNECTORS);
522 $params["verb"] = "post";
525 $params["object"] = [
526 'objectType' => "note",
527 'content' => $content];
529 if (!empty($title)) {
530 $params["object"]["displayName"] = $title;
533 if (!empty($receiver["to"])) {
534 $params["to"] = $receiver["to"];
537 if (!empty($receiver["bto"])) {
538 $params["bto"] = $receiver["bto"];
541 if (!empty($receiver["cc"])) {
542 $params["cc"] = $receiver["cc"];
545 if (!empty($receiver["bcc"])) {
546 $params["bcc"] = $receiver["bcc"];
549 $inReplyTo = ["id" => $orig_post["uri"],
550 "objectType" => "note"];
552 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
553 $inReplyTo["objectType"] = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
556 $params["object"] = [
557 'objectType' => "comment",
558 'content' => $content,
559 'inReplyTo' => $inReplyTo];
562 $params["object"]["displayName"] = $title;
566 $client = new oauth_client_class;
567 $client->oauth_version = '1.0a';
568 $client->url_parameters = false;
569 $client->authorization_header = true;
570 $client->access_token = $oauth_token;
571 $client->access_token_secret = $oauth_token_secret;
572 $client->client_id = $consumer_key;
573 $client->client_secret = $consumer_secret;
575 $username = $user.'@'.$host;
576 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
578 if (pumpio_reachable($url)) {
579 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
585 if ($user->generator->displayName) {
586 DI::pConfig()->set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
589 $post_id = $user->object->id;
590 Logger::log('pumpio_send '.$username.': success '.$post_id);
591 if ($post_id && $iscomment) {
592 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
593 Item::update(['extid' => $post_id], ['id' => $b['id']]);
596 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
602 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
604 // Don't do likes and other stuff if you don't import the timeline
605 if (!DI::pConfig()->get($uid, 'pumpio', 'import')) {
609 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
610 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
611 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
612 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
613 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
614 $username = DI::pConfig()->get($uid, "pumpio", "user");
616 $orig_post = Post::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
618 if (!DBA::isResult($orig_post)) {
622 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
623 $uri = $orig_post["extid"];
625 $uri = $orig_post["uri"];
628 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
629 $objectType = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
630 } elseif (strstr($uri, "/api/comment/")) {
631 $objectType = "comment";
632 } elseif (strstr($uri, "/api/note/")) {
633 $objectType = "note";
634 } elseif (strstr($uri, "/api/image/")) {
635 $objectType = "image";
638 $params["verb"] = $action;
639 $params["object"] = ['id' => $uri,
640 "objectType" => $objectType,
641 "content" => $content];
643 $client = new oauth_client_class;
644 $client->oauth_version = '1.0a';
645 $client->authorization_header = true;
646 $client->url_parameters = false;
648 $client->client_id = $ckey;
649 $client->client_secret = $csecret;
650 $client->access_token = $otoken;
651 $client->access_token_secret = $osecret;
653 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
655 if (pumpio_reachable($url)) {
656 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
662 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
664 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri);
669 function pumpio_sync(App $a)
671 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
673 if (!DBA::isResult($r)) {
677 $last = DI::config()->get('pumpio', 'last_poll');
679 $poll_interval = intval(DI::config()->get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
682 $next = $last + ($poll_interval * 60);
683 if ($next > time()) {
684 Logger::log('pumpio: poll intervall not reached');
688 Logger::log('pumpio: cron_start');
690 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
691 if (DBA::isResult($r)) {
692 foreach ($r as $rr) {
693 Logger::log('pumpio: mirroring user '.$rr['uid']);
694 pumpio_fetchtimeline($a, $rr['uid']);
698 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
699 if ($abandon_days < 1) {
703 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
705 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
706 if (DBA::isResult($r)) {
707 foreach ($r as $rr) {
708 if ($abandon_days != 0) {
709 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
710 if (!DBA::isResult($user)) {
711 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
716 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
717 pumpio_fetchinbox($a, $rr['uid']);
719 // check for new contacts once a day
720 $last_contact_check = DI::pConfig()->get($rr['uid'], 'pumpio', 'contact_check');
721 if ($last_contact_check) {
722 $next_contact_check = $last_contact_check + 86400;
724 $next_contact_check = 0;
727 if ($next_contact_check <= time()) {
728 pumpio_getallusers($a, $rr["uid"]);
729 DI::pConfig()->set($rr['uid'], 'pumpio', 'contact_check', time());
734 Logger::log('pumpio: cron_end');
736 DI::config()->set('pumpio', 'last_poll', time());
739 function pumpio_cron(App $a, $b)
741 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
744 function pumpio_fetchtimeline(App $a, $uid)
746 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
747 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
748 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
749 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
750 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
751 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
752 $username = DI::pConfig()->get($uid, "pumpio", "user");
754 // get the application name for the pump.io app
755 // 1st try personal config, then system config and fallback to the
756 // hostname of the node if neither one is set.
757 $application_name = DI::pConfig()->get($uid, 'pumpio', 'application_name');
758 if ($application_name == "") {
759 $application_name = DI::config()->get('pumpio', 'application_name');
761 if ($application_name == "") {
762 $application_name = DI::baseUrl()->getHostname();
765 $first_time = ($lastdate == "");
767 $client = new oauth_client_class;
768 $client->oauth_version = '1.0a';
769 $client->authorization_header = true;
770 $client->url_parameters = false;
772 $client->client_id = $ckey;
773 $client->client_secret = $csecret;
774 $client->access_token = $otoken;
775 $client->access_token_secret = $osecret;
777 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
779 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);
781 $useraddr = $username.'@'.$hostname;
783 if (pumpio_reachable($url)) {
784 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
791 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
795 $posts = array_reverse($user->items);
797 $initiallastdate = $lastdate;
801 foreach ($posts as $post) {
802 if ($post->published <= $initiallastdate) {
806 if ($lastdate < $post->published) {
807 $lastdate = $post->published;
815 if (@is_array($post->cc)) {
816 $receiptians = array_merge($receiptians, $post->cc);
819 if (@is_array($post->to)) {
820 $receiptians = array_merge($receiptians, $post->to);
824 foreach ($receiptians AS $receiver) {
825 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
830 if ($public && !stristr($post->generator->displayName, $application_name)) {
831 $_SESSION["authenticated"] = true;
832 $_SESSION["uid"] = $uid;
835 $_REQUEST["api_source"] = true;
836 $_REQUEST["profile_uid"] = $uid;
837 $_REQUEST["source"] = "pump.io";
839 if (isset($post->object->id)) {
840 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
843 if ($post->object->displayName != "") {
844 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
846 $_REQUEST["title"] = "";
849 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
851 // To-Do: Picture has to be cached and stored locally
852 if ($post->object->fullImage->url != "") {
853 if ($post->object->fullImage->pump_io->proxyURL != "") {
854 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
856 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
860 Logger::log('pumpio: posting for user '.$uid);
862 require_once('mod/item.php');
865 Logger::log('pumpio: posting done - user '.$uid);
870 if ($lastdate != 0) {
871 DI::pConfig()->set($uid, 'pumpio', 'lastdate', $lastdate);
875 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
877 // Searching for the unliked post
878 // Two queries for speed issues
879 $orig_post = Post::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
880 if (!DBA::isResult($orig_post)) {
881 $orig_post = Post::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
882 if (!DBA::isResult($orig_post)) {
889 if (Strings::compareLink($post->actor->url, $own_id)) {
890 $contactid = $self[0]['id'];
892 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
893 DBA::escape(Strings::normaliseLink($post->actor->url)),
897 if (DBA::isResult($r)) {
898 $contactid = $r[0]['id'];
901 if ($contactid == 0) {
902 $contactid = $orig_post['contact-id'];
906 Item::markForDeletion(['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
908 if (DBA::isResult($r)) {
909 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
911 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
915 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
917 if (empty($post->object->id)) {
918 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
922 // Searching for the liked post
923 // Two queries for speed issues
924 $orig_post = Post::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
925 if (!DBA::isResult($orig_post)) {
926 $orig_post = Post::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
927 if (!DBA::isResult($orig_post)) {
933 if ($threadcompletion) {
934 pumpio_fetchallcomments($a, $uid, $post->object->id);
939 if (Strings::compareLink($post->actor->url, $own_id)) {
940 $contactid = $self[0]['id'];
941 $post->actor->displayName = $self[0]['name'];
942 $post->actor->url = $self[0]['url'];
943 $post->actor->image->url = $self[0]['photo'];
945 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
946 DBA::escape(Strings::normaliseLink($post->actor->url)),
950 if (DBA::isResult($r)) {
951 $contactid = $r[0]['id'];
954 if ($contactid == 0) {
955 $contactid = $orig_post['contact-id'];
959 $condition = ['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
960 if (Post::exists($condition)) {
961 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
966 $likedata['parent'] = $orig_post['id'];
967 $likedata['verb'] = Activity::LIKE;
968 $likedata['gravity'] = GRAVITY_ACTIVITY;
969 $likedata['uid'] = $uid;
970 $likedata['wall'] = 0;
971 $likedata['network'] = Protocol::PUMPIO;
972 $likedata['uri'] = Item::newURI($uid);
973 $likedata['thr-parent'] = $orig_post['uri'];
974 $likedata['contact-id'] = $contactid;
975 $likedata['app'] = $post->generator->displayName;
976 $likedata['author-name'] = $post->actor->displayName;
977 $likedata['author-link'] = $post->actor->url;
978 if (!empty($post->actor->image)) {
979 $likedata['author-avatar'] = $post->actor->image->url;
982 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
983 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
984 $post_type = DI::l10n()->t('status');
985 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
986 $likedata['object-type'] = Activity\ObjectType::NOTE;
988 $likedata['body'] = DI::l10n()->t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
990 $likedata['object'] = '<object><type>' . Activity\ObjectType::NOTE . '</type><local>1</local>' .
991 '<id>' . $orig_post['uri'] . '</id><link>' . XML::escape('<link rel="alternate" type="text/html" href="' . XML::escape($orig_post['plink']) . '" />') . '</link><title>' . $orig_post['title'] . '</title><content>' . $orig_post['body'] . '</content></object>';
993 $ret = Item::insert($likedata);
995 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
998 function pumpio_get_contact($uid, $contact, $no_insert = false)
1000 $cid = Contact::getIdForURL($contact->url, $uid);
1006 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1007 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1009 if (!DBA::isResult($r)) {
1010 // create contact record
1011 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1012 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1013 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1014 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1016 DBA::escape(DateTimeFormat::utcNow()),
1017 DBA::escape($contact->url),
1018 DBA::escape(Strings::normaliseLink($contact->url)),
1019 DBA::escape(str_replace("acct:", "", $contact->id)),
1021 DBA::escape($contact->id), // What is it for?
1022 DBA::escape('pump.io ' . $contact->id), // What is it for?
1023 DBA::escape($contact->displayName),
1024 DBA::escape($contact->preferredUsername),
1025 DBA::escape($contact->image->url),
1026 DBA::escape(Protocol::PUMPIO),
1027 intval(Contact::FRIEND),
1029 DBA::escape($contact->location->displayName),
1030 DBA::escape($contact->summary),
1034 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1035 DBA::escape(Strings::normaliseLink($contact->url)),
1039 if (!DBA::isResult($r)) {
1043 $contact_id = $r[0]['id'];
1045 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1047 $contact_id = $r[0]["id"];
1049 /* if (DB_UPDATE_VERSION >= "1177")
1050 q("UPDATE `contact` SET `location` = '%s',
1053 dbesc($contact->location->displayName),
1054 dbesc($contact->summary),
1060 if (!empty($contact->image->url)) {
1061 Contact::updateAvatar($contact_id, $contact->image->url);
1067 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1069 // Two queries for speed issues
1070 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1071 if (Post::exists($condition)) {
1072 Item::markForDeletion($condition);
1076 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1077 if (Post::exists($condition)) {
1078 Item::markForDeletion($condition);
1084 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1086 if (($post->verb == "like") || ($post->verb == "favorite")) {
1087 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1090 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1091 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1094 if ($post->verb == "delete") {
1095 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1098 if ($post->verb != "update") {
1099 // Two queries for speed issues
1100 if (Post::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1103 if (Post::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1108 // Only handle these three types
1109 if (!strstr("post|share|update", $post->verb)) {
1114 if (@is_array($post->cc)) {
1115 $receiptians = array_merge($receiptians, $post->cc);
1118 if (@is_array($post->to)) {
1119 $receiptians = array_merge($receiptians, $post->to);
1124 foreach ($receiptians AS $receiver) {
1125 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1131 $postarray['network'] = Protocol::PUMPIO;
1132 $postarray['uid'] = $uid;
1133 $postarray['wall'] = 0;
1134 $postarray['uri'] = $post->object->id;
1135 $postarray['object-type'] = ActivityNamespace::ACTIVITY_SCHEMA . strtolower($post->object->objectType);
1137 if ($post->object->objectType != "comment") {
1138 $contact_id = pumpio_get_contact($uid, $post->actor);
1141 $contact_id = $self[0]['id'];
1144 $postarray['thr-parent'] = $post->object->id;
1147 $postarray['private'] = 1;
1148 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1151 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1153 if (Strings::compareLink($post->actor->url, $own_id)) {
1154 $contact_id = $self[0]['id'];
1155 $post->actor->displayName = $self[0]['name'];
1156 $post->actor->url = $self[0]['url'];
1157 $post->actor->image->url = $self[0]['photo'];
1158 } elseif ($contact_id == 0) {
1159 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1160 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1161 DBA::escape(Strings::normaliseLink($post->actor->url)),
1165 if (DBA::isResult($r)) {
1166 $contact_id = $r[0]['id'];
1168 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1169 DBA::escape(Strings::normaliseLink($post->actor->url)),
1173 if (DBA::isResult($r)) {
1174 $contact_id = $r[0]['id'];
1176 $contact_id = $self[0]['id'];
1181 $reply = new stdClass;
1182 $reply->verb = "note";
1184 if (isset($post->cc)) {
1185 $reply->cc = $post->cc;
1188 if (isset($post->to)) {
1189 $reply->to = $post->to;
1192 $reply->object = new stdClass;
1193 $reply->object->objectType = $post->object->inReplyTo->objectType;
1194 $reply->object->content = $post->object->inReplyTo->content;
1195 $reply->object->id = $post->object->inReplyTo->id;
1196 $reply->actor = $post->object->inReplyTo->author;
1197 $reply->url = $post->object->inReplyTo->url;
1198 $reply->generator = new stdClass;
1199 $reply->generator->displayName = "pumpio";
1200 $reply->published = $post->object->inReplyTo->published;
1201 $reply->received = $post->object->inReplyTo->updated;
1202 $reply->url = $post->object->inReplyTo->url;
1203 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1205 $postarray['thr-parent'] = $post->object->inReplyTo->id;
1208 // When there is no content there is no need to continue
1209 if (empty($post->object->content)) {
1213 if (!empty($post->object->pump_io->proxyURL)) {
1214 $postarray['extid'] = $post->object->pump_io->proxyURL;
1217 $postarray['contact-id'] = $contact_id;
1218 $postarray['verb'] = Activity::POST;
1219 $postarray['owner-name'] = $post->actor->displayName;
1220 $postarray['owner-link'] = $post->actor->url;
1221 $postarray['author-name'] = $postarray['owner-name'];
1222 $postarray['author-link'] = $postarray['owner-link'];
1223 if (!empty($post->actor->image)) {
1224 $postarray['owner-avatar'] = $post->actor->image->url;
1225 $postarray['author-avatar'] = $postarray['owner-avatar'];
1227 $postarray['plink'] = $post->object->url;
1228 $postarray['app'] = $post->generator->displayName;
1229 $postarray['title'] = '';
1230 $postarray['body'] = HTML::toBBCode($post->object->content);
1231 $postarray['object'] = json_encode($post);
1233 if (!empty($post->object->fullImage->url)) {
1234 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1237 if (!empty($post->object->displayName)) {
1238 $postarray['title'] = $post->object->displayName;
1241 $postarray['created'] = DateTimeFormat::utc($post->published);
1242 if (isset($post->updated)) {
1243 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1244 } elseif (isset($post->received)) {
1245 $postarray['edited'] = DateTimeFormat::utc($post->received);
1247 $postarray['edited'] = $postarray['created'];
1250 if ($post->verb == "share") {
1251 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1252 $share_author = $post->object->author->displayName;
1253 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1254 $share_author = $post->object->author->preferredUsername;
1256 $share_author = $post->object->author->url;
1259 if (isset($post->object->created)) {
1260 $created = DateTimeFormat::utc($post->object->created);
1265 $postarray['body'] = Friendica\Content\Text\BBCode::getShareOpeningTag($share_author, $post->object->author->url,
1266 $post->object->author->image->url, $post->links->self->href, $created) .
1267 $postarray['body']."[/share]";
1270 if (trim($postarray['body']) == "") {
1274 $top_item = Item::insert($postarray);
1275 $postarray["id"] = $top_item;
1277 if (($top_item == 0) && ($post->verb == "update")) {
1278 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1279 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1280 Item::update($fields, $condition);
1283 if (($post->object->objectType == "comment") && $threadcompletion) {
1284 pumpio_fetchallcomments($a, $uid, $postarray['thr-parent']);
1290 function pumpio_fetchinbox(App $a, $uid)
1292 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1293 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1294 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1295 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1296 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
1297 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1298 $username = DI::pConfig()->get($uid, "pumpio", "user");
1300 $own_id = "https://".$hostname."/".$username;
1302 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1305 $lastitems = q("SELECT `uri` FROM `post-thread-user`
1306 INNER JOIN `post-view` ON `post-view`.`id` = `post-thread-user`.`id`
1307 WHERE `post-thread-user`.`network` = '%s' AND `post-thread-user`.`uid` = %d AND `post-view`.`extid` != ''
1308 ORDER BY `post-thread-user`.`commented` DESC LIMIT 10",
1309 DBA::escape(Protocol::PUMPIO),
1313 $client = new oauth_client_class;
1314 $client->oauth_version = '1.0a';
1315 $client->authorization_header = true;
1316 $client->url_parameters = false;
1318 $client->client_id = $ckey;
1319 $client->client_secret = $csecret;
1320 $client->access_token = $otoken;
1321 $client->access_token_secret = $osecret;
1323 $last_id = DI::pConfig()->get($uid, 'pumpio', 'last_id');
1325 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1327 if ($last_id != "") {
1328 $url .= '?since='.urlencode($last_id);
1331 if (pumpio_reachable($url)) {
1332 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1341 if (!empty($user->items)) {
1342 $posts = array_reverse($user->items);
1344 if (count($posts)) {
1345 foreach ($posts as $post) {
1346 $last_id = $post->id;
1347 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1352 foreach ($lastitems as $item) {
1353 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1356 DI::pConfig()->set($uid, 'pumpio', 'last_id', $last_id);
1359 function pumpio_getallusers(App &$a, $uid)
1361 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1362 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1363 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1364 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1365 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1366 $username = DI::pConfig()->get($uid, "pumpio", "user");
1368 $client = new oauth_client_class;
1369 $client->oauth_version = '1.0a';
1370 $client->authorization_header = true;
1371 $client->url_parameters = false;
1373 $client->client_id = $ckey;
1374 $client->client_secret = $csecret;
1375 $client->access_token = $otoken;
1376 $client->access_token_secret = $osecret;
1378 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1380 if (pumpio_reachable($url)) {
1381 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1386 if (empty($users)) {
1390 if ($users->totalItems > count($users->items)) {
1391 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1393 if (pumpio_reachable($url)) {
1394 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1400 if (!empty($users->items)) {
1401 foreach ($users->items as $user) {
1402 pumpio_get_contact($uid, $user);
1407 function pumpio_getreceiver(App $a, array $b)
1411 if (!$b["private"]) {
1412 if (!strstr($b['postopts'], 'pumpio')) {
1416 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
1419 $receiver["to"][] = [
1420 "objectType" => "collection",
1421 "id" => "http://activityschema.org/collection/public"];
1424 $cids = explode("><", $b["allow_cid"]);
1425 $gids = explode("><", $b["allow_gid"]);
1427 foreach ($cids AS $cid) {
1428 $cid = trim($cid, " <>");
1430 $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",
1433 DBA::escape(Protocol::PUMPIO)
1436 if (DBA::isResult($r)) {
1437 $receiver["bcc"][] = [
1438 "displayName" => $r[0]["name"],
1439 "objectType" => "person",
1440 "preferredUsername" => $r[0]["nick"],
1441 "url" => $r[0]["url"]];
1444 foreach ($gids AS $gid) {
1445 $gid = trim($gid, " <>");
1447 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1448 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1449 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1451 DBA::escape(Protocol::PUMPIO)
1454 foreach ($r AS $row)
1455 $receiver["bcc"][] = [
1456 "displayName" => $row["name"],
1457 "objectType" => "person",
1458 "preferredUsername" => $row["nick"],
1459 "url" => $row["url"]];
1463 if ($b["inform"] != "") {
1464 $inform = explode(",", $b["inform"]);
1466 foreach ($inform AS $cid) {
1467 if (substr($cid, 0, 4) != "cid:") {
1471 $cid = str_replace("cid:", "", $cid);
1473 $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",
1476 DBA::escape(Protocol::PUMPIO)
1479 if (DBA::isResult($r)) {
1480 $receiver["to"][] = [
1481 "displayName" => $r[0]["name"],
1482 "objectType" => "person",
1483 "preferredUsername" => $r[0]["nick"],
1484 "url" => $r[0]["url"]];
1492 function pumpio_fetchallcomments(App $a, $uid, $id)
1494 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1495 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1496 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1497 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1498 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1499 $username = DI::pConfig()->get($uid, "pumpio", "user");
1501 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1503 $own_id = "https://".$hostname."/".$username;
1505 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1508 // Fetching the original post
1509 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1510 $original = Post::selectFirst(['extid'], $condition);
1511 if (!DBA::isResult($original)) {
1515 $url = $original["extid"];
1517 $client = new oauth_client_class;
1518 $client->oauth_version = '1.0a';
1519 $client->authorization_header = true;
1520 $client->url_parameters = false;
1522 $client->client_id = $ckey;
1523 $client->client_secret = $csecret;
1524 $client->access_token = $otoken;
1525 $client->access_token_secret = $osecret;
1527 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1529 if (pumpio_reachable($url)) {
1530 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1539 if ($item->likes->totalItems != 0) {
1540 foreach ($item->likes->items AS $post) {
1541 $like = new stdClass;
1542 $like->object = new stdClass;
1543 $like->object->id = $item->id;
1544 $like->actor = new stdClass;
1545 if (!empty($item->displayName)) {
1546 $like->actor->displayName = $item->displayName;
1548 //$like->actor->preferredUsername = $item->preferredUsername;
1549 //$like->actor->image = $item->image;
1550 $like->actor->url = $item->url;
1551 $like->generator = new stdClass;
1552 $like->generator->displayName = "pumpio";
1553 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1557 if ($item->replies->totalItems == 0) {
1561 foreach ($item->replies->items AS $item) {
1562 if ($item->id == $id) {
1566 // Checking if the comment already exists - Two queries for speed issues
1567 if (Post::exists(['uri' => $item->id, 'uid' => $uid])) {
1571 if (Post::exists(['extid' => $item->id, 'uid' => $uid])) {
1575 $post = new stdClass;
1576 $post->verb = "post";
1577 $post->actor = $item->author;
1578 $post->published = $item->published;
1579 $post->received = $item->updated;
1580 $post->generator = new stdClass;
1581 $post->generator->displayName = "pumpio";
1582 // To-Do: Check for public post
1584 unset($item->author);
1585 unset($item->published);
1586 unset($item->updated);
1588 $post->object = $item;
1590 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1591 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1595 function pumpio_reachable($url)
1597 return DI::httpRequest()->get($url, [HTTPClientOptions::TIMEOUT => 10])->isSuccess();