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;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Item;
23 use Friendica\Model\User;
24 use Friendica\Protocol\Activity;
25 use Friendica\Util\ConfigFileLoader;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
29 use Friendica\Util\XML;
31 require 'addon/pumpio/oauth/http.php';
32 require 'addon/pumpio/oauth/oauth_client.php';
33 require_once "mod/share.php";
35 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
37 function pumpio_install()
39 Hook::register('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
40 Hook::register('hook_fork', 'addon/pumpio/pumpio.php', 'hook_fork');
41 Hook::register('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
42 Hook::register('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
43 Hook::register('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
44 Hook::register('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
45 Hook::register('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
46 Hook::register('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
47 Hook::register('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
50 function pumpio_uninstall()
52 Hook::unregister('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
53 Hook::unregister('hook_fork', 'addon/pumpio/pumpio.php', 'pumpio_hook_fork');
54 Hook::unregister('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
55 Hook::unregister('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
56 Hook::unregister('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
57 Hook::unregister('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
58 Hook::unregister('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
59 Hook::unregister('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
60 Hook::unregister('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
63 function pumpio_module() {}
65 function pumpio_content(App $a)
68 notice(L10n::t('Permission denied.') . EOL);
72 require_once("mod/settings.php");
75 if (isset($a->argv[1])) {
76 switch ($a->argv[1]) {
78 $o = pumpio_connect($a);
81 $o = print_r($a->argv, true);
85 $o = pumpio_connect($a);
90 function pumpio_check_item_notification($a, &$notification_data)
92 $hostname = PConfig::get($notification_data["uid"], 'pumpio', 'host');
93 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
95 $notification_data["profiles"][] = "https://".$hostname."/".$username;
98 function pumpio_registerclient(App $a, $host)
100 $url = "https://".$host."/api/client/register";
104 $application_name = Config::get('pumpio', 'application_name');
106 if ($application_name == "") {
107 $application_name = $a->getHostName();
110 $adminlist = explode(",", str_replace(" ", "", Config::get('config', 'admin_email')));
112 $params["type"] = "client_associate";
113 $params["contacts"] = $adminlist[0];
114 $params["application_type"] = "native";
115 $params["application_name"] = $application_name;
116 $params["logo_url"] = $a->getBaseURL()."/images/friendica-256.png";
117 $params["redirect_uris"] = $a->getBaseURL()."/pumpio/connect";
119 Logger::log("pumpio_registerclient: ".$url." parameters ".print_r($params, true), Logger::DEBUG);
121 $ch = curl_init($url);
122 curl_setopt($ch, CURLOPT_HEADER, false);
123 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
124 curl_setopt($ch, CURLOPT_POST,1);
125 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
126 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
129 $curl_info = curl_getinfo($ch);
131 if ($curl_info["http_code"] == "200") {
132 $values = json_decode($s);
133 Logger::log("pumpio_registerclient: success ".print_r($values, true), Logger::DEBUG);
136 Logger::log("pumpio_registerclient: failed: ".print_r($curl_info, true), Logger::DEBUG);
141 function pumpio_connect(App $a)
143 // Define the needed keys
144 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
145 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
146 $hostname = PConfig::get(local_user(), 'pumpio', 'host');
148 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
149 Logger::log("pumpio_connect: register client");
150 $clientdata = pumpio_registerclient($a, $hostname);
151 PConfig::set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
152 PConfig::set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
154 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
155 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
157 Logger::log("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, Logger::DEBUG);
160 if (($consumer_key == "") || ($consumer_secret == "")) {
161 Logger::log("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
163 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
167 // The callback URL is the script that gets called after the user authenticates with pumpio
168 $callback_url = $a->getBaseURL()."/pumpio/connect";
170 // Let's begin. First we need a Request Token. The request token is required to send the user
171 // to pumpio's login page.
173 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
174 // Consumer Key and Consumer Secret
175 $client = new oauth_client_class;
177 $client->server = '';
178 $client->oauth_version = '1.0a';
179 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
180 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
181 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
182 $client->url_parameters = false;
183 $client->authorization_header = true;
184 $client->redirect_uri = $callback_url;
185 $client->client_id = $consumer_key;
186 $client->client_secret = $consumer_secret;
188 if (($success = $client->Initialize())) {
189 if (($success = $client->Process())) {
190 if (strlen($client->access_token)) {
191 Logger::log("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, Logger::DEBUG);
192 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
193 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
196 $success = $client->Finalize($success);
199 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
203 Logger::log("pumpio_connect: authenticated");
204 $o = L10n::t("You are now authenticated to pumpio.");
205 $o .= '<br /><a href="'.$a->getBaseURL().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
207 Logger::log("pumpio_connect: could not connect");
208 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
214 function pumpio_jot_nets(App $a, array &$jotnets_fields)
216 if (! local_user()) {
220 if (PConfig::get(local_user(), 'pumpio', 'post')) {
221 $jotnets_fields[] = [
222 'type' => 'checkbox',
225 L10n::t('Post to pumpio'),
226 PConfig::get(local_user(), 'pumpio', 'post_by_default')
232 function pumpio_settings(App $a, &$s)
238 /* Add our stylesheet to the page so we can make our settings look nice */
240 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
242 /* Get the current state of our config variables */
244 $import_enabled = PConfig::get(local_user(), 'pumpio', 'import');
245 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
247 $enabled = PConfig::get(local_user(), 'pumpio', 'post');
248 $checked = (($enabled) ? ' checked="checked" ' : '');
249 $css = (($enabled) ? '' : '-disabled');
251 $def_enabled = PConfig::get(local_user(), 'pumpio', 'post_by_default');
252 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
254 $public_enabled = PConfig::get(local_user(), 'pumpio', 'public');
255 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
257 $mirror_enabled = PConfig::get(local_user(), 'pumpio', 'mirror');
258 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
260 $servername = PConfig::get(local_user(), "pumpio", "host");
261 $username = PConfig::get(local_user(), "pumpio", "user");
263 /* Add some HTML to the existing form */
265 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
266 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
268 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
269 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
270 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
273 $s .= '<div id="pumpio-username-wrapper">';
274 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
275 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
276 $s .= '</div><div class="clear"></div>';
278 $s .= '<div id="pumpio-servername-wrapper">';
279 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
280 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
281 $s .= '</div><div class="clear"></div>';
283 if (($username != '') && ($servername != '')) {
284 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
285 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
287 $s .= '<div id="pumpio-password-wrapper">';
288 if (($oauth_token == "") || ($oauth_token_secret == "")) {
289 $s .= '<div id="pumpio-authenticate-wrapper">';
290 $s .= '<a href="'.$a->getBaseURL().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
291 $s .= '</div><div class="clear"></div>';
293 $s .= '<div id="pumpio-import-wrapper">';
294 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
295 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
296 $s .= '</div><div class="clear"></div>';
298 $s .= '<div id="pumpio-enable-wrapper">';
299 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
300 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
301 $s .= '</div><div class="clear"></div>';
303 $s .= '<div id="pumpio-bydefault-wrapper">';
304 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
305 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
306 $s .= '</div><div class="clear"></div>';
308 $s .= '<div id="pumpio-public-wrapper">';
309 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
310 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
311 $s .= '</div><div class="clear"></div>';
313 $s .= '<div id="pumpio-mirror-wrapper">';
314 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
315 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
316 $s .= '</div><div class="clear"></div>';
318 $s .= '<div id="pumpio-delete-wrapper">';
319 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
320 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
321 $s .= '</div><div class="clear"></div>';
324 $s .= '</div><div class="clear"></div>';
327 /* provide a submit button */
329 $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>';
332 function pumpio_settings_post(App $a, array &$b)
334 if (!empty($_POST['pumpio-submit'])) {
335 if (!empty($_POST['pumpio_delete'])) {
336 PConfig::set(local_user(), 'pumpio', 'consumer_key' , '');
337 PConfig::set(local_user(), 'pumpio', 'consumer_secret' , '');
338 PConfig::set(local_user(), 'pumpio', 'oauth_token' , '');
339 PConfig::set(local_user(), 'pumpio', 'oauth_token_secret', '');
340 PConfig::set(local_user(), 'pumpio', 'post' , false);
341 PConfig::set(local_user(), 'pumpio', 'import' , false);
342 PConfig::set(local_user(), 'pumpio', 'host' , '');
343 PConfig::set(local_user(), 'pumpio', 'user' , '');
344 PConfig::set(local_user(), 'pumpio', 'public' , false);
345 PConfig::set(local_user(), 'pumpio', 'mirror' , false);
346 PConfig::set(local_user(), 'pumpio', 'post_by_default' , false);
347 PConfig::set(local_user(), 'pumpio', 'lastdate' , 0);
348 PConfig::set(local_user(), 'pumpio', 'last_id' , '');
350 // filtering the username if it is filled wrong
351 $user = $_POST['pumpio_user'];
352 if (strstr($user, "@")) {
353 $pos = strpos($user, "@");
356 $user = substr($user, 0, $pos);
360 // Filtering the hostname if someone is entering it with "http"
361 $host = $_POST['pumpio_host'];
363 $host = str_replace(["https://", "http://"], ["", ""], $host);
365 PConfig::set(local_user(), 'pumpio', 'post' , $_POST['pumpio'] ?? false);
366 PConfig::set(local_user(), 'pumpio', 'import' , $_POST['pumpio_import'] ?? false);
367 PConfig::set(local_user(), 'pumpio', 'host' , $host);
368 PConfig::set(local_user(), 'pumpio', 'user' , $user);
369 PConfig::set(local_user(), 'pumpio', 'public' , $_POST['pumpio_public'] ?? false);
370 PConfig::set(local_user(), 'pumpio', 'mirror' , $_POST['pumpio_mirror'] ?? false);
371 PConfig::set(local_user(), 'pumpio', 'post_by_default', $_POST['pumpio_bydefault'] ?? false);
373 if (!empty($_POST['pumpio_mirror'])) {
374 PConfig::delete(local_user(), 'pumpio', 'lastdate');
380 function pumpio_load_config(App $a, ConfigFileLoader $loader)
382 $a->getConfigCache()->load($loader->loadAddonConfig('pumpio'));
385 function pumpio_hook_fork(App $a, array &$b)
387 if ($b['name'] != 'notifier_normal') {
393 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
394 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
395 $b['execute'] = false;
399 // if post comes from pump.io don't send it back
400 if ($post['app'] == "pump.io") {
401 $b['execute'] = false;
405 if (PConfig::get($post['uid'], 'pumpio', 'import')) {
406 // Don't fork if it isn't a reply to a pump.io post
407 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::PUMPIO])) {
408 Logger::log('No pump.io parent found for item ' . $post['id']);
409 $b['execute'] = false;
413 // Comments are never exported when we don't import the pumpio timeline
414 if (!strstr($post['postopts'], 'pumpio') || ($post['parent'] != $post['id']) || $post['private']) {
415 $b['execute'] = false;
421 function pumpio_post_local(App $a, array &$b)
423 if (!local_user() || (local_user() != $b['uid'])) {
427 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
429 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
431 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
435 if (!$pumpio_enable) {
439 if (strlen($b['postopts'])) {
440 $b['postopts'] .= ',';
443 $b['postopts'] .= 'pumpio';
446 function pumpio_send(App $a, array &$b)
448 if (!PConfig::get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
452 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
454 if ($b['parent'] != $b['id']) {
455 // Looking if its a reply to a pumpio post
456 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
457 $orig_post = Item::selectFirst([], $condition);
459 if (!DBA::isResult($orig_post)) {
460 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
468 $receiver = pumpio_getreceiver($a, $b);
470 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
472 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
476 // Dont't post if the post doesn't belong to us.
477 // This is a check for forum postings
478 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
479 if ($b['contact-id'] != $self['id']) {
484 if ($b['verb'] == Activity::LIKE) {
486 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
488 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
493 if ($b['verb'] == Activity::DISLIKE) {
497 if (($b['verb'] == Activity::POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
498 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
501 if (($b['verb'] == Activity::POST) && $b['deleted']) {
502 pumpio_action($a, $b["uid"], $b["uri"], "delete");
505 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
509 // if post comes from pump.io don't send it back
510 if ($b['app'] == "pump.io") {
515 // Support for native shares
516 // http://<hostname>/api/<type>/shares?id=<the-object-id>
518 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
519 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
520 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
521 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
523 $host = PConfig::get($b['uid'], "pumpio", "host");
524 $user = PConfig::get($b['uid'], "pumpio", "user");
525 $public = PConfig::get($b['uid'], "pumpio", "public");
527 if ($oauth_token && $oauth_token_secret) {
528 $title = trim($b['title']);
530 $content = BBCode::convert($b['body'], false, 4);
534 $params["verb"] = "post";
537 $params["object"] = [
538 'objectType' => "note",
539 'content' => $content];
541 if (!empty($title)) {
542 $params["object"]["displayName"] = $title;
545 if (!empty($receiver["to"])) {
546 $params["to"] = $receiver["to"];
549 if (!empty($receiver["bto"])) {
550 $params["bto"] = $receiver["bto"];
553 if (!empty($receiver["cc"])) {
554 $params["cc"] = $receiver["cc"];
557 if (!empty($receiver["bcc"])) {
558 $params["bcc"] = $receiver["bcc"];
561 $inReplyTo = ["id" => $orig_post["uri"],
562 "objectType" => "note"];
564 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], Activity\Namespaces::ACTIVITY_SCHEMA))) {
565 $inReplyTo["objectType"] = str_replace(Activity\Namespaces::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
568 $params["object"] = [
569 'objectType' => "comment",
570 'content' => $content,
571 'inReplyTo' => $inReplyTo];
574 $params["object"]["displayName"] = $title;
578 $client = new oauth_client_class;
579 $client->oauth_version = '1.0a';
580 $client->url_parameters = false;
581 $client->authorization_header = true;
582 $client->access_token = $oauth_token;
583 $client->access_token_secret = $oauth_token_secret;
584 $client->client_id = $consumer_key;
585 $client->client_secret = $consumer_secret;
587 $username = $user.'@'.$host;
588 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
590 if (pumpio_reachable($url)) {
591 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
597 if ($user->generator->displayName) {
598 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
601 $post_id = $user->object->id;
602 Logger::log('pumpio_send '.$username.': success '.$post_id);
603 if ($post_id && $iscomment) {
604 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
605 Item::update(['extid' => $post_id], ['id' => $b['id']]);
608 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
614 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
616 // Don't do likes and other stuff if you don't import the timeline
617 if (!PConfig::get($uid, 'pumpio', 'import')) {
621 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
622 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
623 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
624 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
625 $hostname = PConfig::get($uid, 'pumpio', 'host');
626 $username = PConfig::get($uid, "pumpio", "user");
628 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
630 if (!DBA::isResult($orig_post)) {
634 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
635 $uri = $orig_post["extid"];
637 $uri = $orig_post["uri"];
640 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], Activity\Namespaces::ACTIVITY_SCHEMA))) {
641 $objectType = str_replace(Activity\Namespaces::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
642 } elseif (strstr($uri, "/api/comment/")) {
643 $objectType = "comment";
644 } elseif (strstr($uri, "/api/note/")) {
645 $objectType = "note";
646 } elseif (strstr($uri, "/api/image/")) {
647 $objectType = "image";
650 $params["verb"] = $action;
651 $params["object"] = ['id' => $uri,
652 "objectType" => $objectType,
653 "content" => $content];
655 $client = new oauth_client_class;
656 $client->oauth_version = '1.0a';
657 $client->authorization_header = true;
658 $client->url_parameters = false;
660 $client->client_id = $ckey;
661 $client->client_secret = $csecret;
662 $client->access_token = $otoken;
663 $client->access_token_secret = $osecret;
665 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
667 if (pumpio_reachable($url)) {
668 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
674 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
676 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user, true));
681 function pumpio_sync(App $a)
683 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
685 if (!DBA::isResult($r)) {
689 $last = Config::get('pumpio', 'last_poll');
691 $poll_interval = intval(Config::get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
694 $next = $last + ($poll_interval * 60);
695 if ($next > time()) {
696 Logger::log('pumpio: poll intervall not reached');
700 Logger::log('pumpio: cron_start');
702 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
703 if (DBA::isResult($r)) {
704 foreach ($r as $rr) {
705 Logger::log('pumpio: mirroring user '.$rr['uid']);
706 pumpio_fetchtimeline($a, $rr['uid']);
710 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
711 if ($abandon_days < 1) {
715 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
717 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
718 if (DBA::isResult($r)) {
719 foreach ($r as $rr) {
720 if ($abandon_days != 0) {
721 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
722 if (!DBA::isResult($user)) {
723 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
728 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
729 pumpio_fetchinbox($a, $rr['uid']);
731 // check for new contacts once a day
732 $last_contact_check = PConfig::get($rr['uid'], 'pumpio', 'contact_check');
733 if ($last_contact_check) {
734 $next_contact_check = $last_contact_check + 86400;
736 $next_contact_check = 0;
739 if ($next_contact_check <= time()) {
740 pumpio_getallusers($a, $rr["uid"]);
741 PConfig::set($rr['uid'], 'pumpio', 'contact_check', time());
746 Logger::log('pumpio: cron_end');
748 Config::set('pumpio', 'last_poll', time());
751 function pumpio_cron(App $a, $b)
753 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
756 function pumpio_fetchtimeline(App $a, $uid)
758 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
759 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
760 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
761 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
762 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
763 $hostname = PConfig::get($uid, 'pumpio', 'host');
764 $username = PConfig::get($uid, "pumpio", "user");
766 // get the application name for the pump.io app
767 // 1st try personal config, then system config and fallback to the
768 // hostname of the node if neither one is set.
769 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
770 if ($application_name == "") {
771 $application_name = Config::get('pumpio', 'application_name');
773 if ($application_name == "") {
774 $application_name = $a->getHostName();
777 $first_time = ($lastdate == "");
779 $client = new oauth_client_class;
780 $client->oauth_version = '1.0a';
781 $client->authorization_header = true;
782 $client->url_parameters = false;
784 $client->client_id = $ckey;
785 $client->client_secret = $csecret;
786 $client->access_token = $otoken;
787 $client->access_token_secret = $osecret;
789 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
791 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);
793 $useraddr = $username.'@'.$hostname;
795 if (pumpio_reachable($url)) {
796 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
803 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
807 $posts = array_reverse($user->items);
809 $initiallastdate = $lastdate;
813 foreach ($posts as $post) {
814 if ($post->published <= $initiallastdate) {
818 if ($lastdate < $post->published) {
819 $lastdate = $post->published;
827 if (@is_array($post->cc)) {
828 $receiptians = array_merge($receiptians, $post->cc);
831 if (@is_array($post->to)) {
832 $receiptians = array_merge($receiptians, $post->to);
836 foreach ($receiptians AS $receiver) {
837 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
842 if ($public && !stristr($post->generator->displayName, $application_name)) {
843 $_SESSION["authenticated"] = true;
844 $_SESSION["uid"] = $uid;
847 $_REQUEST["api_source"] = true;
848 $_REQUEST["profile_uid"] = $uid;
849 $_REQUEST["source"] = "pump.io";
851 if (isset($post->object->id)) {
852 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
855 if ($post->object->displayName != "") {
856 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
858 $_REQUEST["title"] = "";
861 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
863 // To-Do: Picture has to be cached and stored locally
864 if ($post->object->fullImage->url != "") {
865 if ($post->object->fullImage->pump_io->proxyURL != "") {
866 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
868 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
872 Logger::log('pumpio: posting for user '.$uid);
874 require_once('mod/item.php');
877 Logger::log('pumpio: posting done - user '.$uid);
882 if ($lastdate != 0) {
883 PConfig::set($uid, 'pumpio', 'lastdate', $lastdate);
887 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
889 // Searching for the unliked post
890 // Two queries for speed issues
891 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
892 if (!DBA::isResult($orig_post)) {
893 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
894 if (!DBA::isResult($orig_post)) {
901 if (Strings::compareLink($post->actor->url, $own_id)) {
902 $contactid = $self[0]['id'];
904 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
905 DBA::escape(Strings::normaliseLink($post->actor->url)),
909 if (DBA::isResult($r)) {
910 $contactid = $r[0]['id'];
913 if ($contactid == 0) {
914 $contactid = $orig_post['contact-id'];
918 Item::delete(['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
920 if (DBA::isResult($r)) {
921 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
923 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
927 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
929 require_once('include/items.php');
931 if (empty($post->object->id)) {
932 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
936 // Searching for the liked post
937 // Two queries for speed issues
938 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
939 if (!DBA::isResult($orig_post)) {
940 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
941 if (!DBA::isResult($orig_post)) {
947 if ($threadcompletion) {
948 pumpio_fetchallcomments($a, $uid, $post->object->id);
953 if (Strings::compareLink($post->actor->url, $own_id)) {
954 $contactid = $self[0]['id'];
955 $post->actor->displayName = $self[0]['name'];
956 $post->actor->url = $self[0]['url'];
957 $post->actor->image->url = $self[0]['photo'];
959 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
960 DBA::escape(Strings::normaliseLink($post->actor->url)),
964 if (DBA::isResult($r)) {
965 $contactid = $r[0]['id'];
968 if ($contactid == 0) {
969 $contactid = $orig_post['contact-id'];
973 $condition = ['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
974 if (Item::exists($condition)) {
975 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
980 $likedata['parent'] = $orig_post['id'];
981 $likedata['verb'] = Activity::LIKE;
982 $likedata['gravity'] = GRAVITY_ACTIVITY;
983 $likedata['uid'] = $uid;
984 $likedata['wall'] = 0;
985 $likedata['network'] = Protocol::PUMPIO;
986 $likedata['uri'] = Item::newURI($uid);
987 $likedata['parent-uri'] = $orig_post["uri"];
988 $likedata['contact-id'] = $contactid;
989 $likedata['app'] = $post->generator->displayName;
990 $likedata['author-name'] = $post->actor->displayName;
991 $likedata['author-link'] = $post->actor->url;
992 if (!empty($post->actor->image)) {
993 $likedata['author-avatar'] = $post->actor->image->url;
996 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
997 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
998 $post_type = L10n::t('status');
999 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
1000 $likedata['object-type'] = Activity::OBJ_NOTE;
1002 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
1004 $likedata['object'] = '<object><type>' . Activity::OBJ_NOTE . '</type><local>1</local>' .
1005 '<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>';
1007 $ret = Item::insert($likedata);
1009 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
1012 function pumpio_get_contact($uid, $contact, $no_insert = false)
1014 $cid = Contact::getIdForURL($contact->url, $uid);
1020 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1021 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1023 if (!DBA::isResult($r)) {
1024 // create contact record
1025 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1026 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1027 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1028 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1030 DBA::escape(DateTimeFormat::utcNow()),
1031 DBA::escape($contact->url),
1032 DBA::escape(Strings::normaliseLink($contact->url)),
1033 DBA::escape(str_replace("acct:", "", $contact->id)),
1035 DBA::escape($contact->id), // What is it for?
1036 DBA::escape('pump.io ' . $contact->id), // What is it for?
1037 DBA::escape($contact->displayName),
1038 DBA::escape($contact->preferredUsername),
1039 DBA::escape($contact->image->url),
1040 DBA::escape(Protocol::PUMPIO),
1041 intval(Contact::FRIEND),
1043 DBA::escape($contact->location->displayName),
1044 DBA::escape($contact->summary),
1048 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1049 DBA::escape(Strings::normaliseLink($contact->url)),
1053 if (!DBA::isResult($r)) {
1057 $contact_id = $r[0]['id'];
1059 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1061 $contact_id = $r[0]["id"];
1063 /* if (DB_UPDATE_VERSION >= "1177")
1064 q("UPDATE `contact` SET `location` = '%s',
1067 dbesc($contact->location->displayName),
1068 dbesc($contact->summary),
1074 if (!empty($contact->image->url)) {
1075 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1081 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1083 // Two queries for speed issues
1084 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1085 if (Item::exists($condition)) {
1086 Item::delete($condition);
1090 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1091 if (Item::exists($condition)) {
1092 Item::delete($condition);
1098 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1100 require_once('include/items.php');
1102 if (($post->verb == "like") || ($post->verb == "favorite")) {
1103 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1106 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1107 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1110 if ($post->verb == "delete") {
1111 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1114 if ($post->verb != "update") {
1115 // Two queries for speed issues
1116 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1119 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1124 // Only handle these three types
1125 if (!strstr("post|share|update", $post->verb)) {
1130 if (@is_array($post->cc)) {
1131 $receiptians = array_merge($receiptians, $post->cc);
1134 if (@is_array($post->to)) {
1135 $receiptians = array_merge($receiptians, $post->to);
1140 foreach ($receiptians AS $receiver) {
1141 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1147 $postarray['network'] = Protocol::PUMPIO;
1148 $postarray['uid'] = $uid;
1149 $postarray['wall'] = 0;
1150 $postarray['uri'] = $post->object->id;
1151 $postarray['object-type'] = Activity\Namespaces::ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1153 if ($post->object->objectType != "comment") {
1154 $contact_id = pumpio_get_contact($uid, $post->actor);
1157 $contact_id = $self[0]['id'];
1160 $postarray['parent-uri'] = $post->object->id;
1163 $postarray['private'] = 1;
1164 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1167 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1169 if (Strings::compareLink($post->actor->url, $own_id)) {
1170 $contact_id = $self[0]['id'];
1171 $post->actor->displayName = $self[0]['name'];
1172 $post->actor->url = $self[0]['url'];
1173 $post->actor->image->url = $self[0]['photo'];
1174 } elseif ($contact_id == 0) {
1175 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1176 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1177 DBA::escape(Strings::normaliseLink($post->actor->url)),
1181 if (DBA::isResult($r)) {
1182 $contact_id = $r[0]['id'];
1184 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1185 DBA::escape(Strings::normaliseLink($post->actor->url)),
1189 if (DBA::isResult($r)) {
1190 $contact_id = $r[0]['id'];
1192 $contact_id = $self[0]['id'];
1197 $reply = new stdClass;
1198 $reply->verb = "note";
1200 if (isset($post->cc)) {
1201 $reply->cc = $post->cc;
1204 if (isset($post->to)) {
1205 $reply->to = $post->to;
1208 $reply->object = new stdClass;
1209 $reply->object->objectType = $post->object->inReplyTo->objectType;
1210 $reply->object->content = $post->object->inReplyTo->content;
1211 $reply->object->id = $post->object->inReplyTo->id;
1212 $reply->actor = $post->object->inReplyTo->author;
1213 $reply->url = $post->object->inReplyTo->url;
1214 $reply->generator = new stdClass;
1215 $reply->generator->displayName = "pumpio";
1216 $reply->published = $post->object->inReplyTo->published;
1217 $reply->received = $post->object->inReplyTo->updated;
1218 $reply->url = $post->object->inReplyTo->url;
1219 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1221 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1224 // When there is no content there is no need to continue
1225 if (empty($post->object->content)) {
1229 if (!empty($post->object->pump_io->proxyURL)) {
1230 $postarray['extid'] = $post->object->pump_io->proxyURL;
1233 $postarray['contact-id'] = $contact_id;
1234 $postarray['verb'] = Activity::POST;
1235 $postarray['owner-name'] = $post->actor->displayName;
1236 $postarray['owner-link'] = $post->actor->url;
1237 $postarray['author-name'] = $postarray['owner-name'];
1238 $postarray['author-link'] = $postarray['owner-link'];
1239 if (!empty($post->actor->image)) {
1240 $postarray['owner-avatar'] = $post->actor->image->url;
1241 $postarray['author-avatar'] = $postarray['owner-avatar'];
1243 $postarray['plink'] = $post->object->url;
1244 $postarray['app'] = $post->generator->displayName;
1245 $postarray['title'] = '';
1246 $postarray['body'] = HTML::toBBCode($post->object->content);
1247 $postarray['object'] = json_encode($post);
1249 if (!empty($post->object->fullImage->url)) {
1250 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1253 if (!empty($post->object->displayName)) {
1254 $postarray['title'] = $post->object->displayName;
1257 $postarray['created'] = DateTimeFormat::utc($post->published);
1258 if (isset($post->updated)) {
1259 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1260 } elseif (isset($post->received)) {
1261 $postarray['edited'] = DateTimeFormat::utc($post->received);
1263 $postarray['edited'] = $postarray['created'];
1266 if ($post->verb == "share") {
1267 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1268 $share_author = $post->object->author->displayName;
1269 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1270 $share_author = $post->object->author->preferredUsername;
1272 $share_author = $post->object->author->url;
1275 if (isset($post->object->created)) {
1276 $created = DateTimeFormat::utc($post->object->created);
1281 $postarray['body'] = share_header($share_author, $post->object->author->url,
1282 $post->object->author->image->url, "",
1283 $created, $post->links->self->href).
1284 $postarray['body']."[/share]";
1287 if (trim($postarray['body']) == "") {
1291 $top_item = Item::insert($postarray);
1292 $postarray["id"] = $top_item;
1294 if (($top_item == 0) && ($post->verb == "update")) {
1295 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1296 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1297 Item::update($fields, $condition);
1300 if (($post->object->objectType == "comment") && $threadcompletion) {
1301 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1307 function pumpio_fetchinbox(App $a, $uid)
1309 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1310 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1311 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1312 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1313 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1314 $hostname = PConfig::get($uid, 'pumpio', 'host');
1315 $username = PConfig::get($uid, "pumpio", "user");
1317 $own_id = "https://".$hostname."/".$username;
1319 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1322 $lastitems = q("SELECT `uri` FROM `thread`
1323 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1324 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1325 ORDER BY `thread`.`commented` DESC LIMIT 10",
1326 DBA::escape(Protocol::PUMPIO),
1330 $client = new oauth_client_class;
1331 $client->oauth_version = '1.0a';
1332 $client->authorization_header = true;
1333 $client->url_parameters = false;
1335 $client->client_id = $ckey;
1336 $client->client_secret = $csecret;
1337 $client->access_token = $otoken;
1338 $client->access_token_secret = $osecret;
1340 $last_id = PConfig::get($uid, 'pumpio', 'last_id');
1342 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1344 if ($last_id != "") {
1345 $url .= '?since='.urlencode($last_id);
1348 if (pumpio_reachable($url)) {
1349 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1358 if (!empty($user->items)) {
1359 $posts = array_reverse($user->items);
1361 if (count($posts)) {
1362 foreach ($posts as $post) {
1363 $last_id = $post->id;
1364 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1369 foreach ($lastitems as $item) {
1370 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1373 PConfig::set($uid, 'pumpio', 'last_id', $last_id);
1376 function pumpio_getallusers(App &$a, $uid)
1378 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1379 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1380 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1381 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1382 $hostname = PConfig::get($uid, 'pumpio', 'host');
1383 $username = PConfig::get($uid, "pumpio", "user");
1385 $client = new oauth_client_class;
1386 $client->oauth_version = '1.0a';
1387 $client->authorization_header = true;
1388 $client->url_parameters = false;
1390 $client->client_id = $ckey;
1391 $client->client_secret = $csecret;
1392 $client->access_token = $otoken;
1393 $client->access_token_secret = $osecret;
1395 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1397 if (pumpio_reachable($url)) {
1398 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1403 if (empty($users)) {
1407 if ($users->totalItems > count($users->items)) {
1408 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1410 if (pumpio_reachable($url)) {
1411 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1417 if (!empty($users->items)) {
1418 foreach ($users->items as $user) {
1419 pumpio_get_contact($uid, $user);
1424 function pumpio_getreceiver(App $a, array $b)
1428 if (!$b["private"]) {
1429 if (!strstr($b['postopts'], 'pumpio')) {
1433 $public = PConfig::get($b['uid'], "pumpio", "public");
1436 $receiver["to"][] = [
1437 "objectType" => "collection",
1438 "id" => "http://activityschema.org/collection/public"];
1441 $cids = explode("><", $b["allow_cid"]);
1442 $gids = explode("><", $b["allow_gid"]);
1444 foreach ($cids AS $cid) {
1445 $cid = trim($cid, " <>");
1447 $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",
1450 DBA::escape(Protocol::PUMPIO)
1453 if (DBA::isResult($r)) {
1454 $receiver["bcc"][] = [
1455 "displayName" => $r[0]["name"],
1456 "objectType" => "person",
1457 "preferredUsername" => $r[0]["nick"],
1458 "url" => $r[0]["url"]];
1461 foreach ($gids AS $gid) {
1462 $gid = trim($gid, " <>");
1464 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1465 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1466 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1468 DBA::escape(Protocol::PUMPIO)
1471 foreach ($r AS $row)
1472 $receiver["bcc"][] = [
1473 "displayName" => $row["name"],
1474 "objectType" => "person",
1475 "preferredUsername" => $row["nick"],
1476 "url" => $row["url"]];
1480 if ($b["inform"] != "") {
1481 $inform = explode(",", $b["inform"]);
1483 foreach ($inform AS $cid) {
1484 if (substr($cid, 0, 4) != "cid:") {
1488 $cid = str_replace("cid:", "", $cid);
1490 $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",
1493 DBA::escape(Protocol::PUMPIO)
1496 if (DBA::isResult($r)) {
1497 $receiver["to"][] = [
1498 "displayName" => $r[0]["name"],
1499 "objectType" => "person",
1500 "preferredUsername" => $r[0]["nick"],
1501 "url" => $r[0]["url"]];
1509 function pumpio_fetchallcomments(App $a, $uid, $id)
1511 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1512 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1513 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1514 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1515 $hostname = PConfig::get($uid, 'pumpio', 'host');
1516 $username = PConfig::get($uid, "pumpio", "user");
1518 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1520 $own_id = "https://".$hostname."/".$username;
1522 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1525 // Fetching the original post
1526 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1527 $item = Item::selectFirst(['extid'], $condition);
1528 if (!DBA::isResult($item)) {
1532 $url = $item["extid"];
1534 $client = new oauth_client_class;
1535 $client->oauth_version = '1.0a';
1536 $client->authorization_header = true;
1537 $client->url_parameters = false;
1539 $client->client_id = $ckey;
1540 $client->client_secret = $csecret;
1541 $client->access_token = $otoken;
1542 $client->access_token_secret = $osecret;
1544 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1546 if (pumpio_reachable($url)) {
1547 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1556 if ($item->likes->totalItems != 0) {
1557 foreach ($item->likes->items AS $post) {
1558 $like = new stdClass;
1559 $like->object = new stdClass;
1560 $like->object->id = $item->id;
1561 $like->actor = new stdClass;
1562 if (!empty($item->displayName)) {
1563 $like->actor->displayName = $item->displayName;
1565 //$like->actor->preferredUsername = $item->preferredUsername;
1566 //$like->actor->image = $item->image;
1567 $like->actor->url = $item->url;
1568 $like->generator = new stdClass;
1569 $like->generator->displayName = "pumpio";
1570 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1574 if ($item->replies->totalItems == 0) {
1578 foreach ($item->replies->items AS $item) {
1579 if ($item->id == $id) {
1583 // Checking if the comment already exists - Two queries for speed issues
1584 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1588 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1592 $post = new stdClass;
1593 $post->verb = "post";
1594 $post->actor = $item->author;
1595 $post->published = $item->published;
1596 $post->received = $item->updated;
1597 $post->generator = new stdClass;
1598 $post->generator->displayName = "pumpio";
1599 // To-Do: Check for public post
1601 unset($item->author);
1602 unset($item->published);
1603 unset($item->updated);
1605 $post->object = $item;
1607 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1608 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1612 function pumpio_reachable($url)
1614 return Network::curl($url, false, ['timeout' => 10])->isSuccess();