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 if ($b['parent'] != $b['id']) {
440 // Looking if its a reply to a pumpio post
441 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
442 $orig_post = Post::selectFirst([], $condition);
444 if (!DBA::isResult($orig_post)) {
445 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
453 $receiver = pumpio_getreceiver($a, $b);
455 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
457 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
461 // Dont't post if the post doesn't belong to us.
462 // This is a check for forum postings
463 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
464 if ($b['contact-id'] != $self['id']) {
469 if ($b['verb'] == Activity::LIKE) {
471 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
473 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
478 if ($b['verb'] == Activity::DISLIKE) {
482 if (($b['verb'] == Activity::POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
483 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
486 if (($b['verb'] == Activity::POST) && $b['deleted']) {
487 pumpio_action($a, $b["uid"], $b["uri"], "delete");
490 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
494 // if post comes from pump.io don't send it back
495 if ($b['app'] == "pump.io") {
500 // Support for native shares
501 // http://<hostname>/api/<type>/shares?id=<the-object-id>
503 $oauth_token = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token");
504 $oauth_token_secret = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token_secret");
505 $consumer_key = DI::pConfig()->get($b['uid'], "pumpio","consumer_key");
506 $consumer_secret = DI::pConfig()->get($b['uid'], "pumpio","consumer_secret");
508 $host = DI::pConfig()->get($b['uid'], "pumpio", "host");
509 $user = DI::pConfig()->get($b['uid'], "pumpio", "user");
510 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
512 if ($oauth_token && $oauth_token_secret) {
513 $title = trim($b['title']);
515 $content = BBCode::convert($b['body'], false, BBCode::CONNECTORS);
519 $params["verb"] = "post";
522 $params["object"] = [
523 'objectType' => "note",
524 'content' => $content];
526 if (!empty($title)) {
527 $params["object"]["displayName"] = $title;
530 if (!empty($receiver["to"])) {
531 $params["to"] = $receiver["to"];
534 if (!empty($receiver["bto"])) {
535 $params["bto"] = $receiver["bto"];
538 if (!empty($receiver["cc"])) {
539 $params["cc"] = $receiver["cc"];
542 if (!empty($receiver["bcc"])) {
543 $params["bcc"] = $receiver["bcc"];
546 $inReplyTo = ["id" => $orig_post["uri"],
547 "objectType" => "note"];
549 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
550 $inReplyTo["objectType"] = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
553 $params["object"] = [
554 'objectType' => "comment",
555 'content' => $content,
556 'inReplyTo' => $inReplyTo];
559 $params["object"]["displayName"] = $title;
563 $client = new oauth_client_class;
564 $client->oauth_version = '1.0a';
565 $client->url_parameters = false;
566 $client->authorization_header = true;
567 $client->access_token = $oauth_token;
568 $client->access_token_secret = $oauth_token_secret;
569 $client->client_id = $consumer_key;
570 $client->client_secret = $consumer_secret;
572 $username = $user.'@'.$host;
573 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
575 if (pumpio_reachable($url)) {
576 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
582 if ($user->generator->displayName) {
583 DI::pConfig()->set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
586 $post_id = $user->object->id;
587 Logger::log('pumpio_send '.$username.': success '.$post_id);
588 if ($post_id && $iscomment) {
589 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
590 Item::update(['extid' => $post_id], ['id' => $b['id']]);
593 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
599 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
601 // Don't do likes and other stuff if you don't import the timeline
602 if (!DI::pConfig()->get($uid, 'pumpio', 'import')) {
606 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
607 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
608 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
609 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
610 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
611 $username = DI::pConfig()->get($uid, "pumpio", "user");
613 $orig_post = Post::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
615 if (!DBA::isResult($orig_post)) {
619 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
620 $uri = $orig_post["extid"];
622 $uri = $orig_post["uri"];
625 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
626 $objectType = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
627 } elseif (strstr($uri, "/api/comment/")) {
628 $objectType = "comment";
629 } elseif (strstr($uri, "/api/note/")) {
630 $objectType = "note";
631 } elseif (strstr($uri, "/api/image/")) {
632 $objectType = "image";
635 $params["verb"] = $action;
636 $params["object"] = ['id' => $uri,
637 "objectType" => $objectType,
638 "content" => $content];
640 $client = new oauth_client_class;
641 $client->oauth_version = '1.0a';
642 $client->authorization_header = true;
643 $client->url_parameters = false;
645 $client->client_id = $ckey;
646 $client->client_secret = $csecret;
647 $client->access_token = $otoken;
648 $client->access_token_secret = $osecret;
650 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
652 if (pumpio_reachable($url)) {
653 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
659 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
661 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri);
666 function pumpio_sync(App $a)
668 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
670 if (!DBA::isResult($r)) {
674 $last = DI::config()->get('pumpio', 'last_poll');
676 $poll_interval = intval(DI::config()->get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
679 $next = $last + ($poll_interval * 60);
680 if ($next > time()) {
681 Logger::log('pumpio: poll intervall not reached');
685 Logger::log('pumpio: cron_start');
687 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
688 if (DBA::isResult($r)) {
689 foreach ($r as $rr) {
690 Logger::log('pumpio: mirroring user '.$rr['uid']);
691 pumpio_fetchtimeline($a, $rr['uid']);
695 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
696 if ($abandon_days < 1) {
700 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
702 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
703 if (DBA::isResult($r)) {
704 foreach ($r as $rr) {
705 if ($abandon_days != 0) {
706 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
707 if (!DBA::isResult($user)) {
708 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
713 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
714 pumpio_fetchinbox($a, $rr['uid']);
716 // check for new contacts once a day
717 $last_contact_check = DI::pConfig()->get($rr['uid'], 'pumpio', 'contact_check');
718 if ($last_contact_check) {
719 $next_contact_check = $last_contact_check + 86400;
721 $next_contact_check = 0;
724 if ($next_contact_check <= time()) {
725 pumpio_getallusers($a, $rr["uid"]);
726 DI::pConfig()->set($rr['uid'], 'pumpio', 'contact_check', time());
731 Logger::log('pumpio: cron_end');
733 DI::config()->set('pumpio', 'last_poll', time());
736 function pumpio_cron(App $a, $b)
738 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
741 function pumpio_fetchtimeline(App $a, $uid)
743 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
744 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
745 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
746 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
747 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
748 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
749 $username = DI::pConfig()->get($uid, "pumpio", "user");
751 // get the application name for the pump.io app
752 // 1st try personal config, then system config and fallback to the
753 // hostname of the node if neither one is set.
754 $application_name = DI::pConfig()->get($uid, 'pumpio', 'application_name');
755 if ($application_name == "") {
756 $application_name = DI::config()->get('pumpio', 'application_name');
758 if ($application_name == "") {
759 $application_name = DI::baseUrl()->getHostname();
762 $first_time = ($lastdate == "");
764 $client = new oauth_client_class;
765 $client->oauth_version = '1.0a';
766 $client->authorization_header = true;
767 $client->url_parameters = false;
769 $client->client_id = $ckey;
770 $client->client_secret = $csecret;
771 $client->access_token = $otoken;
772 $client->access_token_secret = $osecret;
774 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
776 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);
778 $useraddr = $username.'@'.$hostname;
780 if (pumpio_reachable($url)) {
781 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
788 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
792 $posts = array_reverse($user->items);
794 $initiallastdate = $lastdate;
798 foreach ($posts as $post) {
799 if ($post->published <= $initiallastdate) {
803 if ($lastdate < $post->published) {
804 $lastdate = $post->published;
812 if (@is_array($post->cc)) {
813 $receiptians = array_merge($receiptians, $post->cc);
816 if (@is_array($post->to)) {
817 $receiptians = array_merge($receiptians, $post->to);
821 foreach ($receiptians AS $receiver) {
822 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
827 if ($public && !stristr($post->generator->displayName, $application_name)) {
828 $_SESSION["authenticated"] = true;
829 $_SESSION["uid"] = $uid;
832 $_REQUEST["api_source"] = true;
833 $_REQUEST["profile_uid"] = $uid;
834 $_REQUEST["source"] = "pump.io";
836 if (isset($post->object->id)) {
837 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
840 if ($post->object->displayName != "") {
841 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
843 $_REQUEST["title"] = "";
846 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
848 // To-Do: Picture has to be cached and stored locally
849 if ($post->object->fullImage->url != "") {
850 if ($post->object->fullImage->pump_io->proxyURL != "") {
851 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
853 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
857 Logger::log('pumpio: posting for user '.$uid);
859 require_once('mod/item.php');
862 Logger::log('pumpio: posting done - user '.$uid);
867 if ($lastdate != 0) {
868 DI::pConfig()->set($uid, 'pumpio', 'lastdate', $lastdate);
872 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
874 // Searching for the unliked post
875 // Two queries for speed issues
876 $orig_post = Post::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
877 if (!DBA::isResult($orig_post)) {
878 $orig_post = Post::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
879 if (!DBA::isResult($orig_post)) {
886 if (Strings::compareLink($post->actor->url, $own_id)) {
887 $contactid = $self[0]['id'];
889 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
890 DBA::escape(Strings::normaliseLink($post->actor->url)),
894 if (DBA::isResult($r)) {
895 $contactid = $r[0]['id'];
898 if ($contactid == 0) {
899 $contactid = $orig_post['contact-id'];
903 Item::markForDeletion(['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
905 if (DBA::isResult($r)) {
906 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
908 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
912 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
914 if (empty($post->object->id)) {
915 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
919 // Searching for the liked post
920 // Two queries for speed issues
921 $orig_post = Post::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
922 if (!DBA::isResult($orig_post)) {
923 $orig_post = Post::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
924 if (!DBA::isResult($orig_post)) {
930 if ($threadcompletion) {
931 pumpio_fetchallcomments($a, $uid, $post->object->id);
936 if (Strings::compareLink($post->actor->url, $own_id)) {
937 $contactid = $self[0]['id'];
938 $post->actor->displayName = $self[0]['name'];
939 $post->actor->url = $self[0]['url'];
940 $post->actor->image->url = $self[0]['photo'];
942 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
943 DBA::escape(Strings::normaliseLink($post->actor->url)),
947 if (DBA::isResult($r)) {
948 $contactid = $r[0]['id'];
951 if ($contactid == 0) {
952 $contactid = $orig_post['contact-id'];
956 $condition = ['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
957 if (Post::exists($condition)) {
958 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
963 $likedata['parent'] = $orig_post['id'];
964 $likedata['verb'] = Activity::LIKE;
965 $likedata['gravity'] = GRAVITY_ACTIVITY;
966 $likedata['uid'] = $uid;
967 $likedata['wall'] = 0;
968 $likedata['network'] = Protocol::PUMPIO;
969 $likedata['uri'] = Item::newURI($uid);
970 $likedata['thr-parent'] = $orig_post['uri'];
971 $likedata['contact-id'] = $contactid;
972 $likedata['app'] = $post->generator->displayName;
973 $likedata['author-name'] = $post->actor->displayName;
974 $likedata['author-link'] = $post->actor->url;
975 if (!empty($post->actor->image)) {
976 $likedata['author-avatar'] = $post->actor->image->url;
979 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
980 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
981 $post_type = DI::l10n()->t('status');
982 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
983 $likedata['object-type'] = Activity\ObjectType::NOTE;
985 $likedata['body'] = DI::l10n()->t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
987 $likedata['object'] = '<object><type>' . Activity\ObjectType::NOTE . '</type><local>1</local>' .
988 '<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>';
990 $ret = Item::insert($likedata);
992 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
995 function pumpio_get_contact($uid, $contact, $no_insert = false)
997 $cid = Contact::getIdForURL($contact->url, $uid);
1003 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1004 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1006 if (!DBA::isResult($r)) {
1007 // create contact record
1008 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1009 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1010 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1011 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1013 DBA::escape(DateTimeFormat::utcNow()),
1014 DBA::escape($contact->url),
1015 DBA::escape(Strings::normaliseLink($contact->url)),
1016 DBA::escape(str_replace("acct:", "", $contact->id)),
1018 DBA::escape($contact->id), // What is it for?
1019 DBA::escape('pump.io ' . $contact->id), // What is it for?
1020 DBA::escape($contact->displayName),
1021 DBA::escape($contact->preferredUsername),
1022 DBA::escape($contact->image->url),
1023 DBA::escape(Protocol::PUMPIO),
1024 intval(Contact::FRIEND),
1026 DBA::escape($contact->location->displayName),
1027 DBA::escape($contact->summary),
1031 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1032 DBA::escape(Strings::normaliseLink($contact->url)),
1036 if (!DBA::isResult($r)) {
1040 $contact_id = $r[0]['id'];
1042 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1044 $contact_id = $r[0]["id"];
1046 /* if (DB_UPDATE_VERSION >= "1177")
1047 q("UPDATE `contact` SET `location` = '%s',
1050 dbesc($contact->location->displayName),
1051 dbesc($contact->summary),
1057 if (!empty($contact->image->url)) {
1058 Contact::updateAvatar($contact_id, $contact->image->url);
1064 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1066 // Two queries for speed issues
1067 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1068 if (Post::exists($condition)) {
1069 Item::markForDeletion($condition);
1073 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1074 if (Post::exists($condition)) {
1075 Item::markForDeletion($condition);
1081 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1083 if (($post->verb == "like") || ($post->verb == "favorite")) {
1084 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1087 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1088 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1091 if ($post->verb == "delete") {
1092 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1095 if ($post->verb != "update") {
1096 // Two queries for speed issues
1097 if (Post::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1100 if (Post::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1105 // Only handle these three types
1106 if (!strstr("post|share|update", $post->verb)) {
1111 if (@is_array($post->cc)) {
1112 $receiptians = array_merge($receiptians, $post->cc);
1115 if (@is_array($post->to)) {
1116 $receiptians = array_merge($receiptians, $post->to);
1121 foreach ($receiptians AS $receiver) {
1122 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1128 $postarray['network'] = Protocol::PUMPIO;
1129 $postarray['uid'] = $uid;
1130 $postarray['wall'] = 0;
1131 $postarray['uri'] = $post->object->id;
1132 $postarray['object-type'] = ActivityNamespace::ACTIVITY_SCHEMA . strtolower($post->object->objectType);
1134 if ($post->object->objectType != "comment") {
1135 $contact_id = pumpio_get_contact($uid, $post->actor);
1138 $contact_id = $self[0]['id'];
1141 $postarray['thr-parent'] = $post->object->id;
1144 $postarray['private'] = 1;
1145 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1148 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1150 if (Strings::compareLink($post->actor->url, $own_id)) {
1151 $contact_id = $self[0]['id'];
1152 $post->actor->displayName = $self[0]['name'];
1153 $post->actor->url = $self[0]['url'];
1154 $post->actor->image->url = $self[0]['photo'];
1155 } elseif ($contact_id == 0) {
1156 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1157 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1158 DBA::escape(Strings::normaliseLink($post->actor->url)),
1162 if (DBA::isResult($r)) {
1163 $contact_id = $r[0]['id'];
1165 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1166 DBA::escape(Strings::normaliseLink($post->actor->url)),
1170 if (DBA::isResult($r)) {
1171 $contact_id = $r[0]['id'];
1173 $contact_id = $self[0]['id'];
1178 $reply = new stdClass;
1179 $reply->verb = "note";
1181 if (isset($post->cc)) {
1182 $reply->cc = $post->cc;
1185 if (isset($post->to)) {
1186 $reply->to = $post->to;
1189 $reply->object = new stdClass;
1190 $reply->object->objectType = $post->object->inReplyTo->objectType;
1191 $reply->object->content = $post->object->inReplyTo->content;
1192 $reply->object->id = $post->object->inReplyTo->id;
1193 $reply->actor = $post->object->inReplyTo->author;
1194 $reply->url = $post->object->inReplyTo->url;
1195 $reply->generator = new stdClass;
1196 $reply->generator->displayName = "pumpio";
1197 $reply->published = $post->object->inReplyTo->published;
1198 $reply->received = $post->object->inReplyTo->updated;
1199 $reply->url = $post->object->inReplyTo->url;
1200 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1202 $postarray['thr-parent'] = $post->object->inReplyTo->id;
1205 // When there is no content there is no need to continue
1206 if (empty($post->object->content)) {
1210 if (!empty($post->object->pump_io->proxyURL)) {
1211 $postarray['extid'] = $post->object->pump_io->proxyURL;
1214 $postarray['contact-id'] = $contact_id;
1215 $postarray['verb'] = Activity::POST;
1216 $postarray['owner-name'] = $post->actor->displayName;
1217 $postarray['owner-link'] = $post->actor->url;
1218 $postarray['author-name'] = $postarray['owner-name'];
1219 $postarray['author-link'] = $postarray['owner-link'];
1220 if (!empty($post->actor->image)) {
1221 $postarray['owner-avatar'] = $post->actor->image->url;
1222 $postarray['author-avatar'] = $postarray['owner-avatar'];
1224 $postarray['plink'] = $post->object->url;
1225 $postarray['app'] = $post->generator->displayName;
1226 $postarray['title'] = '';
1227 $postarray['body'] = HTML::toBBCode($post->object->content);
1228 $postarray['object'] = json_encode($post);
1230 if (!empty($post->object->fullImage->url)) {
1231 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1234 if (!empty($post->object->displayName)) {
1235 $postarray['title'] = $post->object->displayName;
1238 $postarray['created'] = DateTimeFormat::utc($post->published);
1239 if (isset($post->updated)) {
1240 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1241 } elseif (isset($post->received)) {
1242 $postarray['edited'] = DateTimeFormat::utc($post->received);
1244 $postarray['edited'] = $postarray['created'];
1247 if ($post->verb == "share") {
1248 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1249 $share_author = $post->object->author->displayName;
1250 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1251 $share_author = $post->object->author->preferredUsername;
1253 $share_author = $post->object->author->url;
1256 if (isset($post->object->created)) {
1257 $created = DateTimeFormat::utc($post->object->created);
1262 $postarray['body'] = Friendica\Content\Text\BBCode::getShareOpeningTag($share_author, $post->object->author->url,
1263 $post->object->author->image->url, $post->links->self->href, $created) .
1264 $postarray['body']."[/share]";
1267 if (trim($postarray['body']) == "") {
1271 $top_item = Item::insert($postarray);
1272 $postarray["id"] = $top_item;
1274 if (($top_item == 0) && ($post->verb == "update")) {
1275 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1276 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1277 Item::update($fields, $condition);
1280 if (($post->object->objectType == "comment") && $threadcompletion) {
1281 pumpio_fetchallcomments($a, $uid, $postarray['thr-parent']);
1287 function pumpio_fetchinbox(App $a, $uid)
1289 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1290 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1291 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1292 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1293 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
1294 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1295 $username = DI::pConfig()->get($uid, "pumpio", "user");
1297 $own_id = "https://".$hostname."/".$username;
1299 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1302 $lastitems = q("SELECT `uri` FROM `post-thread-user`
1303 INNER JOIN `post-view` ON `post-view`.`id` = `post-thread-user`.`iid`
1304 WHERE `post-thread-user`.`network` = '%s' AND `post-thread-user`.`uid` = %d AND `post-view`.`extid` != ''
1305 ORDER BY `post-thread-user`.`commented` DESC LIMIT 10",
1306 DBA::escape(Protocol::PUMPIO),
1310 $client = new oauth_client_class;
1311 $client->oauth_version = '1.0a';
1312 $client->authorization_header = true;
1313 $client->url_parameters = false;
1315 $client->client_id = $ckey;
1316 $client->client_secret = $csecret;
1317 $client->access_token = $otoken;
1318 $client->access_token_secret = $osecret;
1320 $last_id = DI::pConfig()->get($uid, 'pumpio', 'last_id');
1322 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1324 if ($last_id != "") {
1325 $url .= '?since='.urlencode($last_id);
1328 if (pumpio_reachable($url)) {
1329 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1338 if (!empty($user->items)) {
1339 $posts = array_reverse($user->items);
1341 if (count($posts)) {
1342 foreach ($posts as $post) {
1343 $last_id = $post->id;
1344 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1349 foreach ($lastitems as $item) {
1350 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1353 DI::pConfig()->set($uid, 'pumpio', 'last_id', $last_id);
1356 function pumpio_getallusers(App &$a, $uid)
1358 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1359 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1360 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1361 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1362 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1363 $username = DI::pConfig()->get($uid, "pumpio", "user");
1365 $client = new oauth_client_class;
1366 $client->oauth_version = '1.0a';
1367 $client->authorization_header = true;
1368 $client->url_parameters = false;
1370 $client->client_id = $ckey;
1371 $client->client_secret = $csecret;
1372 $client->access_token = $otoken;
1373 $client->access_token_secret = $osecret;
1375 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1377 if (pumpio_reachable($url)) {
1378 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1383 if (empty($users)) {
1387 if ($users->totalItems > count($users->items)) {
1388 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1390 if (pumpio_reachable($url)) {
1391 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1397 if (!empty($users->items)) {
1398 foreach ($users->items as $user) {
1399 pumpio_get_contact($uid, $user);
1404 function pumpio_getreceiver(App $a, array $b)
1408 if (!$b["private"]) {
1409 if (!strstr($b['postopts'], 'pumpio')) {
1413 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
1416 $receiver["to"][] = [
1417 "objectType" => "collection",
1418 "id" => "http://activityschema.org/collection/public"];
1421 $cids = explode("><", $b["allow_cid"]);
1422 $gids = explode("><", $b["allow_gid"]);
1424 foreach ($cids AS $cid) {
1425 $cid = trim($cid, " <>");
1427 $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",
1430 DBA::escape(Protocol::PUMPIO)
1433 if (DBA::isResult($r)) {
1434 $receiver["bcc"][] = [
1435 "displayName" => $r[0]["name"],
1436 "objectType" => "person",
1437 "preferredUsername" => $r[0]["nick"],
1438 "url" => $r[0]["url"]];
1441 foreach ($gids AS $gid) {
1442 $gid = trim($gid, " <>");
1444 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1445 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1446 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1448 DBA::escape(Protocol::PUMPIO)
1451 foreach ($r AS $row)
1452 $receiver["bcc"][] = [
1453 "displayName" => $row["name"],
1454 "objectType" => "person",
1455 "preferredUsername" => $row["nick"],
1456 "url" => $row["url"]];
1460 if ($b["inform"] != "") {
1461 $inform = explode(",", $b["inform"]);
1463 foreach ($inform AS $cid) {
1464 if (substr($cid, 0, 4) != "cid:") {
1468 $cid = str_replace("cid:", "", $cid);
1470 $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",
1473 DBA::escape(Protocol::PUMPIO)
1476 if (DBA::isResult($r)) {
1477 $receiver["to"][] = [
1478 "displayName" => $r[0]["name"],
1479 "objectType" => "person",
1480 "preferredUsername" => $r[0]["nick"],
1481 "url" => $r[0]["url"]];
1489 function pumpio_fetchallcomments(App $a, $uid, $id)
1491 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1492 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1493 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1494 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1495 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1496 $username = DI::pConfig()->get($uid, "pumpio", "user");
1498 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1500 $own_id = "https://".$hostname."/".$username;
1502 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1505 // Fetching the original post
1506 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1507 $original = Post::selectFirst(['extid'], $condition);
1508 if (!DBA::isResult($original)) {
1512 $url = $original["extid"];
1514 $client = new oauth_client_class;
1515 $client->oauth_version = '1.0a';
1516 $client->authorization_header = true;
1517 $client->url_parameters = false;
1519 $client->client_id = $ckey;
1520 $client->client_secret = $csecret;
1521 $client->access_token = $otoken;
1522 $client->access_token_secret = $osecret;
1524 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1526 if (pumpio_reachable($url)) {
1527 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1536 if ($item->likes->totalItems != 0) {
1537 foreach ($item->likes->items AS $post) {
1538 $like = new stdClass;
1539 $like->object = new stdClass;
1540 $like->object->id = $item->id;
1541 $like->actor = new stdClass;
1542 if (!empty($item->displayName)) {
1543 $like->actor->displayName = $item->displayName;
1545 //$like->actor->preferredUsername = $item->preferredUsername;
1546 //$like->actor->image = $item->image;
1547 $like->actor->url = $item->url;
1548 $like->generator = new stdClass;
1549 $like->generator->displayName = "pumpio";
1550 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1554 if ($item->replies->totalItems == 0) {
1558 foreach ($item->replies->items AS $item) {
1559 if ($item->id == $id) {
1563 // Checking if the comment already exists - Two queries for speed issues
1564 if (Post::exists(['uri' => $item->id, 'uid' => $uid])) {
1568 if (Post::exists(['extid' => $item->id, 'uid' => $uid])) {
1572 $post = new stdClass;
1573 $post->verb = "post";
1574 $post->actor = $item->author;
1575 $post->published = $item->published;
1576 $post->received = $item->updated;
1577 $post->generator = new stdClass;
1578 $post->generator->displayName = "pumpio";
1579 // To-Do: Check for public post
1581 unset($item->author);
1582 unset($item->published);
1583 unset($item->updated);
1585 $post->object = $item;
1587 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1588 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1592 function pumpio_reachable($url)
1594 return DI::httpRequest()->get($url, ['timeout' => 10])->isSuccess();