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\User;
22 use Friendica\Protocol\Activity;
23 use Friendica\Protocol\ActivityNamespace;
24 use Friendica\Util\ConfigFileLoader;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Strings;
27 use Friendica\Util\XML;
29 require 'addon/pumpio/oauth/http.php';
30 require 'addon/pumpio/oauth/oauth_client.php';
31 require_once "mod/share.php";
33 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
35 function pumpio_install()
37 Hook::register('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
38 Hook::register('hook_fork', 'addon/pumpio/pumpio.php', 'hook_fork');
39 Hook::register('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
40 Hook::register('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
41 Hook::register('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
42 Hook::register('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
43 Hook::register('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
44 Hook::register('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
45 Hook::register('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
48 function pumpio_uninstall()
50 Hook::unregister('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
51 Hook::unregister('hook_fork', 'addon/pumpio/pumpio.php', 'pumpio_hook_fork');
52 Hook::unregister('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
53 Hook::unregister('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
54 Hook::unregister('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
55 Hook::unregister('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
56 Hook::unregister('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
57 Hook::unregister('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
58 Hook::unregister('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
61 function pumpio_module() {}
63 function pumpio_content(App $a)
66 notice(DI::l10n()->t('Permission denied.') . EOL);
70 require_once("mod/settings.php");
73 if (isset($a->argv[1])) {
74 switch ($a->argv[1]) {
76 $o = pumpio_connect($a);
79 $o = print_r($a->argv, true);
83 $o = pumpio_connect($a);
88 function pumpio_check_item_notification($a, &$notification_data)
90 $hostname = DI::pConfig()->get($notification_data["uid"], 'pumpio', 'host');
91 $username = DI::pConfig()->get($notification_data["uid"], "pumpio", "user");
93 $notification_data["profiles"][] = "https://".$hostname."/".$username;
96 function pumpio_registerclient(App $a, $host)
98 $url = "https://".$host."/api/client/register";
102 $application_name = DI::config()->get('pumpio', 'application_name');
104 if ($application_name == "") {
105 $application_name = DI::baseUrl()->getHostname();
108 $adminlist = explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email')));
110 $params["type"] = "client_associate";
111 $params["contacts"] = $adminlist[0];
112 $params["application_type"] = "native";
113 $params["application_name"] = $application_name;
114 $params["logo_url"] = DI::baseUrl()->get()."/images/friendica-256.png";
115 $params["redirect_uris"] = DI::baseUrl()->get()."/pumpio/connect";
117 Logger::log("pumpio_registerclient: ".$url." parameters ".print_r($params, true), Logger::DEBUG);
119 $ch = curl_init($url);
120 curl_setopt($ch, CURLOPT_HEADER, false);
121 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
122 curl_setopt($ch, CURLOPT_POST,1);
123 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
124 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
127 $curl_info = curl_getinfo($ch);
129 if ($curl_info["http_code"] == "200") {
130 $values = json_decode($s);
131 Logger::log("pumpio_registerclient: success ".print_r($values, true), Logger::DEBUG);
134 Logger::log("pumpio_registerclient: failed: ".print_r($curl_info, true), Logger::DEBUG);
139 function pumpio_connect(App $a)
141 // Define the needed keys
142 $consumer_key = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_key');
143 $consumer_secret = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_secret');
144 $hostname = DI::pConfig()->get(local_user(), 'pumpio', 'host');
146 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
147 Logger::log("pumpio_connect: register client");
148 $clientdata = pumpio_registerclient($a, $hostname);
149 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
150 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
152 $consumer_key = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_key');
153 $consumer_secret = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_secret');
155 Logger::log("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, Logger::DEBUG);
158 if (($consumer_key == "") || ($consumer_secret == "")) {
159 Logger::log("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
161 $o .= DI::l10n()->t("Unable to register the client at the pump.io server '%s'.", $hostname);
165 // The callback URL is the script that gets called after the user authenticates with pumpio
166 $callback_url = DI::baseUrl()->get()."/pumpio/connect";
168 // Let's begin. First we need a Request Token. The request token is required to send the user
169 // to pumpio's login page.
171 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
172 // Consumer Key and Consumer Secret
173 $client = new oauth_client_class;
175 $client->server = '';
176 $client->oauth_version = '1.0a';
177 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
178 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
179 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
180 $client->url_parameters = false;
181 $client->authorization_header = true;
182 $client->redirect_uri = $callback_url;
183 $client->client_id = $consumer_key;
184 $client->client_secret = $consumer_secret;
186 if (($success = $client->Initialize())) {
187 if (($success = $client->Process())) {
188 if (strlen($client->access_token)) {
189 Logger::log("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, Logger::DEBUG);
190 DI::pConfig()->set(local_user(), "pumpio", "oauth_token", $client->access_token);
191 DI::pConfig()->set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
194 $success = $client->Finalize($success);
197 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
201 Logger::log("pumpio_connect: authenticated");
202 $o = DI::l10n()->t("You are now authenticated to pumpio.");
203 $o .= '<br /><a href="'.DI::baseUrl()->get().'/settings/connectors">'.DI::l10n()->t("return to the connector page").'</a>';
205 Logger::log("pumpio_connect: could not connect");
206 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
212 function pumpio_jot_nets(App $a, array &$jotnets_fields)
214 if (! local_user()) {
218 if (DI::pConfig()->get(local_user(), 'pumpio', 'post')) {
219 $jotnets_fields[] = [
220 'type' => 'checkbox',
223 DI::l10n()->t('Post to pumpio'),
224 DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default')
230 function pumpio_settings(App $a, &$s)
236 /* Add our stylesheet to the page so we can make our settings look nice */
238 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
240 /* Get the current state of our config variables */
242 $import_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'import');
243 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
245 $enabled = DI::pConfig()->get(local_user(), 'pumpio', 'post');
246 $checked = (($enabled) ? ' checked="checked" ' : '');
247 $css = (($enabled) ? '' : '-disabled');
249 $def_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default');
250 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
252 $public_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'public');
253 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
255 $mirror_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'mirror');
256 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
258 $servername = DI::pConfig()->get(local_user(), "pumpio", "host");
259 $username = DI::pConfig()->get(local_user(), "pumpio", "user");
261 /* Add some HTML to the existing form */
263 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
264 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. DI::l10n()->t('Pump.io Import/Export/Mirror').'</h3>';
266 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
267 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
268 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. DI::l10n()->t('Pump.io Import/Export/Mirror').'</h3>';
271 $s .= '<div id="pumpio-username-wrapper">';
272 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.DI::l10n()->t('pump.io username (without the servername)').'</label>';
273 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
274 $s .= '</div><div class="clear"></div>';
276 $s .= '<div id="pumpio-servername-wrapper">';
277 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.DI::l10n()->t('pump.io servername (without "http://" or "https://" )').'</label>';
278 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
279 $s .= '</div><div class="clear"></div>';
281 if (($username != '') && ($servername != '')) {
282 $oauth_token = DI::pConfig()->get(local_user(), "pumpio", "oauth_token");
283 $oauth_token_secret = DI::pConfig()->get(local_user(), "pumpio", "oauth_token_secret");
285 $s .= '<div id="pumpio-password-wrapper">';
286 if (($oauth_token == "") || ($oauth_token_secret == "")) {
287 $s .= '<div id="pumpio-authenticate-wrapper">';
288 $s .= '<a href="'.DI::baseUrl()->get().'/pumpio/connect">'.DI::l10n()->t("Authenticate your pump.io connection").'</a>';
289 $s .= '</div><div class="clear"></div>';
291 $s .= '<div id="pumpio-import-wrapper">';
292 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . DI::l10n()->t('Import the remote timeline') . '</label>';
293 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
294 $s .= '</div><div class="clear"></div>';
296 $s .= '<div id="pumpio-enable-wrapper">';
297 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . DI::l10n()->t('Enable pump.io Post Addon') . '</label>';
298 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
299 $s .= '</div><div class="clear"></div>';
301 $s .= '<div id="pumpio-bydefault-wrapper">';
302 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . DI::l10n()->t('Post to pump.io by default') . '</label>';
303 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
304 $s .= '</div><div class="clear"></div>';
306 $s .= '<div id="pumpio-public-wrapper">';
307 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . DI::l10n()->t('Should posts be public?') . '</label>';
308 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
309 $s .= '</div><div class="clear"></div>';
311 $s .= '<div id="pumpio-mirror-wrapper">';
312 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . DI::l10n()->t('Mirror all public posts') . '</label>';
313 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
314 $s .= '</div><div class="clear"></div>';
316 $s .= '<div id="pumpio-delete-wrapper">';
317 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . DI::l10n()->t('Check to delete this preset') . '</label>';
318 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
319 $s .= '</div><div class="clear"></div>';
322 $s .= '</div><div class="clear"></div>';
325 /* provide a submit button */
327 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div></div>';
330 function pumpio_settings_post(App $a, array &$b)
332 if (!empty($_POST['pumpio-submit'])) {
333 if (!empty($_POST['pumpio_delete'])) {
334 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_key' , '');
335 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_secret' , '');
336 DI::pConfig()->set(local_user(), 'pumpio', 'oauth_token' , '');
337 DI::pConfig()->set(local_user(), 'pumpio', 'oauth_token_secret', '');
338 DI::pConfig()->set(local_user(), 'pumpio', 'post' , false);
339 DI::pConfig()->set(local_user(), 'pumpio', 'import' , false);
340 DI::pConfig()->set(local_user(), 'pumpio', 'host' , '');
341 DI::pConfig()->set(local_user(), 'pumpio', 'user' , '');
342 DI::pConfig()->set(local_user(), 'pumpio', 'public' , false);
343 DI::pConfig()->set(local_user(), 'pumpio', 'mirror' , false);
344 DI::pConfig()->set(local_user(), 'pumpio', 'post_by_default' , false);
345 DI::pConfig()->set(local_user(), 'pumpio', 'lastdate' , 0);
346 DI::pConfig()->set(local_user(), 'pumpio', 'last_id' , '');
348 // filtering the username if it is filled wrong
349 $user = $_POST['pumpio_user'];
350 if (strstr($user, "@")) {
351 $pos = strpos($user, "@");
354 $user = substr($user, 0, $pos);
358 // Filtering the hostname if someone is entering it with "http"
359 $host = $_POST['pumpio_host'];
361 $host = str_replace(["https://", "http://"], ["", ""], $host);
363 DI::pConfig()->set(local_user(), 'pumpio', 'post' , $_POST['pumpio'] ?? false);
364 DI::pConfig()->set(local_user(), 'pumpio', 'import' , $_POST['pumpio_import'] ?? false);
365 DI::pConfig()->set(local_user(), 'pumpio', 'host' , $host);
366 DI::pConfig()->set(local_user(), 'pumpio', 'user' , $user);
367 DI::pConfig()->set(local_user(), 'pumpio', 'public' , $_POST['pumpio_public'] ?? false);
368 DI::pConfig()->set(local_user(), 'pumpio', 'mirror' , $_POST['pumpio_mirror'] ?? false);
369 DI::pConfig()->set(local_user(), 'pumpio', 'post_by_default', $_POST['pumpio_bydefault'] ?? false);
371 if (!empty($_POST['pumpio_mirror'])) {
372 DI::pConfig()->delete(local_user(), 'pumpio', 'lastdate');
378 function pumpio_load_config(App $a, ConfigFileLoader $loader)
380 $a->getConfigCache()->load($loader->loadAddonConfig('pumpio'));
383 function pumpio_hook_fork(App $a, array &$b)
385 if ($b['name'] != 'notifier_normal') {
391 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
392 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
393 $b['execute'] = false;
397 // if post comes from pump.io don't send it back
398 if ($post['app'] == "pump.io") {
399 $b['execute'] = false;
403 if (DI::pConfig()->get($post['uid'], 'pumpio', 'import')) {
404 // Don't fork if it isn't a reply to a pump.io post
405 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::PUMPIO])) {
406 Logger::log('No pump.io parent found for item ' . $post['id']);
407 $b['execute'] = false;
411 // Comments are never exported when we don't import the pumpio timeline
412 if (!strstr($post['postopts'], 'pumpio') || ($post['parent'] != $post['id']) || $post['private']) {
413 $b['execute'] = false;
419 function pumpio_post_local(App $a, array &$b)
421 if (!local_user() || (local_user() != $b['uid'])) {
425 $pumpio_post = intval(DI::pConfig()->get(local_user(), 'pumpio', 'post'));
427 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
429 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default'))) {
433 if (!$pumpio_enable) {
437 if (strlen($b['postopts'])) {
438 $b['postopts'] .= ',';
441 $b['postopts'] .= 'pumpio';
444 function pumpio_send(App $a, array &$b)
446 if (!DI::pConfig()->get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
450 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
452 if ($b['parent'] != $b['id']) {
453 // Looking if its a reply to a pumpio post
454 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
455 $orig_post = Item::selectFirst([], $condition);
457 if (!DBA::isResult($orig_post)) {
458 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
466 $receiver = pumpio_getreceiver($a, $b);
468 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
470 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
474 // Dont't post if the post doesn't belong to us.
475 // This is a check for forum postings
476 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
477 if ($b['contact-id'] != $self['id']) {
482 if ($b['verb'] == Activity::LIKE) {
484 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
486 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
491 if ($b['verb'] == Activity::DISLIKE) {
495 if (($b['verb'] == Activity::POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
496 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
499 if (($b['verb'] == Activity::POST) && $b['deleted']) {
500 pumpio_action($a, $b["uid"], $b["uri"], "delete");
503 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
507 // if post comes from pump.io don't send it back
508 if ($b['app'] == "pump.io") {
513 // Support for native shares
514 // http://<hostname>/api/<type>/shares?id=<the-object-id>
516 $oauth_token = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token");
517 $oauth_token_secret = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token_secret");
518 $consumer_key = DI::pConfig()->get($b['uid'], "pumpio","consumer_key");
519 $consumer_secret = DI::pConfig()->get($b['uid'], "pumpio","consumer_secret");
521 $host = DI::pConfig()->get($b['uid'], "pumpio", "host");
522 $user = DI::pConfig()->get($b['uid'], "pumpio", "user");
523 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
525 if ($oauth_token && $oauth_token_secret) {
526 $title = trim($b['title']);
528 $content = BBCode::convert($b['body'], false, BBCode::CONNECTORS);
532 $params["verb"] = "post";
535 $params["object"] = [
536 'objectType' => "note",
537 'content' => $content];
539 if (!empty($title)) {
540 $params["object"]["displayName"] = $title;
543 if (!empty($receiver["to"])) {
544 $params["to"] = $receiver["to"];
547 if (!empty($receiver["bto"])) {
548 $params["bto"] = $receiver["bto"];
551 if (!empty($receiver["cc"])) {
552 $params["cc"] = $receiver["cc"];
555 if (!empty($receiver["bcc"])) {
556 $params["bcc"] = $receiver["bcc"];
559 $inReplyTo = ["id" => $orig_post["uri"],
560 "objectType" => "note"];
562 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
563 $inReplyTo["objectType"] = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
566 $params["object"] = [
567 'objectType' => "comment",
568 'content' => $content,
569 'inReplyTo' => $inReplyTo];
572 $params["object"]["displayName"] = $title;
576 $client = new oauth_client_class;
577 $client->oauth_version = '1.0a';
578 $client->url_parameters = false;
579 $client->authorization_header = true;
580 $client->access_token = $oauth_token;
581 $client->access_token_secret = $oauth_token_secret;
582 $client->client_id = $consumer_key;
583 $client->client_secret = $consumer_secret;
585 $username = $user.'@'.$host;
586 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
588 if (pumpio_reachable($url)) {
589 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
595 if ($user->generator->displayName) {
596 DI::pConfig()->set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
599 $post_id = $user->object->id;
600 Logger::log('pumpio_send '.$username.': success '.$post_id);
601 if ($post_id && $iscomment) {
602 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
603 Item::update(['extid' => $post_id], ['id' => $b['id']]);
606 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
612 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
614 // Don't do likes and other stuff if you don't import the timeline
615 if (!DI::pConfig()->get($uid, 'pumpio', 'import')) {
619 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
620 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
621 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
622 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
623 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
624 $username = DI::pConfig()->get($uid, "pumpio", "user");
626 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
628 if (!DBA::isResult($orig_post)) {
632 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
633 $uri = $orig_post["extid"];
635 $uri = $orig_post["uri"];
638 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
639 $objectType = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
640 } elseif (strstr($uri, "/api/comment/")) {
641 $objectType = "comment";
642 } elseif (strstr($uri, "/api/note/")) {
643 $objectType = "note";
644 } elseif (strstr($uri, "/api/image/")) {
645 $objectType = "image";
648 $params["verb"] = $action;
649 $params["object"] = ['id' => $uri,
650 "objectType" => $objectType,
651 "content" => $content];
653 $client = new oauth_client_class;
654 $client->oauth_version = '1.0a';
655 $client->authorization_header = true;
656 $client->url_parameters = false;
658 $client->client_id = $ckey;
659 $client->client_secret = $csecret;
660 $client->access_token = $otoken;
661 $client->access_token_secret = $osecret;
663 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
665 if (pumpio_reachable($url)) {
666 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
672 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
674 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri);
679 function pumpio_sync(App $a)
681 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
683 if (!DBA::isResult($r)) {
687 $last = DI::config()->get('pumpio', 'last_poll');
689 $poll_interval = intval(DI::config()->get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
692 $next = $last + ($poll_interval * 60);
693 if ($next > time()) {
694 Logger::log('pumpio: poll intervall not reached');
698 Logger::log('pumpio: cron_start');
700 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
701 if (DBA::isResult($r)) {
702 foreach ($r as $rr) {
703 Logger::log('pumpio: mirroring user '.$rr['uid']);
704 pumpio_fetchtimeline($a, $rr['uid']);
708 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
709 if ($abandon_days < 1) {
713 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
715 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
716 if (DBA::isResult($r)) {
717 foreach ($r as $rr) {
718 if ($abandon_days != 0) {
719 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
720 if (!DBA::isResult($user)) {
721 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
726 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
727 pumpio_fetchinbox($a, $rr['uid']);
729 // check for new contacts once a day
730 $last_contact_check = DI::pConfig()->get($rr['uid'], 'pumpio', 'contact_check');
731 if ($last_contact_check) {
732 $next_contact_check = $last_contact_check + 86400;
734 $next_contact_check = 0;
737 if ($next_contact_check <= time()) {
738 pumpio_getallusers($a, $rr["uid"]);
739 DI::pConfig()->set($rr['uid'], 'pumpio', 'contact_check', time());
744 Logger::log('pumpio: cron_end');
746 DI::config()->set('pumpio', 'last_poll', time());
749 function pumpio_cron(App $a, $b)
751 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
754 function pumpio_fetchtimeline(App $a, $uid)
756 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
757 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
758 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
759 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
760 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
761 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
762 $username = DI::pConfig()->get($uid, "pumpio", "user");
764 // get the application name for the pump.io app
765 // 1st try personal config, then system config and fallback to the
766 // hostname of the node if neither one is set.
767 $application_name = DI::pConfig()->get($uid, 'pumpio', 'application_name');
768 if ($application_name == "") {
769 $application_name = DI::config()->get('pumpio', 'application_name');
771 if ($application_name == "") {
772 $application_name = DI::baseUrl()->getHostname();
775 $first_time = ($lastdate == "");
777 $client = new oauth_client_class;
778 $client->oauth_version = '1.0a';
779 $client->authorization_header = true;
780 $client->url_parameters = false;
782 $client->client_id = $ckey;
783 $client->client_secret = $csecret;
784 $client->access_token = $otoken;
785 $client->access_token_secret = $osecret;
787 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
789 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);
791 $useraddr = $username.'@'.$hostname;
793 if (pumpio_reachable($url)) {
794 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
801 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
805 $posts = array_reverse($user->items);
807 $initiallastdate = $lastdate;
811 foreach ($posts as $post) {
812 if ($post->published <= $initiallastdate) {
816 if ($lastdate < $post->published) {
817 $lastdate = $post->published;
825 if (@is_array($post->cc)) {
826 $receiptians = array_merge($receiptians, $post->cc);
829 if (@is_array($post->to)) {
830 $receiptians = array_merge($receiptians, $post->to);
834 foreach ($receiptians AS $receiver) {
835 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
840 if ($public && !stristr($post->generator->displayName, $application_name)) {
841 $_SESSION["authenticated"] = true;
842 $_SESSION["uid"] = $uid;
845 $_REQUEST["api_source"] = true;
846 $_REQUEST["profile_uid"] = $uid;
847 $_REQUEST["source"] = "pump.io";
849 if (isset($post->object->id)) {
850 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
853 if ($post->object->displayName != "") {
854 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
856 $_REQUEST["title"] = "";
859 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
861 // To-Do: Picture has to be cached and stored locally
862 if ($post->object->fullImage->url != "") {
863 if ($post->object->fullImage->pump_io->proxyURL != "") {
864 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
866 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
870 Logger::log('pumpio: posting for user '.$uid);
872 require_once('mod/item.php');
875 Logger::log('pumpio: posting done - user '.$uid);
880 if ($lastdate != 0) {
881 DI::pConfig()->set($uid, 'pumpio', 'lastdate', $lastdate);
885 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
887 // Searching for the unliked post
888 // Two queries for speed issues
889 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
890 if (!DBA::isResult($orig_post)) {
891 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
892 if (!DBA::isResult($orig_post)) {
899 if (Strings::compareLink($post->actor->url, $own_id)) {
900 $contactid = $self[0]['id'];
902 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
903 DBA::escape(Strings::normaliseLink($post->actor->url)),
907 if (DBA::isResult($r)) {
908 $contactid = $r[0]['id'];
911 if ($contactid == 0) {
912 $contactid = $orig_post['contact-id'];
916 Item::markForDeletion(['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
918 if (DBA::isResult($r)) {
919 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
921 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
925 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
927 if (empty($post->object->id)) {
928 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
932 // Searching for the liked post
933 // Two queries for speed issues
934 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
935 if (!DBA::isResult($orig_post)) {
936 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
937 if (!DBA::isResult($orig_post)) {
943 if ($threadcompletion) {
944 pumpio_fetchallcomments($a, $uid, $post->object->id);
949 if (Strings::compareLink($post->actor->url, $own_id)) {
950 $contactid = $self[0]['id'];
951 $post->actor->displayName = $self[0]['name'];
952 $post->actor->url = $self[0]['url'];
953 $post->actor->image->url = $self[0]['photo'];
955 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
956 DBA::escape(Strings::normaliseLink($post->actor->url)),
960 if (DBA::isResult($r)) {
961 $contactid = $r[0]['id'];
964 if ($contactid == 0) {
965 $contactid = $orig_post['contact-id'];
969 $condition = ['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
970 if (Item::exists($condition)) {
971 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
976 $likedata['parent'] = $orig_post['id'];
977 $likedata['verb'] = Activity::LIKE;
978 $likedata['gravity'] = GRAVITY_ACTIVITY;
979 $likedata['uid'] = $uid;
980 $likedata['wall'] = 0;
981 $likedata['network'] = Protocol::PUMPIO;
982 $likedata['uri'] = Item::newURI($uid);
983 $likedata['parent-uri'] = $orig_post["uri"];
984 $likedata['contact-id'] = $contactid;
985 $likedata['app'] = $post->generator->displayName;
986 $likedata['author-name'] = $post->actor->displayName;
987 $likedata['author-link'] = $post->actor->url;
988 if (!empty($post->actor->image)) {
989 $likedata['author-avatar'] = $post->actor->image->url;
992 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
993 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
994 $post_type = DI::l10n()->t('status');
995 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
996 $likedata['object-type'] = Activity\ObjectType::NOTE;
998 $likedata['body'] = DI::l10n()->t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
1000 $likedata['object'] = '<object><type>' . Activity\ObjectType::NOTE . '</type><local>1</local>' .
1001 '<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>';
1003 $ret = Item::insert($likedata);
1005 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
1008 function pumpio_get_contact($uid, $contact, $no_insert = false)
1010 $cid = Contact::getIdForURL($contact->url, $uid);
1016 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1017 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1019 if (!DBA::isResult($r)) {
1020 // create contact record
1021 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1022 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1023 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1024 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1026 DBA::escape(DateTimeFormat::utcNow()),
1027 DBA::escape($contact->url),
1028 DBA::escape(Strings::normaliseLink($contact->url)),
1029 DBA::escape(str_replace("acct:", "", $contact->id)),
1031 DBA::escape($contact->id), // What is it for?
1032 DBA::escape('pump.io ' . $contact->id), // What is it for?
1033 DBA::escape($contact->displayName),
1034 DBA::escape($contact->preferredUsername),
1035 DBA::escape($contact->image->url),
1036 DBA::escape(Protocol::PUMPIO),
1037 intval(Contact::FRIEND),
1039 DBA::escape($contact->location->displayName),
1040 DBA::escape($contact->summary),
1044 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1045 DBA::escape(Strings::normaliseLink($contact->url)),
1049 if (!DBA::isResult($r)) {
1053 $contact_id = $r[0]['id'];
1055 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1057 $contact_id = $r[0]["id"];
1059 /* if (DB_UPDATE_VERSION >= "1177")
1060 q("UPDATE `contact` SET `location` = '%s',
1063 dbesc($contact->location->displayName),
1064 dbesc($contact->summary),
1070 if (!empty($contact->image->url)) {
1071 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1077 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1079 // Two queries for speed issues
1080 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1081 if (Item::exists($condition)) {
1082 Item::markForDeletion($condition);
1086 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1087 if (Item::exists($condition)) {
1088 Item::markForDeletion($condition);
1094 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1096 if (($post->verb == "like") || ($post->verb == "favorite")) {
1097 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1100 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1101 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1104 if ($post->verb == "delete") {
1105 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1108 if ($post->verb != "update") {
1109 // Two queries for speed issues
1110 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1113 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1118 // Only handle these three types
1119 if (!strstr("post|share|update", $post->verb)) {
1124 if (@is_array($post->cc)) {
1125 $receiptians = array_merge($receiptians, $post->cc);
1128 if (@is_array($post->to)) {
1129 $receiptians = array_merge($receiptians, $post->to);
1134 foreach ($receiptians AS $receiver) {
1135 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1141 $postarray['network'] = Protocol::PUMPIO;
1142 $postarray['uid'] = $uid;
1143 $postarray['wall'] = 0;
1144 $postarray['uri'] = $post->object->id;
1145 $postarray['object-type'] = ActivityNamespace::ACTIVITY_SCHEMA . strtolower($post->object->objectType);
1147 if ($post->object->objectType != "comment") {
1148 $contact_id = pumpio_get_contact($uid, $post->actor);
1151 $contact_id = $self[0]['id'];
1154 $postarray['parent-uri'] = $post->object->id;
1157 $postarray['private'] = 1;
1158 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1161 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1163 if (Strings::compareLink($post->actor->url, $own_id)) {
1164 $contact_id = $self[0]['id'];
1165 $post->actor->displayName = $self[0]['name'];
1166 $post->actor->url = $self[0]['url'];
1167 $post->actor->image->url = $self[0]['photo'];
1168 } elseif ($contact_id == 0) {
1169 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1170 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1171 DBA::escape(Strings::normaliseLink($post->actor->url)),
1175 if (DBA::isResult($r)) {
1176 $contact_id = $r[0]['id'];
1178 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1179 DBA::escape(Strings::normaliseLink($post->actor->url)),
1183 if (DBA::isResult($r)) {
1184 $contact_id = $r[0]['id'];
1186 $contact_id = $self[0]['id'];
1191 $reply = new stdClass;
1192 $reply->verb = "note";
1194 if (isset($post->cc)) {
1195 $reply->cc = $post->cc;
1198 if (isset($post->to)) {
1199 $reply->to = $post->to;
1202 $reply->object = new stdClass;
1203 $reply->object->objectType = $post->object->inReplyTo->objectType;
1204 $reply->object->content = $post->object->inReplyTo->content;
1205 $reply->object->id = $post->object->inReplyTo->id;
1206 $reply->actor = $post->object->inReplyTo->author;
1207 $reply->url = $post->object->inReplyTo->url;
1208 $reply->generator = new stdClass;
1209 $reply->generator->displayName = "pumpio";
1210 $reply->published = $post->object->inReplyTo->published;
1211 $reply->received = $post->object->inReplyTo->updated;
1212 $reply->url = $post->object->inReplyTo->url;
1213 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1215 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1218 // When there is no content there is no need to continue
1219 if (empty($post->object->content)) {
1223 if (!empty($post->object->pump_io->proxyURL)) {
1224 $postarray['extid'] = $post->object->pump_io->proxyURL;
1227 $postarray['contact-id'] = $contact_id;
1228 $postarray['verb'] = Activity::POST;
1229 $postarray['owner-name'] = $post->actor->displayName;
1230 $postarray['owner-link'] = $post->actor->url;
1231 $postarray['author-name'] = $postarray['owner-name'];
1232 $postarray['author-link'] = $postarray['owner-link'];
1233 if (!empty($post->actor->image)) {
1234 $postarray['owner-avatar'] = $post->actor->image->url;
1235 $postarray['author-avatar'] = $postarray['owner-avatar'];
1237 $postarray['plink'] = $post->object->url;
1238 $postarray['app'] = $post->generator->displayName;
1239 $postarray['title'] = '';
1240 $postarray['body'] = HTML::toBBCode($post->object->content);
1241 $postarray['object'] = json_encode($post);
1243 if (!empty($post->object->fullImage->url)) {
1244 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1247 if (!empty($post->object->displayName)) {
1248 $postarray['title'] = $post->object->displayName;
1251 $postarray['created'] = DateTimeFormat::utc($post->published);
1252 if (isset($post->updated)) {
1253 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1254 } elseif (isset($post->received)) {
1255 $postarray['edited'] = DateTimeFormat::utc($post->received);
1257 $postarray['edited'] = $postarray['created'];
1260 if ($post->verb == "share") {
1261 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1262 $share_author = $post->object->author->displayName;
1263 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1264 $share_author = $post->object->author->preferredUsername;
1266 $share_author = $post->object->author->url;
1269 if (isset($post->object->created)) {
1270 $created = DateTimeFormat::utc($post->object->created);
1275 $postarray['body'] = Friendica\Content\Text\BBCode::getShareOpeningTag($share_author, $post->object->author->url,
1276 $post->object->author->image->url, $post->links->self->href, $created) .
1277 $postarray['body']."[/share]";
1280 if (trim($postarray['body']) == "") {
1284 $top_item = Item::insert($postarray);
1285 $postarray["id"] = $top_item;
1287 if (($top_item == 0) && ($post->verb == "update")) {
1288 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1289 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1290 Item::update($fields, $condition);
1293 if (($post->object->objectType == "comment") && $threadcompletion) {
1294 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1300 function pumpio_fetchinbox(App $a, $uid)
1302 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1303 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1304 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1305 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1306 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
1307 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1308 $username = DI::pConfig()->get($uid, "pumpio", "user");
1310 $own_id = "https://".$hostname."/".$username;
1312 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1315 $lastitems = q("SELECT `uri` FROM `thread`
1316 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1317 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1318 ORDER BY `thread`.`commented` DESC LIMIT 10",
1319 DBA::escape(Protocol::PUMPIO),
1323 $client = new oauth_client_class;
1324 $client->oauth_version = '1.0a';
1325 $client->authorization_header = true;
1326 $client->url_parameters = false;
1328 $client->client_id = $ckey;
1329 $client->client_secret = $csecret;
1330 $client->access_token = $otoken;
1331 $client->access_token_secret = $osecret;
1333 $last_id = DI::pConfig()->get($uid, 'pumpio', 'last_id');
1335 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1337 if ($last_id != "") {
1338 $url .= '?since='.urlencode($last_id);
1341 if (pumpio_reachable($url)) {
1342 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1351 if (!empty($user->items)) {
1352 $posts = array_reverse($user->items);
1354 if (count($posts)) {
1355 foreach ($posts as $post) {
1356 $last_id = $post->id;
1357 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1362 foreach ($lastitems as $item) {
1363 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1366 DI::pConfig()->set($uid, 'pumpio', 'last_id', $last_id);
1369 function pumpio_getallusers(App &$a, $uid)
1371 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1372 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1373 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1374 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1375 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1376 $username = DI::pConfig()->get($uid, "pumpio", "user");
1378 $client = new oauth_client_class;
1379 $client->oauth_version = '1.0a';
1380 $client->authorization_header = true;
1381 $client->url_parameters = false;
1383 $client->client_id = $ckey;
1384 $client->client_secret = $csecret;
1385 $client->access_token = $otoken;
1386 $client->access_token_secret = $osecret;
1388 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1390 if (pumpio_reachable($url)) {
1391 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1396 if (empty($users)) {
1400 if ($users->totalItems > count($users->items)) {
1401 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1403 if (pumpio_reachable($url)) {
1404 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1410 if (!empty($users->items)) {
1411 foreach ($users->items as $user) {
1412 pumpio_get_contact($uid, $user);
1417 function pumpio_getreceiver(App $a, array $b)
1421 if (!$b["private"]) {
1422 if (!strstr($b['postopts'], 'pumpio')) {
1426 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
1429 $receiver["to"][] = [
1430 "objectType" => "collection",
1431 "id" => "http://activityschema.org/collection/public"];
1434 $cids = explode("><", $b["allow_cid"]);
1435 $gids = explode("><", $b["allow_gid"]);
1437 foreach ($cids AS $cid) {
1438 $cid = trim($cid, " <>");
1440 $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",
1443 DBA::escape(Protocol::PUMPIO)
1446 if (DBA::isResult($r)) {
1447 $receiver["bcc"][] = [
1448 "displayName" => $r[0]["name"],
1449 "objectType" => "person",
1450 "preferredUsername" => $r[0]["nick"],
1451 "url" => $r[0]["url"]];
1454 foreach ($gids AS $gid) {
1455 $gid = trim($gid, " <>");
1457 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1458 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1459 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1461 DBA::escape(Protocol::PUMPIO)
1464 foreach ($r AS $row)
1465 $receiver["bcc"][] = [
1466 "displayName" => $row["name"],
1467 "objectType" => "person",
1468 "preferredUsername" => $row["nick"],
1469 "url" => $row["url"]];
1473 if ($b["inform"] != "") {
1474 $inform = explode(",", $b["inform"]);
1476 foreach ($inform AS $cid) {
1477 if (substr($cid, 0, 4) != "cid:") {
1481 $cid = str_replace("cid:", "", $cid);
1483 $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",
1486 DBA::escape(Protocol::PUMPIO)
1489 if (DBA::isResult($r)) {
1490 $receiver["to"][] = [
1491 "displayName" => $r[0]["name"],
1492 "objectType" => "person",
1493 "preferredUsername" => $r[0]["nick"],
1494 "url" => $r[0]["url"]];
1502 function pumpio_fetchallcomments(App $a, $uid, $id)
1504 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1505 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1506 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1507 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1508 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1509 $username = DI::pConfig()->get($uid, "pumpio", "user");
1511 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1513 $own_id = "https://".$hostname."/".$username;
1515 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1518 // Fetching the original post
1519 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1520 $item = Item::selectFirst(['extid'], $condition);
1521 if (!DBA::isResult($item)) {
1525 $url = $item["extid"];
1527 $client = new oauth_client_class;
1528 $client->oauth_version = '1.0a';
1529 $client->authorization_header = true;
1530 $client->url_parameters = false;
1532 $client->client_id = $ckey;
1533 $client->client_secret = $csecret;
1534 $client->access_token = $otoken;
1535 $client->access_token_secret = $osecret;
1537 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1539 if (pumpio_reachable($url)) {
1540 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1549 if ($item->likes->totalItems != 0) {
1550 foreach ($item->likes->items AS $post) {
1551 $like = new stdClass;
1552 $like->object = new stdClass;
1553 $like->object->id = $item->id;
1554 $like->actor = new stdClass;
1555 if (!empty($item->displayName)) {
1556 $like->actor->displayName = $item->displayName;
1558 //$like->actor->preferredUsername = $item->preferredUsername;
1559 //$like->actor->image = $item->image;
1560 $like->actor->url = $item->url;
1561 $like->generator = new stdClass;
1562 $like->generator->displayName = "pumpio";
1563 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1567 if ($item->replies->totalItems == 0) {
1571 foreach ($item->replies->items AS $item) {
1572 if ($item->id == $id) {
1576 // Checking if the comment already exists - Two queries for speed issues
1577 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1581 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1585 $post = new stdClass;
1586 $post->verb = "post";
1587 $post->actor = $item->author;
1588 $post->published = $item->published;
1589 $post->received = $item->updated;
1590 $post->generator = new stdClass;
1591 $post->generator->displayName = "pumpio";
1592 // To-Do: Check for public post
1594 unset($item->author);
1595 unset($item->published);
1596 unset($item->updated);
1598 $post->object = $item;
1600 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1601 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1605 function pumpio_reachable($url)
1607 return DI::httpRequest()->curl($url, false, ['timeout' => 10])->isSuccess();