3 * Name: pump.io Post Connector
4 * Description: Bidirectional (posting, relaying and reading) connector for pump.io.
6 * Author: Michael Vogel <http://pirati.ca/profile/heluecht>
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Hook;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBA;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Group;
20 use Friendica\Model\Item;
21 use Friendica\Model\User;
22 use Friendica\Protocol\Activity;
23 use Friendica\Protocol\ActivityNamespace;
24 use Friendica\Util\ConfigFileLoader;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Strings;
27 use Friendica\Util\XML;
29 require 'addon/pumpio/oauth/http.php';
30 require 'addon/pumpio/oauth/oauth_client.php';
31 require_once "mod/share.php";
33 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
35 function pumpio_install()
37 Hook::register('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
38 Hook::register('hook_fork', 'addon/pumpio/pumpio.php', 'hook_fork');
39 Hook::register('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
40 Hook::register('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
41 Hook::register('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
42 Hook::register('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
43 Hook::register('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
44 Hook::register('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
45 Hook::register('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
48 function pumpio_module() {}
50 function pumpio_content(App $a)
53 notice(DI::l10n()->t('Permission denied.') . EOL);
57 require_once("mod/settings.php");
60 if (isset($a->argv[1])) {
61 switch ($a->argv[1]) {
63 $o = pumpio_connect($a);
66 $o = print_r($a->argv, true);
70 $o = pumpio_connect($a);
75 function pumpio_check_item_notification($a, &$notification_data)
77 $hostname = DI::pConfig()->get($notification_data["uid"], 'pumpio', 'host');
78 $username = DI::pConfig()->get($notification_data["uid"], "pumpio", "user");
80 $notification_data["profiles"][] = "https://".$hostname."/".$username;
83 function pumpio_registerclient(App $a, $host)
85 $url = "https://".$host."/api/client/register";
89 $application_name = DI::config()->get('pumpio', 'application_name');
91 if ($application_name == "") {
92 $application_name = DI::baseUrl()->getHostname();
95 $adminlist = explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email')));
97 $params["type"] = "client_associate";
98 $params["contacts"] = $adminlist[0];
99 $params["application_type"] = "native";
100 $params["application_name"] = $application_name;
101 $params["logo_url"] = DI::baseUrl()->get()."/images/friendica-256.png";
102 $params["redirect_uris"] = DI::baseUrl()->get()."/pumpio/connect";
104 Logger::log("pumpio_registerclient: ".$url." parameters ".print_r($params, true), Logger::DEBUG);
106 $ch = curl_init($url);
107 curl_setopt($ch, CURLOPT_HEADER, false);
108 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
109 curl_setopt($ch, CURLOPT_POST,1);
110 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
111 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
114 $curl_info = curl_getinfo($ch);
116 if ($curl_info["http_code"] == "200") {
117 $values = json_decode($s);
118 Logger::log("pumpio_registerclient: success ".print_r($values, true), Logger::DEBUG);
121 Logger::log("pumpio_registerclient: failed: ".print_r($curl_info, true), Logger::DEBUG);
126 function pumpio_connect(App $a)
128 // Define the needed keys
129 $consumer_key = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_key');
130 $consumer_secret = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_secret');
131 $hostname = DI::pConfig()->get(local_user(), 'pumpio', 'host');
133 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
134 Logger::log("pumpio_connect: register client");
135 $clientdata = pumpio_registerclient($a, $hostname);
136 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
137 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
139 $consumer_key = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_key');
140 $consumer_secret = DI::pConfig()->get(local_user(), 'pumpio', 'consumer_secret');
142 Logger::log("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, Logger::DEBUG);
145 if (($consumer_key == "") || ($consumer_secret == "")) {
146 Logger::log("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
148 return DI::l10n()->t("Unable to register the client at the pump.io server '%s'.", $hostname);
151 // The callback URL is the script that gets called after the user authenticates with pumpio
152 $callback_url = DI::baseUrl()->get()."/pumpio/connect";
154 // Let's begin. First we need a Request Token. The request token is required to send the user
155 // to pumpio's login page.
157 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
158 // Consumer Key and Consumer Secret
159 $client = new oauth_client_class;
161 $client->server = '';
162 $client->oauth_version = '1.0a';
163 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
164 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
165 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
166 $client->url_parameters = false;
167 $client->authorization_header = true;
168 $client->redirect_uri = $callback_url;
169 $client->client_id = $consumer_key;
170 $client->client_secret = $consumer_secret;
172 if (($success = $client->Initialize())) {
173 if (($success = $client->Process())) {
174 if (strlen($client->access_token)) {
175 Logger::log("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, Logger::DEBUG);
176 DI::pConfig()->set(local_user(), "pumpio", "oauth_token", $client->access_token);
177 DI::pConfig()->set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
180 $success = $client->Finalize($success);
183 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
187 Logger::log("pumpio_connect: authenticated");
188 $o = DI::l10n()->t("You are now authenticated to pumpio.");
189 $o .= '<br /><a href="'.DI::baseUrl()->get().'/settings/connectors">'.DI::l10n()->t("return to the connector page").'</a>';
191 Logger::log("pumpio_connect: could not connect");
192 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
198 function pumpio_jot_nets(App $a, array &$jotnets_fields)
200 if (! local_user()) {
204 if (DI::pConfig()->get(local_user(), 'pumpio', 'post')) {
205 $jotnets_fields[] = [
206 'type' => 'checkbox',
209 DI::l10n()->t('Post to pumpio'),
210 DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default')
216 function pumpio_settings(App $a, &$s)
222 /* Add our stylesheet to the page so we can make our settings look nice */
224 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
226 /* Get the current state of our config variables */
228 $import_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'import');
229 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
231 $enabled = DI::pConfig()->get(local_user(), 'pumpio', 'post');
232 $checked = (($enabled) ? ' checked="checked" ' : '');
233 $css = (($enabled) ? '' : '-disabled');
235 $def_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default');
236 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
238 $public_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'public');
239 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
241 $mirror_enabled = DI::pConfig()->get(local_user(), 'pumpio', 'mirror');
242 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
244 $servername = DI::pConfig()->get(local_user(), "pumpio", "host");
245 $username = DI::pConfig()->get(local_user(), "pumpio", "user");
247 /* Add some HTML to the existing form */
249 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
250 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. DI::l10n()->t('Pump.io Import/Export/Mirror').'</h3>';
252 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
253 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
254 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. DI::l10n()->t('Pump.io Import/Export/Mirror').'</h3>';
257 $s .= '<div id="pumpio-username-wrapper">';
258 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.DI::l10n()->t('pump.io username (without the servername)').'</label>';
259 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
260 $s .= '</div><div class="clear"></div>';
262 $s .= '<div id="pumpio-servername-wrapper">';
263 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.DI::l10n()->t('pump.io servername (without "http://" or "https://" )').'</label>';
264 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
265 $s .= '</div><div class="clear"></div>';
267 if (($username != '') && ($servername != '')) {
268 $oauth_token = DI::pConfig()->get(local_user(), "pumpio", "oauth_token");
269 $oauth_token_secret = DI::pConfig()->get(local_user(), "pumpio", "oauth_token_secret");
271 $s .= '<div id="pumpio-password-wrapper">';
272 if (($oauth_token == "") || ($oauth_token_secret == "")) {
273 $s .= '<div id="pumpio-authenticate-wrapper">';
274 $s .= '<a href="'.DI::baseUrl()->get().'/pumpio/connect">'.DI::l10n()->t("Authenticate your pump.io connection").'</a>';
275 $s .= '</div><div class="clear"></div>';
277 $s .= '<div id="pumpio-import-wrapper">';
278 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . DI::l10n()->t('Import the remote timeline') . '</label>';
279 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
280 $s .= '</div><div class="clear"></div>';
282 $s .= '<div id="pumpio-enable-wrapper">';
283 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . DI::l10n()->t('Enable pump.io Post Addon') . '</label>';
284 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
285 $s .= '</div><div class="clear"></div>';
287 $s .= '<div id="pumpio-bydefault-wrapper">';
288 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . DI::l10n()->t('Post to pump.io by default') . '</label>';
289 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
290 $s .= '</div><div class="clear"></div>';
292 $s .= '<div id="pumpio-public-wrapper">';
293 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . DI::l10n()->t('Should posts be public?') . '</label>';
294 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
295 $s .= '</div><div class="clear"></div>';
297 $s .= '<div id="pumpio-mirror-wrapper">';
298 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . DI::l10n()->t('Mirror all public posts') . '</label>';
299 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
300 $s .= '</div><div class="clear"></div>';
302 $s .= '<div id="pumpio-delete-wrapper">';
303 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . DI::l10n()->t('Check to delete this preset') . '</label>';
304 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
305 $s .= '</div><div class="clear"></div>';
308 $s .= '</div><div class="clear"></div>';
311 /* provide a submit button */
313 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div></div>';
316 function pumpio_settings_post(App $a, array &$b)
318 if (!empty($_POST['pumpio-submit'])) {
319 if (!empty($_POST['pumpio_delete'])) {
320 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_key' , '');
321 DI::pConfig()->set(local_user(), 'pumpio', 'consumer_secret' , '');
322 DI::pConfig()->set(local_user(), 'pumpio', 'oauth_token' , '');
323 DI::pConfig()->set(local_user(), 'pumpio', 'oauth_token_secret', '');
324 DI::pConfig()->set(local_user(), 'pumpio', 'post' , false);
325 DI::pConfig()->set(local_user(), 'pumpio', 'import' , false);
326 DI::pConfig()->set(local_user(), 'pumpio', 'host' , '');
327 DI::pConfig()->set(local_user(), 'pumpio', 'user' , '');
328 DI::pConfig()->set(local_user(), 'pumpio', 'public' , false);
329 DI::pConfig()->set(local_user(), 'pumpio', 'mirror' , false);
330 DI::pConfig()->set(local_user(), 'pumpio', 'post_by_default' , false);
331 DI::pConfig()->set(local_user(), 'pumpio', 'lastdate' , 0);
332 DI::pConfig()->set(local_user(), 'pumpio', 'last_id' , '');
334 // filtering the username if it is filled wrong
335 $user = $_POST['pumpio_user'];
336 if (strstr($user, "@")) {
337 $pos = strpos($user, "@");
340 $user = substr($user, 0, $pos);
344 // Filtering the hostname if someone is entering it with "http"
345 $host = $_POST['pumpio_host'];
347 $host = str_replace(["https://", "http://"], ["", ""], $host);
349 DI::pConfig()->set(local_user(), 'pumpio', 'post' , $_POST['pumpio'] ?? false);
350 DI::pConfig()->set(local_user(), 'pumpio', 'import' , $_POST['pumpio_import'] ?? false);
351 DI::pConfig()->set(local_user(), 'pumpio', 'host' , $host);
352 DI::pConfig()->set(local_user(), 'pumpio', 'user' , $user);
353 DI::pConfig()->set(local_user(), 'pumpio', 'public' , $_POST['pumpio_public'] ?? false);
354 DI::pConfig()->set(local_user(), 'pumpio', 'mirror' , $_POST['pumpio_mirror'] ?? false);
355 DI::pConfig()->set(local_user(), 'pumpio', 'post_by_default', $_POST['pumpio_bydefault'] ?? false);
357 if (!empty($_POST['pumpio_mirror'])) {
358 DI::pConfig()->delete(local_user(), 'pumpio', 'lastdate');
364 function pumpio_load_config(App $a, ConfigFileLoader $loader)
366 $a->getConfigCache()->load($loader->loadAddonConfig('pumpio'));
369 function pumpio_hook_fork(App $a, array &$b)
371 if ($b['name'] != 'notifier_normal') {
377 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
378 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
379 $b['execute'] = false;
383 // if post comes from pump.io don't send it back
384 if ($post['app'] == "pump.io") {
385 $b['execute'] = false;
389 if (DI::pConfig()->get($post['uid'], 'pumpio', 'import')) {
390 // Don't fork if it isn't a reply to a pump.io post
391 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::PUMPIO])) {
392 Logger::log('No pump.io parent found for item ' . $post['id']);
393 $b['execute'] = false;
397 // Comments are never exported when we don't import the pumpio timeline
398 if (!strstr($post['postopts'], 'pumpio') || ($post['parent'] != $post['id']) || $post['private']) {
399 $b['execute'] = false;
405 function pumpio_post_local(App $a, array &$b)
407 if (!local_user() || (local_user() != $b['uid'])) {
411 $pumpio_post = intval(DI::pConfig()->get(local_user(), 'pumpio', 'post'));
413 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
415 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'pumpio', 'post_by_default'))) {
419 if (!$pumpio_enable) {
423 if (strlen($b['postopts'])) {
424 $b['postopts'] .= ',';
427 $b['postopts'] .= 'pumpio';
430 function pumpio_send(App $a, array &$b)
432 if (!DI::pConfig()->get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
436 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
438 if ($b['parent'] != $b['id']) {
439 // Looking if its a reply to a pumpio post
440 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
441 $orig_post = Item::selectFirst([], $condition);
443 if (!DBA::isResult($orig_post)) {
444 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
452 $receiver = pumpio_getreceiver($a, $b);
454 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
456 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
460 // Dont't post if the post doesn't belong to us.
461 // This is a check for forum postings
462 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
463 if ($b['contact-id'] != $self['id']) {
468 if ($b['verb'] == Activity::LIKE) {
470 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
472 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
477 if ($b['verb'] == Activity::DISLIKE) {
481 if (($b['verb'] == Activity::POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
482 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
485 if (($b['verb'] == Activity::POST) && $b['deleted']) {
486 pumpio_action($a, $b["uid"], $b["uri"], "delete");
489 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
493 // if post comes from pump.io don't send it back
494 if ($b['app'] == "pump.io") {
499 // Support for native shares
500 // http://<hostname>/api/<type>/shares?id=<the-object-id>
502 $oauth_token = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token");
503 $oauth_token_secret = DI::pConfig()->get($b['uid'], "pumpio", "oauth_token_secret");
504 $consumer_key = DI::pConfig()->get($b['uid'], "pumpio","consumer_key");
505 $consumer_secret = DI::pConfig()->get($b['uid'], "pumpio","consumer_secret");
507 $host = DI::pConfig()->get($b['uid'], "pumpio", "host");
508 $user = DI::pConfig()->get($b['uid'], "pumpio", "user");
509 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
511 if ($oauth_token && $oauth_token_secret) {
512 $title = trim($b['title']);
514 $content = BBCode::convert($b['body'], false, BBCode::CONNECTORS);
518 $params["verb"] = "post";
521 $params["object"] = [
522 'objectType' => "note",
523 'content' => $content];
525 if (!empty($title)) {
526 $params["object"]["displayName"] = $title;
529 if (!empty($receiver["to"])) {
530 $params["to"] = $receiver["to"];
533 if (!empty($receiver["bto"])) {
534 $params["bto"] = $receiver["bto"];
537 if (!empty($receiver["cc"])) {
538 $params["cc"] = $receiver["cc"];
541 if (!empty($receiver["bcc"])) {
542 $params["bcc"] = $receiver["bcc"];
545 $inReplyTo = ["id" => $orig_post["uri"],
546 "objectType" => "note"];
548 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
549 $inReplyTo["objectType"] = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
552 $params["object"] = [
553 'objectType' => "comment",
554 'content' => $content,
555 'inReplyTo' => $inReplyTo];
558 $params["object"]["displayName"] = $title;
562 $client = new oauth_client_class;
563 $client->oauth_version = '1.0a';
564 $client->url_parameters = false;
565 $client->authorization_header = true;
566 $client->access_token = $oauth_token;
567 $client->access_token_secret = $oauth_token_secret;
568 $client->client_id = $consumer_key;
569 $client->client_secret = $consumer_secret;
571 $username = $user.'@'.$host;
572 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
574 if (pumpio_reachable($url)) {
575 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
581 if ($user->generator->displayName) {
582 DI::pConfig()->set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
585 $post_id = $user->object->id;
586 Logger::log('pumpio_send '.$username.': success '.$post_id);
587 if ($post_id && $iscomment) {
588 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
589 Item::update(['extid' => $post_id], ['id' => $b['id']]);
592 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
598 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
600 // Don't do likes and other stuff if you don't import the timeline
601 if (!DI::pConfig()->get($uid, 'pumpio', 'import')) {
605 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
606 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
607 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
608 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
609 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
610 $username = DI::pConfig()->get($uid, "pumpio", "user");
612 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
614 if (!DBA::isResult($orig_post)) {
618 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
619 $uri = $orig_post["extid"];
621 $uri = $orig_post["uri"];
624 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], ActivityNamespace::ACTIVITY_SCHEMA))) {
625 $objectType = str_replace(ActivityNamespace::ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
626 } elseif (strstr($uri, "/api/comment/")) {
627 $objectType = "comment";
628 } elseif (strstr($uri, "/api/note/")) {
629 $objectType = "note";
630 } elseif (strstr($uri, "/api/image/")) {
631 $objectType = "image";
634 $params["verb"] = $action;
635 $params["object"] = ['id' => $uri,
636 "objectType" => $objectType,
637 "content" => $content];
639 $client = new oauth_client_class;
640 $client->oauth_version = '1.0a';
641 $client->authorization_header = true;
642 $client->url_parameters = false;
644 $client->client_id = $ckey;
645 $client->client_secret = $csecret;
646 $client->access_token = $otoken;
647 $client->access_token_secret = $osecret;
649 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
651 if (pumpio_reachable($url)) {
652 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
658 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
660 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri);
665 function pumpio_sync(App $a)
667 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
669 if (!DBA::isResult($r)) {
673 $last = DI::config()->get('pumpio', 'last_poll');
675 $poll_interval = intval(DI::config()->get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
678 $next = $last + ($poll_interval * 60);
679 if ($next > time()) {
680 Logger::log('pumpio: poll intervall not reached');
684 Logger::log('pumpio: cron_start');
686 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
687 if (DBA::isResult($r)) {
688 foreach ($r as $rr) {
689 Logger::log('pumpio: mirroring user '.$rr['uid']);
690 pumpio_fetchtimeline($a, $rr['uid']);
694 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
695 if ($abandon_days < 1) {
699 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
701 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
702 if (DBA::isResult($r)) {
703 foreach ($r as $rr) {
704 if ($abandon_days != 0) {
705 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
706 if (!DBA::isResult($user)) {
707 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
712 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
713 pumpio_fetchinbox($a, $rr['uid']);
715 // check for new contacts once a day
716 $last_contact_check = DI::pConfig()->get($rr['uid'], 'pumpio', 'contact_check');
717 if ($last_contact_check) {
718 $next_contact_check = $last_contact_check + 86400;
720 $next_contact_check = 0;
723 if ($next_contact_check <= time()) {
724 pumpio_getallusers($a, $rr["uid"]);
725 DI::pConfig()->set($rr['uid'], 'pumpio', 'contact_check', time());
730 Logger::log('pumpio: cron_end');
732 DI::config()->set('pumpio', 'last_poll', time());
735 function pumpio_cron(App $a, $b)
737 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
740 function pumpio_fetchtimeline(App $a, $uid)
742 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
743 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
744 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
745 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
746 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
747 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
748 $username = DI::pConfig()->get($uid, "pumpio", "user");
750 // get the application name for the pump.io app
751 // 1st try personal config, then system config and fallback to the
752 // hostname of the node if neither one is set.
753 $application_name = DI::pConfig()->get($uid, 'pumpio', 'application_name');
754 if ($application_name == "") {
755 $application_name = DI::config()->get('pumpio', 'application_name');
757 if ($application_name == "") {
758 $application_name = DI::baseUrl()->getHostname();
761 $first_time = ($lastdate == "");
763 $client = new oauth_client_class;
764 $client->oauth_version = '1.0a';
765 $client->authorization_header = true;
766 $client->url_parameters = false;
768 $client->client_id = $ckey;
769 $client->client_secret = $csecret;
770 $client->access_token = $otoken;
771 $client->access_token_secret = $osecret;
773 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
775 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);
777 $useraddr = $username.'@'.$hostname;
779 if (pumpio_reachable($url)) {
780 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
787 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
791 $posts = array_reverse($user->items);
793 $initiallastdate = $lastdate;
797 foreach ($posts as $post) {
798 if ($post->published <= $initiallastdate) {
802 if ($lastdate < $post->published) {
803 $lastdate = $post->published;
811 if (@is_array($post->cc)) {
812 $receiptians = array_merge($receiptians, $post->cc);
815 if (@is_array($post->to)) {
816 $receiptians = array_merge($receiptians, $post->to);
820 foreach ($receiptians AS $receiver) {
821 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
826 if ($public && !stristr($post->generator->displayName, $application_name)) {
827 $_SESSION["authenticated"] = true;
828 $_SESSION["uid"] = $uid;
831 $_REQUEST["api_source"] = true;
832 $_REQUEST["profile_uid"] = $uid;
833 $_REQUEST["source"] = "pump.io";
835 if (isset($post->object->id)) {
836 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
839 if ($post->object->displayName != "") {
840 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
842 $_REQUEST["title"] = "";
845 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
847 // To-Do: Picture has to be cached and stored locally
848 if ($post->object->fullImage->url != "") {
849 if ($post->object->fullImage->pump_io->proxyURL != "") {
850 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
852 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
856 Logger::log('pumpio: posting for user '.$uid);
858 require_once('mod/item.php');
861 Logger::log('pumpio: posting done - user '.$uid);
866 if ($lastdate != 0) {
867 DI::pConfig()->set($uid, 'pumpio', 'lastdate', $lastdate);
871 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
873 // Searching for the unliked post
874 // Two queries for speed issues
875 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
876 if (!DBA::isResult($orig_post)) {
877 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
878 if (!DBA::isResult($orig_post)) {
885 if (Strings::compareLink($post->actor->url, $own_id)) {
886 $contactid = $self[0]['id'];
888 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
889 DBA::escape(Strings::normaliseLink($post->actor->url)),
893 if (DBA::isResult($r)) {
894 $contactid = $r[0]['id'];
897 if ($contactid == 0) {
898 $contactid = $orig_post['contact-id'];
902 Item::markForDeletion(['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
904 if (DBA::isResult($r)) {
905 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
907 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
911 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
913 if (empty($post->object->id)) {
914 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
918 // Searching for the liked post
919 // Two queries for speed issues
920 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
921 if (!DBA::isResult($orig_post)) {
922 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
923 if (!DBA::isResult($orig_post)) {
929 if ($threadcompletion) {
930 pumpio_fetchallcomments($a, $uid, $post->object->id);
935 if (Strings::compareLink($post->actor->url, $own_id)) {
936 $contactid = $self[0]['id'];
937 $post->actor->displayName = $self[0]['name'];
938 $post->actor->url = $self[0]['url'];
939 $post->actor->image->url = $self[0]['photo'];
941 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
942 DBA::escape(Strings::normaliseLink($post->actor->url)),
946 if (DBA::isResult($r)) {
947 $contactid = $r[0]['id'];
950 if ($contactid == 0) {
951 $contactid = $orig_post['contact-id'];
955 $condition = ['verb' => Activity::LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
956 if (Item::exists($condition)) {
957 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
962 $likedata['parent'] = $orig_post['id'];
963 $likedata['verb'] = Activity::LIKE;
964 $likedata['gravity'] = GRAVITY_ACTIVITY;
965 $likedata['uid'] = $uid;
966 $likedata['wall'] = 0;
967 $likedata['network'] = Protocol::PUMPIO;
968 $likedata['uri'] = Item::newURI($uid);
969 $likedata['parent-uri'] = $orig_post["uri"];
970 $likedata['contact-id'] = $contactid;
971 $likedata['app'] = $post->generator->displayName;
972 $likedata['author-name'] = $post->actor->displayName;
973 $likedata['author-link'] = $post->actor->url;
974 if (!empty($post->actor->image)) {
975 $likedata['author-avatar'] = $post->actor->image->url;
978 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
979 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
980 $post_type = DI::l10n()->t('status');
981 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
982 $likedata['object-type'] = Activity\ObjectType::NOTE;
984 $likedata['body'] = DI::l10n()->t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
986 $likedata['object'] = '<object><type>' . Activity\ObjectType::NOTE . '</type><local>1</local>' .
987 '<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>';
989 $ret = Item::insert($likedata);
991 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
994 function pumpio_get_contact($uid, $contact, $no_insert = false)
996 $cid = Contact::getIdForURL($contact->url, $uid);
1002 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1003 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1005 if (!DBA::isResult($r)) {
1006 // create contact record
1007 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1008 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1009 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1010 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1012 DBA::escape(DateTimeFormat::utcNow()),
1013 DBA::escape($contact->url),
1014 DBA::escape(Strings::normaliseLink($contact->url)),
1015 DBA::escape(str_replace("acct:", "", $contact->id)),
1017 DBA::escape($contact->id), // What is it for?
1018 DBA::escape('pump.io ' . $contact->id), // What is it for?
1019 DBA::escape($contact->displayName),
1020 DBA::escape($contact->preferredUsername),
1021 DBA::escape($contact->image->url),
1022 DBA::escape(Protocol::PUMPIO),
1023 intval(Contact::FRIEND),
1025 DBA::escape($contact->location->displayName),
1026 DBA::escape($contact->summary),
1030 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1031 DBA::escape(Strings::normaliseLink($contact->url)),
1035 if (!DBA::isResult($r)) {
1039 $contact_id = $r[0]['id'];
1041 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1043 $contact_id = $r[0]["id"];
1045 /* if (DB_UPDATE_VERSION >= "1177")
1046 q("UPDATE `contact` SET `location` = '%s',
1049 dbesc($contact->location->displayName),
1050 dbesc($contact->summary),
1056 if (!empty($contact->image->url)) {
1057 Contact::updateAvatar($contact_id, $contact->image->url);
1063 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1065 // Two queries for speed issues
1066 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1067 if (Item::exists($condition)) {
1068 Item::markForDeletion($condition);
1072 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1073 if (Item::exists($condition)) {
1074 Item::markForDeletion($condition);
1080 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1082 if (($post->verb == "like") || ($post->verb == "favorite")) {
1083 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1086 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1087 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1090 if ($post->verb == "delete") {
1091 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1094 if ($post->verb != "update") {
1095 // Two queries for speed issues
1096 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1099 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1104 // Only handle these three types
1105 if (!strstr("post|share|update", $post->verb)) {
1110 if (@is_array($post->cc)) {
1111 $receiptians = array_merge($receiptians, $post->cc);
1114 if (@is_array($post->to)) {
1115 $receiptians = array_merge($receiptians, $post->to);
1120 foreach ($receiptians AS $receiver) {
1121 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1127 $postarray['network'] = Protocol::PUMPIO;
1128 $postarray['uid'] = $uid;
1129 $postarray['wall'] = 0;
1130 $postarray['uri'] = $post->object->id;
1131 $postarray['object-type'] = ActivityNamespace::ACTIVITY_SCHEMA . strtolower($post->object->objectType);
1133 if ($post->object->objectType != "comment") {
1134 $contact_id = pumpio_get_contact($uid, $post->actor);
1137 $contact_id = $self[0]['id'];
1140 $postarray['parent-uri'] = $post->object->id;
1143 $postarray['private'] = 1;
1144 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1147 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1149 if (Strings::compareLink($post->actor->url, $own_id)) {
1150 $contact_id = $self[0]['id'];
1151 $post->actor->displayName = $self[0]['name'];
1152 $post->actor->url = $self[0]['url'];
1153 $post->actor->image->url = $self[0]['photo'];
1154 } elseif ($contact_id == 0) {
1155 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1156 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1157 DBA::escape(Strings::normaliseLink($post->actor->url)),
1161 if (DBA::isResult($r)) {
1162 $contact_id = $r[0]['id'];
1164 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1165 DBA::escape(Strings::normaliseLink($post->actor->url)),
1169 if (DBA::isResult($r)) {
1170 $contact_id = $r[0]['id'];
1172 $contact_id = $self[0]['id'];
1177 $reply = new stdClass;
1178 $reply->verb = "note";
1180 if (isset($post->cc)) {
1181 $reply->cc = $post->cc;
1184 if (isset($post->to)) {
1185 $reply->to = $post->to;
1188 $reply->object = new stdClass;
1189 $reply->object->objectType = $post->object->inReplyTo->objectType;
1190 $reply->object->content = $post->object->inReplyTo->content;
1191 $reply->object->id = $post->object->inReplyTo->id;
1192 $reply->actor = $post->object->inReplyTo->author;
1193 $reply->url = $post->object->inReplyTo->url;
1194 $reply->generator = new stdClass;
1195 $reply->generator->displayName = "pumpio";
1196 $reply->published = $post->object->inReplyTo->published;
1197 $reply->received = $post->object->inReplyTo->updated;
1198 $reply->url = $post->object->inReplyTo->url;
1199 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1201 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1204 // When there is no content there is no need to continue
1205 if (empty($post->object->content)) {
1209 if (!empty($post->object->pump_io->proxyURL)) {
1210 $postarray['extid'] = $post->object->pump_io->proxyURL;
1213 $postarray['contact-id'] = $contact_id;
1214 $postarray['verb'] = Activity::POST;
1215 $postarray['owner-name'] = $post->actor->displayName;
1216 $postarray['owner-link'] = $post->actor->url;
1217 $postarray['author-name'] = $postarray['owner-name'];
1218 $postarray['author-link'] = $postarray['owner-link'];
1219 if (!empty($post->actor->image)) {
1220 $postarray['owner-avatar'] = $post->actor->image->url;
1221 $postarray['author-avatar'] = $postarray['owner-avatar'];
1223 $postarray['plink'] = $post->object->url;
1224 $postarray['app'] = $post->generator->displayName;
1225 $postarray['title'] = '';
1226 $postarray['body'] = HTML::toBBCode($post->object->content);
1227 $postarray['object'] = json_encode($post);
1229 if (!empty($post->object->fullImage->url)) {
1230 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1233 if (!empty($post->object->displayName)) {
1234 $postarray['title'] = $post->object->displayName;
1237 $postarray['created'] = DateTimeFormat::utc($post->published);
1238 if (isset($post->updated)) {
1239 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1240 } elseif (isset($post->received)) {
1241 $postarray['edited'] = DateTimeFormat::utc($post->received);
1243 $postarray['edited'] = $postarray['created'];
1246 if ($post->verb == "share") {
1247 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1248 $share_author = $post->object->author->displayName;
1249 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1250 $share_author = $post->object->author->preferredUsername;
1252 $share_author = $post->object->author->url;
1255 if (isset($post->object->created)) {
1256 $created = DateTimeFormat::utc($post->object->created);
1261 $postarray['body'] = Friendica\Content\Text\BBCode::getShareOpeningTag($share_author, $post->object->author->url,
1262 $post->object->author->image->url, $post->links->self->href, $created) .
1263 $postarray['body']."[/share]";
1266 if (trim($postarray['body']) == "") {
1270 $top_item = Item::insert($postarray);
1271 $postarray["id"] = $top_item;
1273 if (($top_item == 0) && ($post->verb == "update")) {
1274 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1275 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1276 Item::update($fields, $condition);
1279 if (($post->object->objectType == "comment") && $threadcompletion) {
1280 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1286 function pumpio_fetchinbox(App $a, $uid)
1288 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1289 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1290 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1291 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1292 $lastdate = DI::pConfig()->get($uid, 'pumpio', 'lastdate');
1293 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1294 $username = DI::pConfig()->get($uid, "pumpio", "user");
1296 $own_id = "https://".$hostname."/".$username;
1298 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1301 $lastitems = q("SELECT `uri` FROM `thread`
1302 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1303 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1304 ORDER BY `thread`.`commented` DESC LIMIT 10",
1305 DBA::escape(Protocol::PUMPIO),
1309 $client = new oauth_client_class;
1310 $client->oauth_version = '1.0a';
1311 $client->authorization_header = true;
1312 $client->url_parameters = false;
1314 $client->client_id = $ckey;
1315 $client->client_secret = $csecret;
1316 $client->access_token = $otoken;
1317 $client->access_token_secret = $osecret;
1319 $last_id = DI::pConfig()->get($uid, 'pumpio', 'last_id');
1321 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1323 if ($last_id != "") {
1324 $url .= '?since='.urlencode($last_id);
1327 if (pumpio_reachable($url)) {
1328 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1337 if (!empty($user->items)) {
1338 $posts = array_reverse($user->items);
1340 if (count($posts)) {
1341 foreach ($posts as $post) {
1342 $last_id = $post->id;
1343 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1348 foreach ($lastitems as $item) {
1349 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1352 DI::pConfig()->set($uid, 'pumpio', 'last_id', $last_id);
1355 function pumpio_getallusers(App &$a, $uid)
1357 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1358 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1359 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1360 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1361 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1362 $username = DI::pConfig()->get($uid, "pumpio", "user");
1364 $client = new oauth_client_class;
1365 $client->oauth_version = '1.0a';
1366 $client->authorization_header = true;
1367 $client->url_parameters = false;
1369 $client->client_id = $ckey;
1370 $client->client_secret = $csecret;
1371 $client->access_token = $otoken;
1372 $client->access_token_secret = $osecret;
1374 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1376 if (pumpio_reachable($url)) {
1377 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1382 if (empty($users)) {
1386 if ($users->totalItems > count($users->items)) {
1387 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1389 if (pumpio_reachable($url)) {
1390 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1396 if (!empty($users->items)) {
1397 foreach ($users->items as $user) {
1398 pumpio_get_contact($uid, $user);
1403 function pumpio_getreceiver(App $a, array $b)
1407 if (!$b["private"]) {
1408 if (!strstr($b['postopts'], 'pumpio')) {
1412 $public = DI::pConfig()->get($b['uid'], "pumpio", "public");
1415 $receiver["to"][] = [
1416 "objectType" => "collection",
1417 "id" => "http://activityschema.org/collection/public"];
1420 $cids = explode("><", $b["allow_cid"]);
1421 $gids = explode("><", $b["allow_gid"]);
1423 foreach ($cids AS $cid) {
1424 $cid = trim($cid, " <>");
1426 $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",
1429 DBA::escape(Protocol::PUMPIO)
1432 if (DBA::isResult($r)) {
1433 $receiver["bcc"][] = [
1434 "displayName" => $r[0]["name"],
1435 "objectType" => "person",
1436 "preferredUsername" => $r[0]["nick"],
1437 "url" => $r[0]["url"]];
1440 foreach ($gids AS $gid) {
1441 $gid = trim($gid, " <>");
1443 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1444 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1445 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1447 DBA::escape(Protocol::PUMPIO)
1450 foreach ($r AS $row)
1451 $receiver["bcc"][] = [
1452 "displayName" => $row["name"],
1453 "objectType" => "person",
1454 "preferredUsername" => $row["nick"],
1455 "url" => $row["url"]];
1459 if ($b["inform"] != "") {
1460 $inform = explode(",", $b["inform"]);
1462 foreach ($inform AS $cid) {
1463 if (substr($cid, 0, 4) != "cid:") {
1467 $cid = str_replace("cid:", "", $cid);
1469 $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",
1472 DBA::escape(Protocol::PUMPIO)
1475 if (DBA::isResult($r)) {
1476 $receiver["to"][] = [
1477 "displayName" => $r[0]["name"],
1478 "objectType" => "person",
1479 "preferredUsername" => $r[0]["nick"],
1480 "url" => $r[0]["url"]];
1488 function pumpio_fetchallcomments(App $a, $uid, $id)
1490 $ckey = DI::pConfig()->get($uid, 'pumpio', 'consumer_key');
1491 $csecret = DI::pConfig()->get($uid, 'pumpio', 'consumer_secret');
1492 $otoken = DI::pConfig()->get($uid, 'pumpio', 'oauth_token');
1493 $osecret = DI::pConfig()->get($uid, 'pumpio', 'oauth_token_secret');
1494 $hostname = DI::pConfig()->get($uid, 'pumpio', 'host');
1495 $username = DI::pConfig()->get($uid, "pumpio", "user");
1497 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1499 $own_id = "https://".$hostname."/".$username;
1501 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1504 // Fetching the original post
1505 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1506 $original = Item::selectFirst(['extid'], $condition);
1507 if (!DBA::isResult($original)) {
1511 $url = $original["extid"];
1513 $client = new oauth_client_class;
1514 $client->oauth_version = '1.0a';
1515 $client->authorization_header = true;
1516 $client->url_parameters = false;
1518 $client->client_id = $ckey;
1519 $client->client_secret = $csecret;
1520 $client->access_token = $otoken;
1521 $client->access_token_secret = $osecret;
1523 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1525 if (pumpio_reachable($url)) {
1526 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1535 if ($item->likes->totalItems != 0) {
1536 foreach ($item->likes->items AS $post) {
1537 $like = new stdClass;
1538 $like->object = new stdClass;
1539 $like->object->id = $item->id;
1540 $like->actor = new stdClass;
1541 if (!empty($item->displayName)) {
1542 $like->actor->displayName = $item->displayName;
1544 //$like->actor->preferredUsername = $item->preferredUsername;
1545 //$like->actor->image = $item->image;
1546 $like->actor->url = $item->url;
1547 $like->generator = new stdClass;
1548 $like->generator->displayName = "pumpio";
1549 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1553 if ($item->replies->totalItems == 0) {
1557 foreach ($item->replies->items AS $item) {
1558 if ($item->id == $id) {
1562 // Checking if the comment already exists - Two queries for speed issues
1563 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1567 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1571 $post = new stdClass;
1572 $post->verb = "post";
1573 $post->actor = $item->author;
1574 $post->published = $item->published;
1575 $post->received = $item->updated;
1576 $post->generator = new stdClass;
1577 $post->generator->displayName = "pumpio";
1578 // To-Do: Check for public post
1580 unset($item->author);
1581 unset($item->published);
1582 unset($item->updated);
1584 $post->object = $item;
1586 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1587 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1591 function pumpio_reachable($url)
1593 return DI::httpRequest()->get($url, ['timeout' => 10])->isSuccess();