KVForm.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. /**
  3. * OpenID protocol key-value/comma-newline format parsing and
  4. * serialization
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * LICENSE: See the COPYING file included in this distribution.
  9. *
  10. * @access private
  11. * @package OpenID
  12. * @author JanRain, Inc. <openid@janrain.com>
  13. * @copyright 2005-2008 Janrain, Inc.
  14. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
  15. */
  16. /**
  17. * Container for key-value/comma-newline OpenID format and parsing
  18. */
  19. class Auth_OpenID_KVForm {
  20. /**
  21. * Convert an OpenID colon/newline separated string into an
  22. * associative array
  23. *
  24. * @static
  25. * @access private
  26. */
  27. static function toArray($kvs, $strict=false)
  28. {
  29. $lines = explode("\n", $kvs);
  30. $last = array_pop($lines);
  31. if ($last !== '') {
  32. array_push($lines, $last);
  33. if ($strict) {
  34. return false;
  35. }
  36. }
  37. $values = array();
  38. for ($lineno = 0; $lineno < count($lines); $lineno++) {
  39. $line = $lines[$lineno];
  40. $kv = explode(':', $line, 2);
  41. if (count($kv) != 2) {
  42. if ($strict) {
  43. return false;
  44. }
  45. continue;
  46. }
  47. $key = $kv[0];
  48. $tkey = trim($key);
  49. if ($tkey != $key) {
  50. if ($strict) {
  51. return false;
  52. }
  53. }
  54. $value = $kv[1];
  55. $tval = trim($value);
  56. if ($tval != $value) {
  57. if ($strict) {
  58. return false;
  59. }
  60. }
  61. $values[$tkey] = $tval;
  62. }
  63. return $values;
  64. }
  65. /**
  66. * Convert an array into an OpenID colon/newline separated string
  67. *
  68. * @static
  69. * @access private
  70. */
  71. static function fromArray($values)
  72. {
  73. if ($values === null) {
  74. return null;
  75. }
  76. ksort($values);
  77. $serialized = '';
  78. foreach ($values as $key => $value) {
  79. if (is_array($value)) {
  80. list($key, $value) = array($value[0], $value[1]);
  81. }
  82. if (strpos($key, ':') !== false) {
  83. return null;
  84. }
  85. if (strpos($key, "\n") !== false) {
  86. return null;
  87. }
  88. if (strpos($value, "\n") !== false) {
  89. return null;
  90. }
  91. $serialized .= "$key:$value\n";
  92. }
  93. return $serialized;
  94. }
  95. }