PageRenderTime 45ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Ldap/Converter.php

https://bitbucket.org/fabiancarlos/feature_seguimentos
PHP | 397 lines | 358 code | 2 blank | 37 comment | 4 complexity | 9ed72a0b32e230a6d7b00bcb01b6f706 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 24354 2011-08-05 07:36:38Z sgehrig $
  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. // prevent numeric values to be treated as date/time
  215. return $value;
  216. } else if ('TRUE' === $value || 'FALSE' === $value) {
  217. return self::fromLdapBoolean($value);
  218. }
  219. if (preg_match('/^\d{4}[\d\+\-Z\.]*$/', $value)) {
  220. return self::fromLdapDateTime($value, $dateTimeAsUtc);
  221. }
  222. try {
  223. return self::fromLdapUnserialize($value);
  224. } catch (UnexpectedValueException $e) { }
  225. break;
  226. }
  227. return $value;
  228. }
  229. /**
  230. * Convert an LDAP-Generalized-Time-entry into a DateTime-Object
  231. *
  232. * CAVEAT: The DateTime-Object returned will alwasy be set to UTC-Timezone.
  233. *
  234. * @param string $date The generalized-Time
  235. * @param boolean $asUtc Return the DateTime with UTC timezone
  236. * @return DateTime
  237. * @throws InvalidArgumentException if a non-parseable-format is given
  238. */
  239. public static function fromLdapDateTime($date, $asUtc = true)
  240. {
  241. $datepart = array ();
  242. if (!preg_match('/^(\d{4})/', $date, $datepart) ) {
  243. throw new InvalidArgumentException('Invalid date format found');
  244. }
  245. if ($datepart[1] < 4) {
  246. throw new InvalidArgumentException('Invalid date format found (too short)');
  247. }
  248. $time = array (
  249. // The year is mandatory!
  250. 'year' => $datepart[1],
  251. 'month' => 1,
  252. 'day' => 1,
  253. 'hour' => 0,
  254. 'minute' => 0,
  255. 'second' => 0,
  256. 'offdir' => '+',
  257. 'offsethours' => 0,
  258. 'offsetminutes' => 0
  259. );
  260. $length = strlen($date);
  261. // Check for month.
  262. if ($length >= 6) {
  263. $month = substr($date, 4, 2);
  264. if ($month < 1 || $month > 12) {
  265. throw new InvalidArgumentException('Invalid date format found (invalid month)');
  266. }
  267. $time['month'] = $month;
  268. }
  269. // Check for day
  270. if ($length >= 8) {
  271. $day = substr($date, 6, 2);
  272. if ($day < 1 || $day > 31) {
  273. throw new InvalidArgumentException('Invalid date format found (invalid day)');
  274. }
  275. $time['day'] = $day;
  276. }
  277. // Check for Hour
  278. if ($length >= 10) {
  279. $hour = substr($date, 8, 2);
  280. if ($hour < 0 || $hour > 23) {
  281. throw new InvalidArgumentException('Invalid date format found (invalid hour)');
  282. }
  283. $time['hour'] = $hour;
  284. }
  285. // Check for minute
  286. if ($length >= 12) {
  287. $minute = substr($date, 10, 2);
  288. if ($minute < 0 || $minute > 59) {
  289. throw new InvalidArgumentException('Invalid date format found (invalid minute)');
  290. }
  291. $time['minute'] = $minute;
  292. }
  293. // Check for seconds
  294. if ($length >= 14) {
  295. $second = substr($date, 12, 2);
  296. if ($second < 0 || $second > 59) {
  297. throw new InvalidArgumentException('Invalid date format found (invalid second)');
  298. }
  299. $time['second'] = $second;
  300. }
  301. // Set Offset
  302. $offsetRegEx = '/([Z\-\+])(\d{2}\'?){0,1}(\d{2}\'?){0,1}$/';
  303. $off = array ();
  304. if (preg_match($offsetRegEx, $date, $off)) {
  305. $offset = $off[1];
  306. if ($offset == '+' || $offset == '-') {
  307. $time['offdir'] = $offset;
  308. // we have an offset, so lets calculate it.
  309. if (isset($off[2])) {
  310. $offsetHours = substr($off[2], 0, 2);
  311. if ($offsetHours < 0 || $offsetHours > 12) {
  312. throw new InvalidArgumentException('Invalid date format found (invalid offset hour)');
  313. }
  314. $time['offsethours'] = $offsetHours;
  315. }
  316. if (isset($off[3])) {
  317. $offsetMinutes = substr($off[3], 0, 2);
  318. if ($offsetMinutes < 0 || $offsetMinutes > 59) {
  319. throw new InvalidArgumentException('Invalid date format found (invalid offset minute)');
  320. }
  321. $time['offsetminutes'] = $offsetMinutes;
  322. }
  323. }
  324. }
  325. // Raw-Data is present, so lets create a DateTime-Object from it.
  326. $offset = $time['offdir']
  327. . str_pad($time['offsethours'],2,'0',STR_PAD_LEFT)
  328. . str_pad($time['offsetminutes'],2,'0',STR_PAD_LEFT);
  329. $timestring = $time['year'] . '-'
  330. . str_pad($time['month'], 2, '0', STR_PAD_LEFT) . '-'
  331. . str_pad($time['day'], 2, '0', STR_PAD_LEFT) . ' '
  332. . str_pad($time['hour'], 2, '0', STR_PAD_LEFT) . ':'
  333. . str_pad($time['minute'], 2, '0', STR_PAD_LEFT) . ':'
  334. . str_pad($time['second'], 2, '0', STR_PAD_LEFT)
  335. . $time['offdir']
  336. . str_pad($time['offsethours'], 2, '0', STR_PAD_LEFT)
  337. . str_pad($time['offsetminutes'], 2, '0', STR_PAD_LEFT);
  338. $date = new DateTime($timestring);
  339. if ($asUtc) {
  340. $date->setTimezone(new DateTimeZone('UTC'));
  341. }
  342. return $date;
  343. }
  344. /**
  345. * Convert an LDAP-compatible boolean value into a PHP-compatible one
  346. *
  347. * @param string $value The value to convert
  348. * @return boolean
  349. * @throws InvalidArgumentException
  350. */
  351. public static function fromLdapBoolean($value)
  352. {
  353. if ( 'TRUE' === $value ) {
  354. return true;
  355. } else if ( 'FALSE' === $value ) {
  356. return false;
  357. } else {
  358. throw new InvalidArgumentException('The given value is not a boolean value');
  359. }
  360. }
  361. /**
  362. * Unserialize a serialized value to return the corresponding object
  363. *
  364. * @param string $value The value to convert
  365. * @return mixed
  366. * @throws UnexpectedValueException
  367. */
  368. public static function fromLdapUnserialize($value)
  369. {
  370. $v = @unserialize($value);
  371. if (false===$v && $value != 'b:0;') {
  372. throw new UnexpectedValueException('The given value could not be unserialized');
  373. }
  374. return $v;
  375. }
  376. }