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\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Logger;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBA;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Item;
24 use Friendica\Model\User;
25 use Friendica\Protocol\Activity;
26 use Friendica\Protocol\ActivityNamespace;
27 use Friendica\Util\ConfigFileLoader;
28 use Friendica\Util\DateTimeFormat;
29 use Friendica\Util\Network;
30 use Friendica\Util\Strings;
31 use Friendica\Util\XML;
33 require 'addon/pumpio/oauth/http.php';
34 require 'addon/pumpio/oauth/oauth_client.php';
35 require_once "mod/share.php";
37 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
39 function pumpio_install()
41 Hook::register('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
42 Hook::register('hook_fork', 'addon/pumpio/pumpio.php', 'hook_fork');
43 Hook::register('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
44 Hook::register('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
45 Hook::register('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
46 Hook::register('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
47 Hook::register('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
48 Hook::register('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
49 Hook::register('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
52 function pumpio_uninstall()
54 Hook::unregister('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
55 Hook::unregister('hook_fork', 'addon/pumpio/pumpio.php', 'pumpio_hook_fork');
56 Hook::unregister('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
57 Hook::unregister('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
58 Hook::unregister('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
59 Hook::unregister('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
60 Hook::unregister('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
61 Hook::unregister('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
62 Hook::unregister('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
65 function pumpio_module() {}
67 function pumpio_content(App $a)
70 notice(L10n::t('Permission denied.') . EOL);
74 require_once("mod/settings.php");
77 if (isset($a->argv[1])) {
78 switch ($a->argv[1]) {
80 $o = pumpio_connect($a);
83 $o = print_r($a->argv, true);
87 $o = pumpio_connect($a);
92 function pumpio_check_item_notification($a, &$notification_data)
94 $hostname = PConfig::get($notification_data["uid"], 'pumpio', 'host');
95 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
97 $notification_data["profiles"][] = "https://".$hostname."/".$username;
100 function pumpio_registerclient(App $a, $host)
102 $url = "https://".$host."/api/client/register";
106 $application_name = Config::get('pumpio', 'application_name');
108 if ($application_name == "") {
109 $application_name = DI::baseUrl()->getHostname();
112 $adminlist = explode(",", str_replace(" ", "", Config::get('config', 'admin_email')));
114 $params["type"] = "client_associate";
115 $params["contacts"] = $adminlist[0];
116 $params["application_type"] = "native";
117 $params["application_name"] = $application_name;
118 $params["logo_url"] = DI::baseUrl()->get()."/images/friendica-256.png";
119 $params["redirect_uris"] = DI::baseUrl()->get()."/pumpio/connect";
121 Logger::log("pumpio_registerclient: ".$url." parameters ".print_r($params, true), Logger::DEBUG);
123 $ch = curl_init($url);
124 curl_setopt($ch, CURLOPT_HEADER, false);
125 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
126 curl_setopt($ch, CURLOPT_POST,1);
127 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
128 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
131 $curl_info = curl_getinfo($ch);
133 if ($curl_info["http_code"] == "200") {
134 $values = json_decode($s);
135 Logger::log("pumpio_registerclient: success ".print_r($values, true), Logger::DEBUG);
138 Logger::log("pumpio_registerclient: failed: ".print_r($curl_info, true), Logger::DEBUG);
143 function pumpio_connect(App $a)
145 // Define the needed keys
146 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
147 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
148 $hostname = PConfig::get(local_user(), 'pumpio', 'host');
150 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
151 Logger::log("pumpio_connect: register client");
152 $clientdata = pumpio_registerclient($a, $hostname);
153 PConfig::set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
154 PConfig::set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
156 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
157 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
159 Logger::log("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, Logger::DEBUG);
162 if (($consumer_key == "") || ($consumer_secret == "")) {
163 Logger::log("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
165 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
169 // The callback URL is the script that gets called after the user authenticates with pumpio
170 $callback_url = DI::baseUrl()->get()."/pumpio/connect";
172 // Let's begin. First we need a Request Token. The request token is required to send the user
173 // to pumpio's login page.
175 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
176 // Consumer Key and Consumer Secret
177 $client = new oauth_client_class;
179 $client->server = '';
180 $client->oauth_version = '1.0a';
181 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
182 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
183 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
184 $client->url_parameters = false;
185 $client->authorization_header = true;
186 $client->redirect_uri = $callback_url;
187 $client->client_id = $consumer_key;
188 $client->client_secret = $consumer_secret;
190 if (($success = $client->Initialize())) {
191 if (($success = $client->Process())) {
192 if (strlen($client->access_token)) {
193 Logger::log("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, Logger::DEBUG);
194 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
195 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
198 $success = $client->Finalize($success);
201 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
205 Logger::log("pumpio_connect: authenticated");
206 $o = L10n::t("You are now authenticated to pumpio.");
207 $o .= '<br /><a href="'.DI::baseUrl()->get().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
209 Logger::log("pumpio_connect: could not connect");
210 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
216 function pumpio_jot_nets(App $a, array &$jotnets_fields)
218 if (! local_user()) {
222 if (PConfig::get(local_user(), 'pumpio', 'post')) {
223 $jotnets_fields[] = [
224 'type' => 'checkbox',
227 L10n::t('Post to pumpio'),
228 PConfig::get(local_user(), 'pumpio', 'post_by_default')
234 function pumpio_settings(App $a, &$s)
240 /* Add our stylesheet to the page so we can make our settings look nice */
242 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
244 /* Get the current state of our config variables */
246 $import_enabled = PConfig::get(local_user(), 'pumpio', 'import');
247 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
249 $enabled = PConfig::get(local_user(), 'pumpio', 'post');
250 $checked = (($enabled) ? ' checked="checked" ' : '');
251 $css = (($enabled) ? '' : '-disabled');
253 $def_enabled = PConfig::get(local_user(), 'pumpio', 'post_by_default');
254 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
256 $public_enabled = PConfig::get(local_user(), 'pumpio', 'public');
257 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
259 $mirror_enabled = PConfig::get(local_user(), 'pumpio', 'mirror');
260 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
262 $servername = PConfig::get(local_user(), "pumpio", "host");
263 $username = PConfig::get(local_user(), "pumpio", "user");
265 /* Add some HTML to the existing form */
267 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
268 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
270 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
271 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
272 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
275 $s .= '<div id="pumpio-username-wrapper">';
276 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
277 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
278 $s .= '</div><div class="clear"></div>';
280 $s .= '<div id="pumpio-servername-wrapper">';
281 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
282 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
283 $s .= '</div><div class="clear"></div>';
285 if (($username != '') && ($servername != '')) {
286 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
287 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
289 $s .= '<div id="pumpio-password-wrapper">';
290 if (($oauth_token == "") || ($oauth_token_secret == "")) {
291 $s .= '<div id="pumpio-authenticate-wrapper">';
292 $s .= '<a href="'.DI::baseUrl()->get().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
293 $s .= '</div><div class="clear"></div>';
295 $s .= '<div id="pumpio-import-wrapper">';
296 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
297 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
298 $s .= '</div><div class="clear"></div>';
300 $s .= '<div id="pumpio-enable-wrapper">';
301 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
302 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
303 $s .= '</div><div class="clear"></div>';
305 $s .= '<div id="pumpio-bydefault-wrapper">';
306 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
307 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
308 $s .= '</div><div class="clear"></div>';
310 $s .= '<div id="pumpio-public-wrapper">';
311 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
312 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
313 $s .= '</div><div class="clear"></div>';
315 $s .= '<div id="pumpio-mirror-wrapper">';
316 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
317 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
318 $s .= '</div><div class="clear"></div>';
320 $s .= '<div id="pumpio-delete-wrapper">';
321 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
322 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
323 $s .= '</div><div class="clear"></div>';
326 $s .= '</div><div class="clear"></div>';
329 /* provide a submit button */
331 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div></div>';
334 function pumpio_settings_post(App $a, array &$b)
336 if (!empty($_POST['pumpio-submit'])) {
337 if (!empty($_POST['pumpio_delete'])) {
338 PConfig::set(local_user(), 'pumpio', 'consumer_key' , '');
339 PConfig::set(local_user(), 'pumpio', 'consumer_secret' , '');
340 PConfig::set(local_user(), 'pumpio', 'oauth_token' , '');
341 PConfig::set(local_user(), 'pumpio', 'oauth_token_secret', '');
342 PConfig::set(local_user(), 'pumpio', 'post' , false);
343 PConfig::set(local_user(), 'pumpio', 'import' , false);
344 PConfig::set(local_user(), 'pumpio', 'host' , '');
345 PConfig::set(local_user(), 'pumpio', 'user' , '');
346 PConfig::set(local_user(), 'pumpio', 'public' , false);
347 PConfig::set(local_user(), 'pumpio', 'mirror' , false);
348 PConfig::set(local_user(), 'pumpio', 'post_by_default' , false);
349 PConfig::set(local_user(), 'pumpio', 'lastdate' , 0);
350 PConfig::set(local_user(), 'pumpio', 'last_id' , '');
352 // filtering the username if it is filled wrong
353 $user = $_POST['pumpio_user'];
354 if (strstr($user, "@")) {
355 $pos = strpos($user, "@");
358 $user = substr($user, 0, $pos);
362 // Filtering the hostname if someone is entering it with "http"
363 $host = $_POST['pumpio_host'];
365 $host = str_replace(["https://", "http://"], ["", ""], $host);
367 PConfig::set(local_user(), 'pumpio', 'post' , $_POST['pumpio'] ?? false);
368 PConfig::set(local_user(), 'pumpio', 'import' , $_POST['pumpio_import'] ?? false);
369 PConfig::set(local_user(), 'pumpio', 'host' , $host);
370 PConfig::set(local_user(), 'pumpio', 'user' , $user);
371 PConfig::set(local_user(), 'pumpio', 'public' , $_POST['pumpio_public'] ?? false);
372 PConfig::set(local_user(), 'pumpio', 'mirror' , $_POST['pumpio_mirror'] ?? false);
373 PConfig::set(local_user(), 'pumpio', 'post_by_default', $_POST['pumpio_bydefault'] ?? false);
375 if (!empty($_POST['pumpio_mirror'])) {
376 PConfig::delete(local_user(), 'pumpio', 'lastdate');
382 function pumpio_load_config(App $a, ConfigFileLoader $loader)
384 $a->getConfigCache()->load($loader->loadAddonConfig('pumpio'));
387 function pumpio_hook_fork(App $a, array &$b)
389 if ($b['name'] != 'notifier_normal') {
395 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
396 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
397 $b['execute'] = false;
401 // if post comes from pump.io don't send it back
402 if ($post['app'] == "pump.io") {
403 $b['execute'] = false;
407 if (PConfig::get($post['uid'], 'pumpio', 'import')) {
408 // Don't fork if it isn't a reply to a pump.io post
409 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::PUMPIO])) {
410 Logger::log('No pump.io parent found for item ' . $post['id']);
411 $b['execute'] = false;
415 // Comments are never exported when we don't import the pumpio timeline
416 if (!strstr($post['postopts'], 'pumpio') || ($post['parent'] != $post['id']) || $post['private']) {
417 $b['execute'] = false;
423 function pumpio_post_local(App $a, array &$b)
425 if (!local_user() || (local_user() != $b['uid'])) {
429 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
431 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
433 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
437 if (!$pumpio_enable) {
441 if (strlen($b['postopts'])) {
442 $b['postopts'] .= ',';
445 $b['postopts'] .= 'pumpio';
448 function pumpio_send(App $a, array &$b)
450 if (!PConfig::get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
454 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
456 if ($b['parent'] != $b['id']) {
457 // Looking if its a reply to a pumpio post
458 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
459 $orig_post = Item::selectFirst([], $condition);
461 if (!DBA::isResult($orig_post)) {
462 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
470 $receiver = pumpio_getreceiver($a, $b);
472 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
474 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
478 // Dont't post if the post doesn't belong to us.
479 // This is a check for forum postings
480 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
481 if ($b['contact-id'] != $self['id']) {
486 if ($b['verb'] == Activity::LIKE) {
488 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
490 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
495 if ($b['verb'] == Activity::DISLIKE) {
499 if (($b['verb'] == Activity::POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
500 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
503 if (($b['verb'] == Activity::POST) && $b['deleted']) {
504 pumpio_action($a, $b["uid"], $b["uri"], "delete");
507 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
511 // if post comes from pump.io don't send it back
512 if ($b['app'] == "pump.io") {
517 // Support for native shares
518 // http://<hostname>/api/<type>/shares?id=<the-object-id>
520 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
521 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
522 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
523 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
525 $host = PConfig::get($b['uid'], "pumpio", "host");
526 $user = PConfig::get($b['uid'], "pumpio", "user");
527 $public = PConfig::get($b['uid'], "pumpio", "public");
529 if ($oauth_token && $oauth_token_secret) {
530 $title = trim($b['title']);
532 $content = BBCode::convert($b['body'], false, 4);
536 $params["verb"] = "post";
539 $params["object"] = [
540 'objectType' => "note",
541 'content' => $content];
543 if (!empty($title)) {
544 $params["object"]["displayName"] = $title;
547 if (!empty($receiver["to"])) {
548 $params["to"] = $receiver["to"];
551 if (!empty($receiver["bto"])) {
552 $params["bto"] = $receiver["bto"];
555 if (!empty($receiver["cc"])) {
556 $params["cc"] = $receiver["cc"];
559 if (!empty($receiver["bcc"])) {
560 $params["bcc"] = $receiver["bcc"];
563 $inReplyTo = ["id" => $orig_post["uri"],
564 "objectType" => "note"];
566 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
567 $inReplyTo["objectType"] = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
570 $params["object"] = [
571 'objectType' => "comment",
572 'content' => $content,
573 'inReplyTo' => $inReplyTo];
576 $params["object"]["displayName"] = $title;
580 $client = new oauth_client_class;
581 $client->oauth_version = '1.0a';
582 $client->url_parameters = false;
583 $client->authorization_header = true;
584 $client->access_token = $oauth_token;
585 $client->access_token_secret = $oauth_token_secret;
586 $client->client_id = $consumer_key;
587 $client->client_secret = $consumer_secret;
589 $username = $user.'@'.$host;
590 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
592 if (pumpio_reachable($url)) {
593 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
599 if ($user->generator->displayName) {
600 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
603 $post_id = $user->object->id;
604 Logger::log('pumpio_send '.$username.': success '.$post_id);
605 if ($post_id && $iscomment) {
606 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
607 Item::update(['extid' => $post_id], ['id' => $b['id']]);
610 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
616 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
618 // Don't do likes and other stuff if you don't import the timeline
619 if (!PConfig::get($uid, 'pumpio', 'import')) {
623 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
624 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
625 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
626 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
627 $hostname = PConfig::get($uid, 'pumpio', 'host');
628 $username = PConfig::get($uid, "pumpio", "user");
630 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
632 if (!DBA::isResult($orig_post)) {
636 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
637 $uri = $orig_post["extid"];
639 $uri = $orig_post["uri"];
642 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
643 $objectType = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
644 } elseif (strstr($uri, "/api/comment/")) {
645 $objectType = "comment";
646 } elseif (strstr($uri, "/api/note/")) {
647 $objectType = "note";
648 } elseif (strstr($uri, "/api/image/")) {
649 $objectType = "image";
652 $params["verb"] = $action;
653 $params["object"] = ['id' => $uri,
654 "objectType" => $objectType,
655 "content" => $content];
657 $client = new oauth_client_class;
658 $client->oauth_version = '1.0a';
659 $client->authorization_header = true;
660 $client->url_parameters = false;
662 $client->client_id = $ckey;
663 $client->client_secret = $csecret;
664 $client->access_token = $otoken;
665 $client->access_token_secret = $osecret;
667 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
669 if (pumpio_reachable($url)) {
670 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
676 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
678 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user, true));
683 function pumpio_sync(App $a)
685 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
687 if (!DBA::isResult($r)) {
691 $last = Config::get('pumpio', 'last_poll');
693 $poll_interval = intval(Config::get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
696 $next = $last + ($poll_interval * 60);
697 if ($next > time()) {
698 Logger::log('pumpio: poll intervall not reached');
702 Logger::log('pumpio: cron_start');
704 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
705 if (DBA::isResult($r)) {
706 foreach ($r as $rr) {
707 Logger::log('pumpio: mirroring user '.$rr['uid']);
708 pumpio_fetchtimeline($a, $rr['uid']);
712 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
713 if ($abandon_days < 1) {
717 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
719 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
720 if (DBA::isResult($r)) {
721 foreach ($r as $rr) {
722 if ($abandon_days != 0) {
723 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
724 if (!DBA::isResult($user)) {
725 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
730 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
731 pumpio_fetchinbox($a, $rr['uid']);
733 // check for new contacts once a day
734 $last_contact_check = PConfig::get($rr['uid'], 'pumpio', 'contact_check');
735 if ($last_contact_check) {
736 $next_contact_check = $last_contact_check + 86400;
738 $next_contact_check = 0;
741 if ($next_contact_check <= time()) {
742 pumpio_getallusers($a, $rr["uid"]);
743 PConfig::set($rr['uid'], 'pumpio', 'contact_check', time());
748 Logger::log('pumpio: cron_end');
750 Config::set('pumpio', 'last_poll', time());
753 function pumpio_cron(App $a, $b)
755 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
758 function pumpio_fetchtimeline(App $a, $uid)
760 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
761 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
762 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
763 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
764 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
765 $hostname = PConfig::get($uid, 'pumpio', 'host');
766 $username = PConfig::get($uid, "pumpio", "user");
768 // get the application name for the pump.io app
769 // 1st try personal config, then system config and fallback to the
770 // hostname of the node if neither one is set.
771 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
772 if ($application_name == "") {
773 $application_name = Config::get('pumpio', 'application_name');
775 if ($application_name == "") {
776 $application_name = DI::baseUrl()->getHostname();
779 $first_time = ($lastdate == "");
781 $client = new oauth_client_class;
782 $client->oauth_version = '1.0a';
783 $client->authorization_header = true;
784 $client->url_parameters = false;
786 $client->client_id = $ckey;
787 $client->client_secret = $csecret;
788 $client->access_token = $otoken;
789 $client->access_token_secret = $osecret;
791 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
793 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);
795 $useraddr = $username.'@'.$hostname;
797 if (pumpio_reachable($url)) {
798 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
805 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
809 $posts = array_reverse($user->items);
811 $initiallastdate = $lastdate;
815 foreach ($posts as $post) {
816 if ($post->published <= $initiallastdate) {
820 if ($lastdate < $post->published) {
821 $lastdate = $post->published;
829 if (@is_array($post->cc)) {
830 $receiptians = array_merge($receiptians, $post->cc);
833 if (@is_array($post->to)) {
834 $receiptians = array_merge($receiptians, $post->to);
838 foreach ($receiptians AS $receiver) {
839 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
844 if ($public && !stristr($post->generator->displayName, $application_name)) {
845 $_SESSION["authenticated"] = true;
846 $_SESSION["uid"] = $uid;
849 $_REQUEST["api_source"] = true;
850 $_REQUEST["profile_uid"] = $uid;
851 $_REQUEST["source"] = "pump.io";
853 if (isset($post->object->id)) {
854 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
857 if ($post->object->displayName != "") {
858 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
860 $_REQUEST["title"] = "";
863 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
865 // To-Do: Picture has to be cached and stored locally
866 if ($post->object->fullImage->url != "") {
867 if ($post->object->fullImage->pump_io->proxyURL != "") {
868 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
870 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
874 Logger::log('pumpio: posting for user '.$uid);
876 require_once('mod/item.php');
879 Logger::log('pumpio: posting done - user '.$uid);
884 if ($lastdate != 0) {
885 PConfig::set($uid, 'pumpio', 'lastdate', $lastdate);
889 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
891 // Searching for the unliked post
892 // Two queries for speed issues
893 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
894 if (!DBA::isResult($orig_post)) {
895 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
896 if (!DBA::isResult($orig_post)) {
903 if (Strings::compareLink($post->actor->url, $own_id)) {
904 $contactid = $self[0]['id'];
906 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
907 DBA::escape(Strings::normaliseLink($post->actor->url)),
911 if (DBA::isResult($r)) {
912 $contactid = $r[0]['id'];
915 if ($contactid == 0) {
916 $contactid = $orig_post['contact-id'];
920 Item::delete(['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
922 if (DBA::isResult($r)) {
923 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
925 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
929 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
931 require_once('include/items.php');
933 if (empty($post->object->id)) {
934 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
938 // Searching for the liked post
939 // Two queries for speed issues
940 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
941 if (!DBA::isResult($orig_post)) {
942 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
943 if (!DBA::isResult($orig_post)) {
949 if ($threadcompletion) {
950 pumpio_fetchallcomments($a, $uid, $post->object->id);
955 if (Strings::compareLink($post->actor->url, $own_id)) {
956 $contactid = $self[0]['id'];
957 $post->actor->displayName = $self[0]['name'];
958 $post->actor->url = $self[0]['url'];
959 $post->actor->image->url = $self[0]['photo'];
961 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
962 DBA::escape(Strings::normaliseLink($post->actor->url)),
966 if (DBA::isResult($r)) {
967 $contactid = $r[0]['id'];
970 if ($contactid == 0) {
971 $contactid = $orig_post['contact-id'];
975 $condition = ['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
976 if (Item::exists($condition)) {
977 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
982 $likedata['parent'] = $orig_post['id'];
983 $likedata['verb'] = Activity::LIKE;
984 $likedata['gravity'] = GRAVITY_ACTIVITY;
985 $likedata['uid'] = $uid;
986 $likedata['wall'] = 0;
987 $likedata['network'] = Protocol::PUMPIO;
988 $likedata['uri'] = Item::newURI($uid);
989 $likedata['parent-uri'] = $orig_post["uri"];
990 $likedata['contact-id'] = $contactid;
991 $likedata['app'] = $post->generator->displayName;
992 $likedata['author-name'] = $post->actor->displayName;
993 $likedata['author-link'] = $post->actor->url;
994 if (!empty($post->actor->image)) {
995 $likedata['author-avatar'] = $post->actor->image->url;
998 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
999 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
1000 $post_type = L10n::t('status');
1001 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
1002 $likedata['object-type'] = Activity\ObjectType::NOTE;
1004 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
1006 $likedata['object'] = '<object><type>' . Activity\ObjectType::NOTE . '</type><local>1</local>' .
1007 '<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>';
1009 $ret = Item::insert($likedata);
1011 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
1014 function pumpio_get_contact($uid, $contact, $no_insert = false)
1016 $cid = Contact::getIdForURL($contact->url, $uid);
1022 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1023 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1025 if (!DBA::isResult($r)) {
1026 // create contact record
1027 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1028 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1029 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1030 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1032 DBA::escape(DateTimeFormat::utcNow()),
1033 DBA::escape($contact->url),
1034 DBA::escape(Strings::normaliseLink($contact->url)),
1035 DBA::escape(str_replace("acct:", "", $contact->id)),
1037 DBA::escape($contact->id), // What is it for?
1038 DBA::escape('pump.io ' . $contact->id), // What is it for?
1039 DBA::escape($contact->displayName),
1040 DBA::escape($contact->preferredUsername),
1041 DBA::escape($contact->image->url),
1042 DBA::escape(Protocol::PUMPIO),
1043 intval(Contact::FRIEND),
1045 DBA::escape($contact->location->displayName),
1046 DBA::escape($contact->summary),
1050 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1051 DBA::escape(Strings::normaliseLink($contact->url)),
1055 if (!DBA::isResult($r)) {
1059 $contact_id = $r[0]['id'];
1061 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1063 $contact_id = $r[0]["id"];
1065 /* if (DB_UPDATE_VERSION >= "1177")
1066 q("UPDATE `contact` SET `location` = '%s',
1069 dbesc($contact->location->displayName),
1070 dbesc($contact->summary),
1076 if (!empty($contact->image->url)) {
1077 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1083 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1085 // Two queries for speed issues
1086 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1087 if (Item::exists($condition)) {
1088 Item::delete($condition);
1092 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1093 if (Item::exists($condition)) {
1094 Item::delete($condition);
1100 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1102 require_once('include/items.php');
1104 if (($post->verb == "like") || ($post->verb == "favorite")) {
1105 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1108 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1109 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1112 if ($post->verb == "delete") {
1113 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1116 if ($post->verb != "update") {
1117 // Two queries for speed issues
1118 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1121 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1126 // Only handle these three types
1127 if (!strstr("post|share|update", $post->verb)) {
1132 if (@is_array($post->cc)) {
1133 $receiptians = array_merge($receiptians, $post->cc);
1136 if (@is_array($post->to)) {
1137 $receiptians = array_merge($receiptians, $post->to);
1142 foreach ($receiptians AS $receiver) {
1143 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1149 $postarray['network'] = Protocol::PUMPIO;
1150 $postarray['uid'] = $uid;
1151 $postarray['wall'] = 0;
1152 $postarray['uri'] = $post->object->id;
1153 $postarray['object-type'] = ActivityNamespace::ACTIVITY_SCHEMA . strtolower($post->object->objectType);
1155 if ($post->object->objectType != "comment") {
1156 $contact_id = pumpio_get_contact($uid, $post->actor);
1159 $contact_id = $self[0]['id'];
1162 $postarray['parent-uri'] = $post->object->id;
1165 $postarray['private'] = 1;
1166 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1169 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1171 if (Strings::compareLink($post->actor->url, $own_id)) {
1172 $contact_id = $self[0]['id'];
1173 $post->actor->displayName = $self[0]['name'];
1174 $post->actor->url = $self[0]['url'];
1175 $post->actor->image->url = $self[0]['photo'];
1176 } elseif ($contact_id == 0) {
1177 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
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 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1187 DBA::escape(Strings::normaliseLink($post->actor->url)),
1191 if (DBA::isResult($r)) {
1192 $contact_id = $r[0]['id'];
1194 $contact_id = $self[0]['id'];
1199 $reply = new stdClass;
1200 $reply->verb = "note";
1202 if (isset($post->cc)) {
1203 $reply->cc = $post->cc;
1206 if (isset($post->to)) {
1207 $reply->to = $post->to;
1210 $reply->object = new stdClass;
1211 $reply->object->objectType = $post->object->inReplyTo->objectType;
1212 $reply->object->content = $post->object->inReplyTo->content;
1213 $reply->object->id = $post->object->inReplyTo->id;
1214 $reply->actor = $post->object->inReplyTo->author;
1215 $reply->url = $post->object->inReplyTo->url;
1216 $reply->generator = new stdClass;
1217 $reply->generator->displayName = "pumpio";
1218 $reply->published = $post->object->inReplyTo->published;
1219 $reply->received = $post->object->inReplyTo->updated;
1220 $reply->url = $post->object->inReplyTo->url;
1221 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1223 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1226 // When there is no content there is no need to continue
1227 if (empty($post->object->content)) {
1231 if (!empty($post->object->pump_io->proxyURL)) {
1232 $postarray['extid'] = $post->object->pump_io->proxyURL;
1235 $postarray['contact-id'] = $contact_id;
1236 $postarray['verb'] = Activity::POST;
1237 $postarray['owner-name'] = $post->actor->displayName;
1238 $postarray['owner-link'] = $post->actor->url;
1239 $postarray['author-name'] = $postarray['owner-name'];
1240 $postarray['author-link'] = $postarray['owner-link'];
1241 if (!empty($post->actor->image)) {
1242 $postarray['owner-avatar'] = $post->actor->image->url;
1243 $postarray['author-avatar'] = $postarray['owner-avatar'];
1245 $postarray['plink'] = $post->object->url;
1246 $postarray['app'] = $post->generator->displayName;
1247 $postarray['title'] = '';
1248 $postarray['body'] = HTML::toBBCode($post->object->content);
1249 $postarray['object'] = json_encode($post);
1251 if (!empty($post->object->fullImage->url)) {
1252 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1255 if (!empty($post->object->displayName)) {
1256 $postarray['title'] = $post->object->displayName;
1259 $postarray['created'] = DateTimeFormat::utc($post->published);
1260 if (isset($post->updated)) {
1261 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1262 } elseif (isset($post->received)) {
1263 $postarray['edited'] = DateTimeFormat::utc($post->received);
1265 $postarray['edited'] = $postarray['created'];
1268 if ($post->verb == "share") {
1269 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1270 $share_author = $post->object->author->displayName;
1271 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1272 $share_author = $post->object->author->preferredUsername;
1274 $share_author = $post->object->author->url;
1277 if (isset($post->object->created)) {
1278 $created = DateTimeFormat::utc($post->object->created);
1283 $postarray['body'] = share_header($share_author, $post->object->author->url,
1284 $post->object->author->image->url, "",
1285 $created, $post->links->self->href).
1286 $postarray['body']."[/share]";
1289 if (trim($postarray['body']) == "") {
1293 $top_item = Item::insert($postarray);
1294 $postarray["id"] = $top_item;
1296 if (($top_item == 0) && ($post->verb == "update")) {
1297 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1298 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1299 Item::update($fields, $condition);
1302 if (($post->object->objectType == "comment") && $threadcompletion) {
1303 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1309 function pumpio_fetchinbox(App $a, $uid)
1311 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1312 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1313 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1314 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1315 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1316 $hostname = PConfig::get($uid, 'pumpio', 'host');
1317 $username = PConfig::get($uid, "pumpio", "user");
1319 $own_id = "https://".$hostname."/".$username;
1321 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1324 $lastitems = q("SELECT `uri` FROM `thread`
1325 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1326 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1327 ORDER BY `thread`.`commented` DESC LIMIT 10",
1328 DBA::escape(Protocol::PUMPIO),
1332 $client = new oauth_client_class;
1333 $client->oauth_version = '1.0a';
1334 $client->authorization_header = true;
1335 $client->url_parameters = false;
1337 $client->client_id = $ckey;
1338 $client->client_secret = $csecret;
1339 $client->access_token = $otoken;
1340 $client->access_token_secret = $osecret;
1342 $last_id = PConfig::get($uid, 'pumpio', 'last_id');
1344 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1346 if ($last_id != "") {
1347 $url .= '?since='.urlencode($last_id);
1350 if (pumpio_reachable($url)) {
1351 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1360 if (!empty($user->items)) {
1361 $posts = array_reverse($user->items);
1363 if (count($posts)) {
1364 foreach ($posts as $post) {
1365 $last_id = $post->id;
1366 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1371 foreach ($lastitems as $item) {
1372 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1375 PConfig::set($uid, 'pumpio', 'last_id', $last_id);
1378 function pumpio_getallusers(App &$a, $uid)
1380 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1381 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1382 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1383 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1384 $hostname = PConfig::get($uid, 'pumpio', 'host');
1385 $username = PConfig::get($uid, "pumpio", "user");
1387 $client = new oauth_client_class;
1388 $client->oauth_version = '1.0a';
1389 $client->authorization_header = true;
1390 $client->url_parameters = false;
1392 $client->client_id = $ckey;
1393 $client->client_secret = $csecret;
1394 $client->access_token = $otoken;
1395 $client->access_token_secret = $osecret;
1397 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1399 if (pumpio_reachable($url)) {
1400 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1405 if (empty($users)) {
1409 if ($users->totalItems > count($users->items)) {
1410 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1412 if (pumpio_reachable($url)) {
1413 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1419 if (!empty($users->items)) {
1420 foreach ($users->items as $user) {
1421 pumpio_get_contact($uid, $user);
1426 function pumpio_getreceiver(App $a, array $b)
1430 if (!$b["private"]) {
1431 if (!strstr($b['postopts'], 'pumpio')) {
1435 $public = PConfig::get($b['uid'], "pumpio", "public");
1438 $receiver["to"][] = [
1439 "objectType" => "collection",
1440 "id" => "http://activityschema.org/collection/public"];
1443 $cids = explode("><", $b["allow_cid"]);
1444 $gids = explode("><", $b["allow_gid"]);
1446 foreach ($cids AS $cid) {
1447 $cid = trim($cid, " <>");
1449 $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",
1452 DBA::escape(Protocol::PUMPIO)
1455 if (DBA::isResult($r)) {
1456 $receiver["bcc"][] = [
1457 "displayName" => $r[0]["name"],
1458 "objectType" => "person",
1459 "preferredUsername" => $r[0]["nick"],
1460 "url" => $r[0]["url"]];
1463 foreach ($gids AS $gid) {
1464 $gid = trim($gid, " <>");
1466 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1467 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1468 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1470 DBA::escape(Protocol::PUMPIO)
1473 foreach ($r AS $row)
1474 $receiver["bcc"][] = [
1475 "displayName" => $row["name"],
1476 "objectType" => "person",
1477 "preferredUsername" => $row["nick"],
1478 "url" => $row["url"]];
1482 if ($b["inform"] != "") {
1483 $inform = explode(",", $b["inform"]);
1485 foreach ($inform AS $cid) {
1486 if (substr($cid, 0, 4) != "cid:") {
1490 $cid = str_replace("cid:", "", $cid);
1492 $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",
1495 DBA::escape(Protocol::PUMPIO)
1498 if (DBA::isResult($r)) {
1499 $receiver["to"][] = [
1500 "displayName" => $r[0]["name"],
1501 "objectType" => "person",
1502 "preferredUsername" => $r[0]["nick"],
1503 "url" => $r[0]["url"]];
1511 function pumpio_fetchallcomments(App $a, $uid, $id)
1513 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1514 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1515 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1516 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1517 $hostname = PConfig::get($uid, 'pumpio', 'host');
1518 $username = PConfig::get($uid, "pumpio", "user");
1520 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1522 $own_id = "https://".$hostname."/".$username;
1524 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1527 // Fetching the original post
1528 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1529 $item = Item::selectFirst(['extid'], $condition);
1530 if (!DBA::isResult($item)) {
1534 $url = $item["extid"];
1536 $client = new oauth_client_class;
1537 $client->oauth_version = '1.0a';
1538 $client->authorization_header = true;
1539 $client->url_parameters = false;
1541 $client->client_id = $ckey;
1542 $client->client_secret = $csecret;
1543 $client->access_token = $otoken;
1544 $client->access_token_secret = $osecret;
1546 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1548 if (pumpio_reachable($url)) {
1549 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1558 if ($item->likes->totalItems != 0) {
1559 foreach ($item->likes->items AS $post) {
1560 $like = new stdClass;
1561 $like->object = new stdClass;
1562 $like->object->id = $item->id;
1563 $like->actor = new stdClass;
1564 if (!empty($item->displayName)) {
1565 $like->actor->displayName = $item->displayName;
1567 //$like->actor->preferredUsername = $item->preferredUsername;
1568 //$like->actor->image = $item->image;
1569 $like->actor->url = $item->url;
1570 $like->generator = new stdClass;
1571 $like->generator->displayName = "pumpio";
1572 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1576 if ($item->replies->totalItems == 0) {
1580 foreach ($item->replies->items AS $item) {
1581 if ($item->id == $id) {
1585 // Checking if the comment already exists - Two queries for speed issues
1586 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1590 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1594 $post = new stdClass;
1595 $post->verb = "post";
1596 $post->actor = $item->author;
1597 $post->published = $item->published;
1598 $post->received = $item->updated;
1599 $post->generator = new stdClass;
1600 $post->generator->displayName = "pumpio";
1601 // To-Do: Check for public post
1603 unset($item->author);
1604 unset($item->published);
1605 unset($item->updated);
1607 $post->object = $item;
1609 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1610 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1614 function pumpio_reachable($url)
1616 return Network::curl($url, false, ['timeout' => 10])->isSuccess();