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\Network;
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_uninstall()
51 Hook::unregister('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
52 Hook::unregister('hook_fork', 'addon/pumpio/pumpio.php', 'pumpio_hook_fork');
53 Hook::unregister('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
54 Hook::unregister('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
55 Hook::unregister('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
56 Hook::unregister('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
57 Hook::unregister('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
58 Hook::unregister('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
59 Hook::unregister('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
62 function pumpio_module() {}
64 function pumpio_content(App $a)
67 notice(DI::l10n()->t('Permission denied.') . EOL);
71 require_once("mod/settings.php");
74 if (isset($a->argv[1])) {
75 switch ($a->argv[1]) {
77 $o = pumpio_connect($a);
80 $o = print_r($a->argv, true);
84 $o = pumpio_connect($a);
89 function pumpio_check_item_notification($a, &$notification_data)
91 $hostname = DI::pConfig()->get($notification_data["uid"], 'pumpio', 'host');
92 $username = DI::pConfig()->get($notification_data["uid"], "pumpio", "user");
94 $notification_data["profiles"][] = "https://".$hostname."/".$username;
97 function pumpio_registerclient(App $a, $host)
99 $url = "https://".$host."/api/client/register";
103 $application_name = DI::config()->get('pumpio', 'application_name');
105 if ($application_name == "") {
106 $application_name = DI::baseUrl()->getHostname();
109 $adminlist = explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email')));
111 $params["type"] = "client_associate";
112 $params["contacts"] = $adminlist[0];
113 $params["application_type"] = "native";
114 $params["application_name"] = $application_name;
115 $params["logo_url"] = DI::baseUrl()->get()."/images/friendica-256.png";
116 $params["redirect_uris"] = DI::baseUrl()->get()."/pumpio/connect";
118 Logger::log("pumpio_registerclient: ".$url." parameters ".print_r($params, true), Logger::DEBUG);
120 $ch = curl_init($url);
121 curl_setopt($ch, CURLOPT_HEADER, false);
122 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
123 curl_setopt($ch, CURLOPT_POST,1);
124 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
125 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
128 $curl_info = curl_getinfo($ch);
130 if ($curl_info["http_code"] == "200") {
131 $values = json_decode($s);
132 Logger::log("pumpio_registerclient: success ".print_r($values, true), Logger::DEBUG);
135 Logger::log("pumpio_registerclient: failed: ".print_r($curl_info, true), Logger::DEBUG);
140 function pumpio_connect(App $a)
142 // Define the needed keys
143 $consumer_key = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_key');
144 $consumer_secret = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_secret');
145 $hostname = DI::pConfig()->get(local_user(), 'pumpio', 'host');
147 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
148 Logger::log("pumpio_connect: register client");
149 $clientdata = pumpio_registerclient($a, $hostname);
150 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
151 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
153 $consumer_key = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_key');
154 $consumer_secret = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_secret');
156 Logger::log("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, Logger::DEBUG);
159 if (($consumer_key == "") || ($consumer_secret == "")) {
160 Logger::log("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
162 $o .= DI::l10n()->t("Unable to register the client at the pump.io server '%s'.", $hostname);
166 // The callback URL is the script that gets called after the user authenticates with pumpio
167 $callback_url = DI::baseUrl()->get()."/pumpio/connect";
169 // Let's begin. First we need a Request Token. The request token is required to send the user
170 // to pumpio's login page.
172 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
173 // Consumer Key and Consumer Secret
174 $client = new oauth_client_class;
176 $client->server = '';
177 $client->oauth_version = '1.0a';
178 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
179 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
180 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
181 $client->url_parameters = false;
182 $client->authorization_header = true;
183 $client->redirect_uri = $callback_url;
184 $client->client_id = $consumer_key;
185 $client->client_secret = $consumer_secret;
187 if (($success = $client->Initialize())) {
188 if (($success = $client->Process())) {
189 if (strlen($client->access_token)) {
190 Logger::log("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, Logger::DEBUG);
191 DI::pConfig()->set(local_user(), "pumpio", "oauth_token", $client->access_token);
192 DI::pConfig()->set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
195 $success = $client->Finalize($success);
198 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
202 Logger::log("pumpio_connect: authenticated");
203 $o = DI::l10n()->t("You are now authenticated to pumpio.");
204 $o .= '<br /><a href="'.DI::baseUrl()->get().'/settings/connectors">'.DI::l10n()->t("return to the connector page").'</a>';
206 Logger::log("pumpio_connect: could not connect");
207 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
213 function pumpio_jot_nets(App $a, array &$jotnets_fields)
215 if (! local_user()) {
219 if (DI::pConfig()->get(local_user(), 'pumpio', 'post')) {
220 $jotnets_fields[] = [
221 'type' => 'checkbox',
224 DI::l10n()->t('Post to pumpio'),
225 DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default')
231 function pumpio_settings(App $a, &$s)
237 /* Add our stylesheet to the page so we can make our settings look nice */
239 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
241 /* Get the current state of our config variables */
243 $import_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'import');
244 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
246 $enabled = DI::pConfig()->get(local_user(), 'pumpio', 'post');
247 $checked = (($enabled) ? ' checked="checked" ' : '');
248 $css = (($enabled) ? '' : '-disabled');
250 $def_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default');
251 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
253 $public_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'public');
254 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
256 $mirror_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'mirror');
257 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
259 $servername = DI::pConfig()->get(local_user(), "pumpio", "host");
260 $username = DI::pConfig()->get(local_user(), "pumpio", "user");
262 /* Add some HTML to the existing form */
264 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
265 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. DI::l10n()->t('Pump.io Import/Export/Mirror').'</h3>';
267 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
268 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
269 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. DI::l10n()->t('Pump.io Import/Export/Mirror').'</h3>';
272 $s .= '<div id="pumpio-username-wrapper">';
273 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.DI::l10n()->t('pump.io username (without the servername)').'</label>';
274 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
275 $s .= '</div><div class="clear"></div>';
277 $s .= '<div id="pumpio-servername-wrapper">';
278 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.DI::l10n()->t('pump.io servername (without "http://" or "https://" )').'</label>';
279 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
280 $s .= '</div><div class="clear"></div>';
282 if (($username != '') && ($servername != '')) {
283 $oauth_token = DI::pConfig()->get(local_user(), "pumpio", "oauth_token");
284 $oauth_token_secret = DI::pConfig()->get(local_user(), "pumpio", "oauth_token_secret");
286 $s .= '<div id="pumpio-password-wrapper">';
287 if (($oauth_token == "") || ($oauth_token_secret == "")) {
288 $s .= '<div id="pumpio-authenticate-wrapper">';
289 $s .= '<a href="'.DI::baseUrl()->get().'/pumpio/connect">'.DI::l10n()->t("Authenticate your pump.io connection").'</a>';
290 $s .= '</div><div class="clear"></div>';
292 $s .= '<div id="pumpio-import-wrapper">';
293 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . DI::l10n()->t('Import the remote timeline') . '</label>';
294 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
295 $s .= '</div><div class="clear"></div>';
297 $s .= '<div id="pumpio-enable-wrapper">';
298 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . DI::l10n()->t('Enable pump.io Post Addon') . '</label>';
299 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
300 $s .= '</div><div class="clear"></div>';
302 $s .= '<div id="pumpio-bydefault-wrapper">';
303 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . DI::l10n()->t('Post to pump.io by default') . '</label>';
304 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
305 $s .= '</div><div class="clear"></div>';
307 $s .= '<div id="pumpio-public-wrapper">';
308 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . DI::l10n()->t('Should posts be public?') . '</label>';
309 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
310 $s .= '</div><div class="clear"></div>';
312 $s .= '<div id="pumpio-mirror-wrapper">';
313 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . DI::l10n()->t('Mirror all public posts') . '</label>';
314 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
315 $s .= '</div><div class="clear"></div>';
317 $s .= '<div id="pumpio-delete-wrapper">';
318 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . DI::l10n()->t('Check to delete this preset') . '</label>';
319 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
320 $s .= '</div><div class="clear"></div>';
323 $s .= '</div><div class="clear"></div>';
326 /* provide a submit button */
328 $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>';
331 function pumpio_settings_post(App $a, array &$b)
333 if (!empty($_POST['pumpio-submit'])) {
334 if (!empty($_POST['pumpio_delete'])) {
335 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_key' , '');
336 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_secret' , '');
337 DI::pConfig()->set(local_user(), 'pumpio', 'oauth_token' , '');
338 DI::pConfig()->set(local_user(), 'pumpio', 'oauth_token_secret', '');
339 DI::pConfig()->set(local_user(), 'pumpio', 'post' , false);
340 DI::pConfig()->set(local_user(), 'pumpio', 'import' , false);
341 DI::pConfig()->set(local_user(), 'pumpio', 'host' , '');
342 DI::pConfig()->set(local_user(), 'pumpio', 'user' , '');
343 DI::pConfig()->set(local_user(), 'pumpio', 'public' , false);
344 DI::pConfig()->set(local_user(), 'pumpio', 'mirror' , false);
345 DI::pConfig()->set(local_user(), 'pumpio', 'post_by_default' , false);
346 DI::pConfig()->set(local_user(), 'pumpio', 'lastdate' , 0);
347 DI::pConfig()->set(local_user(), 'pumpio', 'last_id' , '');
349 // filtering the username if it is filled wrong
350 $user = $_POST['pumpio_user'];
351 if (strstr($user, "@")) {
352 $pos = strpos($user, "@");
355 $user = substr($user, 0, $pos);
359 // Filtering the hostname if someone is entering it with "http"
360 $host = $_POST['pumpio_host'];
362 $host = str_replace(["https://", "http://"], ["", ""], $host);
364 DI::pConfig()->set(local_user(), 'pumpio', 'post' , $_POST['pumpio'] ?? false);
365 DI::pConfig()->set(local_user(), 'pumpio', 'import' , $_POST['pumpio_import'] ?? false);
366 DI::pConfig()->set(local_user(), 'pumpio', 'host' , $host);
367 DI::pConfig()->set(local_user(), 'pumpio', 'user' , $user);
368 DI::pConfig()->set(local_user(), 'pumpio', 'public' , $_POST['pumpio_public'] ?? false);
369 DI::pConfig()->set(local_user(), 'pumpio', 'mirror' , $_POST['pumpio_mirror'] ?? false);
370 DI::pConfig()->set(local_user(), 'pumpio', 'post_by_default', $_POST['pumpio_bydefault'] ?? false);
372 if (!empty($_POST['pumpio_mirror'])) {
373 DI::pConfig()->delete(local_user(), 'pumpio', 'lastdate');
379 function pumpio_load_config(App $a, ConfigFileLoader $loader)
381 $a->getConfigCache()->load($loader->loadAddonConfig('pumpio'));
384 function pumpio_hook_fork(App $a, array &$b)
386 if ($b['name'] != 'notifier_normal') {
392 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
393 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
394 $b['execute'] = false;
398 // if post comes from pump.io don't send it back
399 if ($post['app'] == "pump.io") {
400 $b['execute'] = false;
404 if (DI::pConfig()->get($post['uid'], 'pumpio', 'import')) {
405 // Don't fork if it isn't a reply to a pump.io post
406 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::PUMPIO])) {
407 Logger::log('No pump.io parent found for item ' . $post['id']);
408 $b['execute'] = false;
412 // Comments are never exported when we don't import the pumpio timeline
413 if (!strstr($post['postopts'], 'pumpio') || ($post['parent'] != $post['id']) || $post['private']) {
414 $b['execute'] = false;
420 function pumpio_post_local(App $a, array &$b)
422 if (!local_user() || (local_user() != $b['uid'])) {
426 $pumpio_post = intval(DI::pConfig()->get(local_user(), 'pumpio', 'post'));
428 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
430 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default'))) {
434 if (!$pumpio_enable) {
438 if (strlen($b['postopts'])) {
439 $b['postopts'] .= ',';
442 $b['postopts'] .= 'pumpio';
445 function pumpio_send(App $a, array &$b)
447 if (!DI::pConfig()->get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
451 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
453 if ($b['parent'] != $b['id']) {
454 // Looking if its a reply to a pumpio post
455 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
456 $orig_post = Item::selectFirst([], $condition);
458 if (!DBA::isResult($orig_post)) {
459 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
467 $receiver = pumpio_getreceiver($a, $b);
469 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
471 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
475 // Dont't post if the post doesn't belong to us.
476 // This is a check for forum postings
477 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
478 if ($b['contact-id'] != $self['id']) {
483 if ($b['verb'] == Activity::LIKE) {
485 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
487 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
492 if ($b['verb'] == Activity::DISLIKE) {
496 if (($b['verb'] == Activity::POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
497 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
500 if (($b['verb'] == Activity::POST) && $b['deleted']) {
501 pumpio_action($a, $b["uid"], $b["uri"], "delete");
504 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
508 // if post comes from pump.io don't send it back
509 if ($b['app'] == "pump.io") {
514 // Support for native shares
515 // http://<hostname>/api/<type>/shares?id=<the-object-id>
517 $oauth_token = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token");
518 $oauth_token_secret = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token_secret");
519 $consumer_key = DI::pConfig()->get($b['uid'], "pumpio","consumer_key");
520 $consumer_secret = DI::pConfig()->get($b['uid'], "pumpio","consumer_secret");
522 $host = DI::pConfig()->get($b['uid'], "pumpio", "host");
523 $user = DI::pConfig()->get($b['uid'], "pumpio", "user");
524 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
526 if ($oauth_token && $oauth_token_secret) {
527 $title = trim($b['title']);
529 $content = BBCode::convert($b['body'], false, 4);
533 $params["verb"] = "post";
536 $params["object"] = [
537 'objectType' => "note",
538 'content' => $content];
540 if (!empty($title)) {
541 $params["object"]["displayName"] = $title;
544 if (!empty($receiver["to"])) {
545 $params["to"] = $receiver["to"];
548 if (!empty($receiver["bto"])) {
549 $params["bto"] = $receiver["bto"];
552 if (!empty($receiver["cc"])) {
553 $params["cc"] = $receiver["cc"];
556 if (!empty($receiver["bcc"])) {
557 $params["bcc"] = $receiver["bcc"];
560 $inReplyTo = ["id" => $orig_post["uri"],
561 "objectType" => "note"];
563 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
564 $inReplyTo["objectType"] = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
567 $params["object"] = [
568 'objectType' => "comment",
569 'content' => $content,
570 'inReplyTo' => $inReplyTo];
573 $params["object"]["displayName"] = $title;
577 $client = new oauth_client_class;
578 $client->oauth_version = '1.0a';
579 $client->url_parameters = false;
580 $client->authorization_header = true;
581 $client->access_token = $oauth_token;
582 $client->access_token_secret = $oauth_token_secret;
583 $client->client_id = $consumer_key;
584 $client->client_secret = $consumer_secret;
586 $username = $user.'@'.$host;
587 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
589 if (pumpio_reachable($url)) {
590 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
596 if ($user->generator->displayName) {
597 DI::pConfig()->set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
600 $post_id = $user->object->id;
601 Logger::log('pumpio_send '.$username.': success '.$post_id);
602 if ($post_id && $iscomment) {
603 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
604 Item::update(['extid' => $post_id], ['id' => $b['id']]);
607 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
613 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
615 // Don't do likes and other stuff if you don't import the timeline
616 if (!DI::pConfig()->get($uid, 'pumpio', 'import')) {
620 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
621 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
622 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
623 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
624 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
625 $username = DI::pConfig()->get($uid, "pumpio", "user");
627 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
629 if (!DBA::isResult($orig_post)) {
633 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
634 $uri = $orig_post["extid"];
636 $uri = $orig_post["uri"];
639 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
640 $objectType = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
641 } elseif (strstr($uri, "/api/comment/")) {
642 $objectType = "comment";
643 } elseif (strstr($uri, "/api/note/")) {
644 $objectType = "note";
645 } elseif (strstr($uri, "/api/image/")) {
646 $objectType = "image";
649 $params["verb"] = $action;
650 $params["object"] = ['id' => $uri,
651 "objectType" => $objectType,
652 "content" => $content];
654 $client = new oauth_client_class;
655 $client->oauth_version = '1.0a';
656 $client->authorization_header = true;
657 $client->url_parameters = false;
659 $client->client_id = $ckey;
660 $client->client_secret = $csecret;
661 $client->access_token = $otoken;
662 $client->access_token_secret = $osecret;
664 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
666 if (pumpio_reachable($url)) {
667 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
673 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
675 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri);
680 function pumpio_sync(App $a)
682 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
684 if (!DBA::isResult($r)) {
688 $last = DI::config()->get('pumpio', 'last_poll');
690 $poll_interval = intval(DI::config()->get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
693 $next = $last + ($poll_interval * 60);
694 if ($next > time()) {
695 Logger::log('pumpio: poll intervall not reached');
699 Logger::log('pumpio: cron_start');
701 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
702 if (DBA::isResult($r)) {
703 foreach ($r as $rr) {
704 Logger::log('pumpio: mirroring user '.$rr['uid']);
705 pumpio_fetchtimeline($a, $rr['uid']);
709 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
710 if ($abandon_days < 1) {
714 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
716 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
717 if (DBA::isResult($r)) {
718 foreach ($r as $rr) {
719 if ($abandon_days != 0) {
720 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
721 if (!DBA::isResult($user)) {
722 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
727 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
728 pumpio_fetchinbox($a, $rr['uid']);
730 // check for new contacts once a day
731 $last_contact_check = DI::pConfig()->get($rr['uid'], 'pumpio', 'contact_check');
732 if ($last_contact_check) {
733 $next_contact_check = $last_contact_check + 86400;
735 $next_contact_check = 0;
738 if ($next_contact_check <= time()) {
739 pumpio_getallusers($a, $rr["uid"]);
740 DI::pConfig()->set($rr['uid'], 'pumpio', 'contact_check', time());
745 Logger::log('pumpio: cron_end');
747 DI::config()->set('pumpio', 'last_poll', time());
750 function pumpio_cron(App $a, $b)
752 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
755 function pumpio_fetchtimeline(App $a, $uid)
757 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
758 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
759 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
760 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
761 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
762 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
763 $username = DI::pConfig()->get($uid, "pumpio", "user");
765 // get the application name for the pump.io app
766 // 1st try personal config, then system config and fallback to the
767 // hostname of the node if neither one is set.
768 $application_name = DI::pConfig()->get($uid, 'pumpio', 'application_name');
769 if ($application_name == "") {
770 $application_name = DI::config()->get('pumpio', 'application_name');
772 if ($application_name == "") {
773 $application_name = DI::baseUrl()->getHostname();
776 $first_time = ($lastdate == "");
778 $client = new oauth_client_class;
779 $client->oauth_version = '1.0a';
780 $client->authorization_header = true;
781 $client->url_parameters = false;
783 $client->client_id = $ckey;
784 $client->client_secret = $csecret;
785 $client->access_token = $otoken;
786 $client->access_token_secret = $osecret;
788 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
790 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);
792 $useraddr = $username.'@'.$hostname;
794 if (pumpio_reachable($url)) {
795 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
802 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
806 $posts = array_reverse($user->items);
808 $initiallastdate = $lastdate;
812 foreach ($posts as $post) {
813 if ($post->published <= $initiallastdate) {
817 if ($lastdate < $post->published) {
818 $lastdate = $post->published;
826 if (@is_array($post->cc)) {
827 $receiptians = array_merge($receiptians, $post->cc);
830 if (@is_array($post->to)) {
831 $receiptians = array_merge($receiptians, $post->to);
835 foreach ($receiptians AS $receiver) {
836 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
841 if ($public && !stristr($post->generator->displayName, $application_name)) {
842 $_SESSION["authenticated"] = true;
843 $_SESSION["uid"] = $uid;
846 $_REQUEST["api_source"] = true;
847 $_REQUEST["profile_uid"] = $uid;
848 $_REQUEST["source"] = "pump.io";
850 if (isset($post->object->id)) {
851 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
854 if ($post->object->displayName != "") {
855 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
857 $_REQUEST["title"] = "";
860 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
862 // To-Do: Picture has to be cached and stored locally
863 if ($post->object->fullImage->url != "") {
864 if ($post->object->fullImage->pump_io->proxyURL != "") {
865 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
867 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
871 Logger::log('pumpio: posting for user '.$uid);
873 require_once('mod/item.php');
876 Logger::log('pumpio: posting done - user '.$uid);
881 if ($lastdate != 0) {
882 DI::pConfig()->set($uid, 'pumpio', 'lastdate', $lastdate);
886 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
888 // Searching for the unliked post
889 // Two queries for speed issues
890 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
891 if (!DBA::isResult($orig_post)) {
892 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
893 if (!DBA::isResult($orig_post)) {
900 if (Strings::compareLink($post->actor->url, $own_id)) {
901 $contactid = $self[0]['id'];
903 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
904 DBA::escape(Strings::normaliseLink($post->actor->url)),
908 if (DBA::isResult($r)) {
909 $contactid = $r[0]['id'];
912 if ($contactid == 0) {
913 $contactid = $orig_post['contact-id'];
917 Item::markForDeletion(['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
919 if (DBA::isResult($r)) {
920 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
922 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
926 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
928 require_once('include/items.php');
930 if (empty($post->object->id)) {
931 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
935 // Searching for the liked post
936 // Two queries for speed issues
937 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
938 if (!DBA::isResult($orig_post)) {
939 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
940 if (!DBA::isResult($orig_post)) {
946 if ($threadcompletion) {
947 pumpio_fetchallcomments($a, $uid, $post->object->id);
952 if (Strings::compareLink($post->actor->url, $own_id)) {
953 $contactid = $self[0]['id'];
954 $post->actor->displayName = $self[0]['name'];
955 $post->actor->url = $self[0]['url'];
956 $post->actor->image->url = $self[0]['photo'];
958 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
959 DBA::escape(Strings::normaliseLink($post->actor->url)),
963 if (DBA::isResult($r)) {
964 $contactid = $r[0]['id'];
967 if ($contactid == 0) {
968 $contactid = $orig_post['contact-id'];
972 $condition = ['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
973 if (Item::exists($condition)) {
974 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
979 $likedata['parent'] = $orig_post['id'];
980 $likedata['verb'] = Activity::LIKE;
981 $likedata['gravity'] = GRAVITY_ACTIVITY;
982 $likedata['uid'] = $uid;
983 $likedata['wall'] = 0;
984 $likedata['network'] = Protocol::PUMPIO;
985 $likedata['uri'] = Item::newURI($uid);
986 $likedata['parent-uri'] = $orig_post["uri"];
987 $likedata['contact-id'] = $contactid;
988 $likedata['app'] = $post->generator->displayName;
989 $likedata['author-name'] = $post->actor->displayName;
990 $likedata['author-link'] = $post->actor->url;
991 if (!empty($post->actor->image)) {
992 $likedata['author-avatar'] = $post->actor->image->url;
995 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
996 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
997 $post_type = DI::l10n()->t('status');
998 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
999 $likedata['object-type'] = Activity\ObjectType::NOTE;
1001 $likedata['body'] = DI::l10n()->t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
1003 $likedata['object'] = '<object><type>' . Activity\ObjectType::NOTE . '</type><local>1</local>' .
1004 '<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>';
1006 $ret = Item::insert($likedata);
1008 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
1011 function pumpio_get_contact($uid, $contact, $no_insert = false)
1013 $cid = Contact::getIdForURL($contact->url, $uid);
1019 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1020 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1022 if (!DBA::isResult($r)) {
1023 // create contact record
1024 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1025 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1026 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1027 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1029 DBA::escape(DateTimeFormat::utcNow()),
1030 DBA::escape($contact->url),
1031 DBA::escape(Strings::normaliseLink($contact->url)),
1032 DBA::escape(str_replace("acct:", "", $contact->id)),
1034 DBA::escape($contact->id), // What is it for?
1035 DBA::escape('pump.io ' . $contact->id), // What is it for?
1036 DBA::escape($contact->displayName),
1037 DBA::escape($contact->preferredUsername),
1038 DBA::escape($contact->image->url),
1039 DBA::escape(Protocol::PUMPIO),
1040 intval(Contact::FRIEND),
1042 DBA::escape($contact->location->displayName),
1043 DBA::escape($contact->summary),
1047 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1048 DBA::escape(Strings::normaliseLink($contact->url)),
1052 if (!DBA::isResult($r)) {
1056 $contact_id = $r[0]['id'];
1058 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1060 $contact_id = $r[0]["id"];
1062 /* if (DB_UPDATE_VERSION >= "1177")
1063 q("UPDATE `contact` SET `location` = '%s',
1066 dbesc($contact->location->displayName),
1067 dbesc($contact->summary),
1073 if (!empty($contact->image->url)) {
1074 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1080 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1082 // Two queries for speed issues
1083 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1084 if (Item::exists($condition)) {
1085 Item::markForDeletion($condition);
1089 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1090 if (Item::exists($condition)) {
1091 Item::markForDeletion($condition);
1097 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1099 require_once('include/items.php');
1101 if (($post->verb == "like") || ($post->verb == "favorite")) {
1102 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1105 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1106 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1109 if ($post->verb == "delete") {
1110 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1113 if ($post->verb != "update") {
1114 // Two queries for speed issues
1115 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1118 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1123 // Only handle these three types
1124 if (!strstr("post|share|update", $post->verb)) {
1129 if (@is_array($post->cc)) {
1130 $receiptians = array_merge($receiptians, $post->cc);
1133 if (@is_array($post->to)) {
1134 $receiptians = array_merge($receiptians, $post->to);
1139 foreach ($receiptians AS $receiver) {
1140 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1146 $postarray['network'] = Protocol::PUMPIO;
1147 $postarray['uid'] = $uid;
1148 $postarray['wall'] = 0;
1149 $postarray['uri'] = $post->object->id;
1150 $postarray['object-type'] = ActivityNamespace::ACTIVITY_SCHEMA . strtolower($post->object->objectType);
1152 if ($post->object->objectType != "comment") {
1153 $contact_id = pumpio_get_contact($uid, $post->actor);
1156 $contact_id = $self[0]['id'];
1159 $postarray['parent-uri'] = $post->object->id;
1162 $postarray['private'] = 1;
1163 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1166 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1168 if (Strings::compareLink($post->actor->url, $own_id)) {
1169 $contact_id = $self[0]['id'];
1170 $post->actor->displayName = $self[0]['name'];
1171 $post->actor->url = $self[0]['url'];
1172 $post->actor->image->url = $self[0]['photo'];
1173 } elseif ($contact_id == 0) {
1174 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1175 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1176 DBA::escape(Strings::normaliseLink($post->actor->url)),
1180 if (DBA::isResult($r)) {
1181 $contact_id = $r[0]['id'];
1183 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1184 DBA::escape(Strings::normaliseLink($post->actor->url)),
1188 if (DBA::isResult($r)) {
1189 $contact_id = $r[0]['id'];
1191 $contact_id = $self[0]['id'];
1196 $reply = new stdClass;
1197 $reply->verb = "note";
1199 if (isset($post->cc)) {
1200 $reply->cc = $post->cc;
1203 if (isset($post->to)) {
1204 $reply->to = $post->to;
1207 $reply->object = new stdClass;
1208 $reply->object->objectType = $post->object->inReplyTo->objectType;
1209 $reply->object->content = $post->object->inReplyTo->content;
1210 $reply->object->id = $post->object->inReplyTo->id;
1211 $reply->actor = $post->object->inReplyTo->author;
1212 $reply->url = $post->object->inReplyTo->url;
1213 $reply->generator = new stdClass;
1214 $reply->generator->displayName = "pumpio";
1215 $reply->published = $post->object->inReplyTo->published;
1216 $reply->received = $post->object->inReplyTo->updated;
1217 $reply->url = $post->object->inReplyTo->url;
1218 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1220 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1223 // When there is no content there is no need to continue
1224 if (empty($post->object->content)) {
1228 if (!empty($post->object->pump_io->proxyURL)) {
1229 $postarray['extid'] = $post->object->pump_io->proxyURL;
1232 $postarray['contact-id'] = $contact_id;
1233 $postarray['verb'] = Activity::POST;
1234 $postarray['owner-name'] = $post->actor->displayName;
1235 $postarray['owner-link'] = $post->actor->url;
1236 $postarray['author-name'] = $postarray['owner-name'];
1237 $postarray['author-link'] = $postarray['owner-link'];
1238 if (!empty($post->actor->image)) {
1239 $postarray['owner-avatar'] = $post->actor->image->url;
1240 $postarray['author-avatar'] = $postarray['owner-avatar'];
1242 $postarray['plink'] = $post->object->url;
1243 $postarray['app'] = $post->generator->displayName;
1244 $postarray['title'] = '';
1245 $postarray['body'] = HTML::toBBCode($post->object->content);
1246 $postarray['object'] = json_encode($post);
1248 if (!empty($post->object->fullImage->url)) {
1249 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1252 if (!empty($post->object->displayName)) {
1253 $postarray['title'] = $post->object->displayName;
1256 $postarray['created'] = DateTimeFormat::utc($post->published);
1257 if (isset($post->updated)) {
1258 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1259 } elseif (isset($post->received)) {
1260 $postarray['edited'] = DateTimeFormat::utc($post->received);
1262 $postarray['edited'] = $postarray['created'];
1265 if ($post->verb == "share") {
1266 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1267 $share_author = $post->object->author->displayName;
1268 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1269 $share_author = $post->object->author->preferredUsername;
1271 $share_author = $post->object->author->url;
1274 if (isset($post->object->created)) {
1275 $created = DateTimeFormat::utc($post->object->created);
1280 $postarray['body'] = share_header($share_author, $post->object->author->url,
1281 $post->object->author->image->url, "",
1282 $created, $post->links->self->href).
1283 $postarray['body']."[/share]";
1286 if (trim($postarray['body']) == "") {
1290 $top_item = Item::insert($postarray);
1291 $postarray["id"] = $top_item;
1293 if (($top_item == 0) && ($post->verb == "update")) {
1294 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1295 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1296 Item::update($fields, $condition);
1299 if (($post->object->objectType == "comment") && $threadcompletion) {
1300 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1306 function pumpio_fetchinbox(App $a, $uid)
1308 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1309 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1310 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1311 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1312 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
1313 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1314 $username = DI::pConfig()->get($uid, "pumpio", "user");
1316 $own_id = "https://".$hostname."/".$username;
1318 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1321 $lastitems = q("SELECT `uri` FROM `thread`
1322 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1323 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1324 ORDER BY `thread`.`commented` DESC LIMIT 10",
1325 DBA::escape(Protocol::PUMPIO),
1329 $client = new oauth_client_class;
1330 $client->oauth_version = '1.0a';
1331 $client->authorization_header = true;
1332 $client->url_parameters = false;
1334 $client->client_id = $ckey;
1335 $client->client_secret = $csecret;
1336 $client->access_token = $otoken;
1337 $client->access_token_secret = $osecret;
1339 $last_id = DI::pConfig()->get($uid, 'pumpio', 'last_id');
1341 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1343 if ($last_id != "") {
1344 $url .= '?since='.urlencode($last_id);
1347 if (pumpio_reachable($url)) {
1348 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1357 if (!empty($user->items)) {
1358 $posts = array_reverse($user->items);
1360 if (count($posts)) {
1361 foreach ($posts as $post) {
1362 $last_id = $post->id;
1363 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1368 foreach ($lastitems as $item) {
1369 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1372 DI::pConfig()->set($uid, 'pumpio', 'last_id', $last_id);
1375 function pumpio_getallusers(App &$a, $uid)
1377 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1378 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1379 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1380 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1381 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1382 $username = DI::pConfig()->get($uid, "pumpio", "user");
1384 $client = new oauth_client_class;
1385 $client->oauth_version = '1.0a';
1386 $client->authorization_header = true;
1387 $client->url_parameters = false;
1389 $client->client_id = $ckey;
1390 $client->client_secret = $csecret;
1391 $client->access_token = $otoken;
1392 $client->access_token_secret = $osecret;
1394 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1396 if (pumpio_reachable($url)) {
1397 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1402 if (empty($users)) {
1406 if ($users->totalItems > count($users->items)) {
1407 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1409 if (pumpio_reachable($url)) {
1410 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1416 if (!empty($users->items)) {
1417 foreach ($users->items as $user) {
1418 pumpio_get_contact($uid, $user);
1423 function pumpio_getreceiver(App $a, array $b)
1427 if (!$b["private"]) {
1428 if (!strstr($b['postopts'], 'pumpio')) {
1432 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
1435 $receiver["to"][] = [
1436 "objectType" => "collection",
1437 "id" => "http://activityschema.org/collection/public"];
1440 $cids = explode("><", $b["allow_cid"]);
1441 $gids = explode("><", $b["allow_gid"]);
1443 foreach ($cids AS $cid) {
1444 $cid = trim($cid, " <>");
1446 $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",
1449 DBA::escape(Protocol::PUMPIO)
1452 if (DBA::isResult($r)) {
1453 $receiver["bcc"][] = [
1454 "displayName" => $r[0]["name"],
1455 "objectType" => "person",
1456 "preferredUsername" => $r[0]["nick"],
1457 "url" => $r[0]["url"]];
1460 foreach ($gids AS $gid) {
1461 $gid = trim($gid, " <>");
1463 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1464 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1465 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1467 DBA::escape(Protocol::PUMPIO)
1470 foreach ($r AS $row)
1471 $receiver["bcc"][] = [
1472 "displayName" => $row["name"],
1473 "objectType" => "person",
1474 "preferredUsername" => $row["nick"],
1475 "url" => $row["url"]];
1479 if ($b["inform"] != "") {
1480 $inform = explode(",", $b["inform"]);
1482 foreach ($inform AS $cid) {
1483 if (substr($cid, 0, 4) != "cid:") {
1487 $cid = str_replace("cid:", "", $cid);
1489 $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",
1492 DBA::escape(Protocol::PUMPIO)
1495 if (DBA::isResult($r)) {
1496 $receiver["to"][] = [
1497 "displayName" => $r[0]["name"],
1498 "objectType" => "person",
1499 "preferredUsername" => $r[0]["nick"],
1500 "url" => $r[0]["url"]];
1508 function pumpio_fetchallcomments(App $a, $uid, $id)
1510 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1511 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1512 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1513 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1514 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1515 $username = DI::pConfig()->get($uid, "pumpio", "user");
1517 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1519 $own_id = "https://".$hostname."/".$username;
1521 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1524 // Fetching the original post
1525 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1526 $item = Item::selectFirst(['extid'], $condition);
1527 if (!DBA::isResult($item)) {
1531 $url = $item["extid"];
1533 $client = new oauth_client_class;
1534 $client->oauth_version = '1.0a';
1535 $client->authorization_header = true;
1536 $client->url_parameters = false;
1538 $client->client_id = $ckey;
1539 $client->client_secret = $csecret;
1540 $client->access_token = $otoken;
1541 $client->access_token_secret = $osecret;
1543 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1545 if (pumpio_reachable($url)) {
1546 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1555 if ($item->likes->totalItems != 0) {
1556 foreach ($item->likes->items AS $post) {
1557 $like = new stdClass;
1558 $like->object = new stdClass;
1559 $like->object->id = $item->id;
1560 $like->actor = new stdClass;
1561 if (!empty($item->displayName)) {
1562 $like->actor->displayName = $item->displayName;
1564 //$like->actor->preferredUsername = $item->preferredUsername;
1565 //$like->actor->image = $item->image;
1566 $like->actor->url = $item->url;
1567 $like->generator = new stdClass;
1568 $like->generator->displayName = "pumpio";
1569 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1573 if ($item->replies->totalItems == 0) {
1577 foreach ($item->replies->items AS $item) {
1578 if ($item->id == $id) {
1582 // Checking if the comment already exists - Two queries for speed issues
1583 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1587 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1591 $post = new stdClass;
1592 $post->verb = "post";
1593 $post->actor = $item->author;
1594 $post->published = $item->published;
1595 $post->received = $item->updated;
1596 $post->generator = new stdClass;
1597 $post->generator->displayName = "pumpio";
1598 // To-Do: Check for public post
1600 unset($item->author);
1601 unset($item->published);
1602 unset($item->updated);
1604 $post->object = $item;
1606 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1607 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1611 function pumpio_reachable($url)
1613 return Network::curl($url, false, ['timeout' => 10])->isSuccess();