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\GContact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Item;
24 use Friendica\Model\Queue;
25 use Friendica\Model\User;
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 'include/enotify.php';
34 require_once "mod/share.php";
36 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
38 function pumpio_install()
40 Hook::register('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
41 Hook::register('hook_fork', 'addon/pumpio/pumpio.php', 'hook_fork');
42 Hook::register('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
43 Hook::register('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
44 Hook::register('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
45 Hook::register('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
46 Hook::register('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
47 Hook::register('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
48 Hook::register('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
49 Hook::register('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
52 function pumpio_uninstall()
54 Hook::unregister('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
55 Hook::unregister('hook_fork', 'addon/pumpio/pumpio.php', 'pumpio_hook_fork');
56 Hook::unregister('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
57 Hook::unregister('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
58 Hook::unregister('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
59 Hook::unregister('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
60 Hook::unregister('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
61 Hook::unregister('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
62 Hook::unregister('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
63 Hook::unregister('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
66 function pumpio_module() {}
68 function pumpio_content(App $a)
71 notice(L10n::t('Permission denied.') . EOL);
75 require_once("mod/settings.php");
78 if (isset($a->argv[1])) {
79 switch ($a->argv[1]) {
81 $o = pumpio_connect($a);
84 $o = print_r($a->argv, true);
88 $o = pumpio_connect($a);
93 function pumpio_check_item_notification($a, &$notification_data)
95 $hostname = PConfig::get($notification_data["uid"], 'pumpio', 'host');
96 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
98 $notification_data["profiles"][] = "https://".$hostname."/".$username;
101 function pumpio_registerclient(App $a, $host)
103 $url = "https://".$host."/api/client/register";
107 $application_name = Config::get('pumpio', 'application_name');
109 if ($application_name == "") {
110 $application_name = $a->getHostName();
113 $adminlist = explode(",", str_replace(" ", "", Config::get('config', 'admin_email')));
115 $params["type"] = "client_associate";
116 $params["contacts"] = $adminlist[0];
117 $params["application_type"] = "native";
118 $params["application_name"] = $application_name;
119 $params["logo_url"] = $a->getBaseURL()."/images/friendica-256.png";
120 $params["redirect_uris"] = $a->getBaseURL()."/pumpio/connect";
122 Logger::log("pumpio_registerclient: ".$url." parameters ".print_r($params, true), Logger::DEBUG);
124 $ch = curl_init($url);
125 curl_setopt($ch, CURLOPT_HEADER, false);
126 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
127 curl_setopt($ch, CURLOPT_POST,1);
128 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
129 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
132 $curl_info = curl_getinfo($ch);
134 if ($curl_info["http_code"] == "200") {
135 $values = json_decode($s);
136 Logger::log("pumpio_registerclient: success ".print_r($values, true), Logger::DEBUG);
139 Logger::log("pumpio_registerclient: failed: ".print_r($curl_info, true), Logger::DEBUG);
144 function pumpio_connect(App $a)
146 // Define the needed keys
147 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
148 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
149 $hostname = PConfig::get(local_user(), 'pumpio', 'host');
151 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
152 Logger::log("pumpio_connect: register client");
153 $clientdata = pumpio_registerclient($a, $hostname);
154 PConfig::set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
155 PConfig::set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
157 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
158 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
160 Logger::log("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, Logger::DEBUG);
163 if (($consumer_key == "") || ($consumer_secret == "")) {
164 Logger::log("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
166 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
170 // The callback URL is the script that gets called after the user authenticates with pumpio
171 $callback_url = $a->getBaseURL()."/pumpio/connect";
173 // Let's begin. First we need a Request Token. The request token is required to send the user
174 // to pumpio's login page.
176 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
177 // Consumer Key and Consumer Secret
178 $client = new oauth_client_class;
180 $client->server = '';
181 $client->oauth_version = '1.0a';
182 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
183 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
184 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
185 $client->url_parameters = false;
186 $client->authorization_header = true;
187 $client->redirect_uri = $callback_url;
188 $client->client_id = $consumer_key;
189 $client->client_secret = $consumer_secret;
191 if (($success = $client->Initialize())) {
192 if (($success = $client->Process())) {
193 if (strlen($client->access_token)) {
194 Logger::log("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, Logger::DEBUG);
195 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
196 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
199 $success = $client->Finalize($success);
202 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
206 Logger::log("pumpio_connect: authenticated");
207 $o = L10n::t("You are now authenticated to pumpio.");
208 $o .= '<br /><a href="'.$a->getBaseURL().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
210 Logger::log("pumpio_connect: could not connect");
211 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
217 function pumpio_jot_nets(App $a, &$b)
219 if (! local_user()) {
223 $pumpio_post = PConfig::get(local_user(), 'pumpio', 'post');
225 if (intval($pumpio_post) == 1) {
226 $pumpio_defpost = PConfig::get(local_user(), 'pumpio', 'post_by_default');
227 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
228 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
229 . L10n::t('Post to pumpio') . '</div>';
233 function pumpio_settings(App $a, &$s)
239 /* Add our stylesheet to the page so we can make our settings look nice */
241 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
243 /* Get the current state of our config variables */
245 $import_enabled = PConfig::get(local_user(), 'pumpio', 'import');
246 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
248 $enabled = PConfig::get(local_user(), 'pumpio', 'post');
249 $checked = (($enabled) ? ' checked="checked" ' : '');
250 $css = (($enabled) ? '' : '-disabled');
252 $def_enabled = PConfig::get(local_user(), 'pumpio', 'post_by_default');
253 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
255 $public_enabled = PConfig::get(local_user(), 'pumpio', 'public');
256 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
258 $mirror_enabled = PConfig::get(local_user(), 'pumpio', 'mirror');
259 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
261 $servername = PConfig::get(local_user(), "pumpio", "host");
262 $username = PConfig::get(local_user(), "pumpio", "user");
264 /* Add some HTML to the existing form */
266 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
267 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
269 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
270 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
271 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
274 $s .= '<div id="pumpio-username-wrapper">';
275 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
276 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
277 $s .= '</div><div class="clear"></div>';
279 $s .= '<div id="pumpio-servername-wrapper">';
280 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
281 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
282 $s .= '</div><div class="clear"></div>';
284 if (($username != '') && ($servername != '')) {
285 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
286 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
288 $s .= '<div id="pumpio-password-wrapper">';
289 if (($oauth_token == "") || ($oauth_token_secret == "")) {
290 $s .= '<div id="pumpio-authenticate-wrapper">';
291 $s .= '<a href="'.$a->getBaseURL().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
292 $s .= '</div><div class="clear"></div>';
294 $s .= '<div id="pumpio-import-wrapper">';
295 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
296 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
297 $s .= '</div><div class="clear"></div>';
299 $s .= '<div id="pumpio-enable-wrapper">';
300 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
301 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
302 $s .= '</div><div class="clear"></div>';
304 $s .= '<div id="pumpio-bydefault-wrapper">';
305 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
306 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
307 $s .= '</div><div class="clear"></div>';
309 $s .= '<div id="pumpio-public-wrapper">';
310 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
311 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
312 $s .= '</div><div class="clear"></div>';
314 $s .= '<div id="pumpio-mirror-wrapper">';
315 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
316 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
317 $s .= '</div><div class="clear"></div>';
319 $s .= '<div id="pumpio-delete-wrapper">';
320 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
321 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
322 $s .= '</div><div class="clear"></div>';
325 $s .= '</div><div class="clear"></div>';
328 /* provide a submit button */
330 $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>';
333 function pumpio_settings_post(App $a, array &$b)
335 if (!empty($_POST['pumpio-submit'])) {
336 if (!empty($_POST['pumpio_delete'])) {
337 PConfig::set(local_user(), 'pumpio', 'consumer_key' , '');
338 PConfig::set(local_user(), 'pumpio', 'consumer_secret' , '');
339 PConfig::set(local_user(), 'pumpio', 'oauth_token' , '');
340 PConfig::set(local_user(), 'pumpio', 'oauth_token_secret', '');
341 PConfig::set(local_user(), 'pumpio', 'post' , false);
342 PConfig::set(local_user(), 'pumpio', 'import' , false);
343 PConfig::set(local_user(), 'pumpio', 'host' , '');
344 PConfig::set(local_user(), 'pumpio', 'user' , '');
345 PConfig::set(local_user(), 'pumpio', 'public' , false);
346 PConfig::set(local_user(), 'pumpio', 'mirror' , false);
347 PConfig::set(local_user(), 'pumpio', 'post_by_default' , false);
348 PConfig::set(local_user(), 'pumpio', 'lastdate' , 0);
349 PConfig::set(local_user(), 'pumpio', 'last_id' , '');
351 // filtering the username if it is filled wrong
352 $user = $_POST['pumpio_user'];
353 if (strstr($user, "@")) {
354 $pos = strpos($user, "@");
357 $user = substr($user, 0, $pos);
361 // Filtering the hostname if someone is entering it with "http"
362 $host = $_POST['pumpio_host'];
364 $host = str_replace(["https://", "http://"], ["", ""], $host);
366 PConfig::set(local_user(), 'pumpio', 'post' , defaults($_POST, 'pumpio', false));
367 PConfig::set(local_user(), 'pumpio', 'import' , defaults($_POST, 'pumpio_import', false));
368 PConfig::set(local_user(), 'pumpio', 'host' , $host);
369 PConfig::set(local_user(), 'pumpio', 'user' , $user);
370 PConfig::set(local_user(), 'pumpio', 'public' , defaults($_POST, 'pumpio_public', false));
371 PConfig::set(local_user(), 'pumpio', 'mirror' , defaults($_POST, 'pumpio_mirror', false));
372 PConfig::set(local_user(), 'pumpio', 'post_by_default', defaults($_POST, 'pumpio_bydefault', false));
374 if (!empty($_POST['pumpio_mirror'])) {
375 PConfig::delete(local_user(), 'pumpio', 'lastdate');
381 function pumpio_load_config(App $a)
383 $a->loadConfigFile(__DIR__ . '/config/pumpio.config.php');
386 function pumpio_hook_fork(App $a, array &$b)
388 if ($b['name'] != 'notifier_normal') {
394 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
395 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
396 $b['execute'] = false;
400 // if post comes from pump.io don't send it back
401 if ($post['app'] == "pump.io") {
402 $b['execute'] = false;
406 if (PConfig::get($post['uid'], 'pumpio', 'import')) {
407 // Don't fork if it isn't a reply to a pump.io post
408 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::PUMPIO])) {
409 Logger::log('No pump.io parent found for item ' . $post['id']);
410 $b['execute'] = false;
414 // Comments are never exported when we don't import the pumpio timeline
415 if (!strstr($post['postopts'], 'pumpio') || ($post['parent'] != $post['id']) || $post['private']) {
416 $b['execute'] = false;
422 function pumpio_post_local(App $a, array &$b)
424 if (!local_user() || (local_user() != $b['uid'])) {
428 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
430 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
432 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
436 if (!$pumpio_enable) {
440 if (strlen($b['postopts'])) {
441 $b['postopts'] .= ',';
444 $b['postopts'] .= 'pumpio';
447 function pumpio_send(App $a, array &$b)
449 if (!PConfig::get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
453 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
455 if ($b['parent'] != $b['id']) {
456 // Looking if its a reply to a pumpio post
457 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
458 $orig_post = Item::selectFirst([], $condition);
460 if (!DBA::isResult($orig_post)) {
461 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
469 $receiver = pumpio_getreceiver($a, $b);
471 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
473 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
477 // Dont't post if the post doesn't belong to us.
478 // This is a check for forum postings
479 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
480 if ($b['contact-id'] != $self['id']) {
485 if ($b['verb'] == ACTIVITY_LIKE) {
487 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
489 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
494 if ($b['verb'] == ACTIVITY_DISLIKE) {
498 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
499 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
502 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
503 pumpio_action($a, $b["uid"], $b["uri"], "delete");
506 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
510 // if post comes from pump.io don't send it back
511 if ($b['app'] == "pump.io") {
516 // Support for native shares
517 // http://<hostname>/api/<type>/shares?id=<the-object-id>
519 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
520 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
521 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
522 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
524 $host = PConfig::get($b['uid'], "pumpio", "host");
525 $user = PConfig::get($b['uid'], "pumpio", "user");
526 $public = PConfig::get($b['uid'], "pumpio", "public");
528 if ($oauth_token && $oauth_token_secret) {
529 $title = trim($b['title']);
531 $content = BBCode::convert($b['body'], false, 4);
535 $params["verb"] = "post";
538 $params["object"] = [
539 'objectType' => "note",
540 'content' => $content];
542 if (!empty($title)) {
543 $params["object"]["displayName"] = $title;
546 if (!empty($receiver["to"])) {
547 $params["to"] = $receiver["to"];
550 if (!empty($receiver["bto"])) {
551 $params["bto"] = $receiver["bto"];
554 if (!empty($receiver["cc"])) {
555 $params["cc"] = $receiver["cc"];
558 if (!empty($receiver["bcc"])) {
559 $params["bcc"] = $receiver["bcc"];
562 $inReplyTo = ["id" => $orig_post["uri"],
563 "objectType" => "note"];
565 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
566 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
569 $params["object"] = [
570 'objectType' => "comment",
571 'content' => $content,
572 'inReplyTo' => $inReplyTo];
575 $params["object"]["displayName"] = $title;
579 $client = new oauth_client_class;
580 $client->oauth_version = '1.0a';
581 $client->url_parameters = false;
582 $client->authorization_header = true;
583 $client->access_token = $oauth_token;
584 $client->access_token_secret = $oauth_token_secret;
585 $client->client_id = $consumer_key;
586 $client->client_secret = $consumer_secret;
588 $username = $user.'@'.$host;
589 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
591 if (pumpio_reachable($url)) {
592 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
598 if ($user->generator->displayName) {
599 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
602 $post_id = $user->object->id;
603 Logger::log('pumpio_send '.$username.': success '.$post_id);
604 if ($post_id && $iscomment) {
605 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
606 Item::update(['extid' => $post_id], ['id' => $b['id']]);
609 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
611 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
612 if (DBA::isResult($r)) {
613 $a->contact = $r[0]["id"];
616 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
618 Queue::add($a->contact, Protocol::PUMPIO, $s);
619 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
624 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
626 // Don't do likes and other stuff if you don't import the timeline
627 if (!PConfig::get($uid, 'pumpio', 'import')) {
631 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
632 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
633 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
634 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
635 $hostname = PConfig::get($uid, 'pumpio', 'host');
636 $username = PConfig::get($uid, "pumpio", "user");
638 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
640 if (!DBA::isResult($orig_post)) {
644 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
645 $uri = $orig_post["extid"];
647 $uri = $orig_post["uri"];
650 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
651 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
652 } elseif (strstr($uri, "/api/comment/")) {
653 $objectType = "comment";
654 } elseif (strstr($uri, "/api/note/")) {
655 $objectType = "note";
656 } elseif (strstr($uri, "/api/image/")) {
657 $objectType = "image";
660 $params["verb"] = $action;
661 $params["object"] = ['id' => $uri,
662 "objectType" => $objectType,
663 "content" => $content];
665 $client = new oauth_client_class;
666 $client->oauth_version = '1.0a';
667 $client->authorization_header = true;
668 $client->url_parameters = false;
670 $client->client_id = $ckey;
671 $client->client_secret = $csecret;
672 $client->access_token = $otoken;
673 $client->access_token_secret = $osecret;
675 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
677 if (pumpio_reachable($url)) {
678 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
684 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
686 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user, true));
688 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $uid);
689 if (DBA::isResult($r)) {
690 $a->contact = $r[0]["id"];
693 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
695 Queue::add($a->contact, Protocol::PUMPIO, $s);
696 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
700 function pumpio_sync(App $a)
702 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
704 if (!DBA::isResult($r)) {
708 $last = Config::get('pumpio', 'last_poll');
710 $poll_interval = intval(Config::get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
713 $next = $last + ($poll_interval * 60);
714 if ($next > time()) {
715 Logger::log('pumpio: poll intervall not reached');
719 Logger::log('pumpio: cron_start');
721 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
722 if (DBA::isResult($r)) {
723 foreach ($r as $rr) {
724 Logger::log('pumpio: mirroring user '.$rr['uid']);
725 pumpio_fetchtimeline($a, $rr['uid']);
729 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
730 if ($abandon_days < 1) {
734 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
736 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
737 if (DBA::isResult($r)) {
738 foreach ($r as $rr) {
739 if ($abandon_days != 0) {
740 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
741 if (!DBA::isResult($user)) {
742 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
747 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
748 pumpio_fetchinbox($a, $rr['uid']);
750 // check for new contacts once a day
751 $last_contact_check = PConfig::get($rr['uid'], 'pumpio', 'contact_check');
752 if ($last_contact_check) {
753 $next_contact_check = $last_contact_check + 86400;
755 $next_contact_check = 0;
758 if ($next_contact_check <= time()) {
759 pumpio_getallusers($a, $rr["uid"]);
760 PConfig::set($rr['uid'], 'pumpio', 'contact_check', time());
765 Logger::log('pumpio: cron_end');
767 Config::set('pumpio', 'last_poll', time());
770 function pumpio_cron(App $a, $b)
772 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
775 function pumpio_fetchtimeline(App $a, $uid)
777 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
778 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
779 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
780 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
781 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
782 $hostname = PConfig::get($uid, 'pumpio', 'host');
783 $username = PConfig::get($uid, "pumpio", "user");
785 // get the application name for the pump.io app
786 // 1st try personal config, then system config and fallback to the
787 // hostname of the node if neither one is set.
788 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
789 if ($application_name == "") {
790 $application_name = Config::get('pumpio', 'application_name');
792 if ($application_name == "") {
793 $application_name = $a->getHostName();
796 $first_time = ($lastdate == "");
798 $client = new oauth_client_class;
799 $client->oauth_version = '1.0a';
800 $client->authorization_header = true;
801 $client->url_parameters = false;
803 $client->client_id = $ckey;
804 $client->client_secret = $csecret;
805 $client->access_token = $otoken;
806 $client->access_token_secret = $osecret;
808 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
810 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);
812 $useraddr = $username.'@'.$hostname;
814 if (pumpio_reachable($url)) {
815 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
822 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
826 $posts = array_reverse($user->items);
828 $initiallastdate = $lastdate;
832 foreach ($posts as $post) {
833 if ($post->published <= $initiallastdate) {
837 if ($lastdate < $post->published) {
838 $lastdate = $post->published;
846 if (@is_array($post->cc)) {
847 $receiptians = array_merge($receiptians, $post->cc);
850 if (@is_array($post->to)) {
851 $receiptians = array_merge($receiptians, $post->to);
855 foreach ($receiptians AS $receiver) {
856 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
861 if ($public && !stristr($post->generator->displayName, $application_name)) {
862 $_SESSION["authenticated"] = true;
863 $_SESSION["uid"] = $uid;
866 $_REQUEST["api_source"] = true;
867 $_REQUEST["profile_uid"] = $uid;
868 $_REQUEST["source"] = "pump.io";
870 if (isset($post->object->id)) {
871 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
874 if ($post->object->displayName != "") {
875 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
877 $_REQUEST["title"] = "";
880 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
882 // To-Do: Picture has to be cached and stored locally
883 if ($post->object->fullImage->url != "") {
884 if ($post->object->fullImage->pump_io->proxyURL != "") {
885 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
887 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
891 Logger::log('pumpio: posting for user '.$uid);
893 require_once('mod/item.php');
896 Logger::log('pumpio: posting done - user '.$uid);
901 if ($lastdate != 0) {
902 PConfig::set($uid, 'pumpio', 'lastdate', $lastdate);
906 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
908 // Searching for the unliked post
909 // Two queries for speed issues
910 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
911 if (!DBA::isResult($orig_post)) {
912 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
913 if (!DBA::isResult($orig_post)) {
920 if (Strings::compareLink($post->actor->url, $own_id)) {
921 $contactid = $self[0]['id'];
923 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
924 DBA::escape(Strings::normaliseLink($post->actor->url)),
928 if (DBA::isResult($r)) {
929 $contactid = $r[0]['id'];
932 if ($contactid == 0) {
933 $contactid = $orig_post['contact-id'];
937 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
939 if (DBA::isResult($r)) {
940 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
942 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
946 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
948 require_once('include/items.php');
950 if (empty($post->object->id)) {
951 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
955 // Searching for the liked post
956 // Two queries for speed issues
957 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
958 if (!DBA::isResult($orig_post)) {
959 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
960 if (!DBA::isResult($orig_post)) {
966 if ($threadcompletion) {
967 pumpio_fetchallcomments($a, $uid, $post->object->id);
972 if (Strings::compareLink($post->actor->url, $own_id)) {
973 $contactid = $self[0]['id'];
974 $post->actor->displayName = $self[0]['name'];
975 $post->actor->url = $self[0]['url'];
976 $post->actor->image->url = $self[0]['photo'];
978 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
979 DBA::escape(Strings::normaliseLink($post->actor->url)),
983 if (DBA::isResult($r)) {
984 $contactid = $r[0]['id'];
987 if ($contactid == 0) {
988 $contactid = $orig_post['contact-id'];
992 $condition = ['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
993 if (Item::exists($condition)) {
994 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
999 $likedata['parent'] = $orig_post['id'];
1000 $likedata['verb'] = ACTIVITY_LIKE;
1001 $likedata['gravity'] = GRAVITY_ACTIVITY;
1002 $likedata['uid'] = $uid;
1003 $likedata['wall'] = 0;
1004 $likedata['network'] = Protocol::PUMPIO;
1005 $likedata['uri'] = Item::newURI($uid);
1006 $likedata['parent-uri'] = $orig_post["uri"];
1007 $likedata['contact-id'] = $contactid;
1008 $likedata['app'] = $post->generator->displayName;
1009 $likedata['author-name'] = $post->actor->displayName;
1010 $likedata['author-link'] = $post->actor->url;
1011 if (!empty($post->actor->image)) {
1012 $likedata['author-avatar'] = $post->actor->image->url;
1015 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
1016 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
1017 $post_type = L10n::t('status');
1018 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
1019 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
1021 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
1023 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
1024 '<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>';
1026 $ret = Item::insert($likedata);
1028 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
1031 function pumpio_get_contact($uid, $contact, $no_insert = false)
1033 $gcontact = ["url" => $contact->url, "network" => Protocol::PUMPIO, "generation" => 2,
1034 "name" => $contact->displayName, "hide" => true,
1035 "nick" => $contact->preferredUsername,
1036 "addr" => str_replace("acct:", "", $contact->id)];
1038 if (!empty($contact->location->displayName)) {
1039 $gcontact["location"] = $contact->location->displayName;
1042 if (!empty($contact->summary)) {
1043 $gcontact["about"] = $contact->summary;
1046 if (!empty($contact->image->url)) {
1047 $gcontact["photo"] = $contact->image->url;
1050 GContact::update($gcontact);
1051 $cid = Contact::getIdForURL($contact->url, $uid);
1057 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1058 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1060 if (!DBA::isResult($r)) {
1061 // create contact record
1062 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1063 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1064 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1065 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1067 DBA::escape(DateTimeFormat::utcNow()),
1068 DBA::escape($contact->url),
1069 DBA::escape(Strings::normaliseLink($contact->url)),
1070 DBA::escape(str_replace("acct:", "", $contact->id)),
1072 DBA::escape($contact->id), // What is it for?
1073 DBA::escape('pump.io ' . $contact->id), // What is it for?
1074 DBA::escape($contact->displayName),
1075 DBA::escape($contact->preferredUsername),
1076 DBA::escape($contact->image->url),
1077 DBA::escape(Protocol::PUMPIO),
1078 intval(Contact::FRIEND),
1080 DBA::escape($contact->location->displayName),
1081 DBA::escape($contact->summary),
1085 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1086 DBA::escape(Strings::normaliseLink($contact->url)),
1090 if (!DBA::isResult($r)) {
1094 $contact_id = $r[0]['id'];
1096 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1098 $contact_id = $r[0]["id"];
1100 /* if (DB_UPDATE_VERSION >= "1177")
1101 q("UPDATE `contact` SET `location` = '%s',
1104 dbesc($contact->location->displayName),
1105 dbesc($contact->summary),
1111 if (!empty($contact->image->url)) {
1112 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1118 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1120 // Two queries for speed issues
1121 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1122 if (Item::exists($condition)) {
1123 Item::delete($condition);
1127 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1128 if (Item::exists($condition)) {
1129 Item::delete($condition);
1135 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1137 require_once('include/items.php');
1139 if (($post->verb == "like") || ($post->verb == "favorite")) {
1140 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1143 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1144 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1147 if ($post->verb == "delete") {
1148 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1151 if ($post->verb != "update") {
1152 // Two queries for speed issues
1153 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1156 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1161 // Only handle these three types
1162 if (!strstr("post|share|update", $post->verb)) {
1167 if (@is_array($post->cc)) {
1168 $receiptians = array_merge($receiptians, $post->cc);
1171 if (@is_array($post->to)) {
1172 $receiptians = array_merge($receiptians, $post->to);
1177 foreach ($receiptians AS $receiver) {
1178 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1184 $postarray['network'] = Protocol::PUMPIO;
1185 $postarray['uid'] = $uid;
1186 $postarray['wall'] = 0;
1187 $postarray['uri'] = $post->object->id;
1188 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1190 if ($post->object->objectType != "comment") {
1191 $contact_id = pumpio_get_contact($uid, $post->actor);
1194 $contact_id = $self[0]['id'];
1197 $postarray['parent-uri'] = $post->object->id;
1200 $postarray['private'] = 1;
1201 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1204 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1206 if (Strings::compareLink($post->actor->url, $own_id)) {
1207 $contact_id = $self[0]['id'];
1208 $post->actor->displayName = $self[0]['name'];
1209 $post->actor->url = $self[0]['url'];
1210 $post->actor->image->url = $self[0]['photo'];
1211 } elseif ($contact_id == 0) {
1212 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1213 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1214 DBA::escape(Strings::normaliseLink($post->actor->url)),
1218 if (DBA::isResult($r)) {
1219 $contact_id = $r[0]['id'];
1221 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1222 DBA::escape(Strings::normaliseLink($post->actor->url)),
1226 if (DBA::isResult($r)) {
1227 $contact_id = $r[0]['id'];
1229 $contact_id = $self[0]['id'];
1234 $reply = new stdClass;
1235 $reply->verb = "note";
1237 if (isset($post->cc)) {
1238 $reply->cc = $post->cc;
1241 if (isset($post->to)) {
1242 $reply->to = $post->to;
1245 $reply->object = new stdClass;
1246 $reply->object->objectType = $post->object->inReplyTo->objectType;
1247 $reply->object->content = $post->object->inReplyTo->content;
1248 $reply->object->id = $post->object->inReplyTo->id;
1249 $reply->actor = $post->object->inReplyTo->author;
1250 $reply->url = $post->object->inReplyTo->url;
1251 $reply->generator = new stdClass;
1252 $reply->generator->displayName = "pumpio";
1253 $reply->published = $post->object->inReplyTo->published;
1254 $reply->received = $post->object->inReplyTo->updated;
1255 $reply->url = $post->object->inReplyTo->url;
1256 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1258 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1261 // When there is no content there is no need to continue
1262 if (empty($post->object->content)) {
1266 if (!empty($post->object->pump_io->proxyURL)) {
1267 $postarray['extid'] = $post->object->pump_io->proxyURL;
1270 $postarray['contact-id'] = $contact_id;
1271 $postarray['verb'] = ACTIVITY_POST;
1272 $postarray['owner-name'] = $post->actor->displayName;
1273 $postarray['owner-link'] = $post->actor->url;
1274 $postarray['author-name'] = $postarray['owner-name'];
1275 $postarray['author-link'] = $postarray['owner-link'];
1276 if (!empty($post->actor->image)) {
1277 $postarray['owner-avatar'] = $post->actor->image->url;
1278 $postarray['author-avatar'] = $postarray['owner-avatar'];
1280 $postarray['plink'] = $post->object->url;
1281 $postarray['app'] = $post->generator->displayName;
1282 $postarray['title'] = '';
1283 $postarray['body'] = HTML::toBBCode($post->object->content);
1284 $postarray['object'] = json_encode($post);
1286 if (!empty($post->object->fullImage->url)) {
1287 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1290 if (!empty($post->object->displayName)) {
1291 $postarray['title'] = $post->object->displayName;
1294 $postarray['created'] = DateTimeFormat::utc($post->published);
1295 if (isset($post->updated)) {
1296 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1297 } elseif (isset($post->received)) {
1298 $postarray['edited'] = DateTimeFormat::utc($post->received);
1300 $postarray['edited'] = $postarray['created'];
1303 if ($post->verb == "share") {
1304 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1305 $share_author = $post->object->author->displayName;
1306 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1307 $share_author = $post->object->author->preferredUsername;
1309 $share_author = $post->object->author->url;
1312 if (isset($post->object->created)) {
1313 $created = DateTimeFormat::utc($post->object->created);
1318 $postarray['body'] = share_header($share_author, $post->object->author->url,
1319 $post->object->author->image->url, "",
1320 $created, $post->links->self->href).
1321 $postarray['body']."[/share]";
1324 if (trim($postarray['body']) == "") {
1328 $top_item = Item::insert($postarray);
1329 $postarray["id"] = $top_item;
1331 if (($top_item == 0) && ($post->verb == "update")) {
1332 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1333 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1334 Item::update($fields, $condition);
1337 if (($post->object->objectType == "comment") && $threadcompletion) {
1338 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1344 function pumpio_fetchinbox(App $a, $uid)
1346 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1347 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1348 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1349 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1350 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1351 $hostname = PConfig::get($uid, 'pumpio', 'host');
1352 $username = PConfig::get($uid, "pumpio", "user");
1354 $own_id = "https://".$hostname."/".$username;
1356 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1359 $lastitems = q("SELECT `uri` FROM `thread`
1360 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1361 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1362 ORDER BY `thread`.`commented` DESC LIMIT 10",
1363 DBA::escape(Protocol::PUMPIO),
1367 $client = new oauth_client_class;
1368 $client->oauth_version = '1.0a';
1369 $client->authorization_header = true;
1370 $client->url_parameters = false;
1372 $client->client_id = $ckey;
1373 $client->client_secret = $csecret;
1374 $client->access_token = $otoken;
1375 $client->access_token_secret = $osecret;
1377 $last_id = PConfig::get($uid, 'pumpio', 'last_id');
1379 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1381 if ($last_id != "") {
1382 $url .= '?since='.urlencode($last_id);
1385 if (pumpio_reachable($url)) {
1386 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1395 if (!empty($user->items)) {
1396 $posts = array_reverse($user->items);
1398 if (count($posts)) {
1399 foreach ($posts as $post) {
1400 $last_id = $post->id;
1401 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1406 foreach ($lastitems as $item) {
1407 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1410 PConfig::set($uid, 'pumpio', 'last_id', $last_id);
1413 function pumpio_getallusers(App &$a, $uid)
1415 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1416 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1417 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1418 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1419 $hostname = PConfig::get($uid, 'pumpio', 'host');
1420 $username = PConfig::get($uid, "pumpio", "user");
1422 $client = new oauth_client_class;
1423 $client->oauth_version = '1.0a';
1424 $client->authorization_header = true;
1425 $client->url_parameters = false;
1427 $client->client_id = $ckey;
1428 $client->client_secret = $csecret;
1429 $client->access_token = $otoken;
1430 $client->access_token_secret = $osecret;
1432 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1434 if (pumpio_reachable($url)) {
1435 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1440 if (empty($users)) {
1444 if ($users->totalItems > count($users->items)) {
1445 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1447 if (pumpio_reachable($url)) {
1448 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1454 if (!empty($users->items)) {
1455 foreach ($users->items as $user) {
1456 pumpio_get_contact($uid, $user);
1461 function pumpio_queue_hook(App $a, array &$b)
1463 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1464 DBA::escape(Protocol::PUMPIO)
1467 if (!DBA::isResult($qi)) {
1471 foreach ($qi as $x) {
1472 if ($x['network'] !== Protocol::PUMPIO) {
1476 Logger::log('pumpio_queue: run');
1478 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1479 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1482 if (!DBA::isResult($r)) {
1488 //Logger::log('pumpio_queue: fetching userdata '.print_r($userdata, true));
1490 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1491 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1492 $consumer_key = PConfig::get($userdata['uid'], "pumpio", "consumer_key");
1493 $consumer_secret = PConfig::get($userdata['uid'], "pumpio", "consumer_secret");
1495 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1496 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1500 if ($oauth_token && $oauth_token_secret &&
1501 $consumer_key && $consumer_secret) {
1502 $username = $user.'@'.$host;
1504 Logger::log('pumpio_queue: able to post for user '.$username);
1506 $z = unserialize($x['content']);
1508 $client = new oauth_client_class;
1509 $client->oauth_version = '1.0a';
1510 $client->url_parameters = false;
1511 $client->authorization_header = true;
1512 $client->access_token = $oauth_token;
1513 $client->access_token_secret = $oauth_token_secret;
1514 $client->client_id = $consumer_key;
1515 $client->client_secret = $consumer_secret;
1517 if (pumpio_reachable($z['url'])) {
1518 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1524 $post_id = $user->object->id;
1525 Logger::log('pumpio_queue: send '.$username.': success '.$post_id);
1526 if ($post_id && $iscomment) {
1527 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1528 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1530 Queue::removeItem($x['id']);
1532 Logger::log('pumpio_queue: send '.$username.': '.$z['url'].' general error: ' . print_r($user, true));
1535 Logger::log("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1539 Logger::log('pumpio_queue: delayed');
1540 Queue::updateTime($x['id']);
1545 function pumpio_getreceiver(App $a, array $b)
1549 if (!$b["private"]) {
1550 if (!strstr($b['postopts'], 'pumpio')) {
1554 $public = PConfig::get($b['uid'], "pumpio", "public");
1557 $receiver["to"][] = [
1558 "objectType" => "collection",
1559 "id" => "http://activityschema.org/collection/public"];
1562 $cids = explode("><", $b["allow_cid"]);
1563 $gids = explode("><", $b["allow_gid"]);
1565 foreach ($cids AS $cid) {
1566 $cid = trim($cid, " <>");
1568 $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",
1571 DBA::escape(Protocol::PUMPIO)
1574 if (DBA::isResult($r)) {
1575 $receiver["bcc"][] = [
1576 "displayName" => $r[0]["name"],
1577 "objectType" => "person",
1578 "preferredUsername" => $r[0]["nick"],
1579 "url" => $r[0]["url"]];
1582 foreach ($gids AS $gid) {
1583 $gid = trim($gid, " <>");
1585 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1586 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1587 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1589 DBA::escape(Protocol::PUMPIO)
1592 foreach ($r AS $row)
1593 $receiver["bcc"][] = [
1594 "displayName" => $row["name"],
1595 "objectType" => "person",
1596 "preferredUsername" => $row["nick"],
1597 "url" => $row["url"]];
1601 if ($b["inform"] != "") {
1602 $inform = explode(",", $b["inform"]);
1604 foreach ($inform AS $cid) {
1605 if (substr($cid, 0, 4) != "cid:") {
1609 $cid = str_replace("cid:", "", $cid);
1611 $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",
1614 DBA::escape(Protocol::PUMPIO)
1617 if (DBA::isResult($r)) {
1618 $receiver["to"][] = [
1619 "displayName" => $r[0]["name"],
1620 "objectType" => "person",
1621 "preferredUsername" => $r[0]["nick"],
1622 "url" => $r[0]["url"]];
1630 function pumpio_fetchallcomments(App $a, $uid, $id)
1632 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1633 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1634 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1635 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1636 $hostname = PConfig::get($uid, 'pumpio', 'host');
1637 $username = PConfig::get($uid, "pumpio", "user");
1639 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1641 $own_id = "https://".$hostname."/".$username;
1643 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1646 // Fetching the original post
1647 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1648 $item = Item::selectFirst(['extid'], $condition);
1649 if (!DBA::isResult($item)) {
1653 $url = $item["extid"];
1655 $client = new oauth_client_class;
1656 $client->oauth_version = '1.0a';
1657 $client->authorization_header = true;
1658 $client->url_parameters = false;
1660 $client->client_id = $ckey;
1661 $client->client_secret = $csecret;
1662 $client->access_token = $otoken;
1663 $client->access_token_secret = $osecret;
1665 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1667 if (pumpio_reachable($url)) {
1668 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1677 if ($item->likes->totalItems != 0) {
1678 foreach ($item->likes->items AS $post) {
1679 $like = new stdClass;
1680 $like->object = new stdClass;
1681 $like->object->id = $item->id;
1682 $like->actor = new stdClass;
1683 if (!empty($item->displayName)) {
1684 $like->actor->displayName = $item->displayName;
1686 //$like->actor->preferredUsername = $item->preferredUsername;
1687 //$like->actor->image = $item->image;
1688 $like->actor->url = $item->url;
1689 $like->generator = new stdClass;
1690 $like->generator->displayName = "pumpio";
1691 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1695 if ($item->replies->totalItems == 0) {
1699 foreach ($item->replies->items AS $item) {
1700 if ($item->id == $id) {
1704 // Checking if the comment already exists - Two queries for speed issues
1705 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1709 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1713 $post = new stdClass;
1714 $post->verb = "post";
1715 $post->actor = $item->author;
1716 $post->published = $item->published;
1717 $post->received = $item->updated;
1718 $post->generator = new stdClass;
1719 $post->generator->displayName = "pumpio";
1720 // To-Do: Check for public post
1722 unset($item->author);
1723 unset($item->published);
1724 unset($item->updated);
1726 $post->object = $item;
1728 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1729 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1733 function pumpio_reachable($url)
1735 return Network::curl($url, false, $redirects, ['timeout'=>10])->isSuccess();