PHP OpenID consumer
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

discoverer.inc.php 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?PHP
  2. /* Poidsy 0.5 - http://chris.smith.name/projects/poidsy
  3. * Copyright (c) 2008-2009 Chris Smith
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. * SOFTWARE.
  22. */
  23. require_once(dirname(__FILE__) . '/logging.inc.php');
  24. class Server {
  25. private $url = null;
  26. private $version = 1;
  27. private $services = array();
  28. public function __construct($url, $version) {
  29. $this->url = $url;
  30. $this->version = $version;
  31. }
  32. public function getURL() {
  33. return $this->url;
  34. }
  35. public function getVersion() {
  36. return $this->version;
  37. }
  38. public function getServices() {
  39. return $this->services;
  40. }
  41. public function addServices($services) {
  42. foreach ($services as $service) {
  43. $this->services[] = $service;
  44. }
  45. }
  46. public function hasService($service) {
  47. return array_search($service, $this->services) !== false;
  48. }
  49. }
  50. class Discoverer {
  51. private $server = null;
  52. private $servers = array();
  53. private $claimedId = '';
  54. private $identity = '';
  55. private $version = 1;
  56. public function __construct($uri, $normalise = true) {
  57. if ($uri !== null) {
  58. $this->discover($this->identity = ($normalise ? $this->normalise($uri) : $uri));
  59. }
  60. }
  61. public function getServer() {
  62. return $this->server;
  63. }
  64. public function hasServer($server) {
  65. foreach ($this->servers as $match) {
  66. if ($match->getURL() == $server) {
  67. return true;
  68. }
  69. }
  70. return false;
  71. }
  72. public function getDelegate() {
  73. return $this->claimedId;
  74. }
  75. public function getIdentity() {
  76. return $this->identity;
  77. }
  78. public function getVersion() {
  79. return $this->version;
  80. }
  81. public static function normalise($uri) {
  82. // Strip xri:// prefix
  83. if (substr($uri, 0, 6) == 'xri://') {
  84. $uri = substr($uri, 6);
  85. }
  86. // If the first char is a global context symbol, treat it as XRI
  87. if (in_array($uri[0], array('=', '@', '+', '$', '!'))) {
  88. // TODO: Implement
  89. throw new Exception('This implementation does not currently support XRI');
  90. }
  91. // Add http:// if needed
  92. if (strpos($uri, '://') === false) {
  93. $uri = 'http://' . $uri;
  94. }
  95. $bits = @parse_url($uri);
  96. $result = $bits['scheme'] . '://';
  97. if (defined('OPENID_ALLOWUSER') && isset($bits['user'])) {
  98. $result .= $bits['user'];
  99. if (isset($bits['pass'])) {
  100. $result .= ':' . $bits['pass'];
  101. }
  102. $result .= '@';
  103. }
  104. $result .= preg_replace('/\.$/', '', $bits['host']);
  105. if (isset($bits['port']) && !empty($bits['port']) &&
  106. (($bits['scheme'] == 'http' && $bits['port'] != '80') ||
  107. ($bits['scheme'] == 'https' && $bits['port'] != '443') ||
  108. ($bits['scheme'] != 'http' && $bits['scheme'] != 'https'))) {
  109. $result .= ':' . $bits['port'];
  110. }
  111. if (isset($bits['path'])) {
  112. do {
  113. $bits['path'] = preg_replace('#/([^/]*)/\.\./#', '/', str_replace('/./', '/', $old = $bits['path']));
  114. } while ($old != $bits['path']);
  115. $result .= $bits['path'];
  116. } else {
  117. $result .= '/';
  118. }
  119. if (defined('OPENID_ALLOWQUERY') && isset($bits['query'])) {
  120. $result .= '?' . $bits['query'];
  121. }
  122. return $result;
  123. }
  124. private function discover($uri) {
  125. Logger::log('Performing discovery for %s', $uri);
  126. $this->claimedId = $uri;
  127. $this->server = null;
  128. if (!$this->yadisDiscover($uri)) {
  129. $this->htmlDiscover($uri);
  130. }
  131. }
  132. private function yadisDiscover($uri, $allowLocation = true) {
  133. Logger::log('Attempting Yadis discovery on %s', $uri);
  134. $ctx = stream_context_create(array(
  135. 'http' => array(
  136. 'header' => "Accept: application/xrds+xml\r\n",
  137. )
  138. ));
  139. $fh = @fopen($uri, 'r', false, $ctx);
  140. if (!$fh) {
  141. Logger::log('Unable to open stream');
  142. return false;
  143. }
  144. $details = stream_get_meta_data($fh);
  145. $data = '';
  146. while (!feof($fh) && strpos($data, '</head>') === false) {
  147. $data .= fgets($fh);
  148. }
  149. fclose($fh);
  150. foreach ($details['wrapper_data'] as $line) {
  151. if ($allowLocation && preg_match('/^X-XRDS-Location:\s*(.*?)$/i', $line, $m)) {
  152. // TODO: Allow relative URLs?
  153. return $this->yadisDiscover($m[1], false);
  154. } else if (preg_match('#^Content-type:\s*application/xrds\+xml(;.*?)?$#i', $line)) {
  155. return $this->parseYadis($data);
  156. }
  157. }
  158. return $this->parseYadisHTML($data);
  159. }
  160. private function parseYadis($data) {
  161. $sxml = @new SimpleXMLElement($data);
  162. if (!$sxml) {
  163. Logger::log('Failed to parse XRDS data as XML');
  164. // TODO: Die somehow?
  165. return false;
  166. }
  167. // TODO: Better handling of namespaces
  168. $found = false;
  169. foreach ($sxml->XRD->Service as $service) {
  170. $services = array();
  171. $server = null;
  172. foreach ($service->Type as $type) {
  173. Logger::log('Found service of type %s', $type);
  174. if ((String) $type == 'http://specs.openid.net/auth/2.0/server') {
  175. $this->version = 2;
  176. $this->server = (String) $service->URI;
  177. $this->identity = 'http://specs.openid.net/auth/2.0/identifier_select';
  178. $this->servers[] = $server = new Server($this->server, 2);
  179. Logger::log('OpenID EP found (server). Server: %s, identity: %s, claimed id: %s', $this->server, $this->identity, $this->claimedId);
  180. $found = true;
  181. } else if ((String) $type == 'http://specs.openid.net/auth/2.0/signon') {
  182. $this->version = 2;
  183. $this->server = (String) $service->URI;
  184. $this->servers[] = $server = new Server($this->server, 2);
  185. if (isset($service->LocalID)) {
  186. $this->identity = (String) $service->LocalID;
  187. } else {
  188. $this->identity = 'http://specs.openid.net/auth/2.0/identifier_select';
  189. }
  190. Logger::log('OpenID EP found (signon). Server: %s, identity: %s, claimed id: %s', $this->server, $this->identity, $this->claimedId);
  191. $found = true;
  192. } else {
  193. $services[] = (String) $type;
  194. }
  195. }
  196. if ($server != null) {
  197. $server->addServices($services);
  198. }
  199. }
  200. return $found;
  201. }
  202. private function parseYadisHTML($data) {
  203. $meta = self::getMetaTags($data);
  204. if (isset($meta['x-xrds-location'])) {
  205. Logger::log('Found XRDS meta tag: %s', $meta['x-xrds-location']);
  206. // TODO: Allow relative URLs?
  207. return $this->yadisDiscover($meta['x-xrds-location'], false);
  208. }
  209. return false;
  210. }
  211. private function htmlDiscover($uri) {
  212. Logger::log('Performing HTML discovery on %s', $uri);
  213. $fh = @fopen($uri, 'r');
  214. if (!$fh) {
  215. Logger::log('Unable to open stream');
  216. return;
  217. }
  218. $details = stream_get_meta_data($fh);
  219. foreach ($details['wrapper_data'] as $line) {
  220. if (preg_match('/^Location: (.*?)$/i', $line, $m)) {
  221. if (strpos($m[1], '://') !== false) {
  222. // Fully qualified URL
  223. $this->identity = $m[1];
  224. } else if ($m[1][0] == '/') {
  225. // Absolute URL
  226. $this->identity = preg_replace('#^(.*?://.*?)/.*$#', '\1', $this->identity) . $m[1];
  227. } else {
  228. // Relative URL
  229. $this->identity = preg_replace('#^(.*?://.*/).*?$#', '\1', $this->identity) . $m[1];
  230. }
  231. }
  232. $this->identity = self::normalise($this->identity);
  233. }
  234. Logger::log('Identity: %s', $this->identity);
  235. $data = '';
  236. while (!feof($fh) && strpos($data, '</head>') === false) {
  237. $data .= fgets($fh);
  238. }
  239. fclose($fh);
  240. $this->parseHtml($data);
  241. }
  242. protected static function getLinks($data) {
  243. return self::getTags($data, 'link', 'rel', 'href');
  244. }
  245. protected static function getMetaTags($data) {
  246. return self::getTags($data, 'meta', 'http-equiv', 'content');
  247. }
  248. protected static function getTags($data, $tag, $att1, $att2) {
  249. preg_match_all('#<' . $tag . '\s*(.*?)\s*/?' . '>#is', $data, $matches);
  250. $links = array();
  251. foreach ($matches[1] as $link) {
  252. $rel = $href = null;
  253. if (preg_match('#' . $att1 . '\s*=\s*(?:([^"\'>\s]*)|"([^">]*)"|\'([^\'>]*)\')(?:\s|$)#is', $link, $m)) {
  254. array_shift($m);
  255. $rel = implode('', $m);
  256. }
  257. if (preg_match('#' . $att2 . '\s*=\s*(?:([^"\'>\s]*)|"([^">]*)"|\'([^\'>]*)\')(?:\s|$)#is', $link, $m)) {
  258. array_shift($m);
  259. $href = implode('', $m);
  260. }
  261. $links[strtolower($rel)] = html_entity_decode($href);
  262. }
  263. return $links;
  264. }
  265. public function parseHtml($data) {
  266. $links = self::getLinks($data);
  267. if (isset($links['openid2.provider'])) {
  268. $this->version = 2;
  269. $this->server = $links['openid2.provider'];
  270. $this->servers[] = new Server($this->server, 2);
  271. if (isset($links['openid2.local_id'])) {
  272. $this->identity = $links['openid2.local_id'];
  273. }
  274. Logger::log('OpenID EP found. Server: %s, identity: %s, claimed id: %s', $this->server, $this->identity, $this->claimedId);
  275. } else if (isset($links['openid.server'])) {
  276. $this->version = 1;
  277. $this->server = $links['openid.server'];
  278. $this->servers[] = new Server($this->server, 2);
  279. if (isset($links['openid.delegate'])) {
  280. $this->claimedId = $links['openid.claimedId'];
  281. }
  282. Logger::log('OpenID EP found. Server: %s, identity: %s, claimed id: %s', $this->server, $this->identity, $this->claimedId);
  283. }
  284. }
  285. }
  286. ?>