Converter.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Ldap
  17. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * Zend_Ldap_Converter is a collection of useful LDAP related conversion functions.
  23. *
  24. * @category Zend
  25. * @package Zend_Ldap
  26. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  27. * @license http://framework.zend.com/license/new-bsd New BSD License
  28. */
  29. class Zend_Ldap_Converter
  30. {
  31. const STANDARD = 0;
  32. const BOOLEAN = 1;
  33. const GENERALIZED_TIME = 2;
  34. /**
  35. * Converts all ASCII chars < 32 to "\HEX"
  36. *
  37. * @see Net_LDAP2_Util::asc2hex32() from Benedikt Hallinger <beni@php.net>
  38. * @link http://pear.php.net/package/Net_LDAP2
  39. * @author Benedikt Hallinger <beni@php.net>
  40. *
  41. * @param string $string String to convert
  42. * @return string
  43. */
  44. public static function ascToHex32($string)
  45. {
  46. for ($i = 0; $i<strlen($string); $i++) {
  47. $char = substr($string, $i, 1);
  48. if (ord($char)<32) {
  49. $hex = dechex(ord($char));
  50. if (strlen($hex) == 1) $hex = '0' . $hex;
  51. $string = str_replace($char, '\\' . $hex, $string);
  52. }
  53. }
  54. return $string;
  55. }
  56. /**
  57. * Converts all Hex expressions ("\HEX") to their original ASCII characters
  58. *
  59. * @see Net_LDAP2_Util::hex2asc() from Benedikt Hallinger <beni@php.net>,
  60. * heavily based on work from DavidSmith@byu.net
  61. * @link http://pear.php.net/package/Net_LDAP2
  62. * @author Benedikt Hallinger <beni@php.net>, heavily based on work from DavidSmith@byu.net
  63. *
  64. * @param string $string String to convert
  65. * @return string
  66. */
  67. public static function hex32ToAsc($string)
  68. {
  69. // Using a callback, since PHP 5.5 has deprecated the /e modifier in preg_replace.
  70. $string = preg_replace_callback("/\\\([0-9A-Fa-f]{2})/", array('Zend_Ldap_Converter', '_charHex32ToAsc'), $string);
  71. return $string;
  72. }
  73. /**
  74. * Convert a single slash-prefixed character from Hex32 to ASCII.
  75. * Used as a callback in @see hex32ToAsc()
  76. * @param array $matches
  77. *
  78. * @return string
  79. */
  80. private static function _charHex32ToAsc(array $matches) {
  81. return chr(hexdec($matches[0]));
  82. }
  83. /**
  84. * Convert any value to an LDAP-compatible value.
  85. *
  86. * By setting the <var>$type</var>-parameter the conversion of a certain
  87. * type can be forced
  88. *
  89. * @todo write more tests
  90. *
  91. * @param mixed $value The value to convert
  92. * @param int $ytpe The conversion type to use
  93. * @return string
  94. * @throws Zend_Ldap_Converter_Exception
  95. */
  96. public static function toLdap($value, $type = self::STANDARD)
  97. {
  98. try {
  99. switch ($type) {
  100. case self::BOOLEAN:
  101. return self::toldapBoolean($value);
  102. break;
  103. case self::GENERALIZED_TIME:
  104. return self::toLdapDatetime($value);
  105. break;
  106. default:
  107. if (is_string($value)) {
  108. return $value;
  109. } else if (is_int($value) || is_float($value)) {
  110. return (string)$value;
  111. } else if (is_bool($value)) {
  112. return self::toldapBoolean($value);
  113. } else if (is_object($value)) {
  114. if ($value instanceof DateTime) {
  115. return self::toLdapDatetime($value);
  116. } else if ($value instanceof Zend_Date) {
  117. return self::toLdapDatetime($value);
  118. } else {
  119. return self::toLdapSerialize($value);
  120. }
  121. } else if (is_array($value)) {
  122. return self::toLdapSerialize($value);
  123. } else if (is_resource($value) && get_resource_type($value) === 'stream') {
  124. return stream_get_contents($value);
  125. } else {
  126. return null;
  127. }
  128. break;
  129. }
  130. } catch (Exception $e) {
  131. throw new Zend_Ldap_Converter_Exception($e->getMessage(), $e->getCode(), $e);
  132. }
  133. }
  134. /**
  135. * Converts a date-entity to an LDAP-compatible date-string
  136. *
  137. * The date-entity <var>$date</var> can be either a timestamp, a
  138. * DateTime Object, a string that is parseable by strtotime() or a Zend_Date
  139. * Object.
  140. *
  141. * @param integer|string|DateTimt|Zend_Date $date The date-entity
  142. * @param boolean $asUtc Whether to return the LDAP-compatible date-string
  143. * as UTC or as local value
  144. * @return string
  145. * @throws InvalidArgumentException
  146. */
  147. public static function toLdapDateTime($date, $asUtc = true)
  148. {
  149. if (!($date instanceof DateTime)) {
  150. if (is_int($date)) {
  151. $date = new DateTime('@' . $date);
  152. $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
  153. } else if (is_string($date)) {
  154. $date = new DateTime($date);
  155. } else if ($date instanceof Zend_Date) {
  156. $date = new DateTime($date->get(Zend_Date::ISO_8601));
  157. } else {
  158. throw new InvalidArgumentException('Parameter $date is not of the expected type');
  159. }
  160. }
  161. $timezone = $date->format('O');
  162. if (true === $asUtc) {
  163. $date->setTimezone(new DateTimeZone('UTC'));
  164. $timezone = 'Z';
  165. }
  166. if ( '+0000' === $timezone ) {
  167. $timezone = 'Z';
  168. }
  169. return $date->format('YmdHis') . $timezone;
  170. }
  171. /**
  172. * Convert a boolean value to an LDAP-compatible string
  173. *
  174. * This converts a boolean value of TRUE, an integer-value of 1 and a
  175. * case-insensitive string 'true' to an LDAP-compatible 'TRUE'. All other
  176. * other values are converted to an LDAP-compatible 'FALSE'.
  177. *
  178. * @param boolean|integer|string $value The boolean value to encode
  179. * @return string
  180. */
  181. public static function toLdapBoolean($value)
  182. {
  183. $return = 'FALSE';
  184. if (!is_scalar($value)) {
  185. return $return;
  186. }
  187. if (true === $value || 'true' === strtolower($value) || 1 === $value) {
  188. $return = 'TRUE';
  189. }
  190. return $return;
  191. }
  192. /**
  193. * Serialize any value for storage in LDAP
  194. *
  195. * @param mixed $value The value to serialize
  196. * @return string
  197. */
  198. public static function toLdapSerialize($value)
  199. {
  200. return serialize($value);
  201. }
  202. /**
  203. * Convert an LDAP-compatible value to a corresponding PHP-value.
  204. *
  205. * By setting the <var>$type</var>-parameter the conversion of a certain
  206. * type can be forced
  207. * .
  208. * @param string $value The value to convert
  209. * @param int $ytpe The conversion type to use
  210. * @param boolean $dateTimeAsUtc Return DateTime values in UTC timezone
  211. * @return mixed
  212. * @throws Zend_Ldap_Converter_Exception
  213. */
  214. public static function fromLdap($value, $type = self::STANDARD, $dateTimeAsUtc = true)
  215. {
  216. switch ($type) {
  217. case self::BOOLEAN:
  218. return self::fromldapBoolean($value);
  219. break;
  220. case self::GENERALIZED_TIME:
  221. return self::fromLdapDateTime($value);
  222. break;
  223. default:
  224. if (is_numeric($value)) {
  225. // prevent numeric values to be treated as date/time
  226. return $value;
  227. } else if ('TRUE' === $value || 'FALSE' === $value) {
  228. return self::fromLdapBoolean($value);
  229. }
  230. if (preg_match('/^\d{4}[\d\+\-Z\.]*$/', $value)) {
  231. return self::fromLdapDateTime($value, $dateTimeAsUtc);
  232. }
  233. try {
  234. return self::fromLdapUnserialize($value);
  235. } catch (UnexpectedValueException $e) { }
  236. break;
  237. }
  238. return $value;
  239. }
  240. /**
  241. * Convert an LDAP-Generalized-Time-entry into a DateTime-Object
  242. *
  243. * CAVEAT: The DateTime-Object returned will alwasy be set to UTC-Timezone.
  244. *
  245. * @param string $date The generalized-Time
  246. * @param boolean $asUtc Return the DateTime with UTC timezone
  247. * @return DateTime
  248. * @throws InvalidArgumentException if a non-parseable-format is given
  249. */
  250. public static function fromLdapDateTime($date, $asUtc = true)
  251. {
  252. $datepart = array ();
  253. if (!preg_match('/^(\d{4})/', $date, $datepart) ) {
  254. throw new InvalidArgumentException('Invalid date format found');
  255. }
  256. if ($datepart[1] < 4) {
  257. throw new InvalidArgumentException('Invalid date format found (too short)');
  258. }
  259. $time = array (
  260. // The year is mandatory!
  261. 'year' => $datepart[1],
  262. 'month' => 1,
  263. 'day' => 1,
  264. 'hour' => 0,
  265. 'minute' => 0,
  266. 'second' => 0,
  267. 'offdir' => '+',
  268. 'offsethours' => 0,
  269. 'offsetminutes' => 0
  270. );
  271. $length = strlen($date);
  272. // Check for month.
  273. if ($length >= 6) {
  274. $month = substr($date, 4, 2);
  275. if ($month < 1 || $month > 12) {
  276. throw new InvalidArgumentException('Invalid date format found (invalid month)');
  277. }
  278. $time['month'] = $month;
  279. }
  280. // Check for day
  281. if ($length >= 8) {
  282. $day = substr($date, 6, 2);
  283. if ($day < 1 || $day > 31) {
  284. throw new InvalidArgumentException('Invalid date format found (invalid day)');
  285. }
  286. $time['day'] = $day;
  287. }
  288. // Check for Hour
  289. if ($length >= 10) {
  290. $hour = substr($date, 8, 2);
  291. if ($hour < 0 || $hour > 23) {
  292. throw new InvalidArgumentException('Invalid date format found (invalid hour)');
  293. }
  294. $time['hour'] = $hour;
  295. }
  296. // Check for minute
  297. if ($length >= 12) {
  298. $minute = substr($date, 10, 2);
  299. if ($minute < 0 || $minute > 59) {
  300. throw new InvalidArgumentException('Invalid date format found (invalid minute)');
  301. }
  302. $time['minute'] = $minute;
  303. }
  304. // Check for seconds
  305. if ($length >= 14) {
  306. $second = substr($date, 12, 2);
  307. if ($second < 0 || $second > 59) {
  308. throw new InvalidArgumentException('Invalid date format found (invalid second)');
  309. }
  310. $time['second'] = $second;
  311. }
  312. // Set Offset
  313. $offsetRegEx = '/([Z\-\+])(\d{2}\'?){0,1}(\d{2}\'?){0,1}$/';
  314. $off = array ();
  315. if (preg_match($offsetRegEx, $date, $off)) {
  316. $offset = $off[1];
  317. if ($offset == '+' || $offset == '-') {
  318. $time['offdir'] = $offset;
  319. // we have an offset, so lets calculate it.
  320. if (isset($off[2])) {
  321. $offsetHours = substr($off[2], 0, 2);
  322. if ($offsetHours < 0 || $offsetHours > 12) {
  323. throw new InvalidArgumentException('Invalid date format found (invalid offset hour)');
  324. }
  325. $time['offsethours'] = $offsetHours;
  326. }
  327. if (isset($off[3])) {
  328. $offsetMinutes = substr($off[3], 0, 2);
  329. if ($offsetMinutes < 0 || $offsetMinutes > 59) {
  330. throw new InvalidArgumentException('Invalid date format found (invalid offset minute)');
  331. }
  332. $time['offsetminutes'] = $offsetMinutes;
  333. }
  334. }
  335. }
  336. // Raw-Data is present, so lets create a DateTime-Object from it.
  337. $offset = $time['offdir']
  338. . str_pad($time['offsethours'],2,'0',STR_PAD_LEFT)
  339. . str_pad($time['offsetminutes'],2,'0',STR_PAD_LEFT);
  340. $timestring = $time['year'] . '-'
  341. . str_pad($time['month'], 2, '0', STR_PAD_LEFT) . '-'
  342. . str_pad($time['day'], 2, '0', STR_PAD_LEFT) . ' '
  343. . str_pad($time['hour'], 2, '0', STR_PAD_LEFT) . ':'
  344. . str_pad($time['minute'], 2, '0', STR_PAD_LEFT) . ':'
  345. . str_pad($time['second'], 2, '0', STR_PAD_LEFT)
  346. . $time['offdir']
  347. . str_pad($time['offsethours'], 2, '0', STR_PAD_LEFT)
  348. . str_pad($time['offsetminutes'], 2, '0', STR_PAD_LEFT);
  349. $date = new DateTime($timestring);
  350. if ($asUtc) {
  351. $date->setTimezone(new DateTimeZone('UTC'));
  352. }
  353. return $date;
  354. }
  355. /**
  356. * Convert an LDAP-compatible boolean value into a PHP-compatible one
  357. *
  358. * @param string $value The value to convert
  359. * @return boolean
  360. * @throws InvalidArgumentException
  361. */
  362. public static function fromLdapBoolean($value)
  363. {
  364. if ( 'TRUE' === $value ) {
  365. return true;
  366. } else if ( 'FALSE' === $value ) {
  367. return false;
  368. } else {
  369. throw new InvalidArgumentException('The given value is not a boolean value');
  370. }
  371. }
  372. /**
  373. * Unserialize a serialized value to return the corresponding object
  374. *
  375. * @param string $value The value to convert
  376. * @return mixed
  377. * @throws UnexpectedValueException
  378. */
  379. public static function fromLdapUnserialize($value)
  380. {
  381. $v = @unserialize($value);
  382. if (false===$v && $value != 'b:0;') {
  383. throw new UnexpectedValueException('The given value could not be unserialized');
  384. }
  385. return $v;
  386. }
  387. }