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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?PHP
  2. /* Poidsy 0.5 - http://chris.smith.name/projects/poidsy
  3. * Copyright (c) 2008-2010 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. const ID_SELECT_URL = 'http://specs.openid.net/auth/2.0/identifier_select';
  52. private $version; // OpenID 2 teminology || OpenID 1 terminology
  53. // --------------------- || ----------------------
  54. private $userSuppliedId; // User supplied ID || [Same as Claimed ID]
  55. private $claimedId; // Claimed ID || Claimed ID
  56. private $endpointUrl; // OP Endpoint URL || Identity Provider
  57. private $opLocalId; // OP-local ID || Delegate
  58. public function __construct($uri, $normalise = true) {
  59. if ($uri !== null) {
  60. $this->discover($this->userSuppliedId = ($normalise ? $this->normalise($uri) : $uri));
  61. }
  62. }
  63. public function getEndpointUrl() {
  64. return $this->endpointUrl;
  65. }
  66. public function getUserSuppliedId() {
  67. return $this->userSuppliedId;
  68. }
  69. public function getClaimedId() {
  70. return $this->claimedId;
  71. }
  72. public function getOpLocalId() {
  73. return $this->opLocalId;
  74. }
  75. public function getVersion() {
  76. return $this->version;
  77. }
  78. public static function normalise($uri) {
  79. // Strip xri:// prefix
  80. if (substr($uri, 0, 6) == 'xri://') {
  81. $uri = substr($uri, 6);
  82. }
  83. // If the first char is a global context symbol, treat it as XRI
  84. if (in_array($uri[0], array('=', '@', '+', '$', '!'))) {
  85. // TODO: Implement
  86. throw new Exception('This implementation does not currently support XRI');
  87. }
  88. // Add http:// if needed
  89. if (strpos($uri, '://') === false) {
  90. $uri = 'http://' . $uri;
  91. }
  92. $bits = @parse_url($uri);
  93. $result = $bits['scheme'] . '://';
  94. if (defined('OPENID_ALLOWUSER') && isset($bits['user'])) {
  95. $result .= $bits['user'];
  96. if (isset($bits['pass'])) {
  97. $result .= ':' . $bits['pass'];
  98. }
  99. $result .= '@';
  100. }
  101. $result .= preg_replace('/\.$/', '', $bits['host']);
  102. if (isset($bits['port']) && !empty($bits['port']) &&
  103. (($bits['scheme'] == 'http' && $bits['port'] != '80') ||
  104. ($bits['scheme'] == 'https' && $bits['port'] != '443') ||
  105. ($bits['scheme'] != 'http' && $bits['scheme'] != 'https'))) {
  106. $result .= ':' . $bits['port'];
  107. }
  108. if (isset($bits['path'])) {
  109. do {
  110. $bits['path'] = preg_replace('#/([^/]*)/\.\./#', '/', str_replace('/./', '/', $old = $bits['path']));
  111. } while ($old != $bits['path']);
  112. $result .= $bits['path'];
  113. } else {
  114. $result .= '/';
  115. }
  116. if (defined('OPENID_ALLOWQUERY') && isset($bits['query'])) {
  117. $result .= '?' . $bits['query'];
  118. }
  119. return $result;
  120. }
  121. private function discover($uri) {
  122. Logger::log('Performing discovery for %s', $uri);
  123. if (!$this->yadisDiscover($uri)) {
  124. $this->htmlDiscover($uri);
  125. }
  126. }
  127. private function yadisDiscover($uri, $allowLocation = true) {
  128. Logger::log('Attempting Yadis discovery on %s', $uri);
  129. $ctx = stream_context_create(array(
  130. 'http' => array(
  131. 'header' => "Accept: application/xrds+xml\r\n",
  132. )
  133. ));
  134. $fh = @fopen($uri, 'r', false, $ctx);
  135. if (!$fh) {
  136. Logger::log('Unable to open stream');
  137. return false;
  138. }
  139. $details = stream_get_meta_data($fh);
  140. $data = '';
  141. while (!feof($fh) && strpos($data, '</head>') === false) {
  142. $data .= fgets($fh);
  143. }
  144. fclose($fh);
  145. foreach ($details['wrapper_data'] as $line) {
  146. if ($allowLocation && preg_match('/^X-XRDS-Location:\s*(.*?)$/i', $line, $m)) {
  147. // TODO: Allow relative URLs?
  148. return $this->yadisDiscover($m[1], false);
  149. } else if (preg_match('#^Content-type:\s*application/xrds\+xml(;.*?)?$#i', $line)) {
  150. return $this->parseYadis($data);
  151. }
  152. }
  153. return $this->parseYadisHTML($data);
  154. }
  155. private function parseYadis($data) {
  156. $sxml = @new SimpleXMLElement($data);
  157. if (!$sxml) {
  158. Logger::log('Failed to parse XRDS data as XML');
  159. // TODO: Die somehow?
  160. return false;
  161. }
  162. // TODO: Better handling of namespaces
  163. $found = false;
  164. foreach ($sxml->XRD->Service as $service) {
  165. $services = array();
  166. $server = null;
  167. foreach ($service->Type as $type) {
  168. Logger::log('Found service of type %s', $type);
  169. if ((String) $type == 'http://specs.openid.net/auth/2.0/server') {
  170. $this->version = 2;
  171. $this->server = (String) $service->URI;
  172. $this->identity = self::ID_SELECT_URL;
  173. $this->servers[] = $server = new Server($this->server, 2);
  174. Logger::log('OpenID EP found (server). Server: %s, identity: %s, claimed id: %s', $this->server, $this->identity, $this->claimedId);
  175. $found = true;
  176. } else if ((String) $type == 'http://specs.openid.net/auth/2.0/signon') {
  177. $this->version = 2;
  178. $this->server = (String) $service->URI;
  179. $this->servers[] = $server = new Server($this->server, 2);
  180. if (isset($service->LocalID)) {
  181. $this->identity = (String) $service->LocalID;
  182. } else {
  183. $this->identity = self::ID_SELECT_URL;
  184. }
  185. Logger::log('OpenID EP found (signon). Server: %s, identity: %s, claimed id: %s', $this->server, $this->identity, $this->claimedId);
  186. $found = true;
  187. } else {
  188. $services[] = (String) $type;
  189. }
  190. }
  191. if ($server != null) {
  192. $server->addServices($services);
  193. }
  194. }
  195. return $found;
  196. }
  197. private function parseYadisHTML($data) {
  198. $meta = self::getMetaTags($data);
  199. if (isset($meta['x-xrds-location'])) {
  200. Logger::log('Found XRDS meta tag: %s', $meta['x-xrds-location']);
  201. // TODO: Allow relative URLs?
  202. return $this->yadisDiscover($meta['x-xrds-location'], false);
  203. }
  204. return false;
  205. }
  206. private function htmlDiscover($uri) {
  207. Logger::log('Performing HTML discovery on %s', $uri);
  208. $fh = @fopen($uri, 'r');
  209. if (!$fh) {
  210. Logger::log('Unable to open stream');
  211. return;
  212. }
  213. $this->claimedId = $uri;
  214. $details = stream_get_meta_data($fh);
  215. foreach ($details['wrapper_data'] as $line) {
  216. if (preg_match('/^Location: (.*?)$/i', $line, $m)) {
  217. if (strpos($m[1], '://') !== false) {
  218. // Fully qualified URL
  219. $this->claimedId = $m[1];
  220. } else if ($m[1][0] == '/') {
  221. // Absolute URL
  222. $this->claimedId = preg_replace('#^(.*?://.*?)/.*$#', '\1', $this->claimedId) . $m[1];
  223. } else {
  224. // Relative URL
  225. $this->claimedId = preg_replace('#^(.*?://.*/).*?$#', '\1', $this->claimedId) . $m[1];
  226. }
  227. }
  228. $this->claimedId = self::normalise($this->claimedId);
  229. }
  230. Logger::log('Claimed identity: %s', $this->claimedId);
  231. $data = '';
  232. while (!feof($fh) && strpos($data, '</head>') === false) {
  233. $data .= fgets($fh);
  234. }
  235. fclose($fh);
  236. $this->parseHtml($data);
  237. }
  238. protected static function getLinks($data) {
  239. return self::getTags($data, 'link', 'rel', 'href', true);
  240. }
  241. protected static function getMetaTags($data) {
  242. return self::getTags($data, 'meta', 'http-equiv', 'content');
  243. }
  244. protected static function getTags($data, $tag, $att1, $att2, $split = false) {
  245. preg_match_all('#<' . $tag . '\s*(.*?)\s*/?' . '>#is', $data, $matches);
  246. $links = array();
  247. foreach ($matches[1] as $link) {
  248. $rel = $href = null;
  249. if (preg_match('#' . $att1 . '\s*=\s*(?:([^"\'>\s]*)|"([^">]*)"|\'([^\'>]*)\')(?:\s|$)#is', $link, $m)) {
  250. array_shift($m);
  251. $rel = implode('', $m);
  252. }
  253. if (preg_match('#' . $att2 . '\s*=\s*(?:([^"\'>\s]*)|"([^">]*)"|\'([^\'>]*)\')(?:\s|$)#is', $link, $m)) {
  254. array_shift($m);
  255. $href = implode('', $m);
  256. }
  257. if ($split) {
  258. foreach (explode(' ', strtolower($rel)) as $part) {
  259. $links[$part] = html_entity_decode($href);
  260. }
  261. } else {
  262. $links[strtolower($rel)] = html_entity_decode($href);
  263. }
  264. }
  265. return $links;
  266. }
  267. public function parseHtml($data) {
  268. $links = self::getLinks($data);
  269. if (isset($links['openid2.provider'])) {
  270. $this->version = 2;
  271. $this->endpointUrl = $links['openid2.provider'];
  272. //$this->servers[] = new Server($this->server, 2);
  273. $this->claimedId = $this->userSuppliedId;
  274. $this->opLocalId = isset($links['openid2.local_id']) ? $links['openid2.local_id'] : $this->claimedId;
  275. Logger::log('OpenID EP found. End point: %s, claimed id: %s, op local id: %s', $this->endpointUrl, $this->claimedId, $this->opLocalId);
  276. } else if (isset($links['openid.server'])) {
  277. $this->version = 1;
  278. $this->endpointUrl = $links['openid.server'];
  279. //$this->servers[] = new Server($this->server, 2);
  280. $this->claimedId = $this->userSuppliedId;
  281. if (isset($links['openid.delegate'])) {
  282. $this->opLocalId = $links['openid.delegate'];
  283. }
  284. Logger::log('OpenID EP found. End point: %s, claimed id: %s, op local id: %s', $this->endpointUrl, $this->claimedId, $this->opLocalId);
  285. }
  286. }
  287. }
  288. ?>