V.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. <?php
  2. /**
  3. * @see http://pl2.php.net/manual/en/book.var.php
  4. *
  5. * Define Your own convert function: var func_type_convert_{$type}($var);
  6. */
  7. class V {
  8. /**
  9. * Get variable from array or object - case insensitive
  10. */
  11. public static function geti($name, $default, $from, $type = '', $filterCallback = null) {
  12. $lowerFrom = array();
  13. if (!is_object($from) && !is_array($from)) throw new Exception("Bad param - from must be array or object");
  14. foreach ((array)$from as $fieldName => $value) {
  15. $lowerFrom[ strtolower($fieldName) ] = $value;
  16. }
  17. return V::get(strtolower($name), $default, $lowerFrom, $type, $filterCallback);
  18. }
  19. /**
  20. * Get variable from array or object.
  21. */
  22. public static function get($name, $default, $from, $type = '', $filterCallback = null) {
  23. if (empty($name)) return null;
  24. $ret = null;
  25. if (is_bool($name)) $name = (int)$name;
  26. if (!is_string($name) && !is_numeric($name)) {
  27. //var_dump($name);
  28. //echo'<pre>';print_r(debug_backtrace());echo'</pre>';
  29. throw new Exception("Error name is not scalar! '{$name}'");
  30. }
  31. if (is_array($from)) {
  32. if (array_key_exists($name, $from)) {
  33. $ret = $from[$name];
  34. }
  35. }
  36. else if (is_object($from)) {
  37. if (isset($from->$name)) {
  38. $ret = $from->$name;
  39. }
  40. }
  41. if (isset($ret) && $type != '') {
  42. $ret = V::convert($ret, $type);
  43. }
  44. if (!empty($filterCallback)) {
  45. if ($type == 'array' && is_array($ret) && !empty($ret)) {
  46. $ret = V::filter($ret, $filterCallback);
  47. }
  48. }
  49. $ret = (null !== $ret)? $ret : $default;
  50. return $ret;
  51. }
  52. /**
  53. * Convert variable type.
  54. * @usage: V::convert($from, 'url');
  55. */
  56. public static function convert($from, $type = 'string') {
  57. $type = strtolower($type);
  58. // is_scalar($from) - return TRUE if int,float,string,bool, FALSE if array,object,resource, ...
  59. $ret = null;
  60. switch ($type) {
  61. case 'string':
  62. if (is_scalar($from)) {
  63. $ret = $from;
  64. settype($ret, $type);
  65. }
  66. break;
  67. case 'word':
  68. if (is_scalar($from)) {
  69. $ret = $from;
  70. settype($ret, 'string');
  71. $ret = trim($ret);
  72. if (false !== ($pos = strpos($ret, ' '))) {
  73. $ret = substr($ret, 0, $pos);
  74. }
  75. }
  76. break;
  77. case 'login':// [a-zA-Z.-_]
  78. if (is_scalar($from)) {
  79. $ret = $from;
  80. settype($ret, 'string');
  81. $ret = trim($ret);
  82. if (!preg_match("/^[a-zA-Z.-_]*$/", $ret, $matches)) {
  83. $ret = null;
  84. }
  85. }
  86. break;
  87. case 'url':// [a-zA-Z0-9_-]
  88. if (is_scalar($from)) {
  89. $ret = $from;
  90. settype($ret, 'string');
  91. $ret = trim($ret);
  92. $pl_letters = array('ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż', 'Ą', 'Ć', 'Ę', 'Ł', 'Ń', 'Ó', 'Ś', 'Ź', 'Ż');
  93. $en_letters = array('a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z', 'A', 'C', 'E', 'L', 'N', 'O', 'S', 'Z', 'Z');
  94. $ret = str_replace($pl_letters, $en_letters, $ret);
  95. $ret = preg_replace('/[^a-zA-Z0-9_-]+/', '_', $ret);
  96. }
  97. break;
  98. case 'int':
  99. case 'integer':
  100. if (is_scalar($from)) {
  101. $ret = $from;
  102. settype($ret, $type);
  103. }
  104. break;
  105. case 'float':
  106. case 'double':
  107. if (is_scalar($from)) {
  108. $ret = str_replace(',', '.', $from);
  109. settype($ret, $type);
  110. }
  111. break;
  112. case 'price':// 0.00 - decimal(n, 2)
  113. if (is_scalar($from)) {
  114. $ret = str_replace(',', '.', $from);
  115. settype($ret, 'float');
  116. $ret = round($ret, 2);
  117. }
  118. break;
  119. case 'object':
  120. case 'array':
  121. if (is_scalar($from) || is_array($from) || is_object($from)) {
  122. $ret = $from;
  123. settype($ret, $type);
  124. }
  125. break;
  126. case 'int_array':
  127. if (is_scalar($from) || is_array($from) || is_object($from)) {
  128. $ret = array();
  129. $arr = $from;
  130. settype($arr, 'array');
  131. foreach ($arr as $v) {
  132. $v = V::convert($v, 'int');
  133. $ret[] = $v;
  134. }
  135. }
  136. break;
  137. case 'uint_array':// uncigned int array
  138. if (is_scalar($from) || is_array($from) || is_object($from)) {
  139. $ret = array();
  140. $arr = $from;
  141. settype($arr, 'array');
  142. foreach ($arr as $v) {
  143. $v = V::convert($v, 'int');
  144. if ($v <= 0) continue;
  145. $ret[] = $v;
  146. }
  147. }
  148. break;
  149. case 'float_array':// uncigned int array
  150. if (is_scalar($from) || is_array($from) || is_object($from)) {
  151. $ret = array();
  152. $arr = $from;
  153. settype($arr, 'array');
  154. foreach ($arr as $v) {
  155. $v = V::convert($v, 'float');
  156. $ret[] = $v;
  157. }
  158. }
  159. break;
  160. case 'bool':
  161. case 'boolean': return (bool)$from;
  162. default:
  163. $fun = 'func_type_convert_'.$type;
  164. if (function_exists($fun)) {
  165. $ret = $fun($from);
  166. }
  167. break;
  168. }
  169. return $ret;
  170. }
  171. /**
  172. * Merge the contents of two objects/array.
  173. *
  174. * array V::extend(mixed $defaults, mixed $params);
  175. * @see http://api.jquery.com/jQuery.extend/
  176. * is_scalar($from) - return TRUE if int,float,string,bool, FALSE if array,object,resource, ...
  177. */
  178. public static function extend($defaults, $params) {
  179. $ret = array();
  180. $d = (is_array($defaults))? $defaults : (array)$defaults;
  181. $p = (is_array($params))? $params : (array)$params;
  182. foreach ($d as $k => $v) {
  183. $ret[$k] = $v;
  184. }
  185. foreach ($p as $k => $v) {
  186. if (array_key_exists($k, $ret) && (is_array($ret[$k]) || is_object($ret[$k])) && (is_array($v) || is_object($v))) {
  187. $ret[$k] = V::extend($ret[$k], $v);
  188. } else {
  189. $ret[$k] = $v;
  190. }
  191. }
  192. return $ret;
  193. }
  194. public static function json_encode_latin2($o, $force_object = false) {
  195. if ($o === '') {
  196. return '""';
  197. }
  198. else if (!$o) {
  199. return 'null';
  200. }
  201. else if (is_array($o)) {
  202. $arr = '';
  203. if ($force_object) {
  204. foreach ($o as $k => $v) {
  205. $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  206. }
  207. return '{'.implode(',',$arr).'}';
  208. }
  209. else {
  210. foreach ($o as $k => $v) {
  211. if (is_string($k)) $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  212. else $arr[] = V::json_encode_latin2($v);
  213. }
  214. return '['.implode(',',$arr).']';
  215. }
  216. }
  217. else if (is_object($o)) {
  218. $arr = '';
  219. foreach (get_object_vars($o) as $k => $v) {
  220. $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  221. }
  222. return '{'.implode(',',$arr).'}';
  223. }
  224. else if (is_string($o)) {
  225. return '"'.addslashes(str_replace(array("\n","\r"), array('\n',''), $o)).'"';
  226. }
  227. else if (is_numeric($o)) {
  228. return ''.$o.'';
  229. }
  230. else if (is_bool($o)) {
  231. return ''.(($o)? 'true' : 'false').'';
  232. }
  233. }
  234. public static function copy($o) {
  235. $null = null;
  236. if (!$o) {
  237. return $null;
  238. }
  239. else if (is_array($o)) {
  240. $ret = array();
  241. foreach ($o as $k => $v) {
  242. $ret[$k] = $v;
  243. }
  244. return $ret;
  245. }
  246. else if (is_object($o)) {
  247. $ret = new stdClass();
  248. foreach (get_object_vars($o) as $k => $v) {
  249. $ret->$k = $v;
  250. }
  251. return $ret;
  252. }
  253. else {
  254. $ret = $o;
  255. return $ret;
  256. }
  257. }
  258. public static function make_link($prefix = '', $params = array()) {
  259. $ret = '';
  260. if ($prefix) {
  261. $ret = $prefix;
  262. }
  263. if (!empty($params)) {
  264. $ret_arr = array();
  265. foreach ($params as $k => $v) {
  266. $ret_arr[] = $k . "=" . $v;
  267. }
  268. $ret .= "?" . implode("&", $ret_arr);
  269. }
  270. return $ret;
  271. }
  272. public static function strShort($label, $maxLength = 10, $suffix = ' ...') {
  273. if (strlen($label) > $maxLength) {
  274. $pos = strpos($label, ' - ');
  275. if ($pos > $maxLength || $pos < 5) {
  276. $label = substr($label, 0, $pos) . $suffix;
  277. } else {
  278. $label = substr($label, 0, $pos);
  279. }
  280. }
  281. return $label;
  282. }
  283. public static function strShortUtf8($label, $maxLength = 10, $suffix = ' ...') {
  284. if (mb_strlen($label, 'utf-8') > $maxLength) {
  285. $pos = mb_strpos($label, ' - ', 0, 'utf-8');
  286. if ($pos > $maxLength || $pos < 5) {
  287. $label = mb_substr($label, 0, $maxLength, 'utf-8') . $suffix;
  288. } else {
  289. $label = mb_substr($label, 0, $pos, 'utf-8');
  290. }
  291. }
  292. return $label;
  293. }
  294. public static function filter($array, $filterCallback) {
  295. if (!is_callable($filterCallback)) {
  296. throw new Exception("callback is not callable '" . ((is_array($filterCallback))? implode('.', $filterCallback) : $filterCallback) . "'");
  297. }
  298. return array_filter($array, $filterCallback);
  299. }
  300. public static function filterNotEmpty($value) {
  301. return !empty($value);
  302. }
  303. public static function filterInteger($value) {// An integer or string with integer value
  304. if (is_int($value)) {
  305. return true;
  306. } else if (is_string($value)) {
  307. if ((string)(int)$value === $value) {
  308. return true;
  309. }
  310. }
  311. return false;
  312. }
  313. public static function filterNegativeInteger($value) {// An integer containing only negative values (..,-2,-1)
  314. if (V::filterInteger($value)) {
  315. if (intval($value) < 0) {
  316. return true;
  317. }
  318. }
  319. return false;
  320. }
  321. public static function filterNonNegativeInteger($value) {// An integer containing only non-negative values (0,1,2,..)
  322. if (V::filterInteger($value)) {
  323. if (intval($value) >= 0) {
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. public static function filterNonPositiveInteger($value) {// An integer containing only non-positive values (..,-2,-1,0)
  330. if (V::filterInteger($value)) {
  331. if (intval($value) <= 0) {
  332. return true;
  333. }
  334. }
  335. return false;
  336. }
  337. public static function filterPositiveInteger($value) {// An integer containing only positive values (1,2,..)
  338. if (V::filterInteger($value)) {
  339. if (intval($value) > 0) {
  340. return true;
  341. }
  342. }
  343. return false;
  344. }
  345. public static function validate($argName, $args, $params) {
  346. //$what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$when_values));
  347. $argValue = V::get($argName, null, $args);
  348. $fldLabel = V::get('fld_label', $argName, $params);
  349. if (array_key_exists('not_empty', $params) && true == $params['not_empty']) {
  350. if (!array_key_exists($argName, $args) || empty($args[$argName])) throw new Exception("Field {$fldLabel} not set.");
  351. }
  352. $params['fld_label'] = $fldLabel;
  353. return V::validateValue($argValue, $params);
  354. }
  355. public static function validateValue($value, $params) {
  356. $fldLabel = V::get('fld_label', '', $params);
  357. $maxLength = V::get('max_length', 0, $params);
  358. if ($maxLength > 0) {
  359. if (strlen($value) > $maxLength) throw new Exception("'{$fldLabel}' cannot be longer then {$maxLength}.");
  360. }
  361. $allowedValues = V::get('values', null, $params);
  362. if (is_array($allowedValues) && !empty($allowedValues)) {
  363. if (!in_array($value, $allowedValues)) throw new Exception("'{$fldLabel}' value is not allowed");
  364. }
  365. $type = V::get('type', null, $params);
  366. if ($type != null) {
  367. if ('word' == $type) {
  368. if (!is_scalar($value) || !preg_match('/^[a-zA-Z_-]*$/', $value)) throw new Exception("required type '{$type}' ({$fldLabel})");
  369. } else if ('login' == $type) {
  370. if (!is_scalar($value) || !preg_match('/^[a-zA-Z\._-]*$/', $value)) throw new Exception("required type '{$type}' ({$fldLabel})");
  371. } else {
  372. throw new Exception("Unimplemented type to validate: '{$type}'");
  373. }
  374. }
  375. if (array_key_exists('equal', $params)) {
  376. if ($value != $params['equal']) throw new Exception(V::get('error_msg_equal', "'{$fldLabel}' must be equal to '{$params['equal']}'", $params));
  377. }
  378. if (array_key_exists('equalStrict', $params)) {
  379. if ($value !== $params['equalStrict']) throw new Exception(V::get('error_msg_equalStrict', "'{$fldLabel}' must be strict equal to '{$params['equal']}'", $params));
  380. }
  381. return $value;
  382. }
  383. public static function exec($cmd, &$out, &$ret) {
  384. $out = null;
  385. $ret = null;
  386. $path = "PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/opt/local/lib/mysql55/bin:/Applications/Server.app/Contents/ServerRoot/usr/bin:/Applications/Server.app/Contents/ServerRoot/usr/sbin:/Users/pl/programy/bin";
  387. $cmd = "{$path}\n{$cmd}";
  388. exec($cmd, $out, $ret);
  389. return $ret;
  390. }
  391. public static function execRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  392. $out = null;
  393. $ret = null;
  394. $pass = $password;
  395. $pass = str_replace('!', '\!', $pass);
  396. $sshPort = (22 != $port)? "-p {$port}" : '';
  397. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  398. declare PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/opt/local/lib/mysql55/bin/:/Applications/Server.app/Contents/ServerRoot/usr/sbin/
  399. '.$command.'
  400. EOF';
  401. exec($cmd, $out, $ret);
  402. return $ret;
  403. }
  404. public static function execRootRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  405. $out = null;
  406. $ret = null;
  407. $pass = $password;
  408. $pass = str_replace('!', '\!', $pass);
  409. $sshPort = (22 != $port)? "-p {$port}" : '';
  410. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o StrictHostKeyChecking=no -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  411. sudo -n su -
  412. declare PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/opt/local/lib/mysql55/bin/:/Applications/Server.app/Contents/ServerRoot/usr/sbin/
  413. '.$command.'
  414. EOF';
  415. exec($cmd, $out, $ret);
  416. return $ret;
  417. }
  418. public static function cloneArray($arr) {
  419. return $arr;
  420. }
  421. public static function humanFileSize($bytes) {
  422. $bytes = intval($bytes);
  423. $arBytes = array(
  424. 0 => array("UNIT" => "TB", "VALUE" => pow(1024, 4)),
  425. 1 => array("UNIT" => "GB", "VALUE" => pow(1024, 3)),
  426. 2 => array("UNIT" => "MB", "VALUE" => pow(1024, 2)),
  427. 3 => array("UNIT" => "KB", "VALUE" => 1024),
  428. 4 => array("UNIT" => "B", "VALUE" => 1)
  429. );
  430. foreach($arBytes as $arItem) {
  431. if ($bytes >= $arItem["VALUE"]) {
  432. $result = $bytes / $arItem["VALUE"];
  433. $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
  434. break;
  435. }
  436. }
  437. return $result;
  438. }
  439. public static function kwotaSlownie($kwota = 0, $waluta = "PLN") {
  440. if (!preg_match("/^[[:digit:]]*(\.[[:digit:]]+)?$/",$kwota)) throw new Exception("Błędna liczba");
  441. if (!preg_match("/^[[:digit:]]{0,48}(\.[[:digit:]]+)?$/",$kwota)) throw new Exception("Zbyt duża liczba");
  442. $waluty = array(
  443. 'PLN' => array('złoty','złotych','złote'),
  444. 'USD' => array('dolar','dolarów','dolary')
  445. );
  446. $jednosci = array('zero','jeden','dwa','trzy','cztery','pięć','sześć','siedem','osiem','dziewięć','dziesięć','jedenaście',
  447. 'dwanaście','trzynaście','czternaście','piętnaście','szesnaście','siednaście','osiemnaście','dziewiętnaście');
  448. $dziesiatki = array('','','dwadzieścia','trzydzieści','czterdzieści','pięćdziesiąt','sześćdziesiąt','siedemdziesiąt','osiemdziesiąt','dziewięćdziesiąt');
  449. $setki = array('','sto','dwieście','trzysta','czterysta','pięćset','sześćset','siedemset','osiemset','dziewięćset');
  450. if (!isset($waluty[$waluta])) $tysiace[] = array($waluta,$waluta,$waluta);
  451. else $tysiace[] = $waluty[$waluta];
  452. $tysiace[] = array('tysiąc','tysięcy','tysiące');
  453. $tysiace[] = array('milion','milionów','miliony');
  454. $tysiace[] = array('miliard','miliardów','miliardy');
  455. $tysiace[] = array('bilion','bilionów','bilony');
  456. $tysiace[] = array('biliard','biliardów','biliardy');
  457. $tysiace[] = array('trylion','trylionów','tryliony');
  458. $tysiace[] = array('tryliard','tryliardów','tryliardy');
  459. $tysiace[] = array('kwadrylion','kwadrylionów','kwadryliony');
  460. $tysiace[] = array('kwadryliard','kwadryliardów','kwaryliardy');
  461. $tysiace[] = array('kwintylion','kwintylionów','kwintyliony');
  462. $tysiace[] = array('kwintyliard','kwintyliardów','kwintyliardy');
  463. $tysiace[] = array('sekstylion','sekstylionów','sepstyliony');
  464. $tysiace[] = array('sekstyliard','sekstyliardów','sekstyliardy');
  465. $tysiace[] = array('septylion','septylionów','septyliony');
  466. $tysiace[] = array('septyliard','septyliardów','septyliardy');
  467. $kwota = (!substr_count($kwota, '.')) ? $kwota.'.00' : $kwota;
  468. list($zlote, $grosze) = explode('.', $kwota);
  469. $zlote = ltrim($zlote, '0');
  470. if ($zlote == '') $zlote = '0';
  471. if (strlen($grosze) == 1) $grosze .= "0";
  472. elseif (strlen($grosze) > 2) $grosze = round(substr($grosze, 0, 2).".".substr($grosze, 2), 0);
  473. $zlote = strrev(wordwrap(strrev($zlote), 3, '.', true));
  474. $zloteArr = explode('.', $zlote);
  475. foreach ($zloteArr as $i => $l) {
  476. $tysiac = count($zloteArr) - $i - 1;
  477. $setka = $setki[floor($l/100)];
  478. $dziesiatka = $dziesiatki[floor(($l%100)/10)];
  479. $jednosc = $dziesiatka ? $jednosci[$l%10] : $jednosci[$l%100];
  480. if ($l == 1 and ($tysiac > 0 or count($zloteArr) == 1)) $odmiana = 0;
  481. elseif (floor($l%100/10) != 1 and $l%10 >= 2 and $l%10 <= 4) $odmiana = 2;
  482. else $odmiana = 1;
  483. if ($setka) $resultArr[] = $setka;
  484. if ($dziesiatka) $resultArr[] = $dziesiatka;
  485. if ($jednosc == $jednosci[0] && $zlote != '0') $jednosc = '';
  486. if ($jednosc) $resultArr[] = $jednosc;
  487. if ($setka || $dziesiatka || $jednosc || $tysiac == 0) $resultArr[] = $tysiace[$tysiac][$odmiana];
  488. }
  489. $resultArr[] = $grosze . "/100";
  490. return implode(" ", $resultArr);
  491. }
  492. public static function nettoOdBrutto($brutto = 0, $vat = "23") {
  493. if ($vat < 0) throw new Exception("Stawka VAT nie może być liczbą ujemną!");
  494. $netto = round($brutto/(1+$vat/100),2);
  495. if (round($netto*(1+$vat/100),2) > $brutto) $netto -= 0.01;
  496. return $netto;
  497. }
  498. public static function makePick($fieldName, $default = '', $type = null) {
  499. return function ($item) use ($fieldName, $default, $type) {
  500. return V::get($fieldName, $default, $item, $type);
  501. };
  502. }
  503. public static function pickSimgleValue($items, $fieldName) {
  504. return array_map(
  505. function ($row) use ($fieldName) {
  506. return V::get($fieldName, '', $row);
  507. }
  508. , $items
  509. );
  510. }
  511. public static function pickArrayValues($items, $fieldNames) {
  512. return $items;
  513. }
  514. public static function arrayToXML($array, $formatOutput = false, $root = "root") {
  515. $arrayToXML_rec = function($data, $dom, $node, $parent = null) use (&$arrayToXML_rec) {
  516. $child = $dom->createElement($node);
  517. if (!$parent) $parent = $dom;
  518. if (is_array($data)) {
  519. foreach ($data as $key => $value) {
  520. if (is_numeric($key)) $arrayToXML_rec($value, $dom, $node, $parent);
  521. else $arrayToXML_rec($value, $dom, $key, $child);
  522. }
  523. } else {
  524. if ($data) {
  525. if ($data == htmlspecialchars($data)) $child->nodeValue = $data;
  526. else $child->appendChild($dom->createCDATASection($data));
  527. } else $parent->appendChild($child);
  528. }
  529. if ($child->hasChildNodes()) $parent->appendChild($child);
  530. };
  531. if (!is_array($array)) throw new Exception("First argument need to be an array");
  532. $dom = new DOMDocument('1.0', 'UTF-8');
  533. $dom->preserveWhiteSpace = false;
  534. $dom->formatOutput = $formatOutput;
  535. $arrayToXML_rec($array, $dom, $root);
  536. return $dom->saveXML();
  537. }
  538. // date("Y-m-d H:i:s") . substr((string)microtime(), 1, 6),
  539. // a: '2017-07-25 13:06:15.59124',
  540. // b: '2017-07-25 13:06:15.56161',
  541. // result: '0.02963'
  542. public static function milisecondsStringDiff($a, $b) {
  543. if (25 != strlen($a)) return "Wrong length in 1st arg";
  544. if (25 != strlen($b)) return "Wrong length in 2nd arg";
  545. $aTime = array_sum([
  546. intVal(substr($a, 11, 2)) * 100000 * 60 * 60, // hour
  547. intVal(substr($a, 14, 2)) * 100000 * 60, // min
  548. intVal(substr($a, 17, 2)) * 100000, // sec
  549. intVal(substr($a, 20, 5)), // mili sec (5 digits)
  550. ]);
  551. $bTime = array_sum([
  552. intVal(substr($b, 11, 2)) * 100000 * 60 * 60, // hour
  553. intVal(substr($b, 14, 2)) * 100000 * 60, // min
  554. intVal(substr($b, 17, 2)) * 100000, // sec
  555. intVal(substr($b, 20, 5)), // mili sec (5 digits)
  556. ]);
  557. return sprintf("%0.5f", abs($aTime - $bTime) / 100000);
  558. }
  559. public static function isNip($nip) {
  560. if (!(is_numeric($nip) && preg_match('/^[[:digit:]]{10}$/', $nip))) return false;
  561. $waga = [6, 5, 7, 2, 3, 4, 5, 6, 7];
  562. $c = 0;
  563. for ($i = 0; $i < 9; $i++) $c += $nip[$i] * $waga[$i];
  564. $c = ($c % 11) % 10;
  565. return ($nip[9] == $c);
  566. }
  567. public static function isRegon($regon) {
  568. if (!(is_numeric($regon) && preg_match('/^[[:digit:]]{9}$/', $regon))) return false;
  569. $waga = [8, 9, 2, 3, 4, 5, 6, 7];
  570. $c = 0;
  571. for ($i = 0; $i < 8; $i++) $c += $regon[$i] * $waga[$i];
  572. $c = ($c % 11) % 10;
  573. return ($regon[8] == $c);
  574. }
  575. }