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\Config\ConfigFileLoader;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Network;
29 use Friendica\Util\Strings;
30 use Friendica\Util\XML;
32 require 'addon/pumpio/oauth/http.php';
33 require 'addon/pumpio/oauth/oauth_client.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, array &$jotnets_fields)
219 if (! local_user()) {
223 if (PConfig::get(local_user(), 'pumpio', 'post')) {
224 $jotnets_fields[] = [
225 'type' => 'checkbox',
228 L10n::t('Post to pumpio'),
229 PConfig::get(local_user(), 'pumpio', 'post_by_default')
235 function pumpio_settings(App $a, &$s)
241 /* Add our stylesheet to the page so we can make our settings look nice */
243 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
245 /* Get the current state of our config variables */
247 $import_enabled = PConfig::get(local_user(), 'pumpio', 'import');
248 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
250 $enabled = PConfig::get(local_user(), 'pumpio', 'post');
251 $checked = (($enabled) ? ' checked="checked" ' : '');
252 $css = (($enabled) ? '' : '-disabled');
254 $def_enabled = PConfig::get(local_user(), 'pumpio', 'post_by_default');
255 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
257 $public_enabled = PConfig::get(local_user(), 'pumpio', 'public');
258 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
260 $mirror_enabled = PConfig::get(local_user(), 'pumpio', 'mirror');
261 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
263 $servername = PConfig::get(local_user(), "pumpio", "host");
264 $username = PConfig::get(local_user(), "pumpio", "user");
266 /* Add some HTML to the existing form */
268 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
269 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
271 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
272 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
273 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
276 $s .= '<div id="pumpio-username-wrapper">';
277 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
278 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
279 $s .= '</div><div class="clear"></div>';
281 $s .= '<div id="pumpio-servername-wrapper">';
282 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
283 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
284 $s .= '</div><div class="clear"></div>';
286 if (($username != '') && ($servername != '')) {
287 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
288 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
290 $s .= '<div id="pumpio-password-wrapper">';
291 if (($oauth_token == "") || ($oauth_token_secret == "")) {
292 $s .= '<div id="pumpio-authenticate-wrapper">';
293 $s .= '<a href="'.$a->getBaseURL().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
294 $s .= '</div><div class="clear"></div>';
296 $s .= '<div id="pumpio-import-wrapper">';
297 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
298 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
299 $s .= '</div><div class="clear"></div>';
301 $s .= '<div id="pumpio-enable-wrapper">';
302 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
303 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
304 $s .= '</div><div class="clear"></div>';
306 $s .= '<div id="pumpio-bydefault-wrapper">';
307 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
308 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
309 $s .= '</div><div class="clear"></div>';
311 $s .= '<div id="pumpio-public-wrapper">';
312 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
313 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
314 $s .= '</div><div class="clear"></div>';
316 $s .= '<div id="pumpio-mirror-wrapper">';
317 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
318 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
319 $s .= '</div><div class="clear"></div>';
321 $s .= '<div id="pumpio-delete-wrapper">';
322 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
323 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
324 $s .= '</div><div class="clear"></div>';
327 $s .= '</div><div class="clear"></div>';
330 /* provide a submit button */
332 $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>';
335 function pumpio_settings_post(App $a, array &$b)
337 if (!empty($_POST['pumpio-submit'])) {
338 if (!empty($_POST['pumpio_delete'])) {
339 PConfig::set(local_user(), 'pumpio', 'consumer_key' , '');
340 PConfig::set(local_user(), 'pumpio', 'consumer_secret' , '');
341 PConfig::set(local_user(), 'pumpio', 'oauth_token' , '');
342 PConfig::set(local_user(), 'pumpio', 'oauth_token_secret', '');
343 PConfig::set(local_user(), 'pumpio', 'post' , false);
344 PConfig::set(local_user(), 'pumpio', 'import' , false);
345 PConfig::set(local_user(), 'pumpio', 'host' , '');
346 PConfig::set(local_user(), 'pumpio', 'user' , '');
347 PConfig::set(local_user(), 'pumpio', 'public' , false);
348 PConfig::set(local_user(), 'pumpio', 'mirror' , false);
349 PConfig::set(local_user(), 'pumpio', 'post_by_default' , false);
350 PConfig::set(local_user(), 'pumpio', 'lastdate' , 0);
351 PConfig::set(local_user(), 'pumpio', 'last_id' , '');
353 // filtering the username if it is filled wrong
354 $user = $_POST['pumpio_user'];
355 if (strstr($user, "@")) {
356 $pos = strpos($user, "@");
359 $user = substr($user, 0, $pos);
363 // Filtering the hostname if someone is entering it with "http"
364 $host = $_POST['pumpio_host'];
366 $host = str_replace(["https://", "http://"], ["", ""], $host);
368 PConfig::set(local_user(), 'pumpio', 'post' , defaults($_POST, 'pumpio', false));
369 PConfig::set(local_user(), 'pumpio', 'import' , defaults($_POST, 'pumpio_import', false));
370 PConfig::set(local_user(), 'pumpio', 'host' , $host);
371 PConfig::set(local_user(), 'pumpio', 'user' , $user);
372 PConfig::set(local_user(), 'pumpio', 'public' , defaults($_POST, 'pumpio_public', false));
373 PConfig::set(local_user(), 'pumpio', 'mirror' , defaults($_POST, 'pumpio_mirror', false));
374 PConfig::set(local_user(), 'pumpio', 'post_by_default', defaults($_POST, 'pumpio_bydefault', false));
376 if (!empty($_POST['pumpio_mirror'])) {
377 PConfig::delete(local_user(), 'pumpio', 'lastdate');
383 function pumpio_load_config(App $a, ConfigFileLoader $loader)
385 $a->getConfigCache()->load($loader->loadAddonConfig('pumpio'));
388 function pumpio_hook_fork(App $a, array &$b)
390 if ($b['name'] != 'notifier_normal') {
396 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
397 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
398 $b['execute'] = false;
402 // if post comes from pump.io don't send it back
403 if ($post['app'] == "pump.io") {
404 $b['execute'] = false;
408 if (PConfig::get($post['uid'], 'pumpio', 'import')) {
409 // Don't fork if it isn't a reply to a pump.io post
410 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::PUMPIO])) {
411 Logger::log('No pump.io parent found for item ' . $post['id']);
412 $b['execute'] = false;
416 // Comments are never exported when we don't import the pumpio timeline
417 if (!strstr($post['postopts'], 'pumpio') || ($post['parent'] != $post['id']) || $post['private']) {
418 $b['execute'] = false;
424 function pumpio_post_local(App $a, array &$b)
426 if (!local_user() || (local_user() != $b['uid'])) {
430 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
432 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
434 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
438 if (!$pumpio_enable) {
442 if (strlen($b['postopts'])) {
443 $b['postopts'] .= ',';
446 $b['postopts'] .= 'pumpio';
449 function pumpio_send(App $a, array &$b)
451 if (!PConfig::get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
455 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
457 if ($b['parent'] != $b['id']) {
458 // Looking if its a reply to a pumpio post
459 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
460 $orig_post = Item::selectFirst([], $condition);
462 if (!DBA::isResult($orig_post)) {
463 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
471 $receiver = pumpio_getreceiver($a, $b);
473 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
475 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
479 // Dont't post if the post doesn't belong to us.
480 // This is a check for forum postings
481 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
482 if ($b['contact-id'] != $self['id']) {
487 if ($b['verb'] == ACTIVITY_LIKE) {
489 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
491 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
496 if ($b['verb'] == ACTIVITY_DISLIKE) {
500 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
501 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
504 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
505 pumpio_action($a, $b["uid"], $b["uri"], "delete");
508 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
512 // if post comes from pump.io don't send it back
513 if ($b['app'] == "pump.io") {
518 // Support for native shares
519 // http://<hostname>/api/<type>/shares?id=<the-object-id>
521 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
522 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
523 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
524 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
526 $host = PConfig::get($b['uid'], "pumpio", "host");
527 $user = PConfig::get($b['uid'], "pumpio", "user");
528 $public = PConfig::get($b['uid'], "pumpio", "public");
530 if ($oauth_token && $oauth_token_secret) {
531 $title = trim($b['title']);
533 $content = BBCode::convert($b['body'], false, 4);
537 $params["verb"] = "post";
540 $params["object"] = [
541 'objectType' => "note",
542 'content' => $content];
544 if (!empty($title)) {
545 $params["object"]["displayName"] = $title;
548 if (!empty($receiver["to"])) {
549 $params["to"] = $receiver["to"];
552 if (!empty($receiver["bto"])) {
553 $params["bto"] = $receiver["bto"];
556 if (!empty($receiver["cc"])) {
557 $params["cc"] = $receiver["cc"];
560 if (!empty($receiver["bcc"])) {
561 $params["bcc"] = $receiver["bcc"];
564 $inReplyTo = ["id" => $orig_post["uri"],
565 "objectType" => "note"];
567 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
568 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
571 $params["object"] = [
572 'objectType' => "comment",
573 'content' => $content,
574 'inReplyTo' => $inReplyTo];
577 $params["object"]["displayName"] = $title;
581 $client = new oauth_client_class;
582 $client->oauth_version = '1.0a';
583 $client->url_parameters = false;
584 $client->authorization_header = true;
585 $client->access_token = $oauth_token;
586 $client->access_token_secret = $oauth_token_secret;
587 $client->client_id = $consumer_key;
588 $client->client_secret = $consumer_secret;
590 $username = $user.'@'.$host;
591 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
593 if (pumpio_reachable($url)) {
594 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
600 if ($user->generator->displayName) {
601 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
604 $post_id = $user->object->id;
605 Logger::log('pumpio_send '.$username.': success '.$post_id);
606 if ($post_id && $iscomment) {
607 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
608 Item::update(['extid' => $post_id], ['id' => $b['id']]);
611 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
613 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
614 if (DBA::isResult($r)) {
615 $a->contact = $r[0]["id"];
618 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
620 Queue::add($a->contact, Protocol::PUMPIO, $s);
621 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
626 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
628 // Don't do likes and other stuff if you don't import the timeline
629 if (!PConfig::get($uid, 'pumpio', 'import')) {
633 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
634 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
635 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
636 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
637 $hostname = PConfig::get($uid, 'pumpio', 'host');
638 $username = PConfig::get($uid, "pumpio", "user");
640 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
642 if (!DBA::isResult($orig_post)) {
646 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
647 $uri = $orig_post["extid"];
649 $uri = $orig_post["uri"];
652 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
653 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
654 } elseif (strstr($uri, "/api/comment/")) {
655 $objectType = "comment";
656 } elseif (strstr($uri, "/api/note/")) {
657 $objectType = "note";
658 } elseif (strstr($uri, "/api/image/")) {
659 $objectType = "image";
662 $params["verb"] = $action;
663 $params["object"] = ['id' => $uri,
664 "objectType" => $objectType,
665 "content" => $content];
667 $client = new oauth_client_class;
668 $client->oauth_version = '1.0a';
669 $client->authorization_header = true;
670 $client->url_parameters = false;
672 $client->client_id = $ckey;
673 $client->client_secret = $csecret;
674 $client->access_token = $otoken;
675 $client->access_token_secret = $osecret;
677 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
679 if (pumpio_reachable($url)) {
680 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
686 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
688 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user, true));
690 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $uid);
691 if (DBA::isResult($r)) {
692 $a->contact = $r[0]["id"];
695 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
697 Queue::add($a->contact, Protocol::PUMPIO, $s);
698 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
702 function pumpio_sync(App $a)
704 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
706 if (!DBA::isResult($r)) {
710 $last = Config::get('pumpio', 'last_poll');
712 $poll_interval = intval(Config::get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
715 $next = $last + ($poll_interval * 60);
716 if ($next > time()) {
717 Logger::log('pumpio: poll intervall not reached');
721 Logger::log('pumpio: cron_start');
723 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
724 if (DBA::isResult($r)) {
725 foreach ($r as $rr) {
726 Logger::log('pumpio: mirroring user '.$rr['uid']);
727 pumpio_fetchtimeline($a, $rr['uid']);
731 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
732 if ($abandon_days < 1) {
736 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
738 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
739 if (DBA::isResult($r)) {
740 foreach ($r as $rr) {
741 if ($abandon_days != 0) {
742 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
743 if (!DBA::isResult($user)) {
744 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
749 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
750 pumpio_fetchinbox($a, $rr['uid']);
752 // check for new contacts once a day
753 $last_contact_check = PConfig::get($rr['uid'], 'pumpio', 'contact_check');
754 if ($last_contact_check) {
755 $next_contact_check = $last_contact_check + 86400;
757 $next_contact_check = 0;
760 if ($next_contact_check <= time()) {
761 pumpio_getallusers($a, $rr["uid"]);
762 PConfig::set($rr['uid'], 'pumpio', 'contact_check', time());
767 Logger::log('pumpio: cron_end');
769 Config::set('pumpio', 'last_poll', time());
772 function pumpio_cron(App $a, $b)
774 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
777 function pumpio_fetchtimeline(App $a, $uid)
779 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
780 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
781 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
782 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
783 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
784 $hostname = PConfig::get($uid, 'pumpio', 'host');
785 $username = PConfig::get($uid, "pumpio", "user");
787 // get the application name for the pump.io app
788 // 1st try personal config, then system config and fallback to the
789 // hostname of the node if neither one is set.
790 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
791 if ($application_name == "") {
792 $application_name = Config::get('pumpio', 'application_name');
794 if ($application_name == "") {
795 $application_name = $a->getHostName();
798 $first_time = ($lastdate == "");
800 $client = new oauth_client_class;
801 $client->oauth_version = '1.0a';
802 $client->authorization_header = true;
803 $client->url_parameters = false;
805 $client->client_id = $ckey;
806 $client->client_secret = $csecret;
807 $client->access_token = $otoken;
808 $client->access_token_secret = $osecret;
810 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
812 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);
814 $useraddr = $username.'@'.$hostname;
816 if (pumpio_reachable($url)) {
817 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
824 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
828 $posts = array_reverse($user->items);
830 $initiallastdate = $lastdate;
834 foreach ($posts as $post) {
835 if ($post->published <= $initiallastdate) {
839 if ($lastdate < $post->published) {
840 $lastdate = $post->published;
848 if (@is_array($post->cc)) {
849 $receiptians = array_merge($receiptians, $post->cc);
852 if (@is_array($post->to)) {
853 $receiptians = array_merge($receiptians, $post->to);
857 foreach ($receiptians AS $receiver) {
858 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
863 if ($public && !stristr($post->generator->displayName, $application_name)) {
864 $_SESSION["authenticated"] = true;
865 $_SESSION["uid"] = $uid;
868 $_REQUEST["api_source"] = true;
869 $_REQUEST["profile_uid"] = $uid;
870 $_REQUEST["source"] = "pump.io";
872 if (isset($post->object->id)) {
873 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
876 if ($post->object->displayName != "") {
877 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
879 $_REQUEST["title"] = "";
882 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
884 // To-Do: Picture has to be cached and stored locally
885 if ($post->object->fullImage->url != "") {
886 if ($post->object->fullImage->pump_io->proxyURL != "") {
887 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
889 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
893 Logger::log('pumpio: posting for user '.$uid);
895 require_once('mod/item.php');
898 Logger::log('pumpio: posting done - user '.$uid);
903 if ($lastdate != 0) {
904 PConfig::set($uid, 'pumpio', 'lastdate', $lastdate);
908 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
910 // Searching for the unliked post
911 // Two queries for speed issues
912 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
913 if (!DBA::isResult($orig_post)) {
914 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
915 if (!DBA::isResult($orig_post)) {
922 if (Strings::compareLink($post->actor->url, $own_id)) {
923 $contactid = $self[0]['id'];
925 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
926 DBA::escape(Strings::normaliseLink($post->actor->url)),
930 if (DBA::isResult($r)) {
931 $contactid = $r[0]['id'];
934 if ($contactid == 0) {
935 $contactid = $orig_post['contact-id'];
939 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
941 if (DBA::isResult($r)) {
942 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
944 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
948 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
950 require_once('include/items.php');
952 if (empty($post->object->id)) {
953 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
957 // Searching for the liked post
958 // Two queries for speed issues
959 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
960 if (!DBA::isResult($orig_post)) {
961 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
962 if (!DBA::isResult($orig_post)) {
968 if ($threadcompletion) {
969 pumpio_fetchallcomments($a, $uid, $post->object->id);
974 if (Strings::compareLink($post->actor->url, $own_id)) {
975 $contactid = $self[0]['id'];
976 $post->actor->displayName = $self[0]['name'];
977 $post->actor->url = $self[0]['url'];
978 $post->actor->image->url = $self[0]['photo'];
980 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
981 DBA::escape(Strings::normaliseLink($post->actor->url)),
985 if (DBA::isResult($r)) {
986 $contactid = $r[0]['id'];
989 if ($contactid == 0) {
990 $contactid = $orig_post['contact-id'];
994 $condition = ['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
995 if (Item::exists($condition)) {
996 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
1001 $likedata['parent'] = $orig_post['id'];
1002 $likedata['verb'] = ACTIVITY_LIKE;
1003 $likedata['gravity'] = GRAVITY_ACTIVITY;
1004 $likedata['uid'] = $uid;
1005 $likedata['wall'] = 0;
1006 $likedata['network'] = Protocol::PUMPIO;
1007 $likedata['uri'] = Item::newURI($uid);
1008 $likedata['parent-uri'] = $orig_post["uri"];
1009 $likedata['contact-id'] = $contactid;
1010 $likedata['app'] = $post->generator->displayName;
1011 $likedata['author-name'] = $post->actor->displayName;
1012 $likedata['author-link'] = $post->actor->url;
1013 if (!empty($post->actor->image)) {
1014 $likedata['author-avatar'] = $post->actor->image->url;
1017 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
1018 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
1019 $post_type = L10n::t('status');
1020 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
1021 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
1023 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
1025 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
1026 '<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>';
1028 $ret = Item::insert($likedata);
1030 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
1033 function pumpio_get_contact($uid, $contact, $no_insert = false)
1035 $gcontact = ["url" => $contact->url, "network" => Protocol::PUMPIO, "generation" => 2,
1036 "name" => $contact->displayName, "hide" => true,
1037 "nick" => $contact->preferredUsername,
1038 "addr" => str_replace("acct:", "", $contact->id)];
1040 if (!empty($contact->location->displayName)) {
1041 $gcontact["location"] = $contact->location->displayName;
1044 if (!empty($contact->summary)) {
1045 $gcontact["about"] = $contact->summary;
1048 if (!empty($contact->image->url)) {
1049 $gcontact["photo"] = $contact->image->url;
1052 GContact::update($gcontact);
1053 $cid = Contact::getIdForURL($contact->url, $uid);
1059 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1060 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1062 if (!DBA::isResult($r)) {
1063 // create contact record
1064 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1065 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1066 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1067 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1069 DBA::escape(DateTimeFormat::utcNow()),
1070 DBA::escape($contact->url),
1071 DBA::escape(Strings::normaliseLink($contact->url)),
1072 DBA::escape(str_replace("acct:", "", $contact->id)),
1074 DBA::escape($contact->id), // What is it for?
1075 DBA::escape('pump.io ' . $contact->id), // What is it for?
1076 DBA::escape($contact->displayName),
1077 DBA::escape($contact->preferredUsername),
1078 DBA::escape($contact->image->url),
1079 DBA::escape(Protocol::PUMPIO),
1080 intval(Contact::FRIEND),
1082 DBA::escape($contact->location->displayName),
1083 DBA::escape($contact->summary),
1087 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1088 DBA::escape(Strings::normaliseLink($contact->url)),
1092 if (!DBA::isResult($r)) {
1096 $contact_id = $r[0]['id'];
1098 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1100 $contact_id = $r[0]["id"];
1102 /* if (DB_UPDATE_VERSION >= "1177")
1103 q("UPDATE `contact` SET `location` = '%s',
1106 dbesc($contact->location->displayName),
1107 dbesc($contact->summary),
1113 if (!empty($contact->image->url)) {
1114 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1120 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1122 // Two queries for speed issues
1123 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1124 if (Item::exists($condition)) {
1125 Item::delete($condition);
1129 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1130 if (Item::exists($condition)) {
1131 Item::delete($condition);
1137 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1139 require_once('include/items.php');
1141 if (($post->verb == "like") || ($post->verb == "favorite")) {
1142 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1145 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1146 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1149 if ($post->verb == "delete") {
1150 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1153 if ($post->verb != "update") {
1154 // Two queries for speed issues
1155 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1158 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1163 // Only handle these three types
1164 if (!strstr("post|share|update", $post->verb)) {
1169 if (@is_array($post->cc)) {
1170 $receiptians = array_merge($receiptians, $post->cc);
1173 if (@is_array($post->to)) {
1174 $receiptians = array_merge($receiptians, $post->to);
1179 foreach ($receiptians AS $receiver) {
1180 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1186 $postarray['network'] = Protocol::PUMPIO;
1187 $postarray['uid'] = $uid;
1188 $postarray['wall'] = 0;
1189 $postarray['uri'] = $post->object->id;
1190 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1192 if ($post->object->objectType != "comment") {
1193 $contact_id = pumpio_get_contact($uid, $post->actor);
1196 $contact_id = $self[0]['id'];
1199 $postarray['parent-uri'] = $post->object->id;
1202 $postarray['private'] = 1;
1203 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1206 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1208 if (Strings::compareLink($post->actor->url, $own_id)) {
1209 $contact_id = $self[0]['id'];
1210 $post->actor->displayName = $self[0]['name'];
1211 $post->actor->url = $self[0]['url'];
1212 $post->actor->image->url = $self[0]['photo'];
1213 } elseif ($contact_id == 0) {
1214 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1215 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1216 DBA::escape(Strings::normaliseLink($post->actor->url)),
1220 if (DBA::isResult($r)) {
1221 $contact_id = $r[0]['id'];
1223 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1224 DBA::escape(Strings::normaliseLink($post->actor->url)),
1228 if (DBA::isResult($r)) {
1229 $contact_id = $r[0]['id'];
1231 $contact_id = $self[0]['id'];
1236 $reply = new stdClass;
1237 $reply->verb = "note";
1239 if (isset($post->cc)) {
1240 $reply->cc = $post->cc;
1243 if (isset($post->to)) {
1244 $reply->to = $post->to;
1247 $reply->object = new stdClass;
1248 $reply->object->objectType = $post->object->inReplyTo->objectType;
1249 $reply->object->content = $post->object->inReplyTo->content;
1250 $reply->object->id = $post->object->inReplyTo->id;
1251 $reply->actor = $post->object->inReplyTo->author;
1252 $reply->url = $post->object->inReplyTo->url;
1253 $reply->generator = new stdClass;
1254 $reply->generator->displayName = "pumpio";
1255 $reply->published = $post->object->inReplyTo->published;
1256 $reply->received = $post->object->inReplyTo->updated;
1257 $reply->url = $post->object->inReplyTo->url;
1258 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1260 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1263 // When there is no content there is no need to continue
1264 if (empty($post->object->content)) {
1268 if (!empty($post->object->pump_io->proxyURL)) {
1269 $postarray['extid'] = $post->object->pump_io->proxyURL;
1272 $postarray['contact-id'] = $contact_id;
1273 $postarray['verb'] = ACTIVITY_POST;
1274 $postarray['owner-name'] = $post->actor->displayName;
1275 $postarray['owner-link'] = $post->actor->url;
1276 $postarray['author-name'] = $postarray['owner-name'];
1277 $postarray['author-link'] = $postarray['owner-link'];
1278 if (!empty($post->actor->image)) {
1279 $postarray['owner-avatar'] = $post->actor->image->url;
1280 $postarray['author-avatar'] = $postarray['owner-avatar'];
1282 $postarray['plink'] = $post->object->url;
1283 $postarray['app'] = $post->generator->displayName;
1284 $postarray['title'] = '';
1285 $postarray['body'] = HTML::toBBCode($post->object->content);
1286 $postarray['object'] = json_encode($post);
1288 if (!empty($post->object->fullImage->url)) {
1289 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1292 if (!empty($post->object->displayName)) {
1293 $postarray['title'] = $post->object->displayName;
1296 $postarray['created'] = DateTimeFormat::utc($post->published);
1297 if (isset($post->updated)) {
1298 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1299 } elseif (isset($post->received)) {
1300 $postarray['edited'] = DateTimeFormat::utc($post->received);
1302 $postarray['edited'] = $postarray['created'];
1305 if ($post->verb == "share") {
1306 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1307 $share_author = $post->object->author->displayName;
1308 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1309 $share_author = $post->object->author->preferredUsername;
1311 $share_author = $post->object->author->url;
1314 if (isset($post->object->created)) {
1315 $created = DateTimeFormat::utc($post->object->created);
1320 $postarray['body'] = share_header($share_author, $post->object->author->url,
1321 $post->object->author->image->url, "",
1322 $created, $post->links->self->href).
1323 $postarray['body']."[/share]";
1326 if (trim($postarray['body']) == "") {
1330 $top_item = Item::insert($postarray);
1331 $postarray["id"] = $top_item;
1333 if (($top_item == 0) && ($post->verb == "update")) {
1334 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1335 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1336 Item::update($fields, $condition);
1339 if (($post->object->objectType == "comment") && $threadcompletion) {
1340 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1346 function pumpio_fetchinbox(App $a, $uid)
1348 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1349 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1350 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1351 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1352 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1353 $hostname = PConfig::get($uid, 'pumpio', 'host');
1354 $username = PConfig::get($uid, "pumpio", "user");
1356 $own_id = "https://".$hostname."/".$username;
1358 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1361 $lastitems = q("SELECT `uri` FROM `thread`
1362 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1363 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1364 ORDER BY `thread`.`commented` DESC LIMIT 10",
1365 DBA::escape(Protocol::PUMPIO),
1369 $client = new oauth_client_class;
1370 $client->oauth_version = '1.0a';
1371 $client->authorization_header = true;
1372 $client->url_parameters = false;
1374 $client->client_id = $ckey;
1375 $client->client_secret = $csecret;
1376 $client->access_token = $otoken;
1377 $client->access_token_secret = $osecret;
1379 $last_id = PConfig::get($uid, 'pumpio', 'last_id');
1381 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1383 if ($last_id != "") {
1384 $url .= '?since='.urlencode($last_id);
1387 if (pumpio_reachable($url)) {
1388 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1397 if (!empty($user->items)) {
1398 $posts = array_reverse($user->items);
1400 if (count($posts)) {
1401 foreach ($posts as $post) {
1402 $last_id = $post->id;
1403 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1408 foreach ($lastitems as $item) {
1409 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1412 PConfig::set($uid, 'pumpio', 'last_id', $last_id);
1415 function pumpio_getallusers(App &$a, $uid)
1417 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1418 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1419 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1420 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1421 $hostname = PConfig::get($uid, 'pumpio', 'host');
1422 $username = PConfig::get($uid, "pumpio", "user");
1424 $client = new oauth_client_class;
1425 $client->oauth_version = '1.0a';
1426 $client->authorization_header = true;
1427 $client->url_parameters = false;
1429 $client->client_id = $ckey;
1430 $client->client_secret = $csecret;
1431 $client->access_token = $otoken;
1432 $client->access_token_secret = $osecret;
1434 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1436 if (pumpio_reachable($url)) {
1437 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1442 if (empty($users)) {
1446 if ($users->totalItems > count($users->items)) {
1447 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1449 if (pumpio_reachable($url)) {
1450 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1456 if (!empty($users->items)) {
1457 foreach ($users->items as $user) {
1458 pumpio_get_contact($uid, $user);
1463 function pumpio_queue_hook(App $a, array &$b)
1465 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1466 DBA::escape(Protocol::PUMPIO)
1469 if (!DBA::isResult($qi)) {
1473 foreach ($qi as $x) {
1474 if ($x['network'] !== Protocol::PUMPIO) {
1478 Logger::log('pumpio_queue: run');
1480 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1481 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1484 if (!DBA::isResult($r)) {
1490 //Logger::log('pumpio_queue: fetching userdata '.print_r($userdata, true));
1492 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1493 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1494 $consumer_key = PConfig::get($userdata['uid'], "pumpio", "consumer_key");
1495 $consumer_secret = PConfig::get($userdata['uid'], "pumpio", "consumer_secret");
1497 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1498 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1502 if ($oauth_token && $oauth_token_secret &&
1503 $consumer_key && $consumer_secret) {
1504 $username = $user.'@'.$host;
1506 Logger::log('pumpio_queue: able to post for user '.$username);
1508 $z = unserialize($x['content']);
1510 $client = new oauth_client_class;
1511 $client->oauth_version = '1.0a';
1512 $client->url_parameters = false;
1513 $client->authorization_header = true;
1514 $client->access_token = $oauth_token;
1515 $client->access_token_secret = $oauth_token_secret;
1516 $client->client_id = $consumer_key;
1517 $client->client_secret = $consumer_secret;
1519 if (pumpio_reachable($z['url'])) {
1520 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1526 $post_id = $user->object->id;
1527 Logger::log('pumpio_queue: send '.$username.': success '.$post_id);
1528 if ($post_id && $iscomment) {
1529 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1530 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1532 Queue::removeItem($x['id']);
1534 Logger::log('pumpio_queue: send '.$username.': '.$z['url'].' general error: ' . print_r($user, true));
1537 Logger::log("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1541 Logger::log('pumpio_queue: delayed');
1542 Queue::updateTime($x['id']);
1547 function pumpio_getreceiver(App $a, array $b)
1551 if (!$b["private"]) {
1552 if (!strstr($b['postopts'], 'pumpio')) {
1556 $public = PConfig::get($b['uid'], "pumpio", "public");
1559 $receiver["to"][] = [
1560 "objectType" => "collection",
1561 "id" => "http://activityschema.org/collection/public"];
1564 $cids = explode("><", $b["allow_cid"]);
1565 $gids = explode("><", $b["allow_gid"]);
1567 foreach ($cids AS $cid) {
1568 $cid = trim($cid, " <>");
1570 $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",
1573 DBA::escape(Protocol::PUMPIO)
1576 if (DBA::isResult($r)) {
1577 $receiver["bcc"][] = [
1578 "displayName" => $r[0]["name"],
1579 "objectType" => "person",
1580 "preferredUsername" => $r[0]["nick"],
1581 "url" => $r[0]["url"]];
1584 foreach ($gids AS $gid) {
1585 $gid = trim($gid, " <>");
1587 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1588 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1589 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1591 DBA::escape(Protocol::PUMPIO)
1594 foreach ($r AS $row)
1595 $receiver["bcc"][] = [
1596 "displayName" => $row["name"],
1597 "objectType" => "person",
1598 "preferredUsername" => $row["nick"],
1599 "url" => $row["url"]];
1603 if ($b["inform"] != "") {
1604 $inform = explode(",", $b["inform"]);
1606 foreach ($inform AS $cid) {
1607 if (substr($cid, 0, 4) != "cid:") {
1611 $cid = str_replace("cid:", "", $cid);
1613 $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",
1616 DBA::escape(Protocol::PUMPIO)
1619 if (DBA::isResult($r)) {
1620 $receiver["to"][] = [
1621 "displayName" => $r[0]["name"],
1622 "objectType" => "person",
1623 "preferredUsername" => $r[0]["nick"],
1624 "url" => $r[0]["url"]];
1632 function pumpio_fetchallcomments(App $a, $uid, $id)
1634 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1635 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1636 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1637 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1638 $hostname = PConfig::get($uid, 'pumpio', 'host');
1639 $username = PConfig::get($uid, "pumpio", "user");
1641 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1643 $own_id = "https://".$hostname."/".$username;
1645 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1648 // Fetching the original post
1649 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1650 $item = Item::selectFirst(['extid'], $condition);
1651 if (!DBA::isResult($item)) {
1655 $url = $item["extid"];
1657 $client = new oauth_client_class;
1658 $client->oauth_version = '1.0a';
1659 $client->authorization_header = true;
1660 $client->url_parameters = false;
1662 $client->client_id = $ckey;
1663 $client->client_secret = $csecret;
1664 $client->access_token = $otoken;
1665 $client->access_token_secret = $osecret;
1667 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1669 if (pumpio_reachable($url)) {
1670 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1679 if ($item->likes->totalItems != 0) {
1680 foreach ($item->likes->items AS $post) {
1681 $like = new stdClass;
1682 $like->object = new stdClass;
1683 $like->object->id = $item->id;
1684 $like->actor = new stdClass;
1685 if (!empty($item->displayName)) {
1686 $like->actor->displayName = $item->displayName;
1688 //$like->actor->preferredUsername = $item->preferredUsername;
1689 //$like->actor->image = $item->image;
1690 $like->actor->url = $item->url;
1691 $like->generator = new stdClass;
1692 $like->generator->displayName = "pumpio";
1693 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1697 if ($item->replies->totalItems == 0) {
1701 foreach ($item->replies->items AS $item) {
1702 if ($item->id == $id) {
1706 // Checking if the comment already exists - Two queries for speed issues
1707 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1711 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1715 $post = new stdClass;
1716 $post->verb = "post";
1717 $post->actor = $item->author;
1718 $post->published = $item->published;
1719 $post->received = $item->updated;
1720 $post->generator = new stdClass;
1721 $post->generator->displayName = "pumpio";
1722 // To-Do: Check for public post
1724 unset($item->author);
1725 unset($item->published);
1726 unset($item->updated);
1728 $post->object = $item;
1730 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1731 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1735 function pumpio_reachable($url)
1737 return Network::curl($url, false, $redirects, ['timeout'=>10])->isSuccess();