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\Addon;
13 use Friendica\Core\Config;
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 Addon::registerHook('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
41 Addon::registerHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
42 Addon::registerHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
43 Addon::registerHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
44 Addon::registerHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
45 Addon::registerHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
46 Addon::registerHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
47 Addon::registerHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
48 Addon::registerHook('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
51 function pumpio_uninstall()
53 Addon::unregisterHook('load_config', 'addon/pumpio/pumpio.php', 'pumpio_load_config');
54 Addon::unregisterHook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
55 Addon::unregisterHook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
56 Addon::unregisterHook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
57 Addon::unregisterHook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
58 Addon::unregisterHook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
59 Addon::unregisterHook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
60 Addon::unregisterHook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
61 Addon::unregisterHook('check_item_notification', 'addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
64 function pumpio_module() {}
66 function pumpio_content(App $a)
69 notice(L10n::t('Permission denied.') . EOL);
73 require_once("mod/settings.php");
76 if (isset($a->argv[1])) {
77 switch ($a->argv[1]) {
79 $o = pumpio_connect($a);
82 $o = print_r($a->argv, true);
86 $o = pumpio_connect($a);
91 function pumpio_check_item_notification($a, &$notification_data)
93 $hostname = PConfig::get($notification_data["uid"], 'pumpio', 'host');
94 $username = PConfig::get($notification_data["uid"], "pumpio", "user");
96 $notification_data["profiles"][] = "https://".$hostname."/".$username;
99 function pumpio_registerclient(App $a, $host)
101 $url = "https://".$host."/api/client/register";
105 $application_name = Config::get('pumpio', 'application_name');
107 if ($application_name == "") {
108 $application_name = $a->getHostName();
111 $adminlist = explode(",", str_replace(" ", "", Config::get('config', 'admin_email')));
113 $params["type"] = "client_associate";
114 $params["contacts"] = $adminlist[0];
115 $params["application_type"] = "native";
116 $params["application_name"] = $application_name;
117 $params["logo_url"] = $a->getBaseURL()."/images/friendica-256.png";
118 $params["redirect_uris"] = $a->getBaseURL()."/pumpio/connect";
120 Logger::log("pumpio_registerclient: ".$url." parameters ".print_r($params, true), Logger::DEBUG);
122 $ch = curl_init($url);
123 curl_setopt($ch, CURLOPT_HEADER, false);
124 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
125 curl_setopt($ch, CURLOPT_POST,1);
126 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
127 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
130 $curl_info = curl_getinfo($ch);
132 if ($curl_info["http_code"] == "200") {
133 $values = json_decode($s);
134 Logger::log("pumpio_registerclient: success ".print_r($values, true), Logger::DEBUG);
137 Logger::log("pumpio_registerclient: failed: ".print_r($curl_info, true), Logger::DEBUG);
142 function pumpio_connect(App $a)
144 // Define the needed keys
145 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
146 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
147 $hostname = PConfig::get(local_user(), 'pumpio', 'host');
149 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
150 Logger::log("pumpio_connect: register client");
151 $clientdata = pumpio_registerclient($a, $hostname);
152 PConfig::set(local_user(), 'pumpio', 'consumer_key', $clientdata->client_id);
153 PConfig::set(local_user(), 'pumpio', 'consumer_secret', $clientdata->client_secret);
155 $consumer_key = PConfig::get(local_user(), 'pumpio', 'consumer_key');
156 $consumer_secret = PConfig::get(local_user(), 'pumpio', 'consumer_secret');
158 Logger::log("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, Logger::DEBUG);
161 if (($consumer_key == "") || ($consumer_secret == "")) {
162 Logger::log("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
164 $o .= L10n::t("Unable to register the client at the pump.io server '%s'.", $hostname);
168 // The callback URL is the script that gets called after the user authenticates with pumpio
169 $callback_url = $a->getBaseURL()."/pumpio/connect";
171 // Let's begin. First we need a Request Token. The request token is required to send the user
172 // to pumpio's login page.
174 // Create a new instance of the oauth_client_class library. For this step, all we need to give the library is our
175 // Consumer Key and Consumer Secret
176 $client = new oauth_client_class;
178 $client->server = '';
179 $client->oauth_version = '1.0a';
180 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
181 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
182 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
183 $client->url_parameters = false;
184 $client->authorization_header = true;
185 $client->redirect_uri = $callback_url;
186 $client->client_id = $consumer_key;
187 $client->client_secret = $consumer_secret;
189 if (($success = $client->Initialize())) {
190 if (($success = $client->Process())) {
191 if (strlen($client->access_token)) {
192 Logger::log("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, Logger::DEBUG);
193 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
194 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
197 $success = $client->Finalize($success);
200 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
204 Logger::log("pumpio_connect: authenticated");
205 $o = L10n::t("You are now authenticated to pumpio.");
206 $o .= '<br /><a href="'.$a->getBaseURL().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
208 Logger::log("pumpio_connect: could not connect");
209 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
215 function pumpio_jot_nets(App $a, &$b)
217 if (! local_user()) {
221 $pumpio_post = PConfig::get(local_user(), 'pumpio', 'post');
223 if (intval($pumpio_post) == 1) {
224 $pumpio_defpost = PConfig::get(local_user(), 'pumpio', 'post_by_default');
225 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
226 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
227 . L10n::t('Post to pumpio') . '</div>';
231 function pumpio_settings(App $a, &$s)
237 /* Add our stylesheet to the page so we can make our settings look nice */
239 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
241 /* Get the current state of our config variables */
243 $import_enabled = PConfig::get(local_user(), 'pumpio', 'import');
244 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
246 $enabled = PConfig::get(local_user(), 'pumpio', 'post');
247 $checked = (($enabled) ? ' checked="checked" ' : '');
248 $css = (($enabled) ? '' : '-disabled');
250 $def_enabled = PConfig::get(local_user(), 'pumpio', 'post_by_default');
251 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
253 $public_enabled = PConfig::get(local_user(), 'pumpio', 'public');
254 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
256 $mirror_enabled = PConfig::get(local_user(), 'pumpio', 'mirror');
257 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
259 $servername = PConfig::get(local_user(), "pumpio", "host");
260 $username = PConfig::get(local_user(), "pumpio", "user");
262 /* Add some HTML to the existing form */
264 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
265 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. L10n::t('Pump.io Import/Export/Mirror').'</h3>';
267 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
268 $s .= '<span class="fakelink" 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>';
272 $s .= '<div id="pumpio-username-wrapper">';
273 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.L10n::t('pump.io username (without the servername)').'</label>';
274 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
275 $s .= '</div><div class="clear"></div>';
277 $s .= '<div id="pumpio-servername-wrapper">';
278 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.L10n::t('pump.io servername (without "http://" or "https://" )').'</label>';
279 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
280 $s .= '</div><div class="clear"></div>';
282 if (($username != '') && ($servername != '')) {
283 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
284 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
286 $s .= '<div id="pumpio-password-wrapper">';
287 if (($oauth_token == "") || ($oauth_token_secret == "")) {
288 $s .= '<div id="pumpio-authenticate-wrapper">';
289 $s .= '<a href="'.$a->getBaseURL().'/pumpio/connect">'.L10n::t("Authenticate your pump.io connection").'</a>';
290 $s .= '</div><div class="clear"></div>';
292 $s .= '<div id="pumpio-import-wrapper">';
293 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . L10n::t('Import the remote timeline') . '</label>';
294 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
295 $s .= '</div><div class="clear"></div>';
297 $s .= '<div id="pumpio-enable-wrapper">';
298 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . L10n::t('Enable pump.io Post Addon') . '</label>';
299 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
300 $s .= '</div><div class="clear"></div>';
302 $s .= '<div id="pumpio-bydefault-wrapper">';
303 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . L10n::t('Post to pump.io by default') . '</label>';
304 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
305 $s .= '</div><div class="clear"></div>';
307 $s .= '<div id="pumpio-public-wrapper">';
308 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . L10n::t('Should posts be public?') . '</label>';
309 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
310 $s .= '</div><div class="clear"></div>';
312 $s .= '<div id="pumpio-mirror-wrapper">';
313 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . L10n::t('Mirror all public posts') . '</label>';
314 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
315 $s .= '</div><div class="clear"></div>';
317 $s .= '<div id="pumpio-delete-wrapper">';
318 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . L10n::t('Check to delete this preset') . '</label>';
319 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
320 $s .= '</div><div class="clear"></div>';
323 $s .= '</div><div class="clear"></div>';
326 /* provide a submit button */
328 $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>';
331 function pumpio_settings_post(App $a, array &$b)
333 if (!empty($_POST['pumpio-submit'])) {
334 if (!empty($_POST['pumpio_delete'])) {
335 PConfig::set(local_user(), 'pumpio', 'consumer_key' , '');
336 PConfig::set(local_user(), 'pumpio', 'consumer_secret' , '');
337 PConfig::set(local_user(), 'pumpio', 'oauth_token' , '');
338 PConfig::set(local_user(), 'pumpio', 'oauth_token_secret', '');
339 PConfig::set(local_user(), 'pumpio', 'post' , false);
340 PConfig::set(local_user(), 'pumpio', 'import' , false);
341 PConfig::set(local_user(), 'pumpio', 'host' , '');
342 PConfig::set(local_user(), 'pumpio', 'user' , '');
343 PConfig::set(local_user(), 'pumpio', 'public' , false);
344 PConfig::set(local_user(), 'pumpio', 'mirror' , false);
345 PConfig::set(local_user(), 'pumpio', 'post_by_default' , false);
346 PConfig::set(local_user(), 'pumpio', 'lastdate' , 0);
347 PConfig::set(local_user(), 'pumpio', 'last_id' , '');
349 // filtering the username if it is filled wrong
350 $user = $_POST['pumpio_user'];
351 if (strstr($user, "@")) {
352 $pos = strpos($user, "@");
355 $user = substr($user, 0, $pos);
359 // Filtering the hostname if someone is entering it with "http"
360 $host = $_POST['pumpio_host'];
362 $host = str_replace(["https://", "http://"], ["", ""], $host);
364 PConfig::set(local_user(), 'pumpio', 'post' , defaults($_POST, 'pumpio', false));
365 PConfig::set(local_user(), 'pumpio', 'import' , defaults($_POST, 'pumpio_import', false));
366 PConfig::set(local_user(), 'pumpio', 'host' , $host);
367 PConfig::set(local_user(), 'pumpio', 'user' , $user);
368 PConfig::set(local_user(), 'pumpio', 'public' , defaults($_POST, 'pumpio_public', false));
369 PConfig::set(local_user(), 'pumpio', 'mirror' , defaults($_POST, 'pumpio_mirror', false));
370 PConfig::set(local_user(), 'pumpio', 'post_by_default', defaults($_POST, 'pumpio_bydefault', false));
372 if (!empty($_POST['pumpio_mirror'])) {
373 PConfig::delete(local_user(), 'pumpio', 'lastdate');
379 function pumpio_load_config(App $a)
381 $a->loadConfigFile(__DIR__. '/config/pumpio.ini.php');
384 function pumpio_post_local(App $a, array &$b)
386 if (!local_user() || (local_user() != $b['uid'])) {
390 $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post'));
392 $pumpio_enable = (($pumpio_post && !empty($_REQUEST['pumpio_enable'])) ? intval($_REQUEST['pumpio_enable']) : 0);
394 if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
398 if (!$pumpio_enable) {
402 if (strlen($b['postopts'])) {
403 $b['postopts'] .= ',';
406 $b['postopts'] .= 'pumpio';
409 function pumpio_send(App $a, array &$b)
411 if (!PConfig::get($b["uid"], 'pumpio', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
415 Logger::log("pumpio_send: parameter ".print_r($b, true), Logger::DATA);
417 if ($b['parent'] != $b['id']) {
418 // Looking if its a reply to a pumpio post
419 $condition = ['id' => $b['parent'], 'network' => Protocol::PUMPIO];
420 $orig_post = Item::selectFirst([], $condition);
422 if (!DBA::isResult($orig_post)) {
423 Logger::log("pumpio_send: no pumpio post ".$b["parent"]);
431 $receiver = pumpio_getreceiver($a, $b);
433 Logger::log("pumpio_send: receiver ".print_r($receiver, true));
435 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'], 'pumpio'))) {
439 // Dont't post if the post doesn't belong to us.
440 // This is a check for forum postings
441 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
442 if ($b['contact-id'] != $self['id']) {
447 if ($b['verb'] == ACTIVITY_LIKE) {
449 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
451 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
456 if ($b['verb'] == ACTIVITY_DISLIKE) {
460 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted']) {
461 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
464 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
465 pumpio_action($a, $b["uid"], $b["uri"], "delete");
468 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
472 // if post comes from pump.io don't send it back
473 if ($b['app'] == "pump.io") {
478 // Support for native shares
479 // http://<hostname>/api/<type>/shares?id=<the-object-id>
481 $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
482 $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
483 $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
484 $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
486 $host = PConfig::get($b['uid'], "pumpio", "host");
487 $user = PConfig::get($b['uid'], "pumpio", "user");
488 $public = PConfig::get($b['uid'], "pumpio", "public");
490 if ($oauth_token && $oauth_token_secret) {
491 $title = trim($b['title']);
493 $content = BBCode::convert($b['body'], false, 4);
497 $params["verb"] = "post";
500 $params["object"] = [
501 'objectType' => "note",
502 'content' => $content];
504 if (!empty($title)) {
505 $params["object"]["displayName"] = $title;
508 if (!empty($receiver["to"])) {
509 $params["to"] = $receiver["to"];
512 if (!empty($receiver["bto"])) {
513 $params["bto"] = $receiver["bto"];
516 if (!empty($receiver["cc"])) {
517 $params["cc"] = $receiver["cc"];
520 if (!empty($receiver["bcc"])) {
521 $params["bcc"] = $receiver["bcc"];
524 $inReplyTo = ["id" => $orig_post["uri"],
525 "objectType" => "note"];
527 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
528 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
531 $params["object"] = [
532 'objectType' => "comment",
533 'content' => $content,
534 'inReplyTo' => $inReplyTo];
537 $params["object"]["displayName"] = $title;
541 $client = new oauth_client_class;
542 $client->oauth_version = '1.0a';
543 $client->url_parameters = false;
544 $client->authorization_header = true;
545 $client->access_token = $oauth_token;
546 $client->access_token_secret = $oauth_token_secret;
547 $client->client_id = $consumer_key;
548 $client->client_secret = $consumer_secret;
550 $username = $user.'@'.$host;
551 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
553 if (pumpio_reachable($url)) {
554 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
560 if ($user->generator->displayName) {
561 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
564 $post_id = $user->object->id;
565 Logger::log('pumpio_send '.$username.': success '.$post_id);
566 if ($post_id && $iscomment) {
567 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
568 Item::update(['extid' => $post_id], ['id' => $b['id']]);
571 Logger::log('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user, true));
573 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
574 if (DBA::isResult($r)) {
575 $a->contact = $r[0]["id"];
578 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
580 Queue::add($a->contact, Protocol::PUMPIO, $s);
581 notice(L10n::t('Pump.io post failed. Queued for retry.').EOL);
586 function pumpio_action(App $a, $uid, $uri, $action, $content = "")
588 // Don't do likes and other stuff if you don't import the timeline
589 if (!PConfig::get($uid, 'pumpio', 'import')) {
593 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
594 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
595 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
596 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
597 $hostname = PConfig::get($uid, 'pumpio', 'host');
598 $username = PConfig::get($uid, "pumpio", "user");
600 $orig_post = Item::selectFirst([], ['uri' => $uri, 'uid' => $uid]);
602 if (!DBA::isResult($orig_post)) {
606 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/")) {
607 $uri = $orig_post["extid"];
609 $uri = $orig_post["uri"];
612 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) {
613 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
614 } elseif (strstr($uri, "/api/comment/")) {
615 $objectType = "comment";
616 } elseif (strstr($uri, "/api/note/")) {
617 $objectType = "note";
618 } elseif (strstr($uri, "/api/image/")) {
619 $objectType = "image";
622 $params["verb"] = $action;
623 $params["object"] = ['id' => $uri,
624 "objectType" => $objectType,
625 "content" => $content];
627 $client = new oauth_client_class;
628 $client->oauth_version = '1.0a';
629 $client->authorization_header = true;
630 $client->url_parameters = false;
632 $client->client_id = $ckey;
633 $client->client_secret = $csecret;
634 $client->access_token = $otoken;
635 $client->access_token_secret = $osecret;
637 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
639 if (pumpio_reachable($url)) {
640 $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
646 Logger::log('pumpio_action '.$username.' '.$action.': success '.$uri);
648 Logger::log('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user, true));
650 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $uid);
651 if (DBA::isResult($r)) {
652 $a->contact = $r[0]["id"];
655 $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
657 Queue::add($a->contact, Protocol::PUMPIO, $s);
658 notice(L10n::t('Pump.io like failed. Queued for retry.').EOL);
662 function pumpio_sync(App $a)
664 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'");
666 if (!DBA::isResult($r)) {
670 $last = Config::get('pumpio', 'last_poll');
672 $poll_interval = intval(Config::get('pumpio', 'poll_interval', PUMPIO_DEFAULT_POLL_INTERVAL));
675 $next = $last + ($poll_interval * 60);
676 if ($next > time()) {
677 Logger::log('pumpio: poll intervall not reached');
681 Logger::log('pumpio: cron_start');
683 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
684 if (DBA::isResult($r)) {
685 foreach ($r as $rr) {
686 Logger::log('pumpio: mirroring user '.$rr['uid']);
687 pumpio_fetchtimeline($a, $rr['uid']);
691 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
692 if ($abandon_days < 1) {
696 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
698 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
699 if (DBA::isResult($r)) {
700 foreach ($r as $rr) {
701 if ($abandon_days != 0) {
702 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
703 if (!DBA::isResult($user)) {
704 Logger::log('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
709 Logger::log('pumpio: importing timeline from user '.$rr['uid']);
710 pumpio_fetchinbox($a, $rr['uid']);
712 // check for new contacts once a day
713 $last_contact_check = PConfig::get($rr['uid'], 'pumpio', 'contact_check');
714 if ($last_contact_check) {
715 $next_contact_check = $last_contact_check + 86400;
717 $next_contact_check = 0;
720 if ($next_contact_check <= time()) {
721 pumpio_getallusers($a, $rr["uid"]);
722 PConfig::set($rr['uid'], 'pumpio', 'contact_check', time());
727 Logger::log('pumpio: cron_end');
729 Config::set('pumpio', 'last_poll', time());
732 function pumpio_cron(App $a, $b)
734 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
737 function pumpio_fetchtimeline(App $a, $uid)
739 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
740 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
741 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
742 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
743 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
744 $hostname = PConfig::get($uid, 'pumpio', 'host');
745 $username = PConfig::get($uid, "pumpio", "user");
747 // get the application name for the pump.io app
748 // 1st try personal config, then system config and fallback to the
749 // hostname of the node if neither one is set.
750 $application_name = PConfig::get($uid, 'pumpio', 'application_name');
751 if ($application_name == "") {
752 $application_name = Config::get('pumpio', 'application_name');
754 if ($application_name == "") {
755 $application_name = $a->getHostName();
758 $first_time = ($lastdate == "");
760 $client = new oauth_client_class;
761 $client->oauth_version = '1.0a';
762 $client->authorization_header = true;
763 $client->url_parameters = false;
765 $client->client_id = $ckey;
766 $client->client_secret = $csecret;
767 $client->access_token = $otoken;
768 $client->access_token_secret = $osecret;
770 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
772 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);
774 $useraddr = $username.'@'.$hostname;
776 if (pumpio_reachable($url)) {
777 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
784 Logger::log('pumpio: error fetching posts for user '.$uid." ".$useraddr." ".print_r($user, true));
788 $posts = array_reverse($user->items);
790 $initiallastdate = $lastdate;
794 foreach ($posts as $post) {
795 if ($post->published <= $initiallastdate) {
799 if ($lastdate < $post->published) {
800 $lastdate = $post->published;
808 if (@is_array($post->cc)) {
809 $receiptians = array_merge($receiptians, $post->cc);
812 if (@is_array($post->to)) {
813 $receiptians = array_merge($receiptians, $post->to);
817 foreach ($receiptians AS $receiver) {
818 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
823 if ($public && !stristr($post->generator->displayName, $application_name)) {
824 $_SESSION["authenticated"] = true;
825 $_SESSION["uid"] = $uid;
828 $_REQUEST["api_source"] = true;
829 $_REQUEST["profile_uid"] = $uid;
830 $_REQUEST["source"] = "pump.io";
832 if (isset($post->object->id)) {
833 $_REQUEST['message_id'] = Protocol::PUMPIO.":".$post->object->id;
836 if ($post->object->displayName != "") {
837 $_REQUEST["title"] = HTML::toBBCode($post->object->displayName);
839 $_REQUEST["title"] = "";
842 $_REQUEST["body"] = HTML::toBBCode($post->object->content);
844 // To-Do: Picture has to be cached and stored locally
845 if ($post->object->fullImage->url != "") {
846 if ($post->object->fullImage->pump_io->proxyURL != "") {
847 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
849 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
853 Logger::log('pumpio: posting for user '.$uid);
855 require_once('mod/item.php');
858 Logger::log('pumpio: posting done - user '.$uid);
863 if ($lastdate != 0) {
864 PConfig::set($uid, 'pumpio', 'lastdate', $lastdate);
868 function pumpio_dounlike(App $a, $uid, $self, $post, $own_id)
870 // Searching for the unliked post
871 // Two queries for speed issues
872 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
873 if (!DBA::isResult($orig_post)) {
874 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
875 if (!DBA::isResult($orig_post)) {
882 if (Strings::compareLink($post->actor->url, $own_id)) {
883 $contactid = $self[0]['id'];
885 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
886 DBA::escape(Strings::normaliseLink($post->actor->url)),
890 if (DBA::isResult($r)) {
891 $contactid = $r[0]['id'];
894 if ($contactid == 0) {
895 $contactid = $orig_post['contact-id'];
899 Item::delete(['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']]);
901 if (DBA::isResult($r)) {
902 Logger::log("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
904 Logger::log("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
908 function pumpio_dolike(App $a, $uid, $self, $post, $own_id, $threadcompletion = true)
910 require_once('include/items.php');
912 if (empty($post->object->id)) {
913 Logger::log('Got empty like: '.print_r($post, true), Logger::DEBUG);
917 // Searching for the liked post
918 // Two queries for speed issues
919 $orig_post = Item::selectFirst([], ['uri' => $post->object->id, 'uid' => $uid]);
920 if (!DBA::isResult($orig_post)) {
921 $orig_post = Item::selectFirst([], ['extid' => $post->object->id, 'uid' => $uid]);
922 if (!DBA::isResult($orig_post)) {
928 if ($threadcompletion) {
929 pumpio_fetchallcomments($a, $uid, $post->object->id);
934 if (Strings::compareLink($post->actor->url, $own_id)) {
935 $contactid = $self[0]['id'];
936 $post->actor->displayName = $self[0]['name'];
937 $post->actor->url = $self[0]['url'];
938 $post->actor->image->url = $self[0]['photo'];
940 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
941 DBA::escape(Strings::normaliseLink($post->actor->url)),
945 if (DBA::isResult($r)) {
946 $contactid = $r[0]['id'];
949 if ($contactid == 0) {
950 $contactid = $orig_post['contact-id'];
954 $condition = ['verb' => ACTIVITY_LIKE, 'uid' => $uid, 'contact-id' => $contactid, 'thr-parent' => $orig_post['uri']];
955 if (Item::exists($condition)) {
956 Logger::log("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
961 $likedata['parent'] = $orig_post['id'];
962 $likedata['verb'] = ACTIVITY_LIKE;
963 $likedata['gravity'] = GRAVITY_ACTIVITY;
964 $likedata['uid'] = $uid;
965 $likedata['wall'] = 0;
966 $likedata['network'] = Protocol::PUMPIO;
967 $likedata['uri'] = Item::newURI($uid);
968 $likedata['parent-uri'] = $orig_post["uri"];
969 $likedata['contact-id'] = $contactid;
970 $likedata['app'] = $post->generator->displayName;
971 $likedata['author-name'] = $post->actor->displayName;
972 $likedata['author-link'] = $post->actor->url;
973 if (!empty($post->actor->image)) {
974 $likedata['author-avatar'] = $post->actor->image->url;
977 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
978 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
979 $post_type = L10n::t('status');
980 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
981 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
983 $likedata['body'] = L10n::t('%1$s likes %2$s\'s %3$s', $author, $objauthor, $plink);
985 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
986 '<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>';
988 $ret = Item::insert($likedata);
990 Logger::log("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
993 function pumpio_get_contact($uid, $contact, $no_insert = false)
995 $gcontact = ["url" => $contact->url, "network" => Protocol::PUMPIO, "generation" => 2,
996 "name" => $contact->displayName, "hide" => true,
997 "nick" => $contact->preferredUsername,
998 "addr" => str_replace("acct:", "", $contact->id)];
1000 if (!empty($contact->location->displayName)) {
1001 $gcontact["location"] = $contact->location->displayName;
1004 if (!empty($contact->summary)) {
1005 $gcontact["about"] = $contact->summary;
1008 if (!empty($contact->image->url)) {
1009 $gcontact["photo"] = $contact->image->url;
1012 GContact::update($gcontact);
1013 $cid = Contact::getIdForURL($contact->url, $uid);
1019 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
1020 intval($uid), DBA::escape(Strings::normaliseLink($contact->url)));
1022 if (!DBA::isResult($r)) {
1023 // create contact record
1024 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1025 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1026 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1027 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1029 DBA::escape(DateTimeFormat::utcNow()),
1030 DBA::escape($contact->url),
1031 DBA::escape(Strings::normaliseLink($contact->url)),
1032 DBA::escape(str_replace("acct:", "", $contact->id)),
1034 DBA::escape($contact->id), // What is it for?
1035 DBA::escape('pump.io ' . $contact->id), // What is it for?
1036 DBA::escape($contact->displayName),
1037 DBA::escape($contact->preferredUsername),
1038 DBA::escape($contact->image->url),
1039 DBA::escape(Protocol::PUMPIO),
1040 intval(Contact::FRIEND),
1042 DBA::escape($contact->location->displayName),
1043 DBA::escape($contact->summary),
1047 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1048 DBA::escape(Strings::normaliseLink($contact->url)),
1052 if (!DBA::isResult($r)) {
1056 $contact_id = $r[0]['id'];
1058 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1060 $contact_id = $r[0]["id"];
1062 /* if (DB_UPDATE_VERSION >= "1177")
1063 q("UPDATE `contact` SET `location` = '%s',
1066 dbesc($contact->location->displayName),
1067 dbesc($contact->summary),
1073 if (!empty($contact->image->url)) {
1074 Contact::updateAvatar($contact->image->url, $uid, $contact_id);
1080 function pumpio_dodelete(App $a, $uid, $self, $post, $own_id)
1082 // Two queries for speed issues
1083 $condition = ['uri' => $post->object->id, 'uid' => $uid];
1084 if (Item::exists($condition)) {
1085 Item::delete($condition);
1089 $condition = ['extid' => $post->object->id, 'uid' => $uid];
1090 if (Item::exists($condition)) {
1091 Item::delete($condition);
1097 function pumpio_dopost(App $a, $client, $uid, $self, $post, $own_id, $threadcompletion = true)
1099 require_once('include/items.php');
1101 if (($post->verb == "like") || ($post->verb == "favorite")) {
1102 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1105 if (($post->verb == "unlike") || ($post->verb == "unfavorite")) {
1106 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1109 if ($post->verb == "delete") {
1110 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1113 if ($post->verb != "update") {
1114 // Two queries for speed issues
1115 if (Item::exists(['uri' => $post->object->id, 'uid' => $uid])) {
1118 if (Item::exists(['extid' => $post->object->id, 'uid' => $uid])) {
1123 // Only handle these three types
1124 if (!strstr("post|share|update", $post->verb)) {
1129 if (@is_array($post->cc)) {
1130 $receiptians = array_merge($receiptians, $post->cc);
1133 if (@is_array($post->to)) {
1134 $receiptians = array_merge($receiptians, $post->to);
1139 foreach ($receiptians AS $receiver) {
1140 if (is_string($receiver->objectType) && ($receiver->id == "http://activityschema.org/collection/public")) {
1146 $postarray['network'] = Protocol::PUMPIO;
1147 $postarray['uid'] = $uid;
1148 $postarray['wall'] = 0;
1149 $postarray['uri'] = $post->object->id;
1150 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1152 if ($post->object->objectType != "comment") {
1153 $contact_id = pumpio_get_contact($uid, $post->actor);
1156 $contact_id = $self[0]['id'];
1159 $postarray['parent-uri'] = $post->object->id;
1162 $postarray['private'] = 1;
1163 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1166 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1168 if (Strings::compareLink($post->actor->url, $own_id)) {
1169 $contact_id = $self[0]['id'];
1170 $post->actor->displayName = $self[0]['name'];
1171 $post->actor->url = $self[0]['url'];
1172 $post->actor->image->url = $self[0]['photo'];
1173 } elseif ($contact_id == 0) {
1174 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1175 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1176 DBA::escape(Strings::normaliseLink($post->actor->url)),
1180 if (DBA::isResult($r)) {
1181 $contact_id = $r[0]['id'];
1183 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1184 DBA::escape(Strings::normaliseLink($post->actor->url)),
1188 if (DBA::isResult($r)) {
1189 $contact_id = $r[0]['id'];
1191 $contact_id = $self[0]['id'];
1196 $reply = new stdClass;
1197 $reply->verb = "note";
1199 if (isset($post->cc)) {
1200 $reply->cc = $post->cc;
1203 if (isset($post->to)) {
1204 $reply->to = $post->to;
1207 $reply->object = new stdClass;
1208 $reply->object->objectType = $post->object->inReplyTo->objectType;
1209 $reply->object->content = $post->object->inReplyTo->content;
1210 $reply->object->id = $post->object->inReplyTo->id;
1211 $reply->actor = $post->object->inReplyTo->author;
1212 $reply->url = $post->object->inReplyTo->url;
1213 $reply->generator = new stdClass;
1214 $reply->generator->displayName = "pumpio";
1215 $reply->published = $post->object->inReplyTo->published;
1216 $reply->received = $post->object->inReplyTo->updated;
1217 $reply->url = $post->object->inReplyTo->url;
1218 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1220 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1223 // When there is no content there is no need to continue
1224 if (empty($post->object->content)) {
1228 if (!empty($post->object->pump_io->proxyURL)) {
1229 $postarray['extid'] = $post->object->pump_io->proxyURL;
1232 $postarray['contact-id'] = $contact_id;
1233 $postarray['verb'] = ACTIVITY_POST;
1234 $postarray['owner-name'] = $post->actor->displayName;
1235 $postarray['owner-link'] = $post->actor->url;
1236 $postarray['author-name'] = $postarray['owner-name'];
1237 $postarray['author-link'] = $postarray['owner-link'];
1238 if (!empty($post->actor->image)) {
1239 $postarray['owner-avatar'] = $post->actor->image->url;
1240 $postarray['author-avatar'] = $postarray['owner-avatar'];
1242 $postarray['plink'] = $post->object->url;
1243 $postarray['app'] = $post->generator->displayName;
1244 $postarray['title'] = '';
1245 $postarray['body'] = HTML::toBBCode($post->object->content);
1246 $postarray['object'] = json_encode($post);
1248 if (!empty($post->object->fullImage->url)) {
1249 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1252 if (!empty($post->object->displayName)) {
1253 $postarray['title'] = $post->object->displayName;
1256 $postarray['created'] = DateTimeFormat::utc($post->published);
1257 if (isset($post->updated)) {
1258 $postarray['edited'] = DateTimeFormat::utc($post->updated);
1259 } elseif (isset($post->received)) {
1260 $postarray['edited'] = DateTimeFormat::utc($post->received);
1262 $postarray['edited'] = $postarray['created'];
1265 if ($post->verb == "share") {
1266 if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) {
1267 $share_author = $post->object->author->displayName;
1268 } elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) {
1269 $share_author = $post->object->author->preferredUsername;
1271 $share_author = $post->object->author->url;
1274 if (isset($post->object->created)) {
1275 $created = DateTimeFormat::utc($post->object->created);
1280 $postarray['body'] = share_header($share_author, $post->object->author->url,
1281 $post->object->author->image->url, "",
1282 $created, $post->links->self->href).
1283 $postarray['body']."[/share]";
1286 if (trim($postarray['body']) == "") {
1290 $top_item = Item::insert($postarray);
1291 $postarray["id"] = $top_item;
1293 if (($top_item == 0) && ($post->verb == "update")) {
1294 $fields = ['title' => $postarray["title"], 'body' => $postarray["body"], 'changed' => $postarray["edited"]];
1295 $condition = ['uri' => $postarray["uri"], 'uid' => $uid];
1296 Item::update($fields, $condition);
1299 if (($post->object->objectType == "comment") && $threadcompletion) {
1300 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1306 function pumpio_fetchinbox(App $a, $uid)
1308 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1309 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1310 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1311 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1312 $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1313 $hostname = PConfig::get($uid, 'pumpio', 'host');
1314 $username = PConfig::get($uid, "pumpio", "user");
1316 $own_id = "https://".$hostname."/".$username;
1318 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1321 $lastitems = q("SELECT `uri` FROM `thread`
1322 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1323 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1324 ORDER BY `thread`.`commented` DESC LIMIT 10",
1325 DBA::escape(Protocol::PUMPIO),
1329 $client = new oauth_client_class;
1330 $client->oauth_version = '1.0a';
1331 $client->authorization_header = true;
1332 $client->url_parameters = false;
1334 $client->client_id = $ckey;
1335 $client->client_secret = $csecret;
1336 $client->access_token = $otoken;
1337 $client->access_token_secret = $osecret;
1339 $last_id = PConfig::get($uid, 'pumpio', 'last_id');
1341 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1343 if ($last_id != "") {
1344 $url .= '?since='.urlencode($last_id);
1347 if (pumpio_reachable($url)) {
1348 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
1358 $posts = array_reverse($user->items);
1360 if (count($posts)) {
1361 foreach ($posts as $post) {
1362 $last_id = $post->id;
1363 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1368 foreach ($lastitems as $item) {
1369 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1372 PConfig::set($uid, 'pumpio', 'last_id', $last_id);
1375 function pumpio_getallusers(App &$a, $uid)
1377 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1378 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1379 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1380 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1381 $hostname = PConfig::get($uid, 'pumpio', 'host');
1382 $username = PConfig::get($uid, "pumpio", "user");
1384 $client = new oauth_client_class;
1385 $client->oauth_version = '1.0a';
1386 $client->authorization_header = true;
1387 $client->url_parameters = false;
1389 $client->client_id = $ckey;
1390 $client->client_secret = $csecret;
1391 $client->access_token = $otoken;
1392 $client->access_token_secret = $osecret;
1394 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1396 if (pumpio_reachable($url)) {
1397 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1402 if (empty($users)) {
1406 if ($users->totalItems > count($users->items)) {
1407 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1409 if (pumpio_reachable($url)) {
1410 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError' => true], $users);
1416 if (!empty($users->items)) {
1417 foreach ($users->items as $user) {
1418 pumpio_get_contact($uid, $user);
1423 function pumpio_queue_hook(App $a, array &$b)
1425 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1426 DBA::escape(Protocol::PUMPIO)
1429 if (!DBA::isResult($qi)) {
1433 foreach ($qi as $x) {
1434 if ($x['network'] !== Protocol::PUMPIO) {
1438 Logger::log('pumpio_queue: run');
1440 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1441 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1444 if (!DBA::isResult($r)) {
1450 //Logger::log('pumpio_queue: fetching userdata '.print_r($userdata, true));
1452 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1453 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1454 $consumer_key = PConfig::get($userdata['uid'], "pumpio", "consumer_key");
1455 $consumer_secret = PConfig::get($userdata['uid'], "pumpio", "consumer_secret");
1457 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1458 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1462 if ($oauth_token && $oauth_token_secret &&
1463 $consumer_key && $consumer_secret) {
1464 $username = $user.'@'.$host;
1466 Logger::log('pumpio_queue: able to post for user '.$username);
1468 $z = unserialize($x['content']);
1470 $client = new oauth_client_class;
1471 $client->oauth_version = '1.0a';
1472 $client->url_parameters = false;
1473 $client->authorization_header = true;
1474 $client->access_token = $oauth_token;
1475 $client->access_token_secret = $oauth_token_secret;
1476 $client->client_id = $consumer_key;
1477 $client->client_secret = $consumer_secret;
1479 if (pumpio_reachable($z['url'])) {
1480 $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
1486 $post_id = $user->object->id;
1487 Logger::log('pumpio_queue: send '.$username.': success '.$post_id);
1488 if ($post_id && $iscomment) {
1489 Logger::log('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1490 Item::update(['extid' => $post_id], ['id' => $z['item']]);
1492 Queue::removeItem($x['id']);
1494 Logger::log('pumpio_queue: send '.$username.': '.$z['url'].' general error: ' . print_r($user, true));
1497 Logger::log("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1501 Logger::log('pumpio_queue: delayed');
1502 Queue::updateTime($x['id']);
1507 function pumpio_getreceiver(App $a, array $b)
1511 if (!$b["private"]) {
1512 if (!strstr($b['postopts'], 'pumpio')) {
1516 $public = PConfig::get($b['uid'], "pumpio", "public");
1519 $receiver["to"][] = [
1520 "objectType" => "collection",
1521 "id" => "http://activityschema.org/collection/public"];
1524 $cids = explode("><", $b["allow_cid"]);
1525 $gids = explode("><", $b["allow_gid"]);
1527 foreach ($cids AS $cid) {
1528 $cid = trim($cid, " <>");
1530 $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",
1533 DBA::escape(Protocol::PUMPIO)
1536 if (DBA::isResult($r)) {
1537 $receiver["bcc"][] = [
1538 "displayName" => $r[0]["name"],
1539 "objectType" => "person",
1540 "preferredUsername" => $r[0]["nick"],
1541 "url" => $r[0]["url"]];
1544 foreach ($gids AS $gid) {
1545 $gid = trim($gid, " <>");
1547 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1548 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ".
1549 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1551 DBA::escape(Protocol::PUMPIO)
1554 foreach ($r AS $row)
1555 $receiver["bcc"][] = [
1556 "displayName" => $row["name"],
1557 "objectType" => "person",
1558 "preferredUsername" => $row["nick"],
1559 "url" => $row["url"]];
1563 if ($b["inform"] != "") {
1564 $inform = explode(",", $b["inform"]);
1566 foreach ($inform AS $cid) {
1567 if (substr($cid, 0, 4) != "cid:") {
1571 $cid = str_replace("cid:", "", $cid);
1573 $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",
1576 DBA::escape(Protocol::PUMPIO)
1579 if (DBA::isResult($r)) {
1580 $receiver["to"][] = [
1581 "displayName" => $r[0]["name"],
1582 "objectType" => "person",
1583 "preferredUsername" => $r[0]["nick"],
1584 "url" => $r[0]["url"]];
1592 function pumpio_fetchallcomments(App $a, $uid, $id)
1594 $ckey = PConfig::get($uid, 'pumpio', 'consumer_key');
1595 $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1596 $otoken = PConfig::get($uid, 'pumpio', 'oauth_token');
1597 $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1598 $hostname = PConfig::get($uid, 'pumpio', 'host');
1599 $username = PConfig::get($uid, "pumpio", "user");
1601 Logger::log("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1603 $own_id = "https://".$hostname."/".$username;
1605 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1608 // Fetching the original post
1609 $condition = ["`uri` = ? AND `uid` = ? AND `extid` != ''", $id, $uid];
1610 $item = Item::selectFirst(['extid'], $condition);
1611 if (!DBA::isResult($item)) {
1615 $url = $item["extid"];
1617 $client = new oauth_client_class;
1618 $client->oauth_version = '1.0a';
1619 $client->authorization_header = true;
1620 $client->url_parameters = false;
1622 $client->client_id = $ckey;
1623 $client->client_secret = $csecret;
1624 $client->access_token = $otoken;
1625 $client->access_token_secret = $osecret;
1627 Logger::log("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1629 if (pumpio_reachable($url)) {
1630 $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
1639 if ($item->likes->totalItems != 0) {
1640 foreach ($item->likes->items AS $post) {
1641 $like = new stdClass;
1642 $like->object = new stdClass;
1643 $like->object->id = $item->id;
1644 $like->actor = new stdClass;
1645 if (!empty($item->displayName)) {
1646 $like->actor->displayName = $item->displayName;
1648 //$like->actor->preferredUsername = $item->preferredUsername;
1649 //$like->actor->image = $item->image;
1650 $like->actor->url = $item->url;
1651 $like->generator = new stdClass;
1652 $like->generator->displayName = "pumpio";
1653 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1657 if ($item->replies->totalItems == 0) {
1661 foreach ($item->replies->items AS $item) {
1662 if ($item->id == $id) {
1666 // Checking if the comment already exists - Two queries for speed issues
1667 if (Item::exists(['uri' => $item->id, 'uid' => $uid])) {
1671 if (Item::exists(['extid' => $item->id, 'uid' => $uid])) {
1675 $post = new stdClass;
1676 $post->verb = "post";
1677 $post->actor = $item->author;
1678 $post->published = $item->published;
1679 $post->received = $item->updated;
1680 $post->generator = new stdClass;
1681 $post->generator->displayName = "pumpio";
1682 // To-Do: Check for public post
1684 unset($item->author);
1685 unset($item->published);
1686 unset($item->updated);
1688 $post->object = $item;
1690 Logger::log("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1691 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1695 function pumpio_reachable($url)
1697 return Network::curl($url, false, $redirects, ['timeout'=>10])->isSuccess();