PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/system/Zend/Ldap/Converter.php

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