PageRenderTime 77ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/web-app/library/Zend/Ldap/Converter.php

https://github.com/ParveenArora/AddressHunter
PHP | 396 lines | 357 code | 2 blank | 37 comment | 4 complexity | f3a347b028c188c4b6837ee2e21be6fb MD5 | raw file
  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-2011 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id: Converter.php 23775 2011-03-01 17:25:24Z ralph $
  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-2011 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. $string = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $string);
  70. return $string;
  71. }
  72. /**
  73. * Convert any value to an LDAP-compatible value.
  74. *
  75. * By setting the <var>$type</var>-parameter the conversion of a certain
  76. * type can be forced
  77. *
  78. * @todo write more tests
  79. *
  80. * @param mixed $value The value to convert
  81. * @param int $ytpe The conversion type to use
  82. * @return string
  83. * @throws Zend_Ldap_Converter_Exception
  84. */
  85. public static function toLdap($value, $type = self::STANDARD)
  86. {
  87. try {
  88. switch ($type) {
  89. case self::BOOLEAN:
  90. return self::toldapBoolean($value);
  91. break;
  92. case self::GENERALIZED_TIME:
  93. return self::toLdapDatetime($value);
  94. break;
  95. default:
  96. if (is_string($value)) {
  97. return $value;
  98. } else if (is_int($value) || is_float($value)) {
  99. return (string)$value;
  100. } else if (is_bool($value)) {
  101. return self::toldapBoolean($value);
  102. } else if (is_object($value)) {
  103. if ($value instanceof DateTime) {
  104. return self::toLdapDatetime($value);
  105. } else if ($value instanceof Zend_Date) {
  106. return self::toLdapDatetime($value);
  107. } else {
  108. return self::toLdapSerialize($value);
  109. }
  110. } else if (is_array($value)) {
  111. return self::toLdapSerialize($value);
  112. } else if (is_resource($value) && get_resource_type($value) === 'stream') {
  113. return stream_get_contents($value);
  114. } else {
  115. return null;
  116. }
  117. break;
  118. }
  119. } catch (Exception $e) {
  120. throw new Zend_Ldap_Converter_Exception($e->getMessage(), $e->getCode(), $e);
  121. }
  122. }
  123. /**
  124. * Converts a date-entity to an LDAP-compatible date-string
  125. *
  126. * The date-entity <var>$date</var> can be either a timestamp, a
  127. * DateTime Object, a string that is parseable by strtotime() or a Zend_Date
  128. * Object.
  129. *
  130. * @param integer|string|DateTimt|Zend_Date $date The date-entity
  131. * @param boolean $asUtc Whether to return the LDAP-compatible date-string
  132. * as UTC or as local value
  133. * @return string
  134. * @throws InvalidArgumentException
  135. */
  136. public static function toLdapDateTime($date, $asUtc = true)
  137. {
  138. if (!($date instanceof DateTime)) {
  139. if (is_int($date)) {
  140. $date = new DateTime('@' . $date);
  141. $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
  142. } else if (is_string($date)) {
  143. $date = new DateTime($date);
  144. } else if ($date instanceof Zend_Date) {
  145. $date = new DateTime($date->get(Zend_Date::ISO_8601));
  146. } else {
  147. throw new InvalidArgumentException('Parameter $date is not of the expected type');
  148. }
  149. }
  150. $timezone = $date->format('O');
  151. if (true === $asUtc) {
  152. $date->setTimezone(new DateTimeZone('UTC'));
  153. $timezone = 'Z';
  154. }
  155. if ( '+0000' === $timezone ) {
  156. $timezone = 'Z';
  157. }
  158. return $date->format('YmdHis') . $timezone;
  159. }
  160. /**
  161. * Convert a boolean value to an LDAP-compatible string
  162. *
  163. * This converts a boolean value of TRUE, an integer-value of 1 and a
  164. * case-insensitive string 'true' to an LDAP-compatible 'TRUE'. All other
  165. * other values are converted to an LDAP-compatible 'FALSE'.
  166. *
  167. * @param boolean|integer|string $value The boolean value to encode
  168. * @return string
  169. */
  170. public static function toLdapBoolean($value)
  171. {
  172. $return = 'FALSE';
  173. if (!is_scalar($value)) {
  174. return $return;
  175. }
  176. if (true === $value || 'true' === strtolower($value) || 1 === $value) {
  177. $return = 'TRUE';
  178. }
  179. return $return;
  180. }
  181. /**
  182. * Serialize any value for storage in LDAP
  183. *
  184. * @param mixed $value The value to serialize
  185. * @return string
  186. */
  187. public static function toLdapSerialize($value)
  188. {
  189. return serialize($value);
  190. }
  191. /**
  192. * Convert an LDAP-compatible value to a corresponding PHP-value.
  193. *
  194. * By setting the <var>$type</var>-parameter the conversion of a certain
  195. * type can be forced
  196. * .
  197. * @param string $value The value to convert
  198. * @param int $ytpe The conversion type to use
  199. * @param boolean $dateTimeAsUtc Return DateTime values in UTC timezone
  200. * @return mixed
  201. * @throws Zend_Ldap_Converter_Exception
  202. */
  203. public static function fromLdap($value, $type = self::STANDARD, $dateTimeAsUtc = true)
  204. {
  205. switch ($type) {
  206. case self::BOOLEAN:
  207. return self::fromldapBoolean($value);
  208. break;
  209. case self::GENERALIZED_TIME:
  210. return self::fromLdapDateTime($value);
  211. break;
  212. default:
  213. if (is_numeric($value)) {
  214. return (float)$value;
  215. } else if ('TRUE' === $value || 'FALSE' === $value) {
  216. return self::fromLdapBoolean($value);
  217. }
  218. if (preg_match('/^\d{4}[\d\+\-Z\.]*$/', $value)) {
  219. return self::fromLdapDateTime($value, $dateTimeAsUtc);
  220. }
  221. try {
  222. return self::fromLdapUnserialize($value);
  223. } catch (UnexpectedValueException $e) { }
  224. break;
  225. }
  226. return $value;
  227. }
  228. /**
  229. * Convert an LDAP-Generalized-Time-entry into a DateTime-Object
  230. *
  231. * CAVEAT: The DateTime-Object returned will alwasy be set to UTC-Timezone.
  232. *
  233. * @param string $date The generalized-Time
  234. * @param boolean $asUtc Return the DateTime with UTC timezone
  235. * @return DateTime
  236. * @throws InvalidArgumentException if a non-parseable-format is given
  237. */
  238. public static function fromLdapDateTime($date, $asUtc = true)
  239. {
  240. $datepart = array ();
  241. if (!preg_match('/^(\d{4})/', $date, $datepart) ) {
  242. throw new InvalidArgumentException('Invalid date format found');
  243. }
  244. if ($datepart[1] < 4) {
  245. throw new InvalidArgumentException('Invalid date format found (too short)');
  246. }
  247. $time = array (
  248. // The year is mandatory!
  249. 'year' => $datepart[1],
  250. 'month' => 1,
  251. 'day' => 1,
  252. 'hour' => 0,
  253. 'minute' => 0,
  254. 'second' => 0,
  255. 'offdir' => '+',
  256. 'offsethours' => 0,
  257. 'offsetminutes' => 0
  258. );
  259. $length = strlen($date);
  260. // Check for month.
  261. if ($length >= 6) {
  262. $month = substr($date, 4, 2);
  263. if ($month < 1 || $month > 12) {
  264. throw new InvalidArgumentException('Invalid date format found (invalid month)');
  265. }
  266. $time['month'] = $month;
  267. }
  268. // Check for day
  269. if ($length >= 8) {
  270. $day = substr($date, 6, 2);
  271. if ($day < 1 || $day > 31) {
  272. throw new InvalidArgumentException('Invalid date format found (invalid day)');
  273. }
  274. $time['day'] = $day;
  275. }
  276. // Check for Hour
  277. if ($length >= 10) {
  278. $hour = substr($date, 8, 2);
  279. if ($hour < 0 || $hour > 23) {
  280. throw new InvalidArgumentException('Invalid date format found (invalid hour)');
  281. }
  282. $time['hour'] = $hour;
  283. }
  284. // Check for minute
  285. if ($length >= 12) {
  286. $minute = substr($date, 10, 2);
  287. if ($minute < 0 || $minute > 59) {
  288. throw new InvalidArgumentException('Invalid date format found (invalid minute)');
  289. }
  290. $time['minute'] = $minute;
  291. }
  292. // Check for seconds
  293. if ($length >= 14) {
  294. $second = substr($date, 12, 2);
  295. if ($second < 0 || $second > 59) {
  296. throw new InvalidArgumentException('Invalid date format found (invalid second)');
  297. }
  298. $time['second'] = $second;
  299. }
  300. // Set Offset
  301. $offsetRegEx = '/([Z\-\+])(\d{2}\'?){0,1}(\d{2}\'?){0,1}$/';
  302. $off = array ();
  303. if (preg_match($offsetRegEx, $date, $off)) {
  304. $offset = $off[1];
  305. if ($offset == '+' || $offset == '-') {
  306. $time['offdir'] = $offset;
  307. // we have an offset, so lets calculate it.
  308. if (isset($off[2])) {
  309. $offsetHours = substr($off[2], 0, 2);
  310. if ($offsetHours < 0 || $offsetHours > 12) {
  311. throw new InvalidArgumentException('Invalid date format found (invalid offset hour)');
  312. }
  313. $time['offsethours'] = $offsetHours;
  314. }
  315. if (isset($off[3])) {
  316. $offsetMinutes = substr($off[3], 0, 2);
  317. if ($offsetMinutes < 0 || $offsetMinutes > 59) {
  318. throw new InvalidArgumentException('Invalid date format found (invalid offset minute)');
  319. }
  320. $time['offsetminutes'] = $offsetMinutes;
  321. }
  322. }
  323. }
  324. // Raw-Data is present, so lets create a DateTime-Object from it.
  325. $offset = $time['offdir']
  326. . str_pad($time['offsethours'],2,'0',STR_PAD_LEFT)
  327. . str_pad($time['offsetminutes'],2,'0',STR_PAD_LEFT);
  328. $timestring = $time['year'] . '-'
  329. . str_pad($time['month'], 2, '0', STR_PAD_LEFT) . '-'
  330. . str_pad($time['day'], 2, '0', STR_PAD_LEFT) . ' '
  331. . str_pad($time['hour'], 2, '0', STR_PAD_LEFT) . ':'
  332. . str_pad($time['minute'], 2, '0', STR_PAD_LEFT) . ':'
  333. . str_pad($time['second'], 2, '0', STR_PAD_LEFT)
  334. . $time['offdir']
  335. . str_pad($time['offsethours'], 2, '0', STR_PAD_LEFT)
  336. . str_pad($time['offsetminutes'], 2, '0', STR_PAD_LEFT);
  337. $date = new DateTime($timestring);
  338. if ($asUtc) {
  339. $date->setTimezone(new DateTimeZone('UTC'));
  340. }
  341. return $date;
  342. }
  343. /**
  344. * Convert an LDAP-compatible boolean value into a PHP-compatible one
  345. *
  346. * @param string $value The value to convert
  347. * @return boolean
  348. * @throws InvalidArgumentException
  349. */
  350. public static function fromLdapBoolean($value)
  351. {
  352. if ( 'TRUE' === $value ) {
  353. return true;
  354. } else if ( 'FALSE' === $value ) {
  355. return false;
  356. } else {
  357. throw new InvalidArgumentException('The given value is not a boolean value');
  358. }
  359. }
  360. /**
  361. * Unserialize a serialized value to return the corresponding object
  362. *
  363. * @param string $value The value to convert
  364. * @return mixed
  365. * @throws UnexpectedValueException
  366. */
  367. public static function fromLdapUnserialize($value)
  368. {
  369. $v = @unserialize($value);
  370. if (false===$v && $value != 'b:0;') {
  371. throw new UnexpectedValueException('The given value could not be unserialized');
  372. }
  373. return $v;
  374. }
  375. }