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\Protocol\Activity;
24 use Friendica\Protocol\ActivityNamespace;
25 use Friendica\Util\ConfigFileLoader;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Strings;
28 use Friendica\Util\XML;
30 require 'addon/pumpio/oauth/http.php';
31 require 'addon/pumpio/oauth/oauth_client.php';
32 require_once "mod/share.php";
34 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
36 function pumpio_install()
38 Hook::register('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
39 Hook::register('hook_fork', 'addon/pumpio/pumpio.php', 'hook_fork');
40 Hook::register('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
41 Hook::register('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
42 Hook::register('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
43 Hook::register('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
44 Hook::register('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
45 Hook::register('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
46 Hook::register('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
49 function pumpio_module() {}
51 function pumpio_content(App $a)
54 notice(DI::l10n()->t('Permission denied.') . EOL);
58 require_once("mod/settings.php");
61 if (isset($a->argv[1])) {
62 switch ($a->argv[1]) {
64 $o = pumpio_connect($a);
67 $o = print_r($a->argv, true);
71 $o = pumpio_connect($a);
76 function pumpio_check_item_notification($a, &$notification_data)
78 $hostname = DI::pConfig()->get($notification_data["uid"], 'pumpio', 'host');
79 $username = DI::pConfig()->get($notification_data["uid"], "pumpio", "user");
81 $notification_data["profiles"][] = "https://".$hostname."/".$username;
84 function pumpio_registerclient(App $a, $host)
86 $url = "https://".$host."/api/client/register";
90 $application_name = DI::config()->get('pumpio', 'application_name');
92 if ($application_name == "") {
93 $application_name = DI::baseUrl()->getHostname();
96 $adminlist = explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email')));
98 $params["type"] = "client_associate";
99 $params["contacts"] = $adminlist[0];
100 $params["application_type"] = "native";
101 $params["application_name"] = $application_name;
102 $params["logo_url"] = DI::baseUrl()->get()."/images/friendica-256.png";
103 $params["redirect_uris"] = DI::baseUrl()->get()."/pumpio/connect";
105 Logger::log("pumpio_registerclient: ".$url." parameters ".print_r($params, true), Logger::DEBUG);
107 $ch = curl_init($url);
108 curl_setopt($ch, CURLOPT_HEADER, false);
109 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
110 curl_setopt($ch, CURLOPT_POST,1);
111 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
112 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
115 $curl_info = curl_getinfo($ch);
117 if ($curl_info["http_code"] == "200") {
118 $values = json_decode($s);
119 Logger::log("pumpio_registerclient: success ".print_r($values, true), Logger::DEBUG);
122 Logger::log("pumpio_registerclient: failed: ".print_r($curl_info, true), Logger::DEBUG);
127 function pumpio_connect(App $a)
129 // Define the needed keys
130 $consumer_key = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_key');
131 $consumer_secret = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_secret');
132 $hostname = DI::pConfig()->get(local_user(), 'pumpio', 'host');
134 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
135 Logger::log("pumpio_connect: register client");
136 $clientdata = pumpio_registerclient($a, $hostname);
137 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
138 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
140 $consumer_key = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_key');
141 $consumer_secret = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_secret');
143 Logger::log("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, Logger::DEBUG);
146 if (($consumer_key == "") || ($consumer_secret == "")) {
147 Logger::log("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
149 return DI::l10n()->t("Unable to register the client at the pump.io server '%s'.", $hostname);
152 // The callback URL is the script that gets called after the user authenticates with pumpio
153 $callback_url = DI::baseUrl()->get()."/pumpio/connect";
155 // Let's begin. First we need a Request Token. The request token is required to send the user
156 // to pumpio's login page.
158 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
159 // Consumer Key and Consumer Secret
160 $client = new oauth_client_class;
162 $client->server = '';
163 $client->oauth_version = '1.0a';
164 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
165 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
166 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
167 $client->url_parameters = false;
168 $client->authorization_header = true;
169 $client->redirect_uri = $callback_url;
170 $client->client_id = $consumer_key;
171 $client->client_secret = $consumer_secret;
173 if (($success = $client->Initialize())) {
174 if (($success = $client->Process())) {
175 if (strlen($client->access_token)) {
176 Logger::log("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, Logger::DEBUG);
177 DI::pConfig()->set(local_user(), "pumpio", "oauth_token", $client->access_token);
178 DI::pConfig()->set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
181 $success = $client->Finalize($success);
184 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
188 Logger::log("pumpio_connect: authenticated");
189 $o = DI::l10n()->t("You are now authenticated to pumpio.");
190 $o .= '<br /><a href="'.DI::baseUrl()->get().'/settings/connectors">'.DI::l10n()->t("return to the connector page").'</a>';
192 Logger::log("pumpio_connect: could not connect");
193 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
199 function pumpio_jot_nets(App $a, array &$jotnets_fields)
201 if (! local_user()) {
205 if (DI::pConfig()->get(local_user(), 'pumpio', 'post')) {
206 $jotnets_fields[] = [
207 'type' => 'checkbox',
210 DI::l10n()->t('Post to pumpio'),
211 DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default')
217 function pumpio_settings(App $a, &$s)
223 /* Add our stylesheet to the page so we can make our settings look nice */
225 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
227 /* Get the current state of our config variables */
229 $import_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'import');
230 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
232 $enabled = DI::pConfig()->get(local_user(), 'pumpio', 'post');
233 $checked = (($enabled) ? ' checked="checked" ' : '');
234 $css = (($enabled) ? '' : '-disabled');
236 $def_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default');
237 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
239 $public_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'public');
240 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
242 $mirror_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'mirror');
243 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
245 $servername = DI::pConfig()->get(local_user(), "pumpio", "host");
246 $username = DI::pConfig()->get(local_user(), "pumpio", "user");
248 /* Add some HTML to the existing form */
250 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
251 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. DI::l10n()->t('Pump.io Import/Export/Mirror').'</h3>';
253 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
254 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
255 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. DI::l10n()->t('Pump.io Import/Export/Mirror').'</h3>';
258 $s .= '<div id="pumpio-username-wrapper">';
259 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.DI::l10n()->t('pump.io username (without the servername)').'</label>';
260 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
261 $s .= '</div><div class="clear"></div>';
263 $s .= '<div id="pumpio-servername-wrapper">';
264 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.DI::l10n()->t('pump.io servername (without "http://" or "https://" )').'</label>';
265 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
266 $s .= '</div><div class="clear"></div>';
268 if (($username != '') && ($servername != '')) {
269 $oauth_token = DI::pConfig()->get(local_user(), "pumpio", "oauth_token");
270 $oauth_token_secret = DI::pConfig()->get(local_user(), "pumpio", "oauth_token_secret");
272 $s .= '<div id="pumpio-password-wrapper">';
273 if (($oauth_token == "") || ($oauth_token_secret == "")) {
274 $s .= '<div id="pumpio-authenticate-wrapper">';
275 $s .= '<a href="'.DI::baseUrl()->get().'/pumpio/connect">'.DI::l10n()->t("Authenticate your pump.io connection").'</a>';
276 $s .= '</div><div class="clear"></div>';
278 $s .= '<div id="pumpio-import-wrapper">';
279 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . DI::l10n()->t('Import the remote timeline') . '</label>';
280 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
281 $s .= '</div><div class="clear"></div>';
283 $s .= '<div id="pumpio-enable-wrapper">';
284 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . DI::l10n()->t('Enable pump.io Post Addon') . '</label>';
285 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
286 $s .= '</div><div class="clear"></div>';
288 $s .= '<div id="pumpio-bydefault-wrapper">';
289 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . DI::l10n()->t('Post to pump.io by default') . '</label>';
290 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
291 $s .= '</div><div class="clear"></div>';
293 $s .= '<div id="pumpio-public-wrapper">';
294 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . DI::l10n()->t('Should posts be public?') . '</label>';
295 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
296 $s .= '</div><div class="clear"></div>';
298 $s .= '<div id="pumpio-mirror-wrapper">';
299 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . DI::l10n()->t('Mirror all public posts') . '</label>';
300 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
301 $s .= '</div><div class="clear"></div>';
303 $s .= '<div id="pumpio-delete-wrapper">';
304 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . DI::l10n()->t('Check to delete this preset') . '</label>';
305 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
306 $s .= '</div><div class="clear"></div>';
309 $s .= '</div><div class="clear"></div>';
312 /* provide a submit button */
314 $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>';
317 function pumpio_settings_post(App $a, array &$b)
319 if (!empty($_POST['pumpio-submit'])) {
320 if (!empty($_POST['pumpio_delete'])) {
321 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_key' , '');
322 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_secret' , '');
323 DI::pConfig()->set(local_user(), 'pumpio', 'oauth_token' , '');
324 DI::pConfig()->set(local_user(), 'pumpio', 'oauth_token_secret', '');
325 DI::pConfig()->set(local_user(), 'pumpio', 'post' , false);
326 DI::pConfig()->set(local_user(), 'pumpio', 'import' , false);
327 DI::pConfig()->set(local_user(), 'pumpio', 'host' , '');
328 DI::pConfig()->set(local_user(), 'pumpio', 'user' , '');
329 DI::pConfig()->set(local_user(), 'pumpio', 'public' , false);
330 DI::pConfig()->set(local_user(), 'pumpio', 'mirror' , false);
331 DI::pConfig()->set(local_user(), 'pumpio', 'post_by_default' , false);
332 DI::pConfig()->set(local_user(), 'pumpio', 'lastdate' , 0);
333 DI::pConfig()->set(local_user(), 'pumpio', 'last_id' , '');
335 // filtering the username if it is filled wrong
336 $user = $_POST['pumpio_user'];
337 if (strstr($user, "@")) {
338 $pos = strpos($user, "@");
341 $user = substr($user, 0, $pos);
345 // Filtering the hostname if someone is entering it with "http"
346 $host = $_POST['pumpio_host'];
348 $host = str_replace(["https://", "http://"], ["", ""], $host);
350 DI::pConfig()->set(local_user(), 'pumpio', 'post' , $_POST['pumpio'] ?? false);
351 DI::pConfig()->set(local_user(), 'pumpio', 'import' , $_POST['pumpio_import'] ?? false);
352 DI::pConfig()->set(local_user(), 'pumpio', 'host' , $host);
353 DI::pConfig()->set(local_user(), 'pumpio', 'user' , $user);
354 DI::pConfig()->set(local_user(), 'pumpio', 'public' , $_POST['pumpio_public'] ?? false);
355 DI::pConfig()->set(local_user(), 'pumpio', 'mirror' , $_POST['pumpio_mirror'] ?? false);
356 DI::pConfig()->set(local_user(), 'pumpio', 'post_by_default', $_POST['pumpio_bydefault'] ?? false);
358 if (!empty($_POST['pumpio_mirror'])) {
359 DI::pConfig()->delete(local_user(), 'pumpio', 'lastdate');
365 function pumpio_load_config(App $a, ConfigFileLoader $loader)
367 $a->getConfigCache()->load($loader->loadAddonConfig('pumpio'));
370 function pumpio_hook_fork(App $a, array &$b)
372 if ($b['name'] != 'notifier_normal') {
378 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
379 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
380 $b['execute'] = false;
384 // if post comes from pump.io don't send it back
385 if ($post['app'] == "pump.io") {
386 $b['execute'] = false;
390 if (DI::pConfig()->get($post['uid'], 'pumpio', 'import')) {
391 // Don't fork if it isn't a reply to a pump.io post
392 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::PUMPIO])) {
393 Logger::log('No pump.io parent found for item ' . $post['id']);
394 $b['execute'] = false;
398 // Comments are never exported when we don't import the pumpio timeline
399 if (!strstr($post['postopts'], 'pumpio') || ($post['parent'] != $post['id']) || $post['private']) {
400 $b['execute'] = false;
406 function pumpio_post_local(App $a, array &$b)
408 if (!local_user() || (local_user() != $b['uid'])) {
412 $pumpio_post = intval(DI::pConfig()->get(local_user(), 'pumpio', 'post'));
414 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
416 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default'))) {
420 if (!$pumpio_enable) {
424 if (strlen($b['postopts'])) {
425 $b['postopts'] .= ',';
428 $b['postopts'] .= 'pumpio';
431 function pumpio_send(App $a, array &$b)
433 if (!DI::pConfig()->get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
437 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
439 $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], $b['body']);
441 if ($b['parent'] != $b['id']) {
442 // Looking if its a reply to a pumpio post
443 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
444 $orig_post = Post::selectFirst([], $condition);
446 if (!DBA::isResult($orig_post)) {
447 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
455 $receiver = pumpio_getreceiver($a, $b);
457 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
459 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
463 // Dont't post if the post doesn't belong to us.
464 // This is a check for forum postings
465 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
466 if ($b['contact-id'] != $self['id']) {
471 if ($b['verb'] == Activity::LIKE) {
473 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
475 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
480 if ($b['verb'] == Activity::DISLIKE) {
484 if (($b['verb'] == Activity::POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
485 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
488 if (($b['verb'] == Activity::POST) && $b['deleted']) {
489 pumpio_action($a, $b["uid"], $b["uri"], "delete");
492 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
496 // if post comes from pump.io don't send it back
497 if ($b['app'] == "pump.io") {
502 // Support for native shares
503 // http://<hostname>/api/<type>/shares?id=<the-object-id>
505 $oauth_token = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token");
506 $oauth_token_secret = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token_secret");
507 $consumer_key = DI::pConfig()->get($b['uid'], "pumpio","consumer_key");
508 $consumer_secret = DI::pConfig()->get($b['uid'], "pumpio","consumer_secret");
510 $host = DI::pConfig()->get($b['uid'], "pumpio", "host");
511 $user = DI::pConfig()->get($b['uid'], "pumpio", "user");
512 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
514 if ($oauth_token && $oauth_token_secret) {
515 $title = trim($b['title']);
517 $content = BBCode::convertForUriId($b['uri-id'], $b['body'], BBCode::CONNECTORS);
521 $params["verb"] = "post";
524 $params["object"] = [
525 'objectType' => "note",
526 'content' => $content];
528 if (!empty($title)) {
529 $params["object"]["displayName"] = $title;
532 if (!empty($receiver["to"])) {
533 $params["to"] = $receiver["to"];
536 if (!empty($receiver["bto"])) {
537 $params["bto"] = $receiver["bto"];
540 if (!empty($receiver["cc"])) {
541 $params["cc"] = $receiver["cc"];
544 if (!empty($receiver["bcc"])) {
545 $params["bcc"] = $receiver["bcc"];
548 $inReplyTo = ["id" => $orig_post["uri"],
549 "objectType" => "note"];
551 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
552 $inReplyTo["objectType"] = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
555 $params["object"] = [
556 'objectType' => "comment",
557 'content' => $content,
558 'inReplyTo' => $inReplyTo];
561 $params["object"]["displayName"] = $title;
565 $client = new oauth_client_class;
566 $client->oauth_version = '1.0a';
567 $client->url_parameters = false;
568 $client->authorization_header = true;
569 $client->access_token = $oauth_token;
570 $client->access_token_secret = $oauth_token_secret;
571 $client->client_id = $consumer_key;
572 $client->client_secret = $consumer_secret;
574 $username = $user.'@'.$host;
575 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
577 if (pumpio_reachable($url)) {
578 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
584 if ($user->generator->displayName) {
585 DI::pConfig()->set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
588 $post_id = $user->object->id;
589 Logger::log('pumpio_send '.$username.': success '.$post_id);
590 if ($post_id && $iscomment) {
591 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
592 Item::update(['extid' => $post_id], ['id' => $b['id']]);
595 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
601 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
603 // Don't do likes and other stuff if you don't import the timeline
604 if (!DI::pConfig()->get($uid, 'pumpio', 'import')) {
608 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
609 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
610 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
611 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
612 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
613 $username = DI::pConfig()->get($uid, "pumpio", "user");
615 $orig_post = Post::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
617 if (!DBA::isResult($orig_post)) {
621 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
622 $uri = $orig_post["extid"];
624 $uri = $orig_post["uri"];
627 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
628 $objectType = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
629 } elseif (strstr($uri, "/api/comment/")) {
630 $objectType = "comment";
631 } elseif (strstr($uri, "/api/note/")) {
632 $objectType = "note";
633 } elseif (strstr($uri, "/api/image/")) {
634 $objectType = "image";
637 $params["verb"] = $action;
638 $params["object"] = ['id' => $uri,
639 "objectType" => $objectType,
640 "content" => $content];
642 $client = new oauth_client_class;
643 $client->oauth_version = '1.0a';
644 $client->authorization_header = true;
645 $client->url_parameters = false;
647 $client->client_id = $ckey;
648 $client->client_secret = $csecret;
649 $client->access_token = $otoken;
650 $client->access_token_secret = $osecret;
652 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
654 if (pumpio_reachable($url)) {
655 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
661 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
663 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri);
668 function pumpio_sync(App $a)
670 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
672 if (!DBA::isResult($r)) {
676 $last = DI::config()->get('pumpio', 'last_poll');
678 $poll_interval = intval(DI::config()->get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
681 $next = $last + ($poll_interval * 60);
682 if ($next > time()) {
683 Logger::log('pumpio: poll intervall not reached');
687 Logger::log('pumpio: cron_start');
689 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
690 if (DBA::isResult($r)) {
691 foreach ($r as $rr) {
692 Logger::log('pumpio: mirroring user '.$rr['uid']);
693 pumpio_fetchtimeline($a, $rr['uid']);
697 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
698 if ($abandon_days < 1) {
702 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
704 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
705 if (DBA::isResult($r)) {
706 foreach ($r as $rr) {
707 if ($abandon_days != 0) {
708 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
709 if (!DBA::isResult($user)) {
710 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
715 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
716 pumpio_fetchinbox($a, $rr['uid']);
718 // check for new contacts once a day
719 $last_contact_check = DI::pConfig()->get($rr['uid'], 'pumpio', 'contact_check');
720 if ($last_contact_check) {
721 $next_contact_check = $last_contact_check + 86400;
723 $next_contact_check = 0;
726 if ($next_contact_check <= time()) {
727 pumpio_getallusers($a, $rr["uid"]);
728 DI::pConfig()->set($rr['uid'], 'pumpio', 'contact_check', time());
733 Logger::log('pumpio: cron_end');
735 DI::config()->set('pumpio', 'last_poll', time());
738 function pumpio_cron(App $a, $b)
740 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
743 function pumpio_fetchtimeline(App $a, $uid)
745 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
746 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
747 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
748 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
749 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
750 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
751 $username = DI::pConfig()->get($uid, "pumpio", "user");
753 // get the application name for the pump.io app
754 // 1st try personal config, then system config and fallback to the
755 // hostname of the node if neither one is set.
756 $application_name = DI::pConfig()->get($uid, 'pumpio', 'application_name');
757 if ($application_name == "") {
758 $application_name = DI::config()->get('pumpio', 'application_name');
760 if ($application_name == "") {
761 $application_name = DI::baseUrl()->getHostname();
764 $first_time = ($lastdate == "");
766 $client = new oauth_client_class;
767 $client->oauth_version = '1.0a';
768 $client->authorization_header = true;
769 $client->url_parameters = false;
771 $client->client_id = $ckey;
772 $client->client_secret = $csecret;
773 $client->access_token = $otoken;
774 $client->access_token_secret = $osecret;
776 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
778 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);
780 $useraddr = $username.'@'.$hostname;
782 if (pumpio_reachable($url)) {
783 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
790 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
794 $posts = array_reverse($user->items);
796 $initiallastdate = $lastdate;
800 foreach ($posts as $post) {
801 if ($post->published <= $initiallastdate) {
805 if ($lastdate < $post->published) {
806 $lastdate = $post->published;
814 if (@is_array($post->cc)) {
815 $receiptians = array_merge($receiptians, $post->cc);
818 if (@is_array($post->to)) {
819 $receiptians = array_merge($receiptians, $post->to);
823 foreach ($receiptians AS $receiver) {
824 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
829 if ($public && !stristr($post->generator->displayName, $application_name)) {
830 $_SESSION["authenticated"] = true;
831 $_SESSION["uid"] = $uid;
834 $_REQUEST["api_source"] = true;
835 $_REQUEST["profile_uid"] = $uid;
836 $_REQUEST["source"] = "pump.io";
838 if (isset($post->object->id)) {
839 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
842 if ($post->object->displayName != "") {
843 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
845 $_REQUEST["title"] = "";
848 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
850 // To-Do: Picture has to be cached and stored locally
851 if ($post->object->fullImage->url != "") {
852 if ($post->object->fullImage->pump_io->proxyURL != "") {
853 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
855 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
859 Logger::log('pumpio: posting for user '.$uid);
861 require_once('mod/item.php');
864 Logger::log('pumpio: posting done - user '.$uid);
869 if ($lastdate != 0) {
870 DI::pConfig()->set($uid, 'pumpio', 'lastdate', $lastdate);
874 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
876 // Searching for the unliked post
877 // Two queries for speed issues
878 $orig_post = Post::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
879 if (!DBA::isResult($orig_post)) {
880 $orig_post = Post::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
881 if (!DBA::isResult($orig_post)) {
888 if (Strings::compareLink($post->actor->url, $own_id)) {
889 $contactid = $self[0]['id'];
891 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
892 DBA::escape(Strings::normaliseLink($post->actor->url)),
896 if (DBA::isResult($r)) {
897 $contactid = $r[0]['id'];
900 if ($contactid == 0) {
901 $contactid = $orig_post['contact-id'];
905 Item::markForDeletion(['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
907 if (DBA::isResult($r)) {
908 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
910 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
914 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
916 if (empty($post->object->id)) {
917 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
921 // Searching for the liked post
922 // Two queries for speed issues
923 $orig_post = Post::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
924 if (!DBA::isResult($orig_post)) {
925 $orig_post = Post::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
926 if (!DBA::isResult($orig_post)) {
932 if ($threadcompletion) {
933 pumpio_fetchallcomments($a, $uid, $post->object->id);
938 if (Strings::compareLink($post->actor->url, $own_id)) {
939 $contactid = $self[0]['id'];
940 $post->actor->displayName = $self[0]['name'];
941 $post->actor->url = $self[0]['url'];
942 $post->actor->image->url = $self[0]['photo'];
944 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
945 DBA::escape(Strings::normaliseLink($post->actor->url)),
949 if (DBA::isResult($r)) {
950 $contactid = $r[0]['id'];
953 if ($contactid == 0) {
954 $contactid = $orig_post['contact-id'];
958 $condition = ['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
959 if (Post::exists($condition)) {
960 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
965 $likedata['parent'] = $orig_post['id'];
966 $likedata['verb'] = Activity::LIKE;
967 $likedata['gravity'] = GRAVITY_ACTIVITY;
968 $likedata['uid'] = $uid;
969 $likedata['wall'] = 0;
970 $likedata['network'] = Protocol::PUMPIO;
971 $likedata['uri'] = Item::newURI($uid);
972 $likedata['thr-parent'] = $orig_post['uri'];
973 $likedata['contact-id'] = $contactid;
974 $likedata['app'] = $post->generator->displayName;
975 $likedata['author-name'] = $post->actor->displayName;
976 $likedata['author-link'] = $post->actor->url;
977 if (!empty($post->actor->image)) {
978 $likedata['author-avatar'] = $post->actor->image->url;
981 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
982 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
983 $post_type = DI::l10n()->t('status');
984 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
985 $likedata['object-type'] = Activity\ObjectType::NOTE;
987 $likedata['body'] = DI::l10n()->t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
989 $likedata['object'] = '<object><type>' . Activity\ObjectType::NOTE . '</type><local>1</local>' .
990 '<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>';
992 $ret = Item::insert($likedata);
994 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
997 function pumpio_get_contact($uid, $contact, $no_insert = false)
999 $cid = Contact::getIdForURL($contact->url, $uid);
1005 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1006 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1008 if (!DBA::isResult($r)) {
1009 // create contact record
1010 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1011 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1012 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1013 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1015 DBA::escape(DateTimeFormat::utcNow()),
1016 DBA::escape($contact->url),
1017 DBA::escape(Strings::normaliseLink($contact->url)),
1018 DBA::escape(str_replace("acct:", "", $contact->id)),
1020 DBA::escape($contact->id), // What is it for?
1021 DBA::escape('pump.io ' . $contact->id), // What is it for?
1022 DBA::escape($contact->displayName),
1023 DBA::escape($contact->preferredUsername),
1024 DBA::escape($contact->image->url),
1025 DBA::escape(Protocol::PUMPIO),
1026 intval(Contact::FRIEND),
1028 DBA::escape($contact->location->displayName),
1029 DBA::escape($contact->summary),
1033 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1034 DBA::escape(Strings::normaliseLink($contact->url)),
1038 if (!DBA::isResult($r)) {
1042 $contact_id = $r[0]['id'];
1044 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1046 $contact_id = $r[0]["id"];
1048 /* if (DB_UPDATE_VERSION >= "1177")
1049 q("UPDATE `contact` SET `location` = '%s',
1052 dbesc($contact->location->displayName),
1053 dbesc($contact->summary),
1059 if (!empty($contact->image->url)) {
1060 Contact::updateAvatar($contact_id, $contact->image->url);
1066 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1068 // Two queries for speed issues
1069 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1070 if (Post::exists($condition)) {
1071 Item::markForDeletion($condition);
1075 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1076 if (Post::exists($condition)) {
1077 Item::markForDeletion($condition);
1083 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1085 if (($post->verb == "like") || ($post->verb == "favorite")) {
1086 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1089 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1090 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1093 if ($post->verb == "delete") {
1094 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1097 if ($post->verb != "update") {
1098 // Two queries for speed issues
1099 if (Post::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1102 if (Post::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1107 // Only handle these three types
1108 if (!strstr("post|share|update", $post->verb)) {
1113 if (@is_array($post->cc)) {
1114 $receiptians = array_merge($receiptians, $post->cc);
1117 if (@is_array($post->to)) {
1118 $receiptians = array_merge($receiptians, $post->to);
1123 foreach ($receiptians AS $receiver) {
1124 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1130 $postarray['network'] = Protocol::PUMPIO;
1131 $postarray['uid'] = $uid;
1132 $postarray['wall'] = 0;
1133 $postarray['uri'] = $post->object->id;
1134 $postarray['object-type'] = ActivityNamespace::ACTIVITY_SCHEMA . strtolower($post->object->objectType);
1136 if ($post->object->objectType != "comment") {
1137 $contact_id = pumpio_get_contact($uid, $post->actor);
1140 $contact_id = $self[0]['id'];
1143 $postarray['thr-parent'] = $post->object->id;
1146 $postarray['private'] = 1;
1147 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1150 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1152 if (Strings::compareLink($post->actor->url, $own_id)) {
1153 $contact_id = $self[0]['id'];
1154 $post->actor->displayName = $self[0]['name'];
1155 $post->actor->url = $self[0]['url'];
1156 $post->actor->image->url = $self[0]['photo'];
1157 } elseif ($contact_id == 0) {
1158 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1159 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1160 DBA::escape(Strings::normaliseLink($post->actor->url)),
1164 if (DBA::isResult($r)) {
1165 $contact_id = $r[0]['id'];
1167 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1168 DBA::escape(Strings::normaliseLink($post->actor->url)),
1172 if (DBA::isResult($r)) {
1173 $contact_id = $r[0]['id'];
1175 $contact_id = $self[0]['id'];
1180 $reply = new stdClass;
1181 $reply->verb = "note";
1183 if (isset($post->cc)) {
1184 $reply->cc = $post->cc;
1187 if (isset($post->to)) {
1188 $reply->to = $post->to;
1191 $reply->object = new stdClass;
1192 $reply->object->objectType = $post->object->inReplyTo->objectType;
1193 $reply->object->content = $post->object->inReplyTo->content;
1194 $reply->object->id = $post->object->inReplyTo->id;
1195 $reply->actor = $post->object->inReplyTo->author;
1196 $reply->url = $post->object->inReplyTo->url;
1197 $reply->generator = new stdClass;
1198 $reply->generator->displayName = "pumpio";
1199 $reply->published = $post->object->inReplyTo->published;
1200 $reply->received = $post->object->inReplyTo->updated;
1201 $reply->url = $post->object->inReplyTo->url;
1202 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1204 $postarray['thr-parent'] = $post->object->inReplyTo->id;
1207 // When there is no content there is no need to continue
1208 if (empty($post->object->content)) {
1212 if (!empty($post->object->pump_io->proxyURL)) {
1213 $postarray['extid'] = $post->object->pump_io->proxyURL;
1216 $postarray['contact-id'] = $contact_id;
1217 $postarray['verb'] = Activity::POST;
1218 $postarray['owner-name'] = $post->actor->displayName;
1219 $postarray['owner-link'] = $post->actor->url;
1220 $postarray['author-name'] = $postarray['owner-name'];
1221 $postarray['author-link'] = $postarray['owner-link'];
1222 if (!empty($post->actor->image)) {
1223 $postarray['owner-avatar'] = $post->actor->image->url;
1224 $postarray['author-avatar'] = $postarray['owner-avatar'];
1226 $postarray['plink'] = $post->object->url;
1227 $postarray['app'] = $post->generator->displayName;
1228 $postarray['title'] = '';
1229 $postarray['body'] = HTML::toBBCode($post->object->content);
1230 $postarray['object'] = json_encode($post);
1232 if (!empty($post->object->fullImage->url)) {
1233 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1236 if (!empty($post->object->displayName)) {
1237 $postarray['title'] = $post->object->displayName;
1240 $postarray['created'] = DateTimeFormat::utc($post->published);
1241 if (isset($post->updated)) {
1242 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1243 } elseif (isset($post->received)) {
1244 $postarray['edited'] = DateTimeFormat::utc($post->received);
1246 $postarray['edited'] = $postarray['created'];
1249 if ($post->verb == "share") {
1250 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1251 $share_author = $post->object->author->displayName;
1252 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1253 $share_author = $post->object->author->preferredUsername;
1255 $share_author = $post->object->author->url;
1258 if (isset($post->object->created)) {
1259 $created = DateTimeFormat::utc($post->object->created);
1264 $postarray['body'] = Friendica\Content\Text\BBCode::getShareOpeningTag($share_author, $post->object->author->url,
1265 $post->object->author->image->url, $post->links->self->href, $created) .
1266 $postarray['body']."[/share]";
1269 if (trim($postarray['body']) == "") {
1273 $top_item = Item::insert($postarray);
1274 $postarray["id"] = $top_item;
1276 if (($top_item == 0) && ($post->verb == "update")) {
1277 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1278 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1279 Item::update($fields, $condition);
1282 if (($post->object->objectType == "comment") && $threadcompletion) {
1283 pumpio_fetchallcomments($a, $uid, $postarray['thr-parent']);
1289 function pumpio_fetchinbox(App $a, $uid)
1291 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1292 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1293 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1294 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1295 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
1296 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1297 $username = DI::pConfig()->get($uid, "pumpio", "user");
1299 $own_id = "https://".$hostname."/".$username;
1301 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1304 $lastitems = q("SELECT `uri` FROM `post-thread-user`
1305 INNER JOIN `post-view` ON `post-view`.`id` = `post-thread-user`.`id`
1306 WHERE `post-thread-user`.`network` = '%s' AND `post-thread-user`.`uid` = %d AND `post-view`.`extid` != ''
1307 ORDER BY `post-thread-user`.`commented` DESC LIMIT 10",
1308 DBA::escape(Protocol::PUMPIO),
1312 $client = new oauth_client_class;
1313 $client->oauth_version = '1.0a';
1314 $client->authorization_header = true;
1315 $client->url_parameters = false;
1317 $client->client_id = $ckey;
1318 $client->client_secret = $csecret;
1319 $client->access_token = $otoken;
1320 $client->access_token_secret = $osecret;
1322 $last_id = DI::pConfig()->get($uid, 'pumpio', 'last_id');
1324 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1326 if ($last_id != "") {
1327 $url .= '?since='.urlencode($last_id);
1330 if (pumpio_reachable($url)) {
1331 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1340 if (!empty($user->items)) {
1341 $posts = array_reverse($user->items);
1343 if (count($posts)) {
1344 foreach ($posts as $post) {
1345 $last_id = $post->id;
1346 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1351 foreach ($lastitems as $item) {
1352 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1355 DI::pConfig()->set($uid, 'pumpio', 'last_id', $last_id);
1358 function pumpio_getallusers(App &$a, $uid)
1360 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1361 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1362 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1363 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1364 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1365 $username = DI::pConfig()->get($uid, "pumpio", "user");
1367 $client = new oauth_client_class;
1368 $client->oauth_version = '1.0a';
1369 $client->authorization_header = true;
1370 $client->url_parameters = false;
1372 $client->client_id = $ckey;
1373 $client->client_secret = $csecret;
1374 $client->access_token = $otoken;
1375 $client->access_token_secret = $osecret;
1377 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1379 if (pumpio_reachable($url)) {
1380 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1385 if (empty($users)) {
1389 if ($users->totalItems > count($users->items)) {
1390 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1392 if (pumpio_reachable($url)) {
1393 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1399 if (!empty($users->items)) {
1400 foreach ($users->items as $user) {
1401 pumpio_get_contact($uid, $user);
1406 function pumpio_getreceiver(App $a, array $b)
1410 if (!$b["private"]) {
1411 if (!strstr($b['postopts'], 'pumpio')) {
1415 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
1418 $receiver["to"][] = [
1419 "objectType" => "collection",
1420 "id" => "http://activityschema.org/collection/public"];
1423 $cids = explode("><", $b["allow_cid"]);
1424 $gids = explode("><", $b["allow_gid"]);
1426 foreach ($cids AS $cid) {
1427 $cid = trim($cid, " <>");
1429 $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",
1432 DBA::escape(Protocol::PUMPIO)
1435 if (DBA::isResult($r)) {
1436 $receiver["bcc"][] = [
1437 "displayName" => $r[0]["name"],
1438 "objectType" => "person",
1439 "preferredUsername" => $r[0]["nick"],
1440 "url" => $r[0]["url"]];
1443 foreach ($gids AS $gid) {
1444 $gid = trim($gid, " <>");
1446 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1447 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1448 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1450 DBA::escape(Protocol::PUMPIO)
1453 foreach ($r AS $row)
1454 $receiver["bcc"][] = [
1455 "displayName" => $row["name"],
1456 "objectType" => "person",
1457 "preferredUsername" => $row["nick"],
1458 "url" => $row["url"]];
1462 if ($b["inform"] != "") {
1463 $inform = explode(",", $b["inform"]);
1465 foreach ($inform AS $cid) {
1466 if (substr($cid, 0, 4) != "cid:") {
1470 $cid = str_replace("cid:", "", $cid);
1472 $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",
1475 DBA::escape(Protocol::PUMPIO)
1478 if (DBA::isResult($r)) {
1479 $receiver["to"][] = [
1480 "displayName" => $r[0]["name"],
1481 "objectType" => "person",
1482 "preferredUsername" => $r[0]["nick"],
1483 "url" => $r[0]["url"]];
1491 function pumpio_fetchallcomments(App $a, $uid, $id)
1493 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1494 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1495 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1496 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1497 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1498 $username = DI::pConfig()->get($uid, "pumpio", "user");
1500 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1502 $own_id = "https://".$hostname."/".$username;
1504 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1507 // Fetching the original post
1508 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1509 $original = Post::selectFirst(['extid'], $condition);
1510 if (!DBA::isResult($original)) {
1514 $url = $original["extid"];
1516 $client = new oauth_client_class;
1517 $client->oauth_version = '1.0a';
1518 $client->authorization_header = true;
1519 $client->url_parameters = false;
1521 $client->client_id = $ckey;
1522 $client->client_secret = $csecret;
1523 $client->access_token = $otoken;
1524 $client->access_token_secret = $osecret;
1526 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1528 if (pumpio_reachable($url)) {
1529 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1538 if ($item->likes->totalItems != 0) {
1539 foreach ($item->likes->items AS $post) {
1540 $like = new stdClass;
1541 $like->object = new stdClass;
1542 $like->object->id = $item->id;
1543 $like->actor = new stdClass;
1544 if (!empty($item->displayName)) {
1545 $like->actor->displayName = $item->displayName;
1547 //$like->actor->preferredUsername = $item->preferredUsername;
1548 //$like->actor->image = $item->image;
1549 $like->actor->url = $item->url;
1550 $like->generator = new stdClass;
1551 $like->generator->displayName = "pumpio";
1552 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1556 if ($item->replies->totalItems == 0) {
1560 foreach ($item->replies->items AS $item) {
1561 if ($item->id == $id) {
1565 // Checking if the comment already exists - Two queries for speed issues
1566 if (Post::exists(['uri' => $item->id, 'uid' => $uid])) {
1570 if (Post::exists(['extid' => $item->id, 'uid' => $uid])) {
1574 $post = new stdClass;
1575 $post->verb = "post";
1576 $post->actor = $item->author;
1577 $post->published = $item->published;
1578 $post->received = $item->updated;
1579 $post->generator = new stdClass;
1580 $post->generator->displayName = "pumpio";
1581 // To-Do: Check for public post
1583 unset($item->author);
1584 unset($item->published);
1585 unset($item->updated);
1587 $post->object = $item;
1589 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1590 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1594 function pumpio_reachable($url)
1596 return DI::httpRequest()->get($url, ['timeout' => 10])->isSuccess();