From e62e49ed3be08e30ab5ea6a5a46e1f90d4715182 Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 25 Feb 2010 09:39:16 -0500 Subject: adding some exception handling for magicenv parsing --- plugins/OStatus/lib/magicenvelope.php | 2 +- plugins/OStatus/lib/salmon.php | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/plugins/OStatus/lib/magicenvelope.php b/plugins/OStatus/lib/magicenvelope.php index 81f4609c5..4a9efe93d 100644 --- a/plugins/OStatus/lib/magicenvelope.php +++ b/plugins/OStatus/lib/magicenvelope.php @@ -59,7 +59,7 @@ class MagicEnvelope $signer_uri = $this->normalizeUser($signer_uri); if (!$this->checkAuthor($text, $signer_uri)) { - return false; + throw new Exception("Unable to determine entry author."); } $signature_alg = Magicsig::fromString($this->getKeyPair($signer_uri)); diff --git a/plugins/OStatus/lib/salmon.php b/plugins/OStatus/lib/salmon.php index b5f178cc6..9d4359f74 100644 --- a/plugins/OStatus/lib/salmon.php +++ b/plugins/OStatus/lib/salmon.php @@ -72,8 +72,12 @@ class Salmon // TODO: Should probably be getting the signer uri as an argument? $signer_uri = $magic_env->getAuthor($text); - $env = $magic_env->signMessage($text, 'application/atom+xml', $signer_uri); - + try { + $env = $magic_env->signMessage($text, 'application/atom+xml', $signer_uri); + } catch (Exception $e) { + common_log(LOG_ERR, "Salmon signing failed: ". $e->getMessage()); + return $text; + } return $magic_env->unfold($env); } -- cgit v1.2.3-54-g00ecf From 5cb6e54bedd6aa7dda14bb43fd29d8c119fe6d4c Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 25 Feb 2010 14:59:15 -0500 Subject: call-time pass by reference --- plugins/OStatus/OStatusPlugin.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/OStatus/OStatusPlugin.php b/plugins/OStatus/OStatusPlugin.php index 7f75b7b2b..9a543df3b 100644 --- a/plugins/OStatus/OStatusPlugin.php +++ b/plugins/OStatus/OStatusPlugin.php @@ -644,7 +644,7 @@ class OStatusPlugin extends Plugin function onStartUserGroupHomeUrl($group, &$url) { - return $this->onStartUserGroupPermalink($group, &$url); + return $this->onStartUserGroupPermalink($group, $url); } function onStartUserGroupPermalink($group, &$url) -- cgit v1.2.3-54-g00ecf From 3d0ba3efc84a78a24d4a3a60472e47aef92546dd Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 25 Feb 2010 17:08:50 -0500 Subject: adding a new, more generic "discovery" class that does LRDD disco (rather than webfinger specific) --- plugins/OStatus/lib/discovery.php | 303 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 303 insertions(+) create mode 100644 plugins/OStatus/lib/discovery.php diff --git a/plugins/OStatus/lib/discovery.php b/plugins/OStatus/lib/discovery.php new file mode 100644 index 000000000..1159f2151 --- /dev/null +++ b/plugins/OStatus/lib/discovery.php @@ -0,0 +1,303 @@ +. + * + * @package StatusNet + * @author James Walker + * @copyright 2010 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 + * @link http://status.net/ + */ + +/** + * This class implements LRDD-based service discovery based on the "Hammer Draft" + * (including webfinger) + * + * @see http://groups.google.com/group/webfinger/browse_thread/thread/9f3d93a479e91bbf + */ +class Discovery +{ + + const LRDD_REL = 'lrdd'; + const PROFILEPAGE = 'http://webfinger.net/rel/profile-page'; + const UPDATESFROM = 'http://schemas.google.com/g/2010#updates-from'; + + public $methods = array(); + + public function __construct() + { + $this->registerMethod('Discovery_LRDD_Host_Meta'); + $this->registerMethod('Discovery_LRDD_Link_Header'); + $this->registerMethod('Discovery_LRDD_Link_HTML'); + } + + + public function registerMethod($class) + { + $this->methods[] = $class; + } + + /** + * Given a "user id" make sure it's normalized to either a webfinger + * acct: uri or a profile HTTP URL. + */ + public static function normalize($user_id) + { + if (substr($user_id, 0, 5) == 'http:' || + substr($user_id, 0, 6) == 'https:' || + substr($user_id, 0, 5) == 'acct:') { + return $user_id; + } + + if (strpos($user_id, '@') !== FALSE) { + return 'acct:' . $user_id; + } + + return 'http://' . $user_id; + } + + public static function isWebfinger($user_id) + { + $uri = Discovery::normalize($user_id); + + return (substr($uri, 0, 5) == 'acct:'); + } + + /** + * This implements the actual lookup procedure + */ + public function lookup($id) + { + // Normalize the incoming $id to make sure we have a uri + $uri = $this->normalize($id); + + foreach ($this->methods as $class) { + $links = call_user_func(array($class, 'discover'), $uri); + + if ($link = Discovery::getService($links, Discovery::LRDD_REL)) { + // Load the LRDD XRD + if ($link['template']) { + $xrd_uri = Discovery::applyTemplate($link['template'], $uri); + } else { + $xrd_uri = $link['href']; + } + + $xrd = $this->fetchXrd($xrd_uri); + if ($xrd) { + return $xrd; + } + } + } + + throw new Exception('Unable to find services for '. $id); + } + + public static function getService($links, $service) { + foreach ($links as $link) { + if ($link['rel'] == $service) { + return $link; + } + } + } + + + public static function applyTemplate($template, $id) + { + $template = str_replace('{uri}', urlencode($id), $template); + + return $template; + } + + + public static function fetchXrd($url) + { + try { + $client = new HTTPClient(); + $response = $client->get($url); + } catch (HTTP_Request2_Exception $e) { + return false; + } + + if ($response->getStatus() != 200) { + return false; + } + + return XRD::parse($response->getBody()); + } +} + +interface Discovery_LRDD +{ + public function discovery($uri); +} + +class Discovery_LRDD_Host_Meta implements Discovery_LRDD +{ + function discover($uri) + { + if (Discovery::isWebfinger($uri)) { + // We have a webfinger acct: - start with host-meta + list($name, $domain) = explode('@', $id); + } else { + $domain = @parse_url($uri, PHP_URL_HOST); + } + + $url = 'http://'. $domain .'/.well-known/host-meta'; + + $xrd = Discovery::fetchXrd($url); + + if ($xrd) { + if ($xrd->host != $domain) { + return false; + } + + return $xrd->links; + } + } +} + +class Discovery_LRDD_Link_Header implements Discovery_LRDD +{ + public function discover($uri) + { + try { + $client = new HTTPClient(); + $response = $client->get($url); + } catch (HTTP_Request2_Exception $e) { + return false; + } + + if ($response->getStatus() != 200) { + return false; + } + + $link_header = $response->getHeader('Link'); + if (!$link_header) { + return false; + } + + return Discovery_LRDD_Link_Header::parseHeader($header); + } + + protected static function parseHeader($header) + { + preg_match('/^<[^>]+>/', $header, $uri_reference); + if (empty($uri_reference)) return; + + $link_uri = trim($uri_reference[0], '<>'); + $link_rel = array(); + $link_type = null; + + // remove uri-reference from header + $header = substr($header, strlen($uri_reference[0])); + + // parse link-params + $params = explode($header, ';'); + + foreach ($params as $param) { + if (empty($param)) continue; + list($param_name, $param_value) = explode('=', $param, 2); + $param_name = trim($param_name); + $param_value = preg_replace('(^"|"$)', '', trim($param_value)); + + // for now we only care about 'rel' and 'type' link params + // TODO do something with the other links-params + switch ($param_name) { + case 'rel': + $link_rel = trim($param_value); + break; + + case 'type': + $link_type = trim($param_value); + } + } + + return array( + 'href' => $link_uri, + 'rel' => $link_rel, + 'type' => $link_type); + } +} + +class Discovery_LRDD_Link_HTML implements Discovery_LRDD +{ + public function discover($uri) + { + try { + $client = new HTTPClient(); + $response = $client->get($url); + } catch (HTTP_Request2_Exception $e) { + return false; + } + + if ($response->getStatus() != 200) { + return false; + } + + return Discovery_LRDD_Link_HTML::parse($response->getBody()); + } + + + public function parse($html) + { + $links = array(); + + preg_match('/]*)?>(.*?)<\/head>/is', $html, $head_matches); + $head_html = $head_matches[2]; + + preg_match_all('/]*>/i', $head_html, $link_matches); + + foreach ($link_matches[0] as $link_html) { + $link_url = null; + $link_rel = null; + $link_type = null; + + preg_match('/\srel=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $rel_matches); + if ( isset($rel_matches[3]) ) { + $link_rel = $rel_matches[3]; + } else if ( isset($rel_matches[1]) ) { + $link_rel = $rel_matches[1]; + } + + preg_match('/\shref=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $href_matches); + if ( isset($href_matches[3]) ) { + $link_uri = $href_matches[3]; + } else if ( isset($href_matches[1]) ) { + $link_uri = $href_matches[1]; + } + + preg_match('/\stype=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $type_matches); + if ( isset($type_matches[3]) ) { + $link_type = $type_matches[3]; + } else if ( isset($type_matches[1]) ) { + $link_type = $type_matches[1]; + } + + $links[] = array( + 'href' => $link_url, + 'rel' => $link_rel, + 'type' => $link_type, + ); + } + + return $links; + } +} -- cgit v1.2.3-54-g00ecf From b2dabe6a48392cc65ec691ab5a52696994233dd5 Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 25 Feb 2010 17:12:46 -0500 Subject: removing the webfinger lib --- plugins/OStatus/lib/webfinger.php | 151 -------------------------------------- 1 file changed, 151 deletions(-) delete mode 100644 plugins/OStatus/lib/webfinger.php diff --git a/plugins/OStatus/lib/webfinger.php b/plugins/OStatus/lib/webfinger.php deleted file mode 100644 index 8a5037629..000000000 --- a/plugins/OStatus/lib/webfinger.php +++ /dev/null @@ -1,151 +0,0 @@ -. - * - * @package StatusNet - * @author James Walker - * @copyright 2010 StatusNet, Inc. - * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 - * @link http://status.net/ - */ - -define('WEBFINGER_SERVICE_REL_VALUE', 'lrdd'); - -/** - * Implement the webfinger protocol. - */ - -class Webfinger -{ - const PROFILEPAGE = 'http://webfinger.net/rel/profile-page'; - const UPDATESFROM = 'http://schemas.google.com/g/2010#updates-from'; - - /** - * Perform a webfinger lookup given an account. - */ - - public function lookup($id) - { - $id = $this->normalize($id); - list($name, $domain) = explode('@', $id); - - $links = $this->getServiceLinks($domain); - if (!$links) { - return false; - } - - $services = array(); - foreach ($links as $link) { - if ($link['template']) { - return $this->getServiceDescription($link['template'], $id); - } - if ($link['href']) { - return $this->getServiceDescription($link['href'], $id); - } - } - } - - /** - * Normalize an account ID - */ - function normalize($id) - { - if (substr($id, 0, 7) == 'acct://') { - return substr($id, 7); - } else if (substr($id, 0, 5) == 'acct:') { - return substr($id, 5); - } - - return $id; - } - - function getServiceLinks($domain) - { - $url = 'http://'. $domain .'/.well-known/host-meta'; - $content = $this->fetchURL($url); - if (empty($content)) { - common_log(LOG_DEBUG, 'Error fetching host-meta'); - return false; - } - $result = XRD::parse($content); - - // Ensure that the host == domain (spec may include signing later) - if ($result->host != $domain) { - return false; - } - - $links = array(); - foreach ($result->links as $link) { - if ($link['rel'] == WEBFINGER_SERVICE_REL_VALUE) { - $links[] = $link; - } - - } - return $links; - } - - function getServiceDescription($template, $id) - { - $url = $this->applyTemplate($template, 'acct:' . $id); - - $content = $this->fetchURL($url); - - if (!$content) { - return false; - } - - return XRD::parse($content); - } - - function fetchURL($url) - { - try { - $client = new HTTPClient(); - $response = $client->get($url); - } catch (HTTP_Request2_Exception $e) { - return false; - } - - if ($response->getStatus() != 200) { - return false; - } - - return $response->getBody(); - } - - function applyTemplate($template, $id) - { - $template = str_replace('{uri}', urlencode($id), $template); - - return $template; - } - - function getHostMeta($domain, $template) { - $xrd = new XRD(); - $xrd->host = $domain; - $xrd->links[] = array('rel' => 'lrdd', - 'template' => $template, - 'title' => array('Resource Descriptor')); - - return $xrd->toXML(); - } -} - -- cgit v1.2.3-54-g00ecf From bd90ef9f66ce281c4ef9af724d574a5ead156310 Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 25 Feb 2010 17:26:10 -0500 Subject: replace webfinger usage in hostmeta.php --- plugins/OStatus/actions/hostmeta.php | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/plugins/OStatus/actions/hostmeta.php b/plugins/OStatus/actions/hostmeta.php index 850b8a0fe..85715ecf4 100644 --- a/plugins/OStatus/actions/hostmeta.php +++ b/plugins/OStatus/actions/hostmeta.php @@ -31,12 +31,18 @@ class HostMetaAction extends Action { parent::handle(); - $w = new Webfinger(); - - $domain = common_config('site', 'server'); $url = common_local_url('webfinger'); $url.= '?uri={uri}'; - print $w->getHostMeta($domain, $url); + + $xrd = new XRD(); + + $xrd = new XRD(); + $xrd->host = $domain; + $xrd->links[] = array('rel' => Discovery::LRDD_REL, + 'template' => $url, + 'title' => array('Resource Descriptor')); + + print $xrd->toXML(); } } -- cgit v1.2.3-54-g00ecf From 5ae64a7adbe7631be918f25eeda383f77b42b758 Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 25 Feb 2010 17:34:56 -0500 Subject: moving references to Webfinger to Discovery --- plugins/OStatus/actions/ostatusinit.php | 4 ++-- plugins/OStatus/actions/webfinger.php | 6 +++--- plugins/OStatus/classes/Ostatus_profile.php | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/plugins/OStatus/actions/ostatusinit.php b/plugins/OStatus/actions/ostatusinit.php index 3f2f6368f..5c8575595 100644 --- a/plugins/OStatus/actions/ostatusinit.php +++ b/plugins/OStatus/actions/ostatusinit.php @@ -131,9 +131,9 @@ class OStatusInitAction extends Action function connectWebfinger($acct) { - $w = new Webfinger; + $disco = new Discovery; - $result = $w->lookup($acct); + $result = $disco->lookup($acct); if (!$result) { $this->clientError(_m("Couldn't look up OStatus account profile.")); } diff --git a/plugins/OStatus/actions/webfinger.php b/plugins/OStatus/actions/webfinger.php index 34336a903..fa41b2444 100644 --- a/plugins/OStatus/actions/webfinger.php +++ b/plugins/OStatus/actions/webfinger.php @@ -40,7 +40,7 @@ class WebfingerAction extends Action function handle() { - $acct = Webfinger::normalize($this->uri); + $acct = Discovery::normalize($this->uri); $xrd = new XRD(); @@ -55,11 +55,11 @@ class WebfingerAction extends Action $xrd->subject = $this->uri; $xrd->alias[] = common_profile_url($nick); - $xrd->links[] = array('rel' => Webfinger::PROFILEPAGE, + $xrd->links[] = array('rel' => Discovery::PROFILEPAGE, 'type' => 'text/html', 'href' => common_profile_url($nick)); - $xrd->links[] = array('rel' => Webfinger::UPDATESFROM, + $xrd->links[] = array('rel' => Discovery::UPDATESFROM, 'href' => common_local_url('ApiTimelineUser', array('id' => $this->user->id, 'format' => 'atom')), diff --git a/plugins/OStatus/classes/Ostatus_profile.php b/plugins/OStatus/classes/Ostatus_profile.php index f23017077..0fec8fc43 100644 --- a/plugins/OStatus/classes/Ostatus_profile.php +++ b/plugins/OStatus/classes/Ostatus_profile.php @@ -1328,9 +1328,9 @@ class Ostatus_profile extends Memcached_DataObject // Now, try some discovery - $wf = new Webfinger(); + $disco = new Discovery(); - $result = $wf->lookup($addr); + $result = $disco->lookup($addr); if (!$result) { return null; @@ -1338,13 +1338,13 @@ class Ostatus_profile extends Memcached_DataObject foreach ($result->links as $link) { switch ($link['rel']) { - case Webfinger::PROFILEPAGE: + case Discovery::PROFILEPAGE: $profileUrl = $link['href']; break; case 'salmon': $salmonEndpoint = $link['href']; break; - case Webfinger::UPDATESFROM: + case Discovery::UPDATESFROM: $feedUrl = $link['href']; break; default: -- cgit v1.2.3-54-g00ecf From 93f4f07c122613c0afd2257bd9e898629124178a Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 25 Feb 2010 17:52:18 -0500 Subject: moving webfinger action to xrdaction --- plugins/OStatus/OStatusPlugin.php | 4 +- plugins/OStatus/actions/hostmeta.php | 2 +- plugins/OStatus/actions/webfinger.php | 109 ---------------------------------- plugins/OStatus/actions/xrd.php | 109 ++++++++++++++++++++++++++++++++++ 4 files changed, 112 insertions(+), 112 deletions(-) delete mode 100644 plugins/OStatus/actions/webfinger.php create mode 100644 plugins/OStatus/actions/xrd.php diff --git a/plugins/OStatus/OStatusPlugin.php b/plugins/OStatus/OStatusPlugin.php index 9a543df3b..91d055498 100644 --- a/plugins/OStatus/OStatusPlugin.php +++ b/plugins/OStatus/OStatusPlugin.php @@ -43,8 +43,8 @@ class OStatusPlugin extends Plugin // Discovery actions $m->connect('.well-known/host-meta', array('action' => 'hostmeta')); - $m->connect('main/webfinger', - array('action' => 'webfinger')); + $m->connect('main/xrd', + array('action' => 'xrd')); $m->connect('main/ostatus', array('action' => 'ostatusinit')); $m->connect('main/ostatus?nickname=:nickname', diff --git a/plugins/OStatus/actions/hostmeta.php b/plugins/OStatus/actions/hostmeta.php index 85715ecf4..3d00b98ae 100644 --- a/plugins/OStatus/actions/hostmeta.php +++ b/plugins/OStatus/actions/hostmeta.php @@ -32,7 +32,7 @@ class HostMetaAction extends Action parent::handle(); $domain = common_config('site', 'server'); - $url = common_local_url('webfinger'); + $url = common_local_url('xrd'); $url.= '?uri={uri}'; $xrd = new XRD(); diff --git a/plugins/OStatus/actions/webfinger.php b/plugins/OStatus/actions/webfinger.php deleted file mode 100644 index fa41b2444..000000000 --- a/plugins/OStatus/actions/webfinger.php +++ /dev/null @@ -1,109 +0,0 @@ -. - */ - -/** - * @package OStatusPlugin - * @maintainer James Walker - */ - -if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } - -class WebfingerAction extends Action -{ - - public $uri; - - function prepare($args) - { - parent::prepare($args); - - $this->uri = $this->trimmed('uri'); - - return true; - } - - function handle() - { - $acct = Discovery::normalize($this->uri); - - $xrd = new XRD(); - - list($nick, $domain) = explode('@', urldecode($acct)); - $nick = common_canonical_nickname($nick); - - $this->user = User::staticGet('nickname', $nick); - if (!$this->user) { - $this->clientError(_('No such user.'), 404); - return false; - } - - $xrd->subject = $this->uri; - $xrd->alias[] = common_profile_url($nick); - $xrd->links[] = array('rel' => Discovery::PROFILEPAGE, - 'type' => 'text/html', - 'href' => common_profile_url($nick)); - - $xrd->links[] = array('rel' => Discovery::UPDATESFROM, - 'href' => common_local_url('ApiTimelineUser', - array('id' => $this->user->id, - 'format' => 'atom')), - 'type' => 'application/atom+xml'); - - // hCard - $xrd->links[] = array('rel' => 'http://microformats.org/profile/hcard', - 'type' => 'text/html', - 'href' => common_profile_url($nick)); - - // XFN - $xrd->links[] = array('rel' => 'http://gmpg.org/xfn/11', - 'type' => 'text/html', - 'href' => common_profile_url($nick)); - // FOAF - $xrd->links[] = array('rel' => 'describedby', - 'type' => 'application/rdf+xml', - 'href' => common_local_url('foaf', - array('nickname' => $nick))); - - $salmon_url = common_local_url('salmon', - array('id' => $this->user->id)); - - $xrd->links[] = array('rel' => 'salmon', - 'href' => $salmon_url); - - // Get this user's keypair - $magickey = Magicsig::staticGet('user_id', $this->user->id); - if (!$magickey) { - // No keypair yet, let's generate one. - $magickey = new Magicsig(); - $magickey->generate(); - } - - $xrd->links[] = array('rel' => Magicsig::PUBLICKEYREL, - 'href' => 'data:application/magic-public-key;'. $magickey->keypair); - - // TODO - finalize where the redirect should go on the publisher - $url = common_local_url('ostatussub') . '?profile={uri}'; - $xrd->links[] = array('rel' => 'http://ostatus.org/schema/1.0/subscribe', - 'template' => $url ); - - header('Content-type: text/xml'); - print $xrd->toXML(); - } - -} diff --git a/plugins/OStatus/actions/xrd.php b/plugins/OStatus/actions/xrd.php new file mode 100644 index 000000000..cc5c70b08 --- /dev/null +++ b/plugins/OStatus/actions/xrd.php @@ -0,0 +1,109 @@ +. + */ + +/** + * @package OStatusPlugin + * @maintainer James Walker + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } + +class XrdAction extends Action +{ + + public $uri; + + function prepare($args) + { + parent::prepare($args); + + $this->uri = $this->trimmed('uri'); + + return true; + } + + function handle() + { + $acct = Discovery::normalize($this->uri); + + $xrd = new XRD(); + + list($nick, $domain) = explode('@', substr(urldecode($acct), 5)); + $nick = common_canonical_nickname($nick); + + $this->user = User::staticGet('nickname', $nick); + if (!$this->user) { + $this->clientError(_('No such user.'), 404); + return false; + } + + $xrd->subject = $this->uri; + $xrd->alias[] = common_profile_url($nick); + $xrd->links[] = array('rel' => Discovery::PROFILEPAGE, + 'type' => 'text/html', + 'href' => common_profile_url($nick)); + + $xrd->links[] = array('rel' => Discovery::UPDATESFROM, + 'href' => common_local_url('ApiTimelineUser', + array('id' => $this->user->id, + 'format' => 'atom')), + 'type' => 'application/atom+xml'); + + // hCard + $xrd->links[] = array('rel' => 'http://microformats.org/profile/hcard', + 'type' => 'text/html', + 'href' => common_profile_url($nick)); + + // XFN + $xrd->links[] = array('rel' => 'http://gmpg.org/xfn/11', + 'type' => 'text/html', + 'href' => common_profile_url($nick)); + // FOAF + $xrd->links[] = array('rel' => 'describedby', + 'type' => 'application/rdf+xml', + 'href' => common_local_url('foaf', + array('nickname' => $nick))); + + $salmon_url = common_local_url('salmon', + array('id' => $this->user->id)); + + $xrd->links[] = array('rel' => 'salmon', + 'href' => $salmon_url); + + // Get this user's keypair + $magickey = Magicsig::staticGet('user_id', $this->user->id); + if (!$magickey) { + // No keypair yet, let's generate one. + $magickey = new Magicsig(); + $magickey->generate($this->user->id); + } + + $xrd->links[] = array('rel' => Magicsig::PUBLICKEYREL, + 'href' => 'data:application/magic-public-key;'. $magickey->keypair); + + // TODO - finalize where the redirect should go on the publisher + $url = common_local_url('ostatussub') . '?profile={uri}'; + $xrd->links[] = array('rel' => 'http://ostatus.org/schema/1.0/subscribe', + 'template' => $url ); + + header('Content-type: text/xml'); + print $xrd->toXML(); + } + +} -- cgit v1.2.3-54-g00ecf From 08413428a7f4613649be3d80fd393a12e33ffbc8 Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 25 Feb 2010 17:52:56 -0500 Subject: typo --- plugins/OStatus/lib/discovery.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/OStatus/lib/discovery.php b/plugins/OStatus/lib/discovery.php index 1159f2151..8aba31328 100644 --- a/plugins/OStatus/lib/discovery.php +++ b/plugins/OStatus/lib/discovery.php @@ -146,12 +146,12 @@ class Discovery interface Discovery_LRDD { - public function discovery($uri); + public function discover($uri); } class Discovery_LRDD_Host_Meta implements Discovery_LRDD { - function discover($uri) + public function discover($uri) { if (Discovery::isWebfinger($uri)) { // We have a webfinger acct: - start with host-meta -- cgit v1.2.3-54-g00ecf From d8d8d59a03ef3fa12a0ea668b4a2f383f80486dc Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Thu, 25 Feb 2010 18:55:11 -0800 Subject: - Updates to use new activity object factories - Prune obsolete feed creation method --- plugins/OStatus/classes/Ostatus_profile.php | 104 ++-------------------------- 1 file changed, 5 insertions(+), 99 deletions(-) diff --git a/plugins/OStatus/classes/Ostatus_profile.php b/plugins/OStatus/classes/Ostatus_profile.php index ad9170f5b..c3ea042ff 100644 --- a/plugins/OStatus/classes/Ostatus_profile.php +++ b/plugins/OStatus/classes/Ostatus_profile.php @@ -150,27 +150,7 @@ class Ostatus_profile extends Memcached_DataObject function asActivityObject() { if ($this->isGroup()) { - $object = new ActivityObject(); - $object->type = 'http://activitystrea.ms/schema/1.0/group'; - $object->id = $this->uri; - $self = $this->localGroup(); - - // @fixme put a standard getAvatar() interface on groups too - if ($self->homepage_logo) { - $object->avatar = $self->homepage_logo; - $map = array('png' => 'image/png', - 'jpg' => 'image/jpeg', - 'jpeg' => 'image/jpeg', - 'gif' => 'image/gif'); - $extension = pathinfo(parse_url($object->avatar, PHP_URL_PATH), PATHINFO_EXTENSION); - if (isset($map[$extension])) { - // @fixme this ain't used/saved yet - $object->avatarType = $map[$extension]; - } - } - - $object->link = $this->uri; // @fixme accurate? - return $object; + return ActivityObject::fromGroup($this->localGroup()); } else { return ActivityObject::fromProfile($this->localProfile()); } @@ -189,57 +169,13 @@ class Ostatus_profile extends Memcached_DataObject */ function asActivityNoun($element) { - $xs = new XMLStringer(true); - $avatarHref = Avatar::defaultImage(AVATAR_PROFILE_SIZE); - $avatarType = 'image/png'; if ($this->isGroup()) { - $type = 'http://activitystrea.ms/schema/1.0/group'; - $self = $this->localGroup(); - - // @fixme put a standard getAvatar() interface on groups too - if ($self->homepage_logo) { - $avatarHref = $self->homepage_logo; - $map = array('png' => 'image/png', - 'jpg' => 'image/jpeg', - 'jpeg' => 'image/jpeg', - 'gif' => 'image/gif'); - $extension = pathinfo(parse_url($avatarHref, PHP_URL_PATH), PATHINFO_EXTENSION); - if (isset($map[$extension])) { - $avatarType = $map[$extension]; - } - } + $noun = ActivityObject::fromGroup($this->localGroup()); + return $noun->asString('activity:' . $element); } else { - $type = 'http://activitystrea.ms/schema/1.0/person'; - $self = $this->localProfile(); - $avatar = $self->getAvatar(AVATAR_PROFILE_SIZE); - if ($avatar) { - $avatarHref = $avatar->url; - $avatarType = $avatar->mediatype; - } + $noun = ActivityObject::fromProfile($this->localProfile()); + return $noun->asString('activity:' . $element); } - $xs->elementStart('activity:' . $element); - $xs->element( - 'activity:object-type', - null, - $type - ); - $xs->element( - 'id', - null, - $this->uri); // ? - $xs->element('title', null, $self->getBestName()); - - $xs->element( - 'link', array( - 'type' => $avatarType, - 'href' => $avatarHref - ), - '' - ); - - $xs->elementEnd('activity:' . $element); - - return $xs->getString(); } /** @@ -486,36 +422,6 @@ class Ostatus_profile extends Memcached_DataObject } } - function atomFeed($actor) - { - $feed = new Atom10Feed(); - // @fixme should these be set up somewhere else? - $feed->addNamespace('activity', 'http://activitystrea.ms/spec/1.0/'); - $feed->addNamespace('thr', 'http://purl.org/syndication/thread/1.0'); - $feed->addNamespace('georss', 'http://www.georss.org/georss'); - $feed->addNamespace('ostatus', 'http://ostatus.org/schema/1.0'); - - $taguribase = common_config('integration', 'taguri'); - $feed->setId("tag:{$taguribase}:UserTimeline:{$actor->id}"); // ??? - - $feed->setTitle($actor->getBestName() . ' timeline'); // @fixme - $feed->setUpdated(time()); - $feed->setPublished(time()); - - $feed->addLink(common_local_url('ApiTimelineUser', - array('id' => $actor->id, - 'type' => 'atom')), - array('rel' => 'self', - 'type' => 'application/atom+xml')); - - $feed->addLink(common_local_url('userbyid', - array('id' => $actor->id)), - array('rel' => 'alternate', - 'type' => 'text/html')); - - return $feed; - } - /** * Read and post notices for updates from the feed. * Currently assumes that all items in the feed are new, -- cgit v1.2.3-54-g00ecf From 8274bbedcf1d8b08682c6f2ee96cc0f6a3c7e293 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Thu, 25 Feb 2010 19:17:50 -0800 Subject: Fix test to account for new way avatars are stored in ActivityObject --- tests/ActivityParseTests.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/ActivityParseTests.php b/tests/ActivityParseTests.php index d1d871734..7bf9cec7c 100644 --- a/tests/ActivityParseTests.php +++ b/tests/ActivityParseTests.php @@ -121,10 +121,14 @@ class ActivityParseTests extends PHPUnit_Framework_TestCase $this->assertEquals($act->actor->title, 'Test User'); $this->assertEquals($act->actor->id, 'http://example.net/mysite/user/3'); $this->assertEquals($act->actor->link, 'http://example.net/mysite/testuser'); + + $avatars = $act->actor->avatarLinks; + $this->assertEquals( - $act->actor->avatar, - 'http://example.net/mysite/avatar/3-96-20100224004207.jpeg' + $avatars[0]->url, + 'http://example.net/mysite/avatar/3-96-20100224004207.jpeg' ); + $this->assertEquals($act->actor->displayName, 'Test User'); $poco = $act->actor->poco; -- cgit v1.2.3-54-g00ecf From 2528bb452b4ed27cc8685f5c8d900fe0742ef229 Mon Sep 17 00:00:00 2001 From: Brion Vibber Date: Thu, 25 Feb 2010 19:48:28 -0800 Subject: OStatus: clean up known-URL hinting during profile setup, saves some extra HTTP hits we were getting when mentioning Buzz feeds. --- plugins/OStatus/classes/Ostatus_profile.php | 82 +++++++++++++++-------------- 1 file changed, 43 insertions(+), 39 deletions(-) diff --git a/plugins/OStatus/classes/Ostatus_profile.php b/plugins/OStatus/classes/Ostatus_profile.php index 75b4bef41..c462fead6 100644 --- a/plugins/OStatus/classes/Ostatus_profile.php +++ b/plugins/OStatus/classes/Ostatus_profile.php @@ -791,11 +791,18 @@ class Ostatus_profile extends Memcached_DataObject { // Get the canonical feed URI and check it $discover = new FeedDiscovery(); - $feeduri = $discover->discoverFromURL($profile_uri); + if ($hints['feedurl']) { + $feeduri = $hints['feedurl']; + $feeduri = $discover->discoverFromFeedURL($feeduri); + } else { + $feeduri = $discover->discoverFromURL($profile_uri); + $hints['feedurl'] = $feeduri; + } - //$feedsub = FeedSub::ensureFeed($feeduri, $discover->feed); $huburi = $discover->getAtomLink('hub'); + $hints['hub'] = $huburi; $salmonuri = $discover->getAtomLink('salmon'); + $hints['salmon'] = $salmonuri; if (!$huburi) { // We can only deal with folks with a PuSH hub @@ -810,7 +817,7 @@ class Ostatus_profile extends Memcached_DataObject if (!empty($subject)) { $subjObject = new ActivityObject($subject); - return self::ensureActivityObjectProfile($subjObject, $feeduri, $salmonuri, $hints); + return self::ensureActivityObjectProfile($subjObject, $hints); } // Otherwise, try the feed author @@ -819,7 +826,7 @@ class Ostatus_profile extends Memcached_DataObject if (!empty($author)) { $authorObject = new ActivityObject($author); - return self::ensureActivityObjectProfile($authorObject, $feeduri, $salmonuri, $hints); + return self::ensureActivityObjectProfile($authorObject, $hints); } // Sheesh. Not a very nice feed! Let's try fingerpoken in the @@ -835,7 +842,7 @@ class Ostatus_profile extends Memcached_DataObject if (!empty($actor)) { $actorObject = new ActivityObject($actor); - return self::ensureActivityObjectProfile($actorObject, $feeduri, $salmonuri, $hints); + return self::ensureActivityObjectProfile($actorObject, $hints); } @@ -843,7 +850,7 @@ class Ostatus_profile extends Memcached_DataObject if (!empty($author)) { $authorObject = new ActivityObject($author); - return self::ensureActivityObjectProfile($authorObject, $feeduri, $salmonuri, $hints); + return self::ensureActivityObjectProfile($authorObject, $hints); } } @@ -988,18 +995,18 @@ class Ostatus_profile extends Memcached_DataObject * @return Ostatus_profile */ - public static function ensureActorProfile($activity, $feeduri=null, $salmonuri=null) + public static function ensureActorProfile($activity, $hints=array()) { - return self::ensureActivityObjectProfile($activity->actor, $feeduri, $salmonuri); + return self::ensureActivityObjectProfile($activity->actor, $hints); } - public static function ensureActivityObjectProfile($object, $feeduri=null, $salmonuri=null, $hints=array()) + public static function ensureActivityObjectProfile($object, $hints=array()) { $profile = self::getActivityObjectProfile($object); if ($profile) { $profile->updateFromActivityObject($object, $hints); } else { - $profile = self::createActivityObjectProfile($object, $feeduri, $salmonuri, $hints); + $profile = self::createActivityObjectProfile($object, $hints); } return $profile; } @@ -1045,58 +1052,55 @@ class Ostatus_profile extends Memcached_DataObject * @fixme validate stuff somewhere */ - protected static function createActorProfile($activity, $feeduri=null, $salmonuri=null) - { - $actor = $activity->actor; - - self::createActivityObjectProfile($actor, $feeduri, $salmonuri); - } - /** * Create local ostatus_profile and profile/user_group entries for * the provided remote user or group. * * @param ActivityObject $object - * @param string $feeduri - * @param string $salmonuri * @param array $hints * - * @fixme fold $feeduri/$salmonuri into $hints * @return Ostatus_profile */ - protected static function createActivityObjectProfile($object, $feeduri=null, $salmonuri=null, $hints=array()) + protected static function createActivityObjectProfile($object, $hints=array()) { - $homeuri = $object->id; + $homeuri = $object->id; + $discover = false; if (!$homeuri) { common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true)); throw new ServerException("No profile URI"); } - if (empty($feeduri)) { - if (array_key_exists('feedurl', $hints)) { - $feeduri = $hints['feedurl']; - } + if (array_key_exists('feedurl', $hints)) { + $feeduri = $hints['feedurl']; + } else { + $discover = new FeedDiscovery(); + $feeduri = $discover->discoverFromURL($homeuri); } - if (empty($salmonuri)) { - if (array_key_exists('salmon', $hints)) { - $salmonuri = $hints['salmon']; + if (array_key_exists('salmon', $hints)) { + $salmonuri = $hints['salmon']; + } else { + if (!$discover) { + $discover = new FeedDiscovery(); + $discover->discoverFromFeedURL($hints['feedurl']); } + $salmonuri = $discover->getAtomLink('salmon'); } - if (!$feeduri || !$salmonuri) { - // Get the canonical feed URI and check it - $discover = new FeedDiscovery(); - $feeduri = $discover->discoverFromURL($homeuri); - + if (array_key_exists('hub', $hints)) { + $huburi = $hints['hub']; + } else { + if (!$discover) { + $discover = new FeedDiscovery(); + $discover->discoverFromFeedURL($hints['feedurl']); + } $huburi = $discover->getAtomLink('hub'); - $salmonuri = $discover->getAtomLink('salmon'); + } - if (!$huburi) { - // We can only deal with folks with a PuSH hub - throw new FeedSubNoHubException(); - } + if (!$huburi) { + // We can only deal with folks with a PuSH hub + throw new FeedSubNoHubException(); } $oprofile = new Ostatus_profile(); -- cgit v1.2.3-54-g00ecf From 0afb09ad64bec9ea7f9569c73899b2c3fbc1e5a5 Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 25 Feb 2010 23:37:59 -0500 Subject: er. right. --- plugins/OStatus/classes/Magicsig.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugins/OStatus/classes/Magicsig.php b/plugins/OStatus/classes/Magicsig.php index 681aec184..02882d19b 100644 --- a/plugins/OStatus/classes/Magicsig.php +++ b/plugins/OStatus/classes/Magicsig.php @@ -90,7 +90,7 @@ class Magicsig extends Memcached_DataObject return parent::insert(); } - public function generate($key_length = 512) + public function generate($user_id, $key_length = 512) { PEAR::pushErrorHandling(PEAR_ERROR_RETURN); @@ -101,6 +101,7 @@ class Magicsig extends Memcached_DataObject $this->_rsa = new Crypt_RSA($params); PEAR::popErrorHandling(); + $this->user_id = $user_id; $this->insert(); } -- cgit v1.2.3-54-g00ecf From 855692141d531287b179841b8816e90023b6ba7b Mon Sep 17 00:00:00 2001 From: James Walker Date: Thu, 25 Feb 2010 23:38:25 -0500 Subject: use a real keypair from discovery --- plugins/OStatus/lib/magicenvelope.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/plugins/OStatus/lib/magicenvelope.php b/plugins/OStatus/lib/magicenvelope.php index 4a9efe93d..4f8f88155 100644 --- a/plugins/OStatus/lib/magicenvelope.php +++ b/plugins/OStatus/lib/magicenvelope.php @@ -50,7 +50,16 @@ class MagicEnvelope public function getKeyPair($signer_uri) { - return 'RSA.79_L2gq-TD72Nsb5yGS0r9stLLpJZF5AHXyxzWmQmlqKl276LEJEs8CppcerLcR90MbYQUwt-SX9slx40Yq3vA==.AQAB.AR-jo5KMfSISmDAT2iMs2_vNFgWRjl5rbJVvA0SpGIEWyPdCGxlPtCbTexp8-0ZEIe8a4SyjatBECH5hxgMTpw=='; + $disco = new Discovery(); + + $links = $disco->lookup($signer_uri); + if ($link = Discovery::getService($links, 'magic-public-key')) { + list($type, $keypair) = explode(';', $link['href']); + return $keypair; + } + + throw new Exception('Unable to locate signer public key'); + //return 'RSA.79_L2gq-TD72Nsb5yGS0r9stLLpJZF5AHXyxzWmQmlqKl276LEJEs8CppcerLcR90MbYQUwt-SX9slx40Yq3vA==.AQAB.AR-jo5KMfSISmDAT2iMs2_vNFgWRjl5rbJVvA0SpGIEWyPdCGxlPtCbTexp8-0ZEIe8a4SyjatBECH5hxgMTpw=='; } -- cgit v1.2.3-54-g00ecf From da4b21d3a95a9d669ea323145dd62eb27297f846 Mon Sep 17 00:00:00 2001 From: Brion Vibber Date: Thu, 25 Feb 2010 21:06:16 -0800 Subject: try/catch on omb profile pings --- lib/profilequeuehandler.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/profilequeuehandler.php b/lib/profilequeuehandler.php index e8a00aef3..6ce93229b 100644 --- a/lib/profilequeuehandler.php +++ b/lib/profilequeuehandler.php @@ -39,7 +39,11 @@ class ProfileQueueHandler extends QueueHandler if (Event::handle('StartBroadcastProfile', array($profile))) { require_once(INSTALLDIR.'/lib/omb.php'); - omb_broadcast_profile($profile); + try { + omb_broadcast_profile($profile); + } catch (Exception $e) { + common_log(LOG_ERR, "Failed sending OMB profiles: " . $e->getMessage()); + } } Event::handle('EndBroadcastProfile', array($profile)); return true; -- cgit v1.2.3-54-g00ecf From 3daf17d935d25d3456043c6d9f4e483b23b525cc Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Thu, 25 Feb 2010 22:02:40 -0800 Subject: Get ApiAction autoloading properly --- lib/api.php | 1356 ----------------------------------------------------- lib/apiaction.php | 1356 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1356 insertions(+), 1356 deletions(-) delete mode 100644 lib/api.php create mode 100644 lib/apiaction.php diff --git a/lib/api.php b/lib/api.php deleted file mode 100644 index d79dc327e..000000000 --- a/lib/api.php +++ /dev/null @@ -1,1356 +0,0 @@ -. - * - * @category API - * @package StatusNet - * @author Craig Andrews - * @author Dan Moore - * @author Evan Prodromou - * @author Jeffery To - * @author Toby Inkster - * @author Zach Copley - * @copyright 2009 StatusNet, Inc. - * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 - * @link http://status.net/ - */ - -if (!defined('STATUSNET')) { - exit(1); -} - -/** - * Contains most of the Twitter-compatible API output functions. - * - * @category API - * @package StatusNet - * @author Craig Andrews - * @author Dan Moore - * @author Evan Prodromou - * @author Jeffery To - * @author Toby Inkster - * @author Zach Copley - * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 - * @link http://status.net/ - */ - -class ApiAction extends Action -{ - const READ_ONLY = 1; - const READ_WRITE = 2; - - var $format = null; - var $user = null; - var $auth_user = null; - var $page = null; - var $count = null; - var $max_id = null; - var $since_id = null; - var $since = null; - - var $access = self::READ_ONLY; // read (default) or read-write - - /** - * Initialization. - * - * @param array $args Web and URL arguments - * - * @return boolean false if user doesn't exist - */ - - function prepare($args) - { - StatusNet::setApi(true); // reduce exception reports to aid in debugging - parent::prepare($args); - - $this->format = $this->arg('format'); - $this->page = (int)$this->arg('page', 1); - $this->count = (int)$this->arg('count', 20); - $this->max_id = (int)$this->arg('max_id', 0); - $this->since_id = (int)$this->arg('since_id', 0); - $this->since = $this->arg('since'); - - return true; - } - - /** - * Handle a request - * - * @param array $args Arguments from $_REQUEST - * - * @return void - */ - - function handle($args) - { - parent::handle($args); - } - - /** - * Overrides XMLOutputter::element to write booleans as strings (true|false). - * See that method's documentation for more info. - * - * @param string $tag Element type or tagname - * @param array $attrs Array of element attributes, as - * key-value pairs - * @param string $content string content of the element - * - * @return void - */ - function element($tag, $attrs=null, $content=null) - { - if (is_bool($content)) { - $content = ($content ? 'true' : 'false'); - } - - return parent::element($tag, $attrs, $content); - } - - function twitterUserArray($profile, $get_notice=false) - { - $twitter_user = array(); - - $twitter_user['id'] = intval($profile->id); - $twitter_user['name'] = $profile->getBestName(); - $twitter_user['screen_name'] = $profile->nickname; - $twitter_user['location'] = ($profile->location) ? $profile->location : null; - $twitter_user['description'] = ($profile->bio) ? $profile->bio : null; - - $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); - $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() : - Avatar::defaultImage(AVATAR_STREAM_SIZE); - - $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null; - $twitter_user['protected'] = false; # not supported by StatusNet yet - $twitter_user['followers_count'] = $profile->subscriberCount(); - - $design = null; - $user = $profile->getUser(); - - // Note: some profiles don't have an associated user - - $defaultDesign = Design::siteDesign(); - - if (!empty($user)) { - $design = $user->getDesign(); - } - - if (empty($design)) { - $design = $defaultDesign; - } - - $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor); - $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue(); - $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor); - $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue(); - $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor); - $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue(); - $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor); - $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue(); - $twitter_user['profile_sidebar_border_color'] = ''; - - $twitter_user['friends_count'] = $profile->subscriptionCount(); - - $twitter_user['created_at'] = $this->dateTwitter($profile->created); - - $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling! - - $timezone = 'UTC'; - - if (!empty($user) && $user->timezone) { - $timezone = $user->timezone; - } - - $t = new DateTime; - $t->setTimezone(new DateTimeZone($timezone)); - - $twitter_user['utc_offset'] = $t->format('Z'); - $twitter_user['time_zone'] = $timezone; - - $twitter_user['profile_background_image_url'] - = empty($design->backgroundimage) - ? '' : ($design->disposition & BACKGROUND_ON) - ? Design::url($design->backgroundimage) : ''; - - $twitter_user['profile_background_tile'] - = empty($design->disposition) - ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false'; - - $twitter_user['statuses_count'] = $profile->noticeCount(); - - // Is the requesting user following this user? - $twitter_user['following'] = false; - $twitter_user['notifications'] = false; - - if (isset($this->auth_user)) { - - $twitter_user['following'] = $this->auth_user->isSubscribed($profile); - - // Notifications on? - $sub = Subscription::pkeyGet(array('subscriber' => - $this->auth_user->id, - 'subscribed' => $profile->id)); - - if ($sub) { - $twitter_user['notifications'] = ($sub->jabber || $sub->sms); - } - } - - if ($get_notice) { - $notice = $profile->getCurrentNotice(); - if ($notice) { - # don't get user! - $twitter_user['status'] = $this->twitterStatusArray($notice, false); - } - } - - return $twitter_user; - } - - function twitterStatusArray($notice, $include_user=true) - { - $base = $this->twitterSimpleStatusArray($notice, $include_user); - - if (!empty($notice->repeat_of)) { - $original = Notice::staticGet('id', $notice->repeat_of); - if (!empty($original)) { - $original_array = $this->twitterSimpleStatusArray($original, $include_user); - $base['retweeted_status'] = $original_array; - } - } - - return $base; - } - - function twitterSimpleStatusArray($notice, $include_user=true) - { - $profile = $notice->getProfile(); - - $twitter_status = array(); - $twitter_status['text'] = $notice->content; - $twitter_status['truncated'] = false; # Not possible on StatusNet - $twitter_status['created_at'] = $this->dateTwitter($notice->created); - $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ? - intval($notice->reply_to) : null; - $twitter_status['source'] = $this->sourceLink($notice->source); - $twitter_status['id'] = intval($notice->id); - - $replier_profile = null; - - if ($notice->reply_to) { - $reply = Notice::staticGet(intval($notice->reply_to)); - if ($reply) { - $replier_profile = $reply->getProfile(); - } - } - - $twitter_status['in_reply_to_user_id'] = - ($replier_profile) ? intval($replier_profile->id) : null; - $twitter_status['in_reply_to_screen_name'] = - ($replier_profile) ? $replier_profile->nickname : null; - - if (isset($notice->lat) && isset($notice->lon)) { - // This is the format that GeoJSON expects stuff to be in - $twitter_status['geo'] = array('type' => 'Point', - 'coordinates' => array((float) $notice->lat, - (float) $notice->lon)); - } else { - $twitter_status['geo'] = null; - } - - if (isset($this->auth_user)) { - $twitter_status['favorited'] = $this->auth_user->hasFave($notice); - } else { - $twitter_status['favorited'] = false; - } - - // Enclosures - $attachments = $notice->attachments(); - - if (!empty($attachments)) { - - $twitter_status['attachments'] = array(); - - foreach ($attachments as $attachment) { - if ($attachment->isEnclosure()) { - $enclosure = array(); - $enclosure['url'] = $attachment->url; - $enclosure['mimetype'] = $attachment->mimetype; - $enclosure['size'] = $attachment->size; - $twitter_status['attachments'][] = $enclosure; - } - } - } - - if ($include_user && $profile) { - # Don't get notice (recursive!) - $twitter_user = $this->twitterUserArray($profile, false); - $twitter_status['user'] = $twitter_user; - } - - return $twitter_status; - } - - function twitterGroupArray($group) - { - $twitter_group=array(); - $twitter_group['id']=$group->id; - $twitter_group['url']=$group->permalink(); - $twitter_group['nickname']=$group->nickname; - $twitter_group['fullname']=$group->fullname; - $twitter_group['homepage_url']=$group->homepage_url; - $twitter_group['original_logo']=$group->original_logo; - $twitter_group['homepage_logo']=$group->homepage_logo; - $twitter_group['stream_logo']=$group->stream_logo; - $twitter_group['mini_logo']=$group->mini_logo; - $twitter_group['homepage']=$group->homepage; - $twitter_group['description']=$group->description; - $twitter_group['location']=$group->location; - $twitter_group['created']=$this->dateTwitter($group->created); - $twitter_group['modified']=$this->dateTwitter($group->modified); - return $twitter_group; - } - - function twitterRssGroupArray($group) - { - $entry = array(); - $entry['content']=$group->description; - $entry['title']=$group->nickname; - $entry['link']=$group->permalink(); - $entry['published']=common_date_iso8601($group->created); - $entry['updated']==common_date_iso8601($group->modified); - $taguribase = common_config('integration', 'groupuri'); - $entry['id'] = "group:$groupuribase:$entry[link]"; - - $entry['description'] = $entry['content']; - $entry['pubDate'] = common_date_rfc2822($group->created); - $entry['guid'] = $entry['link']; - - return $entry; - } - - function twitterRssEntryArray($notice) - { - $profile = $notice->getProfile(); - $entry = array(); - - // We trim() to avoid extraneous whitespace in the output - - $entry['content'] = common_xml_safe_str(trim($notice->rendered)); - $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content)); - $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id)); - $entry['published'] = common_date_iso8601($notice->created); - - $taguribase = TagURI::base(); - $entry['id'] = "tag:$taguribase:$entry[link]"; - - $entry['updated'] = $entry['published']; - $entry['author'] = $profile->getBestName(); - - // Enclosures - $attachments = $notice->attachments(); - $enclosures = array(); - - foreach ($attachments as $attachment) { - $enclosure_o=$attachment->getEnclosure(); - if ($enclosure_o) { - $enclosure = array(); - $enclosure['url'] = $enclosure_o->url; - $enclosure['mimetype'] = $enclosure_o->mimetype; - $enclosure['size'] = $enclosure_o->size; - $enclosures[] = $enclosure; - } - } - - if (!empty($enclosures)) { - $entry['enclosures'] = $enclosures; - } - - // Tags/Categories - $tag = new Notice_tag(); - $tag->notice_id = $notice->id; - if ($tag->find()) { - $entry['tags']=array(); - while ($tag->fetch()) { - $entry['tags'][]=$tag->tag; - } - } - $tag->free(); - - // RSS Item specific - $entry['description'] = $entry['content']; - $entry['pubDate'] = common_date_rfc2822($notice->created); - $entry['guid'] = $entry['link']; - - if (isset($notice->lat) && isset($notice->lon)) { - // This is the format that GeoJSON expects stuff to be in. - // showGeoRSS() below uses it for XML output, so we reuse it - $entry['geo'] = array('type' => 'Point', - 'coordinates' => array((float) $notice->lat, - (float) $notice->lon)); - } else { - $entry['geo'] = null; - } - - return $entry; - } - - function twitterRelationshipArray($source, $target) - { - $relationship = array(); - - $relationship['source'] = - $this->relationshipDetailsArray($source, $target); - $relationship['target'] = - $this->relationshipDetailsArray($target, $source); - - return array('relationship' => $relationship); - } - - function relationshipDetailsArray($source, $target) - { - $details = array(); - - $details['screen_name'] = $source->nickname; - $details['followed_by'] = $target->isSubscribed($source); - $details['following'] = $source->isSubscribed($target); - - $notifications = false; - - if ($source->isSubscribed($target)) { - - $sub = Subscription::pkeyGet(array('subscriber' => - $source->id, 'subscribed' => $target->id)); - - if (!empty($sub)) { - $notifications = ($sub->jabber || $sub->sms); - } - } - - $details['notifications_enabled'] = $notifications; - $details['blocking'] = $source->hasBlocked($target); - $details['id'] = $source->id; - - return $details; - } - - function showTwitterXmlRelationship($relationship) - { - $this->elementStart('relationship'); - - foreach($relationship as $element => $value) { - if ($element == 'source' || $element == 'target') { - $this->elementStart($element); - $this->showXmlRelationshipDetails($value); - $this->elementEnd($element); - } - } - - $this->elementEnd('relationship'); - } - - function showXmlRelationshipDetails($details) - { - foreach($details as $element => $value) { - $this->element($element, null, $value); - } - } - - function showTwitterXmlStatus($twitter_status, $tag='status') - { - $this->elementStart($tag); - foreach($twitter_status as $element => $value) { - switch ($element) { - case 'user': - $this->showTwitterXmlUser($twitter_status['user']); - break; - case 'text': - $this->element($element, null, common_xml_safe_str($value)); - break; - case 'attachments': - $this->showXmlAttachments($twitter_status['attachments']); - break; - case 'geo': - $this->showGeoRSS($value); - break; - case 'retweeted_status': - $this->showTwitterXmlStatus($value, 'retweeted_status'); - break; - default: - $this->element($element, null, $value); - } - } - $this->elementEnd($tag); - } - - function showTwitterXmlGroup($twitter_group) - { - $this->elementStart('group'); - foreach($twitter_group as $element => $value) { - $this->element($element, null, $value); - } - $this->elementEnd('group'); - } - - function showTwitterXmlUser($twitter_user, $role='user') - { - $this->elementStart($role); - foreach($twitter_user as $element => $value) { - if ($element == 'status') { - $this->showTwitterXmlStatus($twitter_user['status']); - } else { - $this->element($element, null, $value); - } - } - $this->elementEnd($role); - } - - function showXmlAttachments($attachments) { - if (!empty($attachments)) { - $this->elementStart('attachments', array('type' => 'array')); - foreach ($attachments as $attachment) { - $attrs = array(); - $attrs['url'] = $attachment['url']; - $attrs['mimetype'] = $attachment['mimetype']; - $attrs['size'] = $attachment['size']; - $this->element('enclosure', $attrs, ''); - } - $this->elementEnd('attachments'); - } - } - - function showGeoRSS($geo) - { - if (empty($geo)) { - // empty geo element - $this->element('geo'); - } else { - $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss')); - $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]); - $this->elementEnd('geo'); - } - } - - function showTwitterRssItem($entry) - { - $this->elementStart('item'); - $this->element('title', null, $entry['title']); - $this->element('description', null, $entry['description']); - $this->element('pubDate', null, $entry['pubDate']); - $this->element('guid', null, $entry['guid']); - $this->element('link', null, $entry['link']); - - # RSS only supports 1 enclosure per item - if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){ - $enclosure = $entry['enclosures'][0]; - $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null); - } - - if(array_key_exists('tags', $entry)){ - foreach($entry['tags'] as $tag){ - $this->element('category', null,$tag); - } - } - - $this->showGeoRSS($entry['geo']); - $this->elementEnd('item'); - } - - function showJsonObjects($objects) - { - print(json_encode($objects)); - } - - function showSingleXmlStatus($notice) - { - $this->initDocument('xml'); - $twitter_status = $this->twitterStatusArray($notice); - $this->showTwitterXmlStatus($twitter_status); - $this->endDocument('xml'); - } - - function show_single_json_status($notice) - { - $this->initDocument('json'); - $status = $this->twitterStatusArray($notice); - $this->showJsonObjects($status); - $this->endDocument('json'); - } - - function showXmlTimeline($notice) - { - - $this->initDocument('xml'); - $this->elementStart('statuses', array('type' => 'array')); - - if (is_array($notice)) { - foreach ($notice as $n) { - $twitter_status = $this->twitterStatusArray($n); - $this->showTwitterXmlStatus($twitter_status); - } - } else { - while ($notice->fetch()) { - $twitter_status = $this->twitterStatusArray($notice); - $this->showTwitterXmlStatus($twitter_status); - } - } - - $this->elementEnd('statuses'); - $this->endDocument('xml'); - } - - function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null) - { - - $this->initDocument('rss'); - - $this->element('title', null, $title); - $this->element('link', null, $link); - if (!is_null($suplink)) { - // For FriendFeed's SUP protocol - $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom', - 'rel' => 'http://api.friendfeed.com/2008/03#sup', - 'href' => $suplink, - 'type' => 'application/json')); - } - - if (!is_null($logo)) { - $this->elementStart('image'); - $this->element('link', null, $link); - $this->element('title', null, $title); - $this->element('url', null, $logo); - $this->elementEnd('image'); - } - - $this->element('description', null, $subtitle); - $this->element('language', null, 'en-us'); - $this->element('ttl', null, '40'); - - if (is_array($notice)) { - foreach ($notice as $n) { - $entry = $this->twitterRssEntryArray($n); - $this->showTwitterRssItem($entry); - } - } else { - while ($notice->fetch()) { - $entry = $this->twitterRssEntryArray($notice); - $this->showTwitterRssItem($entry); - } - } - - $this->endTwitterRss(); - } - - function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null) - { - - $this->initDocument('atom'); - - $this->element('title', null, $title); - $this->element('id', null, $id); - $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null); - - if (!is_null($logo)) { - $this->element('logo',null,$logo); - } - - if (!is_null($suplink)) { - # For FriendFeed's SUP protocol - $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup', - 'href' => $suplink, - 'type' => 'application/json')); - } - - if (!is_null($selfuri)) { - $this->element('link', array('href' => $selfuri, - 'rel' => 'self', 'type' => 'application/atom+xml'), null); - } - - $this->element('updated', null, common_date_iso8601('now')); - $this->element('subtitle', null, $subtitle); - - if (is_array($notice)) { - foreach ($notice as $n) { - $this->raw($n->asAtomEntry()); - } - } else { - while ($notice->fetch()) { - $this->raw($notice->asAtomEntry()); - } - } - - $this->endDocument('atom'); - - } - - function showRssGroups($group, $title, $link, $subtitle) - { - - $this->initDocument('rss'); - - $this->element('title', null, $title); - $this->element('link', null, $link); - $this->element('description', null, $subtitle); - $this->element('language', null, 'en-us'); - $this->element('ttl', null, '40'); - - if (is_array($group)) { - foreach ($group as $g) { - $twitter_group = $this->twitterRssGroupArray($g); - $this->showTwitterRssItem($twitter_group); - } - } else { - while ($group->fetch()) { - $twitter_group = $this->twitterRssGroupArray($group); - $this->showTwitterRssItem($twitter_group); - } - } - - $this->endTwitterRss(); - } - - function showTwitterAtomEntry($entry) - { - $this->elementStart('entry'); - $this->element('title', null, $entry['title']); - $this->element('content', array('type' => 'html'), $entry['content']); - $this->element('id', null, $entry['id']); - $this->element('published', null, $entry['published']); - $this->element('updated', null, $entry['updated']); - $this->element('link', array('type' => 'text/html', - 'href' => $entry['link'], - 'rel' => 'alternate')); - $this->element('link', array('type' => $entry['avatar-type'], - 'href' => $entry['avatar'], - 'rel' => 'image')); - $this->elementStart('author'); - - $this->element('name', null, $entry['author-name']); - $this->element('uri', null, $entry['author-uri']); - - $this->elementEnd('author'); - $this->elementEnd('entry'); - } - - function showXmlDirectMessage($dm) - { - $this->elementStart('direct_message'); - foreach($dm as $element => $value) { - switch ($element) { - case 'sender': - case 'recipient': - $this->showTwitterXmlUser($value, $element); - break; - case 'text': - $this->element($element, null, common_xml_safe_str($value)); - break; - default: - $this->element($element, null, $value); - break; - } - } - $this->elementEnd('direct_message'); - } - - function directMessageArray($message) - { - $dmsg = array(); - - $from_profile = $message->getFrom(); - $to_profile = $message->getTo(); - - $dmsg['id'] = $message->id; - $dmsg['sender_id'] = $message->from_profile; - $dmsg['text'] = trim($message->content); - $dmsg['recipient_id'] = $message->to_profile; - $dmsg['created_at'] = $this->dateTwitter($message->created); - $dmsg['sender_screen_name'] = $from_profile->nickname; - $dmsg['recipient_screen_name'] = $to_profile->nickname; - $dmsg['sender'] = $this->twitterUserArray($from_profile, false); - $dmsg['recipient'] = $this->twitterUserArray($to_profile, false); - - return $dmsg; - } - - function rssDirectMessageArray($message) - { - $entry = array(); - - $from = $message->getFrom(); - - $entry['title'] = sprintf('Message from %1$s to %2$s', - $from->nickname, $message->getTo()->nickname); - - $entry['content'] = common_xml_safe_str($message->rendered); - $entry['link'] = common_local_url('showmessage', array('message' => $message->id)); - $entry['published'] = common_date_iso8601($message->created); - - $taguribase = TagURI::base(); - - $entry['id'] = "tag:$taguribase:$entry[link]"; - $entry['updated'] = $entry['published']; - - $entry['author-name'] = $from->getBestName(); - $entry['author-uri'] = $from->homepage; - - $avatar = $from->getAvatar(AVATAR_STREAM_SIZE); - - $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE); - $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png'; - - // RSS item specific - - $entry['description'] = $entry['content']; - $entry['pubDate'] = common_date_rfc2822($message->created); - $entry['guid'] = $entry['link']; - - return $entry; - } - - function showSingleXmlDirectMessage($message) - { - $this->initDocument('xml'); - $dmsg = $this->directMessageArray($message); - $this->showXmlDirectMessage($dmsg); - $this->endDocument('xml'); - } - - function showSingleJsonDirectMessage($message) - { - $this->initDocument('json'); - $dmsg = $this->directMessageArray($message); - $this->showJsonObjects($dmsg); - $this->endDocument('json'); - } - - function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null) - { - - $this->initDocument('atom'); - - $this->element('title', null, $title); - $this->element('id', null, $id); - $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null); - - if (!is_null($selfuri)) { - $this->element('link', array('href' => $selfuri, - 'rel' => 'self', 'type' => 'application/atom+xml'), null); - } - - $this->element('updated', null, common_date_iso8601('now')); - $this->element('subtitle', null, $subtitle); - - if (is_array($group)) { - foreach ($group as $g) { - $this->raw($g->asAtomEntry()); - } - } else { - while ($group->fetch()) { - $this->raw($group->asAtomEntry()); - } - } - - $this->endDocument('atom'); - - } - - function showJsonTimeline($notice) - { - - $this->initDocument('json'); - - $statuses = array(); - - if (is_array($notice)) { - foreach ($notice as $n) { - $twitter_status = $this->twitterStatusArray($n); - array_push($statuses, $twitter_status); - } - } else { - while ($notice->fetch()) { - $twitter_status = $this->twitterStatusArray($notice); - array_push($statuses, $twitter_status); - } - } - - $this->showJsonObjects($statuses); - - $this->endDocument('json'); - } - - function showJsonGroups($group) - { - - $this->initDocument('json'); - - $groups = array(); - - if (is_array($group)) { - foreach ($group as $g) { - $twitter_group = $this->twitterGroupArray($g); - array_push($groups, $twitter_group); - } - } else { - while ($group->fetch()) { - $twitter_group = $this->twitterGroupArray($group); - array_push($groups, $twitter_group); - } - } - - $this->showJsonObjects($groups); - - $this->endDocument('json'); - } - - function showXmlGroups($group) - { - - $this->initDocument('xml'); - $this->elementStart('groups', array('type' => 'array')); - - if (is_array($group)) { - foreach ($group as $g) { - $twitter_group = $this->twitterGroupArray($g); - $this->showTwitterXmlGroup($twitter_group); - } - } else { - while ($group->fetch()) { - $twitter_group = $this->twitterGroupArray($group); - $this->showTwitterXmlGroup($twitter_group); - } - } - - $this->elementEnd('groups'); - $this->endDocument('xml'); - } - - function showTwitterXmlUsers($user) - { - - $this->initDocument('xml'); - $this->elementStart('users', array('type' => 'array')); - - if (is_array($user)) { - foreach ($user as $u) { - $twitter_user = $this->twitterUserArray($u); - $this->showTwitterXmlUser($twitter_user); - } - } else { - while ($user->fetch()) { - $twitter_user = $this->twitterUserArray($user); - $this->showTwitterXmlUser($twitter_user); - } - } - - $this->elementEnd('users'); - $this->endDocument('xml'); - } - - function showJsonUsers($user) - { - - $this->initDocument('json'); - - $users = array(); - - if (is_array($user)) { - foreach ($user as $u) { - $twitter_user = $this->twitterUserArray($u); - array_push($users, $twitter_user); - } - } else { - while ($user->fetch()) { - $twitter_user = $this->twitterUserArray($user); - array_push($users, $twitter_user); - } - } - - $this->showJsonObjects($users); - - $this->endDocument('json'); - } - - function showSingleJsonGroup($group) - { - $this->initDocument('json'); - $twitter_group = $this->twitterGroupArray($group); - $this->showJsonObjects($twitter_group); - $this->endDocument('json'); - } - - function showSingleXmlGroup($group) - { - $this->initDocument('xml'); - $twitter_group = $this->twitterGroupArray($group); - $this->showTwitterXmlGroup($twitter_group); - $this->endDocument('xml'); - } - - function dateTwitter($dt) - { - $dateStr = date('d F Y H:i:s', strtotime($dt)); - $d = new DateTime($dateStr, new DateTimeZone('UTC')); - $d->setTimezone(new DateTimeZone(common_timezone())); - return $d->format('D M d H:i:s O Y'); - } - - function initDocument($type='xml') - { - switch ($type) { - case 'xml': - header('Content-Type: application/xml; charset=utf-8'); - $this->startXML(); - break; - case 'json': - header('Content-Type: application/json; charset=utf-8'); - - // Check for JSONP callback - $callback = $this->arg('callback'); - if ($callback) { - print $callback . '('; - } - break; - case 'rss': - header("Content-Type: application/rss+xml; charset=utf-8"); - $this->initTwitterRss(); - break; - case 'atom': - header('Content-Type: application/atom+xml; charset=utf-8'); - $this->initTwitterAtom(); - break; - default: - $this->clientError(_('Not a supported data format.')); - break; - } - - return; - } - - function endDocument($type='xml') - { - switch ($type) { - case 'xml': - $this->endXML(); - break; - case 'json': - - // Check for JSONP callback - $callback = $this->arg('callback'); - if ($callback) { - print ')'; - } - break; - case 'rss': - $this->endTwitterRss(); - break; - case 'atom': - $this->endTwitterRss(); - break; - default: - $this->clientError(_('Not a supported data format.')); - break; - } - return; - } - - function clientError($msg, $code = 400, $format = 'xml') - { - $action = $this->trimmed('action'); - - common_debug("User error '$code' on '$action': $msg", __FILE__); - - if (!array_key_exists($code, ClientErrorAction::$status)) { - $code = 400; - } - - $status_string = ClientErrorAction::$status[$code]; - - header('HTTP/1.1 '.$code.' '.$status_string); - - if ($format == 'xml') { - $this->initDocument('xml'); - $this->elementStart('hash'); - $this->element('error', null, $msg); - $this->element('request', null, $_SERVER['REQUEST_URI']); - $this->elementEnd('hash'); - $this->endDocument('xml'); - } elseif ($format == 'json'){ - $this->initDocument('json'); - $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']); - print(json_encode($error_array)); - $this->endDocument('json'); - } else { - - // If user didn't request a useful format, throw a regular client error - throw new ClientException($msg, $code); - } - } - - function serverError($msg, $code = 500, $content_type = 'xml') - { - $action = $this->trimmed('action'); - - common_debug("Server error '$code' on '$action': $msg", __FILE__); - - if (!array_key_exists($code, ServerErrorAction::$status)) { - $code = 400; - } - - $status_string = ServerErrorAction::$status[$code]; - - header('HTTP/1.1 '.$code.' '.$status_string); - - if ($content_type == 'xml') { - $this->initDocument('xml'); - $this->elementStart('hash'); - $this->element('error', null, $msg); - $this->element('request', null, $_SERVER['REQUEST_URI']); - $this->elementEnd('hash'); - $this->endDocument('xml'); - } else { - $this->initDocument('json'); - $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']); - print(json_encode($error_array)); - $this->endDocument('json'); - } - } - - function initTwitterRss() - { - $this->startXML(); - $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom')); - $this->elementStart('channel'); - Event::handle('StartApiRss', array($this)); - } - - function endTwitterRss() - { - $this->elementEnd('channel'); - $this->elementEnd('rss'); - $this->endXML(); - } - - function initTwitterAtom() - { - $this->startXML(); - // FIXME: don't hardcode the language here! - $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom', - 'xml:lang' => 'en-US', - 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0')); - } - - function endTwitterAtom() - { - $this->elementEnd('feed'); - $this->endXML(); - } - - function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true) - { - $profile_array = $this->twitterUserArray($profile, $includeStatuses); - switch ($content_type) { - case 'xml': - $this->showTwitterXmlUser($profile_array); - break; - case 'json': - $this->showJsonObjects($profile_array); - break; - default: - $this->clientError(_('Not a supported data format.')); - return; - } - return; - } - - function getTargetUser($id) - { - if (empty($id)) { - - // Twitter supports these other ways of passing the user ID - if (is_numeric($this->arg('id'))) { - return User::staticGet($this->arg('id')); - } else if ($this->arg('id')) { - $nickname = common_canonical_nickname($this->arg('id')); - return User::staticGet('nickname', $nickname); - } else if ($this->arg('user_id')) { - // This is to ensure that a non-numeric user_id still - // overrides screen_name even if it doesn't get used - if (is_numeric($this->arg('user_id'))) { - return User::staticGet('id', $this->arg('user_id')); - } - } else if ($this->arg('screen_name')) { - $nickname = common_canonical_nickname($this->arg('screen_name')); - return User::staticGet('nickname', $nickname); - } else { - // Fall back to trying the currently authenticated user - return $this->auth_user; - } - - } else if (is_numeric($id)) { - return User::staticGet($id); - } else { - $nickname = common_canonical_nickname($id); - return User::staticGet('nickname', $nickname); - } - } - - function getTargetGroup($id) - { - if (empty($id)) { - if (is_numeric($this->arg('id'))) { - return User_group::staticGet($this->arg('id')); - } else if ($this->arg('id')) { - $nickname = common_canonical_nickname($this->arg('id')); - $local = Local_group::staticGet('nickname', $nickname); - if (empty($local)) { - return null; - } else { - return User_group::staticGet('id', $local->id); - } - } else if ($this->arg('group_id')) { - // This is to ensure that a non-numeric user_id still - // overrides screen_name even if it doesn't get used - if (is_numeric($this->arg('group_id'))) { - return User_group::staticGet('id', $this->arg('group_id')); - } - } else if ($this->arg('group_name')) { - $nickname = common_canonical_nickname($this->arg('group_name')); - $local = Local_group::staticGet('nickname', $nickname); - if (empty($local)) { - return null; - } else { - return User_group::staticGet('id', $local->id); - } - } - - } else if (is_numeric($id)) { - return User_group::staticGet($id); - } else { - $nickname = common_canonical_nickname($id); - $local = Local_group::staticGet('nickname', $nickname); - if (empty($local)) { - return null; - } else { - return User_group::staticGet('id', $local->id); - } - } - } - - function sourceLink($source) - { - $source_name = _($source); - switch ($source) { - case 'web': - case 'xmpp': - case 'mail': - case 'omb': - case 'api': - break; - default: - - $name = null; - $url = null; - - $ns = Notice_source::staticGet($source); - - if ($ns) { - $name = $ns->name; - $url = $ns->url; - } else { - $app = Oauth_application::staticGet('name', $source); - if ($app) { - $name = $app->name; - $url = $app->source_url; - } - } - - if (!empty($name) && !empty($url)) { - $source_name = '' . $name . ''; - } - - break; - } - return $source_name; - } - - /** - * Returns query argument or default value if not found. Certain - * parameters used throughout the API are lightly scrubbed and - * bounds checked. This overrides Action::arg(). - * - * @param string $key requested argument - * @param string $def default value to return if $key is not provided - * - * @return var $var - */ - function arg($key, $def=null) - { - - // XXX: Do even more input validation/scrubbing? - - if (array_key_exists($key, $this->args)) { - switch($key) { - case 'page': - $page = (int)$this->args['page']; - return ($page < 1) ? 1 : $page; - case 'count': - $count = (int)$this->args['count']; - if ($count < 1) { - return 20; - } elseif ($count > 200) { - return 200; - } else { - return $count; - } - case 'since_id': - $since_id = (int)$this->args['since_id']; - return ($since_id < 1) ? 0 : $since_id; - case 'max_id': - $max_id = (int)$this->args['max_id']; - return ($max_id < 1) ? 0 : $max_id; - case 'since': - return strtotime($this->args['since']); - default: - return parent::arg($key, $def); - } - } else { - return $def; - } - } - - function getSelfUri($action, $aargs) - { - parse_str($_SERVER['QUERY_STRING'], $params); - $pstring = ''; - if (!empty($params)) { - unset($params['p']); - $pstring = http_build_query($params); - } - - $uri = common_local_url($action, $aargs); - - if (!empty($pstring)) { - $uri .= '?' . $pstring; - } - - return $uri; - } - -} diff --git a/lib/apiaction.php b/lib/apiaction.php new file mode 100644 index 000000000..d79dc327e --- /dev/null +++ b/lib/apiaction.php @@ -0,0 +1,1356 @@ +. + * + * @category API + * @package StatusNet + * @author Craig Andrews + * @author Dan Moore + * @author Evan Prodromou + * @author Jeffery To + * @author Toby Inkster + * @author Zach Copley + * @copyright 2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +/** + * Contains most of the Twitter-compatible API output functions. + * + * @category API + * @package StatusNet + * @author Craig Andrews + * @author Dan Moore + * @author Evan Prodromou + * @author Jeffery To + * @author Toby Inkster + * @author Zach Copley + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +class ApiAction extends Action +{ + const READ_ONLY = 1; + const READ_WRITE = 2; + + var $format = null; + var $user = null; + var $auth_user = null; + var $page = null; + var $count = null; + var $max_id = null; + var $since_id = null; + var $since = null; + + var $access = self::READ_ONLY; // read (default) or read-write + + /** + * Initialization. + * + * @param array $args Web and URL arguments + * + * @return boolean false if user doesn't exist + */ + + function prepare($args) + { + StatusNet::setApi(true); // reduce exception reports to aid in debugging + parent::prepare($args); + + $this->format = $this->arg('format'); + $this->page = (int)$this->arg('page', 1); + $this->count = (int)$this->arg('count', 20); + $this->max_id = (int)$this->arg('max_id', 0); + $this->since_id = (int)$this->arg('since_id', 0); + $this->since = $this->arg('since'); + + return true; + } + + /** + * Handle a request + * + * @param array $args Arguments from $_REQUEST + * + * @return void + */ + + function handle($args) + { + parent::handle($args); + } + + /** + * Overrides XMLOutputter::element to write booleans as strings (true|false). + * See that method's documentation for more info. + * + * @param string $tag Element type or tagname + * @param array $attrs Array of element attributes, as + * key-value pairs + * @param string $content string content of the element + * + * @return void + */ + function element($tag, $attrs=null, $content=null) + { + if (is_bool($content)) { + $content = ($content ? 'true' : 'false'); + } + + return parent::element($tag, $attrs, $content); + } + + function twitterUserArray($profile, $get_notice=false) + { + $twitter_user = array(); + + $twitter_user['id'] = intval($profile->id); + $twitter_user['name'] = $profile->getBestName(); + $twitter_user['screen_name'] = $profile->nickname; + $twitter_user['location'] = ($profile->location) ? $profile->location : null; + $twitter_user['description'] = ($profile->bio) ? $profile->bio : null; + + $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); + $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() : + Avatar::defaultImage(AVATAR_STREAM_SIZE); + + $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null; + $twitter_user['protected'] = false; # not supported by StatusNet yet + $twitter_user['followers_count'] = $profile->subscriberCount(); + + $design = null; + $user = $profile->getUser(); + + // Note: some profiles don't have an associated user + + $defaultDesign = Design::siteDesign(); + + if (!empty($user)) { + $design = $user->getDesign(); + } + + if (empty($design)) { + $design = $defaultDesign; + } + + $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor); + $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue(); + $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor); + $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue(); + $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor); + $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue(); + $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor); + $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue(); + $twitter_user['profile_sidebar_border_color'] = ''; + + $twitter_user['friends_count'] = $profile->subscriptionCount(); + + $twitter_user['created_at'] = $this->dateTwitter($profile->created); + + $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling! + + $timezone = 'UTC'; + + if (!empty($user) && $user->timezone) { + $timezone = $user->timezone; + } + + $t = new DateTime; + $t->setTimezone(new DateTimeZone($timezone)); + + $twitter_user['utc_offset'] = $t->format('Z'); + $twitter_user['time_zone'] = $timezone; + + $twitter_user['profile_background_image_url'] + = empty($design->backgroundimage) + ? '' : ($design->disposition & BACKGROUND_ON) + ? Design::url($design->backgroundimage) : ''; + + $twitter_user['profile_background_tile'] + = empty($design->disposition) + ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false'; + + $twitter_user['statuses_count'] = $profile->noticeCount(); + + // Is the requesting user following this user? + $twitter_user['following'] = false; + $twitter_user['notifications'] = false; + + if (isset($this->auth_user)) { + + $twitter_user['following'] = $this->auth_user->isSubscribed($profile); + + // Notifications on? + $sub = Subscription::pkeyGet(array('subscriber' => + $this->auth_user->id, + 'subscribed' => $profile->id)); + + if ($sub) { + $twitter_user['notifications'] = ($sub->jabber || $sub->sms); + } + } + + if ($get_notice) { + $notice = $profile->getCurrentNotice(); + if ($notice) { + # don't get user! + $twitter_user['status'] = $this->twitterStatusArray($notice, false); + } + } + + return $twitter_user; + } + + function twitterStatusArray($notice, $include_user=true) + { + $base = $this->twitterSimpleStatusArray($notice, $include_user); + + if (!empty($notice->repeat_of)) { + $original = Notice::staticGet('id', $notice->repeat_of); + if (!empty($original)) { + $original_array = $this->twitterSimpleStatusArray($original, $include_user); + $base['retweeted_status'] = $original_array; + } + } + + return $base; + } + + function twitterSimpleStatusArray($notice, $include_user=true) + { + $profile = $notice->getProfile(); + + $twitter_status = array(); + $twitter_status['text'] = $notice->content; + $twitter_status['truncated'] = false; # Not possible on StatusNet + $twitter_status['created_at'] = $this->dateTwitter($notice->created); + $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ? + intval($notice->reply_to) : null; + $twitter_status['source'] = $this->sourceLink($notice->source); + $twitter_status['id'] = intval($notice->id); + + $replier_profile = null; + + if ($notice->reply_to) { + $reply = Notice::staticGet(intval($notice->reply_to)); + if ($reply) { + $replier_profile = $reply->getProfile(); + } + } + + $twitter_status['in_reply_to_user_id'] = + ($replier_profile) ? intval($replier_profile->id) : null; + $twitter_status['in_reply_to_screen_name'] = + ($replier_profile) ? $replier_profile->nickname : null; + + if (isset($notice->lat) && isset($notice->lon)) { + // This is the format that GeoJSON expects stuff to be in + $twitter_status['geo'] = array('type' => 'Point', + 'coordinates' => array((float) $notice->lat, + (float) $notice->lon)); + } else { + $twitter_status['geo'] = null; + } + + if (isset($this->auth_user)) { + $twitter_status['favorited'] = $this->auth_user->hasFave($notice); + } else { + $twitter_status['favorited'] = false; + } + + // Enclosures + $attachments = $notice->attachments(); + + if (!empty($attachments)) { + + $twitter_status['attachments'] = array(); + + foreach ($attachments as $attachment) { + if ($attachment->isEnclosure()) { + $enclosure = array(); + $enclosure['url'] = $attachment->url; + $enclosure['mimetype'] = $attachment->mimetype; + $enclosure['size'] = $attachment->size; + $twitter_status['attachments'][] = $enclosure; + } + } + } + + if ($include_user && $profile) { + # Don't get notice (recursive!) + $twitter_user = $this->twitterUserArray($profile, false); + $twitter_status['user'] = $twitter_user; + } + + return $twitter_status; + } + + function twitterGroupArray($group) + { + $twitter_group=array(); + $twitter_group['id']=$group->id; + $twitter_group['url']=$group->permalink(); + $twitter_group['nickname']=$group->nickname; + $twitter_group['fullname']=$group->fullname; + $twitter_group['homepage_url']=$group->homepage_url; + $twitter_group['original_logo']=$group->original_logo; + $twitter_group['homepage_logo']=$group->homepage_logo; + $twitter_group['stream_logo']=$group->stream_logo; + $twitter_group['mini_logo']=$group->mini_logo; + $twitter_group['homepage']=$group->homepage; + $twitter_group['description']=$group->description; + $twitter_group['location']=$group->location; + $twitter_group['created']=$this->dateTwitter($group->created); + $twitter_group['modified']=$this->dateTwitter($group->modified); + return $twitter_group; + } + + function twitterRssGroupArray($group) + { + $entry = array(); + $entry['content']=$group->description; + $entry['title']=$group->nickname; + $entry['link']=$group->permalink(); + $entry['published']=common_date_iso8601($group->created); + $entry['updated']==common_date_iso8601($group->modified); + $taguribase = common_config('integration', 'groupuri'); + $entry['id'] = "group:$groupuribase:$entry[link]"; + + $entry['description'] = $entry['content']; + $entry['pubDate'] = common_date_rfc2822($group->created); + $entry['guid'] = $entry['link']; + + return $entry; + } + + function twitterRssEntryArray($notice) + { + $profile = $notice->getProfile(); + $entry = array(); + + // We trim() to avoid extraneous whitespace in the output + + $entry['content'] = common_xml_safe_str(trim($notice->rendered)); + $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content)); + $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id)); + $entry['published'] = common_date_iso8601($notice->created); + + $taguribase = TagURI::base(); + $entry['id'] = "tag:$taguribase:$entry[link]"; + + $entry['updated'] = $entry['published']; + $entry['author'] = $profile->getBestName(); + + // Enclosures + $attachments = $notice->attachments(); + $enclosures = array(); + + foreach ($attachments as $attachment) { + $enclosure_o=$attachment->getEnclosure(); + if ($enclosure_o) { + $enclosure = array(); + $enclosure['url'] = $enclosure_o->url; + $enclosure['mimetype'] = $enclosure_o->mimetype; + $enclosure['size'] = $enclosure_o->size; + $enclosures[] = $enclosure; + } + } + + if (!empty($enclosures)) { + $entry['enclosures'] = $enclosures; + } + + // Tags/Categories + $tag = new Notice_tag(); + $tag->notice_id = $notice->id; + if ($tag->find()) { + $entry['tags']=array(); + while ($tag->fetch()) { + $entry['tags'][]=$tag->tag; + } + } + $tag->free(); + + // RSS Item specific + $entry['description'] = $entry['content']; + $entry['pubDate'] = common_date_rfc2822($notice->created); + $entry['guid'] = $entry['link']; + + if (isset($notice->lat) && isset($notice->lon)) { + // This is the format that GeoJSON expects stuff to be in. + // showGeoRSS() below uses it for XML output, so we reuse it + $entry['geo'] = array('type' => 'Point', + 'coordinates' => array((float) $notice->lat, + (float) $notice->lon)); + } else { + $entry['geo'] = null; + } + + return $entry; + } + + function twitterRelationshipArray($source, $target) + { + $relationship = array(); + + $relationship['source'] = + $this->relationshipDetailsArray($source, $target); + $relationship['target'] = + $this->relationshipDetailsArray($target, $source); + + return array('relationship' => $relationship); + } + + function relationshipDetailsArray($source, $target) + { + $details = array(); + + $details['screen_name'] = $source->nickname; + $details['followed_by'] = $target->isSubscribed($source); + $details['following'] = $source->isSubscribed($target); + + $notifications = false; + + if ($source->isSubscribed($target)) { + + $sub = Subscription::pkeyGet(array('subscriber' => + $source->id, 'subscribed' => $target->id)); + + if (!empty($sub)) { + $notifications = ($sub->jabber || $sub->sms); + } + } + + $details['notifications_enabled'] = $notifications; + $details['blocking'] = $source->hasBlocked($target); + $details['id'] = $source->id; + + return $details; + } + + function showTwitterXmlRelationship($relationship) + { + $this->elementStart('relationship'); + + foreach($relationship as $element => $value) { + if ($element == 'source' || $element == 'target') { + $this->elementStart($element); + $this->showXmlRelationshipDetails($value); + $this->elementEnd($element); + } + } + + $this->elementEnd('relationship'); + } + + function showXmlRelationshipDetails($details) + { + foreach($details as $element => $value) { + $this->element($element, null, $value); + } + } + + function showTwitterXmlStatus($twitter_status, $tag='status') + { + $this->elementStart($tag); + foreach($twitter_status as $element => $value) { + switch ($element) { + case 'user': + $this->showTwitterXmlUser($twitter_status['user']); + break; + case 'text': + $this->element($element, null, common_xml_safe_str($value)); + break; + case 'attachments': + $this->showXmlAttachments($twitter_status['attachments']); + break; + case 'geo': + $this->showGeoRSS($value); + break; + case 'retweeted_status': + $this->showTwitterXmlStatus($value, 'retweeted_status'); + break; + default: + $this->element($element, null, $value); + } + } + $this->elementEnd($tag); + } + + function showTwitterXmlGroup($twitter_group) + { + $this->elementStart('group'); + foreach($twitter_group as $element => $value) { + $this->element($element, null, $value); + } + $this->elementEnd('group'); + } + + function showTwitterXmlUser($twitter_user, $role='user') + { + $this->elementStart($role); + foreach($twitter_user as $element => $value) { + if ($element == 'status') { + $this->showTwitterXmlStatus($twitter_user['status']); + } else { + $this->element($element, null, $value); + } + } + $this->elementEnd($role); + } + + function showXmlAttachments($attachments) { + if (!empty($attachments)) { + $this->elementStart('attachments', array('type' => 'array')); + foreach ($attachments as $attachment) { + $attrs = array(); + $attrs['url'] = $attachment['url']; + $attrs['mimetype'] = $attachment['mimetype']; + $attrs['size'] = $attachment['size']; + $this->element('enclosure', $attrs, ''); + } + $this->elementEnd('attachments'); + } + } + + function showGeoRSS($geo) + { + if (empty($geo)) { + // empty geo element + $this->element('geo'); + } else { + $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss')); + $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]); + $this->elementEnd('geo'); + } + } + + function showTwitterRssItem($entry) + { + $this->elementStart('item'); + $this->element('title', null, $entry['title']); + $this->element('description', null, $entry['description']); + $this->element('pubDate', null, $entry['pubDate']); + $this->element('guid', null, $entry['guid']); + $this->element('link', null, $entry['link']); + + # RSS only supports 1 enclosure per item + if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){ + $enclosure = $entry['enclosures'][0]; + $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null); + } + + if(array_key_exists('tags', $entry)){ + foreach($entry['tags'] as $tag){ + $this->element('category', null,$tag); + } + } + + $this->showGeoRSS($entry['geo']); + $this->elementEnd('item'); + } + + function showJsonObjects($objects) + { + print(json_encode($objects)); + } + + function showSingleXmlStatus($notice) + { + $this->initDocument('xml'); + $twitter_status = $this->twitterStatusArray($notice); + $this->showTwitterXmlStatus($twitter_status); + $this->endDocument('xml'); + } + + function show_single_json_status($notice) + { + $this->initDocument('json'); + $status = $this->twitterStatusArray($notice); + $this->showJsonObjects($status); + $this->endDocument('json'); + } + + function showXmlTimeline($notice) + { + + $this->initDocument('xml'); + $this->elementStart('statuses', array('type' => 'array')); + + if (is_array($notice)) { + foreach ($notice as $n) { + $twitter_status = $this->twitterStatusArray($n); + $this->showTwitterXmlStatus($twitter_status); + } + } else { + while ($notice->fetch()) { + $twitter_status = $this->twitterStatusArray($notice); + $this->showTwitterXmlStatus($twitter_status); + } + } + + $this->elementEnd('statuses'); + $this->endDocument('xml'); + } + + function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null) + { + + $this->initDocument('rss'); + + $this->element('title', null, $title); + $this->element('link', null, $link); + if (!is_null($suplink)) { + // For FriendFeed's SUP protocol + $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom', + 'rel' => 'http://api.friendfeed.com/2008/03#sup', + 'href' => $suplink, + 'type' => 'application/json')); + } + + if (!is_null($logo)) { + $this->elementStart('image'); + $this->element('link', null, $link); + $this->element('title', null, $title); + $this->element('url', null, $logo); + $this->elementEnd('image'); + } + + $this->element('description', null, $subtitle); + $this->element('language', null, 'en-us'); + $this->element('ttl', null, '40'); + + if (is_array($notice)) { + foreach ($notice as $n) { + $entry = $this->twitterRssEntryArray($n); + $this->showTwitterRssItem($entry); + } + } else { + while ($notice->fetch()) { + $entry = $this->twitterRssEntryArray($notice); + $this->showTwitterRssItem($entry); + } + } + + $this->endTwitterRss(); + } + + function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null) + { + + $this->initDocument('atom'); + + $this->element('title', null, $title); + $this->element('id', null, $id); + $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null); + + if (!is_null($logo)) { + $this->element('logo',null,$logo); + } + + if (!is_null($suplink)) { + # For FriendFeed's SUP protocol + $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup', + 'href' => $suplink, + 'type' => 'application/json')); + } + + if (!is_null($selfuri)) { + $this->element('link', array('href' => $selfuri, + 'rel' => 'self', 'type' => 'application/atom+xml'), null); + } + + $this->element('updated', null, common_date_iso8601('now')); + $this->element('subtitle', null, $subtitle); + + if (is_array($notice)) { + foreach ($notice as $n) { + $this->raw($n->asAtomEntry()); + } + } else { + while ($notice->fetch()) { + $this->raw($notice->asAtomEntry()); + } + } + + $this->endDocument('atom'); + + } + + function showRssGroups($group, $title, $link, $subtitle) + { + + $this->initDocument('rss'); + + $this->element('title', null, $title); + $this->element('link', null, $link); + $this->element('description', null, $subtitle); + $this->element('language', null, 'en-us'); + $this->element('ttl', null, '40'); + + if (is_array($group)) { + foreach ($group as $g) { + $twitter_group = $this->twitterRssGroupArray($g); + $this->showTwitterRssItem($twitter_group); + } + } else { + while ($group->fetch()) { + $twitter_group = $this->twitterRssGroupArray($group); + $this->showTwitterRssItem($twitter_group); + } + } + + $this->endTwitterRss(); + } + + function showTwitterAtomEntry($entry) + { + $this->elementStart('entry'); + $this->element('title', null, $entry['title']); + $this->element('content', array('type' => 'html'), $entry['content']); + $this->element('id', null, $entry['id']); + $this->element('published', null, $entry['published']); + $this->element('updated', null, $entry['updated']); + $this->element('link', array('type' => 'text/html', + 'href' => $entry['link'], + 'rel' => 'alternate')); + $this->element('link', array('type' => $entry['avatar-type'], + 'href' => $entry['avatar'], + 'rel' => 'image')); + $this->elementStart('author'); + + $this->element('name', null, $entry['author-name']); + $this->element('uri', null, $entry['author-uri']); + + $this->elementEnd('author'); + $this->elementEnd('entry'); + } + + function showXmlDirectMessage($dm) + { + $this->elementStart('direct_message'); + foreach($dm as $element => $value) { + switch ($element) { + case 'sender': + case 'recipient': + $this->showTwitterXmlUser($value, $element); + break; + case 'text': + $this->element($element, null, common_xml_safe_str($value)); + break; + default: + $this->element($element, null, $value); + break; + } + } + $this->elementEnd('direct_message'); + } + + function directMessageArray($message) + { + $dmsg = array(); + + $from_profile = $message->getFrom(); + $to_profile = $message->getTo(); + + $dmsg['id'] = $message->id; + $dmsg['sender_id'] = $message->from_profile; + $dmsg['text'] = trim($message->content); + $dmsg['recipient_id'] = $message->to_profile; + $dmsg['created_at'] = $this->dateTwitter($message->created); + $dmsg['sender_screen_name'] = $from_profile->nickname; + $dmsg['recipient_screen_name'] = $to_profile->nickname; + $dmsg['sender'] = $this->twitterUserArray($from_profile, false); + $dmsg['recipient'] = $this->twitterUserArray($to_profile, false); + + return $dmsg; + } + + function rssDirectMessageArray($message) + { + $entry = array(); + + $from = $message->getFrom(); + + $entry['title'] = sprintf('Message from %1$s to %2$s', + $from->nickname, $message->getTo()->nickname); + + $entry['content'] = common_xml_safe_str($message->rendered); + $entry['link'] = common_local_url('showmessage', array('message' => $message->id)); + $entry['published'] = common_date_iso8601($message->created); + + $taguribase = TagURI::base(); + + $entry['id'] = "tag:$taguribase:$entry[link]"; + $entry['updated'] = $entry['published']; + + $entry['author-name'] = $from->getBestName(); + $entry['author-uri'] = $from->homepage; + + $avatar = $from->getAvatar(AVATAR_STREAM_SIZE); + + $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE); + $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png'; + + // RSS item specific + + $entry['description'] = $entry['content']; + $entry['pubDate'] = common_date_rfc2822($message->created); + $entry['guid'] = $entry['link']; + + return $entry; + } + + function showSingleXmlDirectMessage($message) + { + $this->initDocument('xml'); + $dmsg = $this->directMessageArray($message); + $this->showXmlDirectMessage($dmsg); + $this->endDocument('xml'); + } + + function showSingleJsonDirectMessage($message) + { + $this->initDocument('json'); + $dmsg = $this->directMessageArray($message); + $this->showJsonObjects($dmsg); + $this->endDocument('json'); + } + + function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null) + { + + $this->initDocument('atom'); + + $this->element('title', null, $title); + $this->element('id', null, $id); + $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null); + + if (!is_null($selfuri)) { + $this->element('link', array('href' => $selfuri, + 'rel' => 'self', 'type' => 'application/atom+xml'), null); + } + + $this->element('updated', null, common_date_iso8601('now')); + $this->element('subtitle', null, $subtitle); + + if (is_array($group)) { + foreach ($group as $g) { + $this->raw($g->asAtomEntry()); + } + } else { + while ($group->fetch()) { + $this->raw($group->asAtomEntry()); + } + } + + $this->endDocument('atom'); + + } + + function showJsonTimeline($notice) + { + + $this->initDocument('json'); + + $statuses = array(); + + if (is_array($notice)) { + foreach ($notice as $n) { + $twitter_status = $this->twitterStatusArray($n); + array_push($statuses, $twitter_status); + } + } else { + while ($notice->fetch()) { + $twitter_status = $this->twitterStatusArray($notice); + array_push($statuses, $twitter_status); + } + } + + $this->showJsonObjects($statuses); + + $this->endDocument('json'); + } + + function showJsonGroups($group) + { + + $this->initDocument('json'); + + $groups = array(); + + if (is_array($group)) { + foreach ($group as $g) { + $twitter_group = $this->twitterGroupArray($g); + array_push($groups, $twitter_group); + } + } else { + while ($group->fetch()) { + $twitter_group = $this->twitterGroupArray($group); + array_push($groups, $twitter_group); + } + } + + $this->showJsonObjects($groups); + + $this->endDocument('json'); + } + + function showXmlGroups($group) + { + + $this->initDocument('xml'); + $this->elementStart('groups', array('type' => 'array')); + + if (is_array($group)) { + foreach ($group as $g) { + $twitter_group = $this->twitterGroupArray($g); + $this->showTwitterXmlGroup($twitter_group); + } + } else { + while ($group->fetch()) { + $twitter_group = $this->twitterGroupArray($group); + $this->showTwitterXmlGroup($twitter_group); + } + } + + $this->elementEnd('groups'); + $this->endDocument('xml'); + } + + function showTwitterXmlUsers($user) + { + + $this->initDocument('xml'); + $this->elementStart('users', array('type' => 'array')); + + if (is_array($user)) { + foreach ($user as $u) { + $twitter_user = $this->twitterUserArray($u); + $this->showTwitterXmlUser($twitter_user); + } + } else { + while ($user->fetch()) { + $twitter_user = $this->twitterUserArray($user); + $this->showTwitterXmlUser($twitter_user); + } + } + + $this->elementEnd('users'); + $this->endDocument('xml'); + } + + function showJsonUsers($user) + { + + $this->initDocument('json'); + + $users = array(); + + if (is_array($user)) { + foreach ($user as $u) { + $twitter_user = $this->twitterUserArray($u); + array_push($users, $twitter_user); + } + } else { + while ($user->fetch()) { + $twitter_user = $this->twitterUserArray($user); + array_push($users, $twitter_user); + } + } + + $this->showJsonObjects($users); + + $this->endDocument('json'); + } + + function showSingleJsonGroup($group) + { + $this->initDocument('json'); + $twitter_group = $this->twitterGroupArray($group); + $this->showJsonObjects($twitter_group); + $this->endDocument('json'); + } + + function showSingleXmlGroup($group) + { + $this->initDocument('xml'); + $twitter_group = $this->twitterGroupArray($group); + $this->showTwitterXmlGroup($twitter_group); + $this->endDocument('xml'); + } + + function dateTwitter($dt) + { + $dateStr = date('d F Y H:i:s', strtotime($dt)); + $d = new DateTime($dateStr, new DateTimeZone('UTC')); + $d->setTimezone(new DateTimeZone(common_timezone())); + return $d->format('D M d H:i:s O Y'); + } + + function initDocument($type='xml') + { + switch ($type) { + case 'xml': + header('Content-Type: application/xml; charset=utf-8'); + $this->startXML(); + break; + case 'json': + header('Content-Type: application/json; charset=utf-8'); + + // Check for JSONP callback + $callback = $this->arg('callback'); + if ($callback) { + print $callback . '('; + } + break; + case 'rss': + header("Content-Type: application/rss+xml; charset=utf-8"); + $this->initTwitterRss(); + break; + case 'atom': + header('Content-Type: application/atom+xml; charset=utf-8'); + $this->initTwitterAtom(); + break; + default: + $this->clientError(_('Not a supported data format.')); + break; + } + + return; + } + + function endDocument($type='xml') + { + switch ($type) { + case 'xml': + $this->endXML(); + break; + case 'json': + + // Check for JSONP callback + $callback = $this->arg('callback'); + if ($callback) { + print ')'; + } + break; + case 'rss': + $this->endTwitterRss(); + break; + case 'atom': + $this->endTwitterRss(); + break; + default: + $this->clientError(_('Not a supported data format.')); + break; + } + return; + } + + function clientError($msg, $code = 400, $format = 'xml') + { + $action = $this->trimmed('action'); + + common_debug("User error '$code' on '$action': $msg", __FILE__); + + if (!array_key_exists($code, ClientErrorAction::$status)) { + $code = 400; + } + + $status_string = ClientErrorAction::$status[$code]; + + header('HTTP/1.1 '.$code.' '.$status_string); + + if ($format == 'xml') { + $this->initDocument('xml'); + $this->elementStart('hash'); + $this->element('error', null, $msg); + $this->element('request', null, $_SERVER['REQUEST_URI']); + $this->elementEnd('hash'); + $this->endDocument('xml'); + } elseif ($format == 'json'){ + $this->initDocument('json'); + $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']); + print(json_encode($error_array)); + $this->endDocument('json'); + } else { + + // If user didn't request a useful format, throw a regular client error + throw new ClientException($msg, $code); + } + } + + function serverError($msg, $code = 500, $content_type = 'xml') + { + $action = $this->trimmed('action'); + + common_debug("Server error '$code' on '$action': $msg", __FILE__); + + if (!array_key_exists($code, ServerErrorAction::$status)) { + $code = 400; + } + + $status_string = ServerErrorAction::$status[$code]; + + header('HTTP/1.1 '.$code.' '.$status_string); + + if ($content_type == 'xml') { + $this->initDocument('xml'); + $this->elementStart('hash'); + $this->element('error', null, $msg); + $this->element('request', null, $_SERVER['REQUEST_URI']); + $this->elementEnd('hash'); + $this->endDocument('xml'); + } else { + $this->initDocument('json'); + $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']); + print(json_encode($error_array)); + $this->endDocument('json'); + } + } + + function initTwitterRss() + { + $this->startXML(); + $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom')); + $this->elementStart('channel'); + Event::handle('StartApiRss', array($this)); + } + + function endTwitterRss() + { + $this->elementEnd('channel'); + $this->elementEnd('rss'); + $this->endXML(); + } + + function initTwitterAtom() + { + $this->startXML(); + // FIXME: don't hardcode the language here! + $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom', + 'xml:lang' => 'en-US', + 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0')); + } + + function endTwitterAtom() + { + $this->elementEnd('feed'); + $this->endXML(); + } + + function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true) + { + $profile_array = $this->twitterUserArray($profile, $includeStatuses); + switch ($content_type) { + case 'xml': + $this->showTwitterXmlUser($profile_array); + break; + case 'json': + $this->showJsonObjects($profile_array); + break; + default: + $this->clientError(_('Not a supported data format.')); + return; + } + return; + } + + function getTargetUser($id) + { + if (empty($id)) { + + // Twitter supports these other ways of passing the user ID + if (is_numeric($this->arg('id'))) { + return User::staticGet($this->arg('id')); + } else if ($this->arg('id')) { + $nickname = common_canonical_nickname($this->arg('id')); + return User::staticGet('nickname', $nickname); + } else if ($this->arg('user_id')) { + // This is to ensure that a non-numeric user_id still + // overrides screen_name even if it doesn't get used + if (is_numeric($this->arg('user_id'))) { + return User::staticGet('id', $this->arg('user_id')); + } + } else if ($this->arg('screen_name')) { + $nickname = common_canonical_nickname($this->arg('screen_name')); + return User::staticGet('nickname', $nickname); + } else { + // Fall back to trying the currently authenticated user + return $this->auth_user; + } + + } else if (is_numeric($id)) { + return User::staticGet($id); + } else { + $nickname = common_canonical_nickname($id); + return User::staticGet('nickname', $nickname); + } + } + + function getTargetGroup($id) + { + if (empty($id)) { + if (is_numeric($this->arg('id'))) { + return User_group::staticGet($this->arg('id')); + } else if ($this->arg('id')) { + $nickname = common_canonical_nickname($this->arg('id')); + $local = Local_group::staticGet('nickname', $nickname); + if (empty($local)) { + return null; + } else { + return User_group::staticGet('id', $local->id); + } + } else if ($this->arg('group_id')) { + // This is to ensure that a non-numeric user_id still + // overrides screen_name even if it doesn't get used + if (is_numeric($this->arg('group_id'))) { + return User_group::staticGet('id', $this->arg('group_id')); + } + } else if ($this->arg('group_name')) { + $nickname = common_canonical_nickname($this->arg('group_name')); + $local = Local_group::staticGet('nickname', $nickname); + if (empty($local)) { + return null; + } else { + return User_group::staticGet('id', $local->id); + } + } + + } else if (is_numeric($id)) { + return User_group::staticGet($id); + } else { + $nickname = common_canonical_nickname($id); + $local = Local_group::staticGet('nickname', $nickname); + if (empty($local)) { + return null; + } else { + return User_group::staticGet('id', $local->id); + } + } + } + + function sourceLink($source) + { + $source_name = _($source); + switch ($source) { + case 'web': + case 'xmpp': + case 'mail': + case 'omb': + case 'api': + break; + default: + + $name = null; + $url = null; + + $ns = Notice_source::staticGet($source); + + if ($ns) { + $name = $ns->name; + $url = $ns->url; + } else { + $app = Oauth_application::staticGet('name', $source); + if ($app) { + $name = $app->name; + $url = $app->source_url; + } + } + + if (!empty($name) && !empty($url)) { + $source_name = '' . $name . ''; + } + + break; + } + return $source_name; + } + + /** + * Returns query argument or default value if not found. Certain + * parameters used throughout the API are lightly scrubbed and + * bounds checked. This overrides Action::arg(). + * + * @param string $key requested argument + * @param string $def default value to return if $key is not provided + * + * @return var $var + */ + function arg($key, $def=null) + { + + // XXX: Do even more input validation/scrubbing? + + if (array_key_exists($key, $this->args)) { + switch($key) { + case 'page': + $page = (int)$this->args['page']; + return ($page < 1) ? 1 : $page; + case 'count': + $count = (int)$this->args['count']; + if ($count < 1) { + return 20; + } elseif ($count > 200) { + return 200; + } else { + return $count; + } + case 'since_id': + $since_id = (int)$this->args['since_id']; + return ($since_id < 1) ? 0 : $since_id; + case 'max_id': + $max_id = (int)$this->args['max_id']; + return ($max_id < 1) ? 0 : $max_id; + case 'since': + return strtotime($this->args['since']); + default: + return parent::arg($key, $def); + } + } else { + return $def; + } + } + + function getSelfUri($action, $aargs) + { + parse_str($_SERVER['QUERY_STRING'], $params); + $pstring = ''; + if (!empty($params)) { + unset($params['p']); + $pstring = http_build_query($params); + } + + $uri = common_local_url($action, $aargs); + + if (!empty($pstring)) { + $uri .= '?' . $pstring; + } + + return $uri; + } + +} -- cgit v1.2.3-54-g00ecf From e650794300f48f75cc4a91ac86d7e7dd9e082136 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Thu, 25 Feb 2010 22:06:31 -0800 Subject: Remove unnecessary requires --- actions/apistatusnetconfig.php | 2 -- actions/twitapisearchatom.php | 2 -- actions/twitapisearchjson.php | 1 - actions/twitapitrends.php | 2 -- lib/apiauth.php | 1 - plugins/Mapstraction/map.php | 2 -- plugins/Realtime/RealtimePlugin.php | 2 -- 7 files changed, 12 deletions(-) diff --git a/actions/apistatusnetconfig.php b/actions/apistatusnetconfig.php index dc1ab8685..296376d19 100644 --- a/actions/apistatusnetconfig.php +++ b/actions/apistatusnetconfig.php @@ -32,8 +32,6 @@ if (!defined('STATUSNET')) { exit(1); } -require_once INSTALLDIR . '/lib/api.php'; - /** * Gives a full dump of configuration variables for this instance * of StatusNet, minus variables that may be security-sensitive (like diff --git a/actions/twitapisearchatom.php b/actions/twitapisearchatom.php index e389ddec8..24aa619bd 100644 --- a/actions/twitapisearchatom.php +++ b/actions/twitapisearchatom.php @@ -31,8 +31,6 @@ if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } -require_once INSTALLDIR.'/lib/api.php'; - /** * Action for outputting search results in Twitter compatible Atom * format. diff --git a/actions/twitapisearchjson.php b/actions/twitapisearchjson.php index 741ed78d6..b5c006aa7 100644 --- a/actions/twitapisearchjson.php +++ b/actions/twitapisearchjson.php @@ -31,7 +31,6 @@ if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } -require_once INSTALLDIR.'/lib/api.php'; require_once INSTALLDIR.'/lib/jsonsearchresultslist.php'; /** diff --git a/actions/twitapitrends.php b/actions/twitapitrends.php index 779405e6d..5a04569a2 100644 --- a/actions/twitapitrends.php +++ b/actions/twitapitrends.php @@ -31,8 +31,6 @@ if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } -require_once INSTALLDIR.'/lib/api.php'; - /** * Returns the top ten queries that are currently trending * diff --git a/lib/apiauth.php b/lib/apiauth.php index 25e2196cf..5090871cf 100644 --- a/lib/apiauth.php +++ b/lib/apiauth.php @@ -38,7 +38,6 @@ if (!defined('STATUSNET')) { exit(1); } -require_once INSTALLDIR . '/lib/api.php'; require_once INSTALLDIR . '/lib/apioauth.php'; /** diff --git a/plugins/Mapstraction/map.php b/plugins/Mapstraction/map.php index a33dfc736..b809c1b8e 100644 --- a/plugins/Mapstraction/map.php +++ b/plugins/Mapstraction/map.php @@ -142,8 +142,6 @@ class MapAction extends OwnerDesignAction // of refactoring from within a plugin, so I'm just abusing // the ApiAction method. Don't do this unless you're me! - require_once(INSTALLDIR.'/lib/api.php'); - $act = new ApiAction('/dev/null'); $arr = $act->twitterStatusArray($notice, true); diff --git a/plugins/Realtime/RealtimePlugin.php b/plugins/Realtime/RealtimePlugin.php index 6c212453e..2b3cb35f1 100644 --- a/plugins/Realtime/RealtimePlugin.php +++ b/plugins/Realtime/RealtimePlugin.php @@ -244,8 +244,6 @@ class RealtimePlugin extends Plugin // of refactoring from within a plugin, so I'm just abusing // the ApiAction method. Don't do this unless you're me! - require_once(INSTALLDIR.'/lib/api.php'); - $act = new ApiAction('/dev/null'); $arr = $act->twitterStatusArray($notice, true); -- cgit v1.2.3-54-g00ecf From 84d0c865c4c2dd597e249c76fa1429175f5461a1 Mon Sep 17 00:00:00 2001 From: James Walker Date: Fri, 26 Feb 2010 03:25:51 -0500 Subject: salmon actually fetching remote keypairs --- plugins/OStatus/OStatusPlugin.php | 14 ++++++++++++++ plugins/OStatus/actions/ostatusinit.php | 2 +- plugins/OStatus/lib/discovery.php | 34 +++++++++++++++++---------------- plugins/OStatus/lib/magicenvelope.php | 5 ++--- 4 files changed, 35 insertions(+), 20 deletions(-) diff --git a/plugins/OStatus/OStatusPlugin.php b/plugins/OStatus/OStatusPlugin.php index 91d055498..46f986682 100644 --- a/plugins/OStatus/OStatusPlugin.php +++ b/plugins/OStatus/OStatusPlugin.php @@ -102,6 +102,20 @@ class OStatusPlugin extends Plugin return true; } + /** + * Add a link header for LRDD Discovery + */ + function onStartShowHTML($action) + { + if ($action instanceof ShowstreamAction) { + $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server'); + $url = common_local_url('xrd'); + $url.= '?uri='. $acct; + + header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"'); + } + } + /** * Set up a PuSH hub link to our internal link for canonical timeline * Atom feeds for users and groups. diff --git a/plugins/OStatus/actions/ostatusinit.php b/plugins/OStatus/actions/ostatusinit.php index 5c8575595..8ba8dcdcc 100644 --- a/plugins/OStatus/actions/ostatusinit.php +++ b/plugins/OStatus/actions/ostatusinit.php @@ -144,7 +144,7 @@ class OStatusInitAction extends Action $user = User::staticGet('nickname', $this->nickname); $target_profile = common_local_url('userbyid', array('id' => $user->id)); - $url = $w->applyTemplate($link['template'], $target_profile); + $url = Discovery::applyTemplate($link['template'], $target_profile); common_log(LOG_INFO, "Sending remote subscriber $acct to $url"); common_redirect($url, 303); } diff --git a/plugins/OStatus/lib/discovery.php b/plugins/OStatus/lib/discovery.php index 8aba31328..c268ad05c 100644 --- a/plugins/OStatus/lib/discovery.php +++ b/plugins/OStatus/lib/discovery.php @@ -91,7 +91,6 @@ class Discovery foreach ($this->methods as $class) { $links = call_user_func(array($class, 'discover'), $uri); - if ($link = Discovery::getService($links, Discovery::LRDD_REL)) { // Load the LRDD XRD if ($link['template']) { @@ -141,7 +140,7 @@ class Discovery } return XRD::parse($response->getBody()); - } + } } interface Discovery_LRDD @@ -153,13 +152,12 @@ class Discovery_LRDD_Host_Meta implements Discovery_LRDD { public function discover($uri) { - if (Discovery::isWebfinger($uri)) { - // We have a webfinger acct: - start with host-meta - list($name, $domain) = explode('@', $id); - } else { - $domain = @parse_url($uri, PHP_URL_HOST); + if (!Discovery::isWebfinger($uri)) { + return false; } + // We have a webfinger acct: - start with host-meta + list($name, $domain) = explode('@', $uri); $url = 'http://'. $domain .'/.well-known/host-meta'; $xrd = Discovery::fetchXrd($url); @@ -180,27 +178,29 @@ class Discovery_LRDD_Link_Header implements Discovery_LRDD { try { $client = new HTTPClient(); - $response = $client->get($url); + $response = $client->get($uri); } catch (HTTP_Request2_Exception $e) { return false; } - + if ($response->getStatus() != 200) { return false; } $link_header = $response->getHeader('Link'); if (!$link_header) { - return false; + // return false; } - return Discovery_LRDD_Link_Header::parseHeader($header); + return Discovery_LRDD_Link_Header::parseHeader($link_header); } protected static function parseHeader($header) { preg_match('/^<[^>]+>/', $header, $uri_reference); - if (empty($uri_reference)) return; + //if (empty($uri_reference)) return; + + $links = array(); $link_uri = trim($uri_reference[0], '<>'); $link_rel = array(); @@ -210,7 +210,7 @@ class Discovery_LRDD_Link_Header implements Discovery_LRDD $header = substr($header, strlen($uri_reference[0])); // parse link-params - $params = explode($header, ';'); + $params = explode(';', $header); foreach ($params as $param) { if (empty($param)) continue; @@ -229,11 +229,13 @@ class Discovery_LRDD_Link_Header implements Discovery_LRDD $link_type = trim($param_value); } } - - return array( + + $links[] = array( 'href' => $link_uri, 'rel' => $link_rel, 'type' => $link_type); + + return $links; } } @@ -243,7 +245,7 @@ class Discovery_LRDD_Link_HTML implements Discovery_LRDD { try { $client = new HTTPClient(); - $response = $client->get($url); + $response = $client->get($uri); } catch (HTTP_Request2_Exception $e) { return false; } diff --git a/plugins/OStatus/lib/magicenvelope.php b/plugins/OStatus/lib/magicenvelope.php index 4f8f88155..c642af548 100644 --- a/plugins/OStatus/lib/magicenvelope.php +++ b/plugins/OStatus/lib/magicenvelope.php @@ -52,14 +52,13 @@ class MagicEnvelope { $disco = new Discovery(); - $links = $disco->lookup($signer_uri); - if ($link = Discovery::getService($links, 'magic-public-key')) { + $xrd = $disco->lookup($signer_uri); + if ($link = Discovery::getService($xrd->links, Magicsig::PUBLICKEYREL)) { list($type, $keypair) = explode(';', $link['href']); return $keypair; } throw new Exception('Unable to locate signer public key'); - //return 'RSA.79_L2gq-TD72Nsb5yGS0r9stLLpJZF5AHXyxzWmQmlqKl276LEJEs8CppcerLcR90MbYQUwt-SX9slx40Yq3vA==.AQAB.AR-jo5KMfSISmDAT2iMs2_vNFgWRjl5rbJVvA0SpGIEWyPdCGxlPtCbTexp8-0ZEIe8a4SyjatBECH5hxgMTpw=='; } -- cgit v1.2.3-54-g00ecf From 22062b665e6d883f5ddfe590af1b9b22833094b0 Mon Sep 17 00:00:00 2001 From: James Walker Date: Fri, 26 Feb 2010 03:28:29 -0500 Subject: remove webfinger.php --- plugins/OStatus/lib/webfinger.php | 164 -------------------------------------- 1 file changed, 164 deletions(-) delete mode 100644 plugins/OStatus/lib/webfinger.php diff --git a/plugins/OStatus/lib/webfinger.php b/plugins/OStatus/lib/webfinger.php deleted file mode 100644 index 4b777c9a0..000000000 --- a/plugins/OStatus/lib/webfinger.php +++ /dev/null @@ -1,164 +0,0 @@ -. - * - * @package StatusNet - * @author James Walker - * @copyright 2010 StatusNet, Inc. - * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 - * @link http://status.net/ - */ - -define('WEBFINGER_SERVICE_REL_VALUE', 'lrdd'); - -/** - * Implement the webfinger protocol. - */ - -class Webfinger -{ - const PROFILEPAGE = 'http://webfinger.net/rel/profile-page'; - const UPDATESFROM = 'http://schemas.google.com/g/2010#updates-from'; - const HCARD = 'http://microformats.org/profile/hcard'; - - /** - * Perform a webfinger lookup given an account. - */ - - public function lookup($id) - { - $id = $this->normalize($id); - list($name, $domain) = explode('@', $id); - - $links = $this->getServiceLinks($domain); - if (!$links) { - return false; - } - - $services = array(); - foreach ($links as $link) { - if ($link['template']) { - return $this->getServiceDescription($link['template'], $id); - } - if ($link['href']) { - return $this->getServiceDescription($link['href'], $id); - } - } - } - - /** - * Normalize an account ID - */ - function normalize($id) - { - if (substr($id, 0, 7) == 'acct://') { - return substr($id, 7); - } else if (substr($id, 0, 5) == 'acct:') { - return substr($id, 5); - } - - return $id; - } - - function getServiceLinks($domain) - { - $url = 'http://'. $domain .'/.well-known/host-meta'; - - $content = $this->fetchURL($url); - - if (empty($content)) { - common_log(LOG_DEBUG, 'Error fetching host-meta'); - return false; - } - - $result = XRD::parse($content); - - // Ensure that the host == domain (spec may include signing later) - if ($result->host != $domain) { - return false; - } - - $links = array(); - foreach ($result->links as $link) { - if ($link['rel'] == WEBFINGER_SERVICE_REL_VALUE) { - $links[] = $link; - } - - } - return $links; - } - - function getServiceDescription($template, $id) - { - $url = $this->applyTemplate($template, 'acct:' . $id); - - $content = $this->fetchURL($url); - - if (!$content) { - return false; - } - - return XRD::parse($content); - } - - function fetchURL($url) - { - try { - $c = Cache::instance(); - $content = $c->get('webfinger:url:'.$url); - if ($content !== false) { - return $content; - } - $client = new HTTPClient(); - $response = $client->get($url); - } catch (HTTP_Request2_Exception $e) { - return false; - } - - if ($response->getStatus() != 200) { - return false; - } - - $body = $response->getBody(); - - $c->set('webfinger:url:'.$url, $body); - - return $body; - } - - function applyTemplate($template, $id) - { - $template = str_replace('{uri}', urlencode($id), $template); - - return $template; - } - - function getHostMeta($domain, $template) { - $xrd = new XRD(); - $xrd->host = $domain; - $xrd->links[] = array('rel' => 'lrdd', - 'template' => $template, - 'title' => array('Resource Descriptor')); - - return $xrd->toXML(); - } -} - -- cgit v1.2.3-54-g00ecf From d1256b547f5f4f02ddc51a5fe2146dbde52aac53 Mon Sep 17 00:00:00 2001 From: James Walker Date: Fri, 26 Feb 2010 03:43:35 -0500 Subject: bad merge.. cleaning up missing webfinger bits --- plugins/OStatus/actions/xrd.php | 2 +- plugins/OStatus/lib/discovery.php | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/plugins/OStatus/actions/xrd.php b/plugins/OStatus/actions/xrd.php index 2a754dcfe..e6b694d61 100644 --- a/plugins/OStatus/actions/xrd.php +++ b/plugins/OStatus/actions/xrd.php @@ -66,7 +66,7 @@ class XrdAction extends Action 'type' => 'application/atom+xml'); // hCard - $xrd->links[] = array('rel' => Webfinger::HCARD, + $xrd->links[] = array('rel' => Discovery::HCARD, 'type' => 'text/html', 'href' => common_local_url('hcard', array('nickname' => $nick))); diff --git a/plugins/OStatus/lib/discovery.php b/plugins/OStatus/lib/discovery.php index c268ad05c..1ab6e51bd 100644 --- a/plugins/OStatus/lib/discovery.php +++ b/plugins/OStatus/lib/discovery.php @@ -39,7 +39,8 @@ class Discovery const LRDD_REL = 'lrdd'; const PROFILEPAGE = 'http://webfinger.net/rel/profile-page'; const UPDATESFROM = 'http://schemas.google.com/g/2010#updates-from'; - + const HCARD = 'http://microformats.org/profile/hcard'; + public $methods = array(); public function __construct() -- cgit v1.2.3-54-g00ecf From ab8bb4d79e5f267323440b8cee01458b393ce2d1 Mon Sep 17 00:00:00 2001 From: James Walker Date: Fri, 26 Feb 2010 04:07:58 -0500 Subject: more cleanup --- plugins/OStatus/classes/Ostatus_profile.php | 2 +- plugins/OStatus/lib/discovery.php | 4 ++++ plugins/OStatus/lib/magicenvelope.php | 21 +++++++++++++++------ 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/plugins/OStatus/classes/Ostatus_profile.php b/plugins/OStatus/classes/Ostatus_profile.php index 4a9aafce1..091056c54 100644 --- a/plugins/OStatus/classes/Ostatus_profile.php +++ b/plugins/OStatus/classes/Ostatus_profile.php @@ -1305,7 +1305,7 @@ class Ostatus_profile extends Memcached_DataObject case Discovery::UPDATESFROM: $feedUrl = $link['href']; break; - case Webfinger::HCARD: + case Discovery::HCARD: $hcardUrl = $link['href']; break; default: diff --git a/plugins/OStatus/lib/discovery.php b/plugins/OStatus/lib/discovery.php index 1ab6e51bd..388df0a28 100644 --- a/plugins/OStatus/lib/discovery.php +++ b/plugins/OStatus/lib/discovery.php @@ -111,6 +111,10 @@ class Discovery } public static function getService($links, $service) { + if (!is_array($links)) { + return false; + } + foreach ($links as $link) { if ($link['rel'] == $service) { return $link; diff --git a/plugins/OStatus/lib/magicenvelope.php b/plugins/OStatus/lib/magicenvelope.php index c642af548..457c0fba2 100644 --- a/plugins/OStatus/lib/magicenvelope.php +++ b/plugins/OStatus/lib/magicenvelope.php @@ -52,12 +52,17 @@ class MagicEnvelope { $disco = new Discovery(); - $xrd = $disco->lookup($signer_uri); - if ($link = Discovery::getService($xrd->links, Magicsig::PUBLICKEYREL)) { - list($type, $keypair) = explode(';', $link['href']); - return $keypair; + try { + $xrd = $disco->lookup($signer_uri); + } catch (Exception $e) { + return false; + } + if ($xrd->links) { + if ($link = Discovery::getService($xrd->links, Magicsig::PUBLICKEYREL)) { + list($type, $keypair) = explode(';', $link['href']); + return $keypair; + } } - throw new Exception('Unable to locate signer public key'); } @@ -70,7 +75,11 @@ class MagicEnvelope throw new Exception("Unable to determine entry author."); } - $signature_alg = Magicsig::fromString($this->getKeyPair($signer_uri)); + $keypair = $this->getKeyPair($signer_uri); + if (!$keypair) { + throw new Exception("Unable to retrive keypair for ". $signer_uri); + } + $signature_alg = Magicsig::fromString($keypair); $armored_text = base64_encode($text); return array( -- cgit v1.2.3-54-g00ecf