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>
9 use Friendica\Core\Worker;
11 require('addon/pumpio/oauth/http.php');
12 require('addon/pumpio/oauth/oauth_client.php');
13 require_once('include/enotify.php');
14 require_once('include/socgraph.php');
15 require_once("include/Photo.php");
16 require_once("mod/share.php");
18 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
20 function pumpio_install() {
21 register_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
22 register_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
23 register_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
24 register_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
25 register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
26 register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
27 register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
28 register_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
31 function pumpio_uninstall() {
32 unregister_hook('post_local', 'addon/pumpio/pumpio.php', 'pumpio_post_local');
33 unregister_hook('notifier_normal', 'addon/pumpio/pumpio.php', 'pumpio_send');
34 unregister_hook('jot_networks', 'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
35 unregister_hook('connector_settings', 'addon/pumpio/pumpio.php', 'pumpio_settings');
36 unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
37 unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
38 unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
39 unregister_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
42 function pumpio_module() {}
44 function pumpio_content(&$a) {
47 notice( t('Permission denied.') . EOL);
51 require_once("mod/settings.php");
54 if (isset($a->argv[1]))
55 switch ($a->argv[1]) {
57 $o = pumpio_connect($a);
60 $o = print_r($a->argv, true);
64 $o = pumpio_connect($a);
69 function pumpio_check_item_notification($a, &$notification_data) {
70 $hostname = get_pconfig($notification_data["uid"], 'pumpio','host');
71 $username = get_pconfig($notification_data["uid"], "pumpio", "user");
73 $notification_data["profiles"][] = "https://".$hostname."/".$username;
77 function pumpio_registerclient(&$a, $host) {
79 $url = "https://".$host."/api/client/register";
83 $application_name = get_config('pumpio', 'application_name');
85 if ($application_name == "")
86 $application_name = $a->get_hostname();
88 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
90 $params["type"] = "client_associate";
91 $params["contacts"] = $adminlist[0];
92 $params["application_type"] = "native";
93 $params["application_name"] = $application_name;
94 $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
95 $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
97 logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
99 $ch = curl_init($url);
100 curl_setopt($ch, CURLOPT_HEADER, false);
101 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
102 curl_setopt($ch, CURLOPT_POST,1);
103 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
104 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
107 $curl_info = curl_getinfo($ch);
109 if ($curl_info["http_code"] == "200") {
110 $values = json_decode($s);
111 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
114 logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
119 function pumpio_connect(&$a) {
120 // Start a session. This is necessary to hold on to a few keys the callback script will also need
123 // Define the needed keys
124 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
125 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
126 $hostname = get_pconfig(local_user(), 'pumpio','host');
128 if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
129 logger("pumpio_connect: register client");
130 $clientdata = pumpio_registerclient($a, $hostname);
131 set_pconfig(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
132 set_pconfig(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
134 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
135 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
137 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
140 if (($consumer_key == "") || ($consumer_secret == "")) {
141 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
143 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
147 // The callback URL is the script that gets called after the user authenticates with pumpio
148 $callback_url = $a->get_baseurl()."/pumpio/connect";
150 // Let's begin. First we need a Request Token. The request token is required to send the user
151 // to pumpio's login page.
153 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
154 // Consumer Key and Consumer Secret
155 $client = new oauth_client_class;
157 $client->server = '';
158 $client->oauth_version = '1.0a';
159 $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
160 $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
161 $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
162 $client->url_parameters = false;
163 $client->authorization_header = true;
164 $client->redirect_uri = $callback_url;
165 $client->client_id = $consumer_key;
166 $client->client_secret = $consumer_secret;
168 if (($success = $client->Initialize())) {
169 if (($success = $client->Process())) {
170 if (strlen($client->access_token)) {
171 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
172 set_pconfig(local_user(), "pumpio", "oauth_token", $client->access_token);
173 set_pconfig(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
176 $success = $client->Finalize($success);
179 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
182 logger("pumpio_connect: authenticated");
183 $o .= t("You are now authenticated to pumpio.");
184 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
186 logger("pumpio_connect: could not connect");
187 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
193 function pumpio_jot_nets(&$a,&$b) {
197 $pumpio_post = get_pconfig(local_user(),'pumpio','post');
198 if(intval($pumpio_post) == 1) {
199 $pumpio_defpost = get_pconfig(local_user(),'pumpio','post_by_default');
200 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
201 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
202 . t('Post to pumpio') . '</div>';
207 function pumpio_settings(&$a,&$s) {
212 /* Add our stylesheet to the page so we can make our settings look nice */
214 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
216 /* Get the current state of our config variables */
218 $import_enabled = get_pconfig(local_user(),'pumpio','import');
219 $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
221 $enabled = get_pconfig(local_user(),'pumpio','post');
222 $checked = (($enabled) ? ' checked="checked" ' : '');
223 $css = (($enabled) ? '' : '-disabled');
225 $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default');
226 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
228 $public_enabled = get_pconfig(local_user(),'pumpio','public');
229 $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
231 $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror');
232 $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
234 $servername = get_pconfig(local_user(), "pumpio", "host");
235 $username = get_pconfig(local_user(), "pumpio", "user");
237 /* Add some HTML to the existing form */
239 $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
240 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
242 $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
243 $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
244 $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
247 $s .= '<div id="pumpio-username-wrapper">';
248 $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
249 $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
250 $s .= '</div><div class="clear"></div>';
252 $s .= '<div id="pumpio-servername-wrapper">';
253 $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
254 $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
255 $s .= '</div><div class="clear"></div>';
257 if (($username != '') && ($servername != '')) {
259 $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token");
260 $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret");
262 $s .= '<div id="pumpio-password-wrapper">';
263 if (($oauth_token == "") || ($oauth_token_secret == "")) {
264 $s .= '<div id="pumpio-authenticate-wrapper">';
265 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
266 $s .= '</div><div class="clear"></div>';
268 $s .= '<div id="pumpio-import-wrapper">';
269 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
270 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
271 $s .= '</div><div class="clear"></div>';
273 $s .= '<div id="pumpio-enable-wrapper">';
274 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
275 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
276 $s .= '</div><div class="clear"></div>';
278 $s .= '<div id="pumpio-bydefault-wrapper">';
279 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
280 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
281 $s .= '</div><div class="clear"></div>';
283 $s .= '<div id="pumpio-public-wrapper">';
284 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
285 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
286 $s .= '</div><div class="clear"></div>';
288 $s .= '<div id="pumpio-mirror-wrapper">';
289 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
290 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
291 $s .= '</div><div class="clear"></div>';
293 $s .= '<div id="pumpio-delete-wrapper">';
294 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
295 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
296 $s .= '</div><div class="clear"></div>';
299 $s .= '</div><div class="clear"></div>';
302 /* provide a submit button */
304 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
308 function pumpio_settings_post(&$a,&$b) {
310 if(x($_POST,'pumpio-submit')) {
311 if(x($_POST,'pumpio_delete')) {
312 set_pconfig(local_user(),'pumpio','consumer_key','');
313 set_pconfig(local_user(),'pumpio','consumer_secret','');
314 set_pconfig(local_user(),'pumpio','oauth_token','');
315 set_pconfig(local_user(),'pumpio','oauth_token_secret','');
316 set_pconfig(local_user(),'pumpio','post',false);
317 set_pconfig(local_user(),'pumpio','import',false);
318 set_pconfig(local_user(),'pumpio','host','');
319 set_pconfig(local_user(),'pumpio','user','');
320 set_pconfig(local_user(),'pumpio','public',false);
321 set_pconfig(local_user(),'pumpio','mirror',false);
322 set_pconfig(local_user(),'pumpio','post_by_default',false);
323 set_pconfig(local_user(),'pumpio','lastdate', 0);
324 set_pconfig(local_user(),'pumpio','last_id', '');
326 // filtering the username if it is filled wrong
327 $user = $_POST['pumpio_user'];
328 if (strstr($user, "@")) {
329 $pos = strpos($user, "@");
331 $user = substr($user, 0, $pos);
334 // Filtering the hostname if someone is entering it with "http"
335 $host = $_POST['pumpio_host'];
337 $host = str_replace(array("https://", "http://"), array("", ""), $host);
339 set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
340 set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
341 set_pconfig(local_user(),'pumpio','host',$host);
342 set_pconfig(local_user(),'pumpio','user',$user);
343 set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
344 set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
345 set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
347 if (!$_POST['pumpio_mirror'])
348 del_pconfig(local_user(),'pumpio','lastdate');
350 //header("Location: ".$a->get_baseurl()."/pumpio/connect");
355 function pumpio_post_local(&$a, &$b) {
357 if (!local_user() || (local_user() != $b['uid'])) {
361 $pumpio_post = intval(get_pconfig(local_user(), 'pumpio', 'post'));
363 $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
365 if ($b['api_source'] && intval(get_pconfig(local_user(), 'pumpio', 'post_by_default'))) {
369 if (!$pumpio_enable) {
373 if (strlen($b['postopts'])) {
374 $b['postopts'] .= ',';
377 $b['postopts'] .= 'pumpio';
383 function pumpio_send(&$a,&$b) {
385 if (!get_pconfig($b["uid"],'pumpio','import')) {
386 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
390 logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
392 if($b['parent'] != $b['id']) {
393 // Looking if its a reply to a pumpio post
394 $r = q("SELECT item.* FROM item, contact WHERE item.id = %d AND item.uid = %d AND contact.id = `contact-id` AND contact.network='%s'LIMIT 1",
395 intval($b["parent"]),
397 dbesc(NETWORK_PUMPIO));
400 logger("pumpio_send: no pumpio post ".$b["parent"]);
409 $receiver = pumpio_getreceiver($a, $b);
411 logger("pumpio_send: receiver ".print_r($receiver, true));
413 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio')))
417 if($b['verb'] == ACTIVITY_LIKE) {
419 pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
421 pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
425 if($b['verb'] == ACTIVITY_DISLIKE)
428 if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
429 pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
431 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
432 pumpio_action($a, $b["uid"], $b["uri"], "delete");
434 if($b['deleted'] || ($b['created'] !== $b['edited']))
437 // if post comes from pump.io don't send it back
438 if($b['app'] == "pump.io")
442 // Support for native shares
443 // http://<hostname>/api/<type>/shares?id=<the-object-id>
445 $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
446 $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
447 $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
448 $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
450 $host = get_pconfig($b['uid'], "pumpio", "host");
451 $user = get_pconfig($b['uid'], "pumpio", "user");
452 $public = get_pconfig($b['uid'], "pumpio", "public");
454 if($oauth_token && $oauth_token_secret) {
456 require_once('include/bbcode.php');
458 $title = trim($b['title']);
460 $content = bbcode($b['body'], false, false, 4);
464 $params["verb"] = "post";
467 $params["object"] = array(
468 'objectType' => "note",
469 'content' => $content);
472 $params["object"]["displayName"] = $title;
474 if (count($receiver["to"]))
475 $params["to"] = $receiver["to"];
477 if (count($receiver["bto"]))
478 $params["bto"] = $receiver["bto"];
480 if (count($receiver["cc"]))
481 $params["cc"] = $receiver["cc"];
483 if (count($receiver["bcc"]))
484 $params["bcc"] = $receiver["bcc"];
487 $inReplyTo = array("id" => $orig_post["uri"],
488 "objectType" => "note");
490 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
491 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
493 $params["object"] = array(
494 'objectType' => "comment",
495 'content' => $content,
496 'inReplyTo' => $inReplyTo);
499 $params["object"]["displayName"] = $title;
502 $client = new oauth_client_class;
503 $client->oauth_version = '1.0a';
504 $client->url_parameters = false;
505 $client->authorization_header = true;
506 $client->access_token = $oauth_token;
507 $client->access_token_secret = $oauth_token_secret;
508 $client->client_id = $consumer_key;
509 $client->client_secret = $consumer_secret;
511 $username = $user.'@'.$host;
512 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
514 if (pumpio_reachable($url))
515 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
521 if ($user->generator->displayName)
522 set_pconfig($b["uid"], "pumpio", "application_name", $user->generator->displayName);
524 $post_id = $user->object->id;
525 logger('pumpio_send '.$username.': success '.$post_id);
526 if($post_id && $iscomment) {
527 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
528 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
534 logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
536 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
538 $a->contact = $r[0]["id"];
540 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
541 require_once('include/queue_fn.php');
542 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
543 notice(t('Pump.io post failed. Queued for retry.').EOL);
549 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
551 // Don't do likes and other stuff if you don't import the timeline
552 if (!get_pconfig($uid,'pumpio','import'))
555 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
556 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
557 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
558 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
559 $hostname = get_pconfig($uid, 'pumpio','host');
560 $username = get_pconfig($uid, "pumpio", "user");
562 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
572 if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
573 $uri = $orig_post["extid"];
575 $uri = $orig_post["uri"];
577 if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
578 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
579 elseif (strstr($uri, "/api/comment/"))
580 $objectType = "comment";
581 elseif (strstr($uri, "/api/note/"))
582 $objectType = "note";
583 elseif (strstr($uri, "/api/image/"))
584 $objectType = "image";
586 $params["verb"] = $action;
587 $params["object"] = array('id' => $uri,
588 "objectType" => $objectType,
589 "content" => $content);
591 $client = new oauth_client_class;
592 $client->oauth_version = '1.0a';
593 $client->authorization_header = true;
594 $client->url_parameters = false;
596 $client->client_id = $ckey;
597 $client->client_secret = $csecret;
598 $client->access_token = $otoken;
599 $client->access_token_secret = $osecret;
601 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
603 if (pumpio_reachable($url))
604 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
609 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
611 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
613 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
615 $a->contact = $r[0]["id"];
617 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
618 require_once('include/queue_fn.php');
619 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
620 notice(t('Pump.io like failed. Queued for retry.').EOL);
624 function pumpio_sync(&$a) {
625 $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
631 $last = get_config('pumpio','last_poll');
633 $poll_interval = intval(get_config('pumpio','poll_interval'));
635 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
638 $next = $last + ($poll_interval * 60);
640 logger('pumpio: poll intervall not reached');
644 logger('pumpio: cron_start');
646 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
649 logger('pumpio: mirroring user '.$rr['uid']);
650 pumpio_fetchtimeline($a, $rr['uid']);
654 $abandon_days = intval(get_config('system','account_abandon_days'));
655 if ($abandon_days < 1)
658 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
660 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
663 if ($abandon_days != 0) {
664 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
666 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
671 logger('pumpio: importing timeline from user '.$rr['uid']);
672 pumpio_fetchinbox($a, $rr['uid']);
674 // check for new contacts once a day
675 $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check');
676 if($last_contact_check)
677 $next_contact_check = $last_contact_check + 86400;
679 $next_contact_check = 0;
681 if($next_contact_check <= time()) {
682 pumpio_getallusers($a, $rr["uid"]);
683 set_pconfig($rr['uid'],'pumpio','contact_check',time());
688 logger('pumpio: cron_end');
690 set_config('pumpio','last_poll', time());
693 function pumpio_cron(&$a,$b) {
694 Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
697 function pumpio_fetchtimeline(&$a, $uid) {
698 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
699 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
700 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
701 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
702 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
703 $hostname = get_pconfig($uid, 'pumpio','host');
704 $username = get_pconfig($uid, "pumpio", "user");
706 // get the application name for the pump.io app
707 // 1st try personal config, then system config and fallback to the
708 // hostname of the node if neither one is set.
709 $application_name = get_pconfig( $uid, 'pumpio', 'application_name');
710 if ($application_name == "")
711 $application_name = get_config('pumpio', 'application_name');
712 if ($application_name == "")
713 $application_name = $a->get_hostname();
715 $first_time = ($lastdate == "");
717 $client = new oauth_client_class;
718 $client->oauth_version = '1.0a';
719 $client->authorization_header = true;
720 $client->url_parameters = false;
722 $client->client_id = $ckey;
723 $client->client_secret = $csecret;
724 $client->access_token = $otoken;
725 $client->access_token_secret = $osecret;
727 $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
729 logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
731 $username = $user.'@'.$host;
733 if (pumpio_reachable($url))
734 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
739 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
743 $posts = array_reverse($user->items);
745 $initiallastdate = $lastdate;
749 foreach ($posts as $post) {
750 if ($post->published <= $initiallastdate)
753 if ($lastdate < $post->published)
754 $lastdate = $post->published;
759 $receiptians = array();
760 if (@is_array($post->cc))
761 $receiptians = array_merge($receiptians, $post->cc);
763 if (@is_array($post->to))
764 $receiptians = array_merge($receiptians, $post->to);
767 foreach ($receiptians AS $receiver)
768 if (is_string($receiver->objectType))
769 if ($receiver->id == "http://activityschema.org/collection/public")
772 if ($public && !stristr($post->generator->displayName, $application_name)) {
773 require_once('include/html2bbcode.php');
775 $_SESSION["authenticated"] = true;
776 $_SESSION["uid"] = $uid;
779 $_REQUEST["type"] = "wall";
780 $_REQUEST["api_source"] = true;
781 $_REQUEST["profile_uid"] = $uid;
782 $_REQUEST["source"] = "pump.io";
784 if (isset($post->object->id)) {
785 $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
788 if ($post->object->displayName != "")
789 $_REQUEST["title"] = html2bbcode($post->object->displayName);
791 $_REQUEST["title"] = "";
793 $_REQUEST["body"] = html2bbcode($post->object->content);
795 // To-Do: Picture has to be cached and stored locally
796 if ($post->object->fullImage->url != "") {
797 if ($post->object->fullImage->pump_io->proxyURL != "")
798 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
800 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
803 logger('pumpio: posting for user '.$uid);
805 require_once('mod/item.php');
808 logger('pumpio: posting done - user '.$uid);
814 set_pconfig($uid,'pumpio','lastdate', $lastdate);
817 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
818 // Searching for the unliked post
819 // Two queries for speed issues
820 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
821 dbesc($post->object->id),
828 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
829 dbesc($post->object->id),
841 if(link_compare($post->actor->url, $own_id)) {
842 $contactid = $self[0]['id'];
844 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
845 dbesc(normalise_link($post->actor->url)),
850 $contactid = $r[0]['id'];
853 $contactid = $orig_post['contact-id'];
856 $r = q("UPDATE `item` SET `deleted` = 1, `unseen` = 1, `changed` = '%s' WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s'",
857 dbesc(datetime_convert()),
858 dbesc(ACTIVITY_LIKE),
861 dbesc($orig_post['uri'])
865 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
867 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
870 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
871 require_once('include/items.php');
873 if ($post->object->id == "") {
874 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
878 // Searching for the liked post
879 // Two queries for speed issues
880 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
881 dbesc($post->object->id),
883 dbesc(NETWORK_PUMPIO)
889 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
890 dbesc($post->object->id),
892 dbesc(NETWORK_PUMPIO)
902 if ($threadcompletion)
903 pumpio_fetchallcomments($a, $uid, $post->object->id);
907 if(link_compare($post->actor->url, $own_id)) {
908 $contactid = $self[0]['id'];
909 $post->actor->displayName = $self[0]['name'];
910 $post->actor->url = $self[0]['url'];
911 $post->actor->image->url = $self[0]['photo'];
913 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
914 dbesc(normalise_link($post->actor->url)),
919 $contactid = $r[0]['id'];
922 $contactid = $orig_post['contact-id'];
925 $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
926 dbesc(ACTIVITY_LIKE),
929 dbesc($orig_post['uri'])
933 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
938 $likedata['parent'] = $orig_post['id'];
939 $likedata['verb'] = ACTIVITY_LIKE;
940 $likedata['gravity'] = 3;
941 $likedata['uid'] = $uid;
942 $likedata['wall'] = 0;
943 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
944 $likedata['parent-uri'] = $orig_post["uri"];
945 $likedata['contact-id'] = $contactid;
946 $likedata['app'] = $post->generator->displayName;
947 $likedata['author-name'] = $post->actor->displayName;
948 $likedata['author-link'] = $post->actor->url;
949 $likedata['author-avatar'] = $post->actor->image->url;
951 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
952 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
953 $post_type = t('status');
954 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
955 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
957 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
959 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
960 '<id>' . $orig_post['uri'] . '</id><link>' . xmlify('<link rel="alternate" type="text/html" href="' . xmlify($orig_post['plink']) . '" />') . '</link><title>' . $orig_post['title'] . '</title><content>' . $orig_post['body'] . '</content></object>';
962 $ret = item_store($likedata);
964 logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
967 function pumpio_get_contact($uid, $contact, $no_insert = false) {
969 update_gcontact(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
970 "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
971 "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
972 "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
973 $cid = get_contact($contact->url, $uid);
978 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
979 intval($uid), dbesc(normalise_link($contact->url)));
982 // create contact record
983 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
984 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
985 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
986 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
988 dbesc(datetime_convert()),
989 dbesc($contact->url),
990 dbesc(normalise_link($contact->url)),
991 dbesc(str_replace("acct:", "", $contact->id)),
993 dbesc($contact->id), // What is it for?
994 dbesc('pump.io ' . $contact->id), // What is it for?
995 dbesc($contact->displayName),
996 dbesc($contact->preferredUsername),
997 dbesc($contact->image->url),
998 dbesc(NETWORK_PUMPIO),
999 intval(CONTACT_IS_FRIEND),
1001 dbesc($contact->location->displayName),
1002 dbesc($contact->summary),
1006 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1007 dbesc(normalise_link($contact->url)),
1015 $contact_id = $r[0]['id'];
1017 $g = q("select def_gid from user where uid = %d limit 1",
1021 if($g && intval($g[0]['def_gid'])) {
1022 require_once('include/group.php');
1023 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1026 $contact_id = $r[0]["id"];
1028 /* if (DB_UPDATE_VERSION >= "1177")
1029 q("UPDATE `contact` SET `location` = '%s',
1032 dbesc($contact->location->displayName),
1033 dbesc($contact->summary),
1039 if (function_exists("update_contact_avatar"))
1040 update_contact_avatar($contact->image->url, $uid, $contact_id);
1042 return($contact_id);
1045 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1047 // Two queries for speed issues
1048 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1049 dbesc($post->object->id),
1054 return drop_item($r[0]["id"], $false);
1056 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1057 dbesc($post->object->id),
1062 return drop_item($r[0]["id"], $false);
1065 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1066 require_once('include/items.php');
1067 require_once('include/html2bbcode.php');
1069 if (($post->verb == "like") || ($post->verb == "favorite"))
1070 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1072 if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1073 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1075 if ($post->verb == "delete")
1076 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1078 if ($post->verb != "update") {
1079 // Two queries for speed issues
1080 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1081 dbesc($post->object->id),
1088 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1089 dbesc($post->object->id),
1097 // Only handle these three types
1098 if (!strstr("post|share|update", $post->verb))
1101 $receiptians = array();
1102 if (@is_array($post->cc))
1103 $receiptians = array_merge($receiptians, $post->cc);
1105 if (@is_array($post->to))
1106 $receiptians = array_merge($receiptians, $post->to);
1108 foreach ($receiptians AS $receiver)
1109 if (is_string($receiver->objectType))
1110 if ($receiver->id == "http://activityschema.org/collection/public")
1113 $postarray = array();
1114 $postarray['network'] = NETWORK_PUMPIO;
1115 $postarray['gravity'] = 0;
1116 $postarray['uid'] = $uid;
1117 $postarray['wall'] = 0;
1118 $postarray['uri'] = $post->object->id;
1119 $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1121 if ($post->object->objectType != "comment") {
1122 $contact_id = pumpio_get_contact($uid, $post->actor);
1125 $contact_id = $self[0]['id'];
1127 $postarray['parent-uri'] = $post->object->id;
1130 $postarray['private'] = 1;
1131 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1134 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1136 if (link_compare($post->actor->url, $own_id)) {
1137 $contact_id = $self[0]['id'];
1138 $post->actor->displayName = $self[0]['name'];
1139 $post->actor->url = $self[0]['url'];
1140 $post->actor->image->url = $self[0]['photo'];
1141 } elseif ($contact_id == 0) {
1142 // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1143 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1144 dbesc(normalise_link($post->actor->url)),
1149 $contact_id = $r[0]['id'];
1151 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1152 dbesc(normalise_link($post->actor->url)),
1157 $contact_id = $r[0]['id'];
1159 $contact_id = $self[0]['id'];
1163 $reply = new stdClass;
1164 $reply->verb = "note";
1165 $reply->cc = $post->cc;
1166 $reply->to = $post->to;
1167 $reply->object = new stdClass;
1168 $reply->object->objectType = $post->object->inReplyTo->objectType;
1169 $reply->object->content = $post->object->inReplyTo->content;
1170 $reply->object->id = $post->object->inReplyTo->id;
1171 $reply->actor = $post->object->inReplyTo->author;
1172 $reply->url = $post->object->inReplyTo->url;
1173 $reply->generator = new stdClass;
1174 $reply->generator->displayName = "pumpio";
1175 $reply->published = $post->object->inReplyTo->published;
1176 $reply->received = $post->object->inReplyTo->updated;
1177 $reply->url = $post->object->inReplyTo->url;
1178 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1180 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1183 if ($post->object->pump_io->proxyURL)
1184 $postarray['extid'] = $post->object->pump_io->proxyURL;
1186 $postarray['contact-id'] = $contact_id;
1187 $postarray['verb'] = ACTIVITY_POST;
1188 $postarray['owner-name'] = $post->actor->displayName;
1189 $postarray['owner-link'] = $post->actor->url;
1190 $postarray['owner-avatar'] = $post->actor->image->url;
1191 $postarray['author-name'] = $post->actor->displayName;
1192 $postarray['author-link'] = $post->actor->url;
1193 $postarray['author-avatar'] = $post->actor->image->url;
1194 $postarray['plink'] = $post->object->url;
1195 $postarray['app'] = $post->generator->displayName;
1196 $postarray['body'] = html2bbcode($post->object->content);
1197 $postarray['object'] = json_encode($post);
1199 if ($post->object->fullImage->url != "")
1200 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1202 if ($post->object->displayName != "")
1203 $postarray['title'] = $post->object->displayName;
1205 $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1206 if (isset($post->updated))
1207 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1208 elseif (isset($post->received))
1209 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1211 $postarray['edited'] = $postarray['created'];
1213 if ($post->verb == "share") {
1214 if (!intval(get_config('system','wall-to-wall_share'))) {
1215 if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1216 $share_author = $post->object->author->displayName;
1217 elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1218 $share_author = $post->object->author->preferredUsername;
1220 $share_author = $post->object->author->url;
1222 $postarray['body'] = share_header($share_author, $post->object->author->url,
1223 $post->object->author->image->url, "",
1224 datetime_convert('UTC','UTC',$post->object->created),
1225 $post->links->self->href).
1226 $postarray['body']."[/share]";
1229 $postarray['body'] = "[share author='".$share_author.
1230 "' profile='".$post->object->author->url.
1231 "' avatar='".$post->object->author->image->url.
1232 "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1233 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1236 // Let shares look like wall-to-wall posts
1237 $postarray['author-name'] = $post->object->author->displayName;
1238 $postarray['author-link'] = $post->object->author->url;
1239 $postarray['author-avatar'] = $post->object->author->image->url;
1243 if (trim($postarray['body']) == "")
1246 $top_item = item_store($postarray);
1247 $postarray["id"] = $top_item;
1249 if (($top_item == 0) && ($post->verb == "update")) {
1250 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1251 dbesc($postarray["title"]),
1252 dbesc($postarray["body"]),
1253 dbesc($postarray["edited"]),
1254 dbesc($postarray["uri"]),
1259 if ($post->object->objectType == "comment") {
1261 if ($threadcompletion)
1262 pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1264 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1271 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1273 if (link_compare($own_id, $postarray['author-link']))
1276 if (!function_exists("check_item_notification")) {
1277 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1278 dbesc($postarray['parent-uri']),
1282 if(count($myconv)) {
1284 foreach($myconv as $conv) {
1285 // now if we find a match, it means we're in this conversation
1287 if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1290 require_once('include/enotify.php');
1292 $conv_parent = $conv['parent'];
1295 'type' => NOTIFY_COMMENT,
1296 'notify_flags' => $user[0]['notify-flags'],
1297 'language' => $user[0]['language'],
1298 'to_name' => $user[0]['username'],
1299 'to_email' => $user[0]['email'],
1300 'uid' => $user[0]['uid'],
1301 'item' => $postarray,
1302 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1303 'source_name' => $postarray['author-name'],
1304 'source_link' => $postarray['author-link'],
1305 'source_photo' => $postarray['author-avatar'],
1306 'verb' => ACTIVITY_POST,
1308 'parent' => $conv_parent,
1311 // only send one notification
1321 function pumpio_fetchinbox(&$a, $uid) {
1323 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1324 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1325 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1326 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1327 $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1328 $hostname = get_pconfig($uid, 'pumpio','host');
1329 $username = get_pconfig($uid, "pumpio", "user");
1331 $own_id = "https://".$hostname."/".$username;
1333 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1336 $lastitems = q("SELECT `uri` FROM `thread`
1337 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1338 WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1339 ORDER BY `thread`.`commented` DESC LIMIT 10",
1340 dbesc(NETWORK_PUMPIO),
1344 $client = new oauth_client_class;
1345 $client->oauth_version = '1.0a';
1346 $client->authorization_header = true;
1347 $client->url_parameters = false;
1349 $client->client_id = $ckey;
1350 $client->client_secret = $csecret;
1351 $client->access_token = $otoken;
1352 $client->access_token_secret = $osecret;
1354 $last_id = get_pconfig($uid,'pumpio','last_id');
1356 $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1359 $url .= '?since='.urlencode($last_id);
1361 if (pumpio_reachable($url))
1362 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1367 $posts = array_reverse($user->items);
1370 foreach ($posts as $post) {
1371 $last_id = $post->id;
1372 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1376 foreach ($lastitems AS $item)
1377 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1379 set_pconfig($uid,'pumpio','last_id', $last_id);
1382 function pumpio_getallusers(&$a, $uid) {
1383 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1384 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1385 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1386 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1387 $hostname = get_pconfig($uid, 'pumpio','host');
1388 $username = get_pconfig($uid, "pumpio", "user");
1390 $client = new oauth_client_class;
1391 $client->oauth_version = '1.0a';
1392 $client->authorization_header = true;
1393 $client->url_parameters = false;
1395 $client->client_id = $ckey;
1396 $client->client_secret = $csecret;
1397 $client->access_token = $otoken;
1398 $client->access_token_secret = $osecret;
1400 $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1402 if (pumpio_reachable($url))
1403 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1407 if ($users->totalItems > count($users->items)) {
1408 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1410 if (pumpio_reachable($url))
1411 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1416 if (is_array($users->items)) {
1417 foreach ($users->items AS $user) {
1418 pumpio_get_contact($uid, $user);
1423 function pumpio_queue_hook(&$a,&$b) {
1425 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1426 dbesc(NETWORK_PUMPIO)
1431 require_once('include/queue_fn.php');
1433 foreach($qi as $x) {
1434 if($x['network'] !== NETWORK_PUMPIO)
1437 logger('pumpio_queue: run');
1439 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1440 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1448 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1450 $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token");
1451 $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret");
1452 $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key");
1453 $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret");
1455 $host = get_pconfig($userdata['uid'], "pumpio", "host");
1456 $user = get_pconfig($userdata['uid'], "pumpio", "user");
1460 if ($oauth_token && $oauth_token_secret &&
1461 $consumer_key && $consumer_secret) {
1462 $username = $user.'@'.$host;
1464 logger('pumpio_queue: able to post for user '.$username);
1466 $z = unserialize($x['content']);
1468 $client = new oauth_client_class;
1469 $client->oauth_version = '1.0a';
1470 $client->url_parameters = false;
1471 $client->authorization_header = true;
1472 $client->access_token = $oauth_token;
1473 $client->access_token_secret = $oauth_token_secret;
1474 $client->client_id = $consumer_key;
1475 $client->client_secret = $consumer_secret;
1477 if (pumpio_reachable($z['url']))
1478 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1483 $post_id = $user->object->id;
1484 logger('pumpio_queue: send '.$username.': success '.$post_id);
1485 if($post_id && $iscomment) {
1486 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1487 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1492 remove_queue_item($x['id']);
1494 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1496 logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1499 logger('pumpio_queue: delayed');
1500 update_queue_time($x['id']);
1505 function pumpio_getreceiver(&$a, $b) {
1507 $receiver = array();
1509 if (!$b["private"]) {
1511 if(! strstr($b['postopts'],'pumpio'))
1514 $public = get_pconfig($b['uid'], "pumpio", "public");
1517 $receiver["to"][] = Array(
1518 "objectType" => "collection",
1519 "id" => "http://activityschema.org/collection/public");
1521 $cids = explode("><", $b["allow_cid"]);
1522 $gids = explode("><", $b["allow_gid"]);
1524 foreach ($cids AS $cid) {
1525 $cid = trim($cid, " <>");
1527 $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",
1530 dbesc(NETWORK_PUMPIO)
1534 $receiver["bcc"][] = Array(
1535 "displayName" => $r[0]["name"],
1536 "objectType" => "person",
1537 "preferredUsername" => $r[0]["nick"],
1538 "url" => $r[0]["url"]);
1541 foreach ($gids AS $gid) {
1542 $gid = trim($gid, " <>");
1544 $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1545 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1546 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1549 dbesc(NETWORK_PUMPIO)
1552 foreach ($r AS $row)
1553 $receiver["bcc"][] = Array(
1554 "displayName" => $row["name"],
1555 "objectType" => "person",
1556 "preferredUsername" => $row["nick"],
1557 "url" => $row["url"]);
1561 if ($b["inform"] != "") {
1563 $inform = explode(",", $b["inform"]);
1565 foreach ($inform AS $cid) {
1566 if (substr($cid, 0, 4) != "cid:")
1569 $cid = str_replace("cid:", "", $cid);
1571 $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",
1574 dbesc(NETWORK_PUMPIO)
1578 $receiver["to"][] = Array(
1579 "displayName" => $r[0]["name"],
1580 "objectType" => "person",
1581 "preferredUsername" => $r[0]["nick"],
1582 "url" => $r[0]["url"]);
1590 function pumpio_fetchallcomments(&$a, $uid, $id) {
1591 $ckey = get_pconfig($uid, 'pumpio', 'consumer_key');
1592 $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1593 $otoken = get_pconfig($uid, 'pumpio', 'oauth_token');
1594 $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1595 $hostname = get_pconfig($uid, 'pumpio','host');
1596 $username = get_pconfig($uid, "pumpio", "user");
1598 logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1600 $own_id = "https://".$hostname."/".$username;
1602 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1605 // Fetching the original post
1606 $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1614 $url = $r[0]["extid"];
1616 $client = new oauth_client_class;
1617 $client->oauth_version = '1.0a';
1618 $client->authorization_header = true;
1619 $client->url_parameters = false;
1621 $client->client_id = $ckey;
1622 $client->client_secret = $csecret;
1623 $client->access_token = $otoken;
1624 $client->access_token_secret = $osecret;
1626 logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1628 if (pumpio_reachable($url))
1629 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1636 if ($item->likes->totalItems != 0) {
1637 foreach ($item->likes->items AS $post) {
1638 $like = new stdClass;
1639 $like->object = new stdClass;
1640 $like->object->id = $item->id;
1641 $like->actor = new stdClass;
1642 $like->actor->displayName = $item->displayName;
1643 $like->actor->preferredUsername = $item->preferredUsername;
1644 $like->actor->url = $item->url;
1645 $like->actor->image = $item->image;
1646 $like->generator = new stdClass;
1647 $like->generator->displayName = "pumpio";
1648 pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1652 if ($item->replies->totalItems == 0)
1655 foreach ($item->replies->items AS $item) {
1656 if ($item->id == $id)
1659 // Checking if the comment already exists - Two queries for speed issues
1660 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1668 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1676 $post = new stdClass;
1677 $post->verb = "post";
1678 $post->actor = $item->author;
1679 $post->published = $item->published;
1680 $post->received = $item->updated;
1681 $post->generator = new stdClass;
1682 $post->generator->displayName = "pumpio";
1683 // To-Do: Check for public post
1685 unset($item->author);
1686 unset($item->published);
1687 unset($item->updated);
1689 $post->object = $item;
1691 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1692 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1697 function pumpio_reachable($url) {
1698 $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
1699 return(intval($data['return_code']) != 0);