V.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. return $ret;
  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. return $ret;
  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. return $ret;
  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. return $ret;
  98. case 'int':
  99. case 'integer':
  100. if (is_scalar($from)) {
  101. $ret = $from;
  102. settype($ret, $type);
  103. }
  104. return $ret;
  105. case 'float':
  106. case 'double':
  107. if (is_scalar($from)) {
  108. $ret = str_replace(',', '.', $from);
  109. settype($ret, $type);
  110. }
  111. return $ret;
  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. return $ret;
  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. return $ret;
  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. return $ret;
  137. case 'uint_array':// unsigned 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. return $ret;
  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. return $ret;
  160. case 'bool':
  161. case 'boolean': return (bool)$from;
  162. case 'minOccurs':
  163. case 'maxOccurs': // The default values for minOccurs and maxOccurs are 1 - @return int or 'unbounded', default is 1
  164. if (!is_scalar($from)) return null;
  165. if (!strlen($from)) return 1;
  166. if ("unbounded" === $from) return "unbounded";
  167. return (int)$from;
  168. default:
  169. $fun = 'func_type_convert_'.$type;
  170. return (function_exists($fun)) ? $fun($from) : null;
  171. }
  172. }
  173. /**
  174. * Merge the contents of two objects/array.
  175. *
  176. * array V::extend(mixed $defaults, mixed $params);
  177. * @see http://api.jquery.com/jQuery.extend/
  178. * is_scalar($from) - return TRUE if int,float,string,bool, FALSE if array,object,resource, ...
  179. */
  180. public static function extend($defaults, $params) {
  181. $ret = array();
  182. $d = (is_array($defaults))? $defaults : (array)$defaults;
  183. $p = (is_array($params))? $params : (array)$params;
  184. foreach ($d as $k => $v) {
  185. $ret[$k] = $v;
  186. }
  187. foreach ($p as $k => $v) {
  188. if (array_key_exists($k, $ret) && (is_array($ret[$k]) || is_object($ret[$k])) && (is_array($v) || is_object($v))) {
  189. $ret[$k] = V::extend($ret[$k], $v);
  190. } else {
  191. $ret[$k] = $v;
  192. }
  193. }
  194. return $ret;
  195. }
  196. public static function json_encode_latin2($o, $force_object = false) {
  197. if ($o === '') {
  198. return '""';
  199. }
  200. else if (!$o) {
  201. return 'null';
  202. }
  203. else if (is_array($o)) {
  204. $arr = '';
  205. if ($force_object) {
  206. foreach ($o as $k => $v) {
  207. $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  208. }
  209. return '{'.implode(',',$arr).'}';
  210. }
  211. else {
  212. foreach ($o as $k => $v) {
  213. if (is_string($k)) $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  214. else $arr[] = V::json_encode_latin2($v);
  215. }
  216. return '['.implode(',',$arr).']';
  217. }
  218. }
  219. else if (is_object($o)) {
  220. $arr = '';
  221. foreach (get_object_vars($o) as $k => $v) {
  222. $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  223. }
  224. return '{'.implode(',',$arr).'}';
  225. }
  226. else if (is_string($o)) {
  227. return '"'.addslashes(str_replace(array("\n","\r"), array('\n',''), $o)).'"';
  228. }
  229. else if (is_numeric($o)) {
  230. return ''.$o.'';
  231. }
  232. else if (is_bool($o)) {
  233. return ''.(($o)? 'true' : 'false').'';
  234. }
  235. }
  236. public static function copy($o) {
  237. $null = null;
  238. if (!$o) {
  239. return $null;
  240. }
  241. else if (is_array($o)) {
  242. $ret = array();
  243. foreach ($o as $k => $v) {
  244. $ret[$k] = $v;
  245. }
  246. return $ret;
  247. }
  248. else if (is_object($o)) {
  249. $ret = new stdClass();
  250. foreach (get_object_vars($o) as $k => $v) {
  251. $ret->$k = $v;
  252. }
  253. return $ret;
  254. }
  255. else {
  256. $ret = $o;
  257. return $ret;
  258. }
  259. }
  260. public static function make_link($prefix = '', $params = array()) {
  261. $ret = '';
  262. if ($prefix) {
  263. $ret = $prefix;
  264. }
  265. if (!empty($params)) {
  266. $ret_arr = array();
  267. foreach ($params as $k => $v) {
  268. $ret_arr[] = $k . "=" . $v;
  269. }
  270. $ret .= "?" . implode("&", $ret_arr);
  271. }
  272. return $ret;
  273. }
  274. public static function strShort($label, $maxLength = 10, $suffix = ' ...') {
  275. if (strlen($label) > $maxLength) {
  276. $pos = strpos($label, ' - ');
  277. if ($pos > $maxLength || $pos < 5) {
  278. $label = substr($label, 0, $maxLength) . $suffix;
  279. } else {
  280. $label = substr($label, 0, $pos);
  281. }
  282. }
  283. return $label;
  284. }
  285. public static function strShortUtf8($label, $maxLength = 10, $suffix = ' ...') {
  286. if (mb_strlen($label, 'utf-8') > $maxLength) {
  287. $pos = mb_strpos($label, ' - ', 0, 'utf-8');
  288. if ($pos > $maxLength || $pos < 5) {
  289. $label = mb_substr($label, 0, $maxLength, 'utf-8') . $suffix;
  290. } else {
  291. $label = mb_substr($label, 0, $pos, 'utf-8');
  292. }
  293. }
  294. return $label;
  295. }
  296. public static function filter($array, $filterCallback) {
  297. if (!is_callable($filterCallback)) {
  298. throw new Exception("callback is not callable '" . ((is_array($filterCallback))? implode('.', $filterCallback) : $filterCallback) . "'");
  299. }
  300. return array_filter($array, $filterCallback);
  301. }
  302. public static function filterNotEmpty($value) {
  303. return !empty($value);
  304. }
  305. public static function filterInteger($value) {// An integer or string with integer value
  306. if (is_int($value)) {
  307. return true;
  308. } else if (is_string($value)) {
  309. if ((string)(int)$value === $value) {
  310. return true;
  311. }
  312. }
  313. return false;
  314. }
  315. public static function filterNegativeInteger($value) {// An integer containing only negative values (..,-2,-1)
  316. if (V::filterInteger($value)) {
  317. if (intval($value) < 0) {
  318. return true;
  319. }
  320. }
  321. return false;
  322. }
  323. public static function filterNonNegativeInteger($value) {// An integer containing only non-negative values (0,1,2,..)
  324. if (V::filterInteger($value)) {
  325. if (intval($value) >= 0) {
  326. return true;
  327. }
  328. }
  329. return false;
  330. }
  331. public static function filterNonPositiveInteger($value) {// An integer containing only non-positive values (..,-2,-1,0)
  332. if (V::filterInteger($value)) {
  333. if (intval($value) <= 0) {
  334. return true;
  335. }
  336. }
  337. return false;
  338. }
  339. public static function filterPositiveInteger($value) {// An integer containing only positive values (1,2,..)
  340. if (V::filterInteger($value)) {
  341. if (intval($value) > 0) {
  342. return true;
  343. }
  344. }
  345. return false;
  346. }
  347. public static function validate($argName, $args, $params) {
  348. //$what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$when_values));
  349. $argValue = V::get($argName, null, $args);
  350. $fldLabel = V::get('fld_label', $argName, $params);
  351. if (array_key_exists('not_empty', $params) && true == $params['not_empty']) {
  352. if (!array_key_exists($argName, $args) || empty($args[$argName])) throw new Exception("Field {$fldLabel} not set.");
  353. }
  354. $params['fld_label'] = $fldLabel;
  355. return V::validateValue($argValue, $params);
  356. }
  357. public static function validateValue($value, $params) {
  358. $fldLabel = V::get('fld_label', '', $params);
  359. $maxLength = V::get('max_length', 0, $params);
  360. if ($maxLength > 0) {
  361. if (strlen($value) > $maxLength) throw new Exception("'{$fldLabel}' cannot be longer then {$maxLength}.");
  362. }
  363. $allowedValues = V::get('values', null, $params);
  364. if (is_array($allowedValues) && !empty($allowedValues)) {
  365. if (!in_array($value, $allowedValues)) throw new Exception("'{$fldLabel}' value is not allowed");
  366. }
  367. $type = V::get('type', null, $params);
  368. if ($type != null) {
  369. if ('word' == $type) {
  370. if (!is_scalar($value) || !preg_match('/^[a-zA-Z_-]*$/', $value)) throw new Exception("required type '{$type}' ({$fldLabel})");
  371. } else if ('login' == $type) {
  372. if (!is_scalar($value) || !preg_match('/^[a-zA-Z\._-]*$/', $value)) throw new Exception("required type '{$type}' ({$fldLabel})");
  373. } else {
  374. throw new Exception("Unimplemented type to validate: '{$type}'");
  375. }
  376. }
  377. if (array_key_exists('equal', $params)) {
  378. if ($value != $params['equal']) throw new Exception(V::get('error_msg_equal', "'{$fldLabel}' must be equal to '{$params['equal']}'", $params));
  379. }
  380. if (array_key_exists('equalStrict', $params)) {
  381. if ($value !== $params['equalStrict']) throw new Exception(V::get('error_msg_equalStrict', "'{$fldLabel}' must be strict equal to '{$params['equal']}'", $params));
  382. }
  383. return $value;
  384. }
  385. public static function exec($cmd, &$out, &$ret) {
  386. $out = null;
  387. $ret = null;
  388. // NOTE: SourceGuardian requires file: "${HOME}/.config/SourceGuardian/"
  389. $cmd = implode("\n", [
  390. "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",
  391. "export HOME='/Library/WebServer'",
  392. $cmd
  393. ]);
  394. exec($cmd, $out, $ret);
  395. return $ret;
  396. }
  397. public static function execRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  398. $out = null;
  399. $ret = null;
  400. $pass = $password;
  401. $pass = str_replace('!', '\!', $pass);
  402. $sshPort = (22 != $port)? "-p {$port}" : '';
  403. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  404. 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/
  405. '.$command.'
  406. EOF';
  407. exec($cmd, $out, $ret);
  408. return $ret;
  409. }
  410. public static function execRootRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  411. $out = null;
  412. $ret = null;
  413. $pass = $password;
  414. $pass = str_replace('!', '\!', $pass);
  415. $sshPort = (22 != $port)? "-p {$port}" : '';
  416. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  417. sudo -n su -
  418. 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/
  419. '.$command.'
  420. EOF';
  421. exec($cmd, $out, $ret);
  422. return $ret;
  423. }
  424. public static function quoteBashEcho($string) {
  425. return str_replace([ '"', '$' ], [ '\"', '\$' ], $string);
  426. }
  427. public static function cloneArray($arr) {
  428. return $arr;
  429. }
  430. public static function humanFileSize($bytes) {
  431. $bytes = intval($bytes);
  432. $arBytes = array(
  433. 0 => array("UNIT" => "TB", "VALUE" => pow(1024, 4)),
  434. 1 => array("UNIT" => "GB", "VALUE" => pow(1024, 3)),
  435. 2 => array("UNIT" => "MB", "VALUE" => pow(1024, 2)),
  436. 3 => array("UNIT" => "KB", "VALUE" => 1024),
  437. 4 => array("UNIT" => "B", "VALUE" => 1)
  438. );
  439. foreach($arBytes as $arItem) {
  440. if ($bytes >= $arItem["VALUE"]) {
  441. $result = $bytes / $arItem["VALUE"];
  442. $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
  443. break;
  444. }
  445. }
  446. return $result;
  447. }
  448. public static function kwotaSlownie($kwota = 0, $waluta = "PLN") {
  449. if (!preg_match("/^[[:digit:]]*(\.[[:digit:]]+)?$/",$kwota)) throw new Exception("Błędna liczba");
  450. if (!preg_match("/^[[:digit:]]{0,48}(\.[[:digit:]]+)?$/",$kwota)) throw new Exception("Zbyt duża liczba");
  451. $waluty = array(
  452. 'PLN' => array('złoty','złotych','złote'),
  453. 'USD' => array('dolar','dolarów','dolary')
  454. );
  455. $jednosci = array('zero','jeden','dwa','trzy','cztery','pięć','sześć','siedem','osiem','dziewięć','dziesięć','jedenaście',
  456. 'dwanaście','trzynaście','czternaście','piętnaście','szesnaście','siednaście','osiemnaście','dziewiętnaście');
  457. $dziesiatki = array('','','dwadzieścia','trzydzieści','czterdzieści','pięćdziesiąt','sześćdziesiąt','siedemdziesiąt','osiemdziesiąt','dziewięćdziesiąt');
  458. $setki = array('','sto','dwieście','trzysta','czterysta','pięćset','sześćset','siedemset','osiemset','dziewięćset');
  459. if (!isset($waluty[$waluta])) $tysiace[] = array($waluta,$waluta,$waluta);
  460. else $tysiace[] = $waluty[$waluta];
  461. $tysiace[] = array('tysiąc','tysięcy','tysiące');
  462. $tysiace[] = array('milion','milionów','miliony');
  463. $tysiace[] = array('miliard','miliardów','miliardy');
  464. $tysiace[] = array('bilion','bilionów','bilony');
  465. $tysiace[] = array('biliard','biliardów','biliardy');
  466. $tysiace[] = array('trylion','trylionów','tryliony');
  467. $tysiace[] = array('tryliard','tryliardów','tryliardy');
  468. $tysiace[] = array('kwadrylion','kwadrylionów','kwadryliony');
  469. $tysiace[] = array('kwadryliard','kwadryliardów','kwaryliardy');
  470. $tysiace[] = array('kwintylion','kwintylionów','kwintyliony');
  471. $tysiace[] = array('kwintyliard','kwintyliardów','kwintyliardy');
  472. $tysiace[] = array('sekstylion','sekstylionów','sepstyliony');
  473. $tysiace[] = array('sekstyliard','sekstyliardów','sekstyliardy');
  474. $tysiace[] = array('septylion','septylionów','septyliony');
  475. $tysiace[] = array('septyliard','septyliardów','septyliardy');
  476. $kwota = (!substr_count($kwota, '.')) ? $kwota.'.00' : $kwota;
  477. list($zlote, $grosze) = explode('.', $kwota);
  478. $zlote = ltrim($zlote, '0');
  479. if ($zlote == '') $zlote = '0';
  480. if (strlen($grosze) == 1) $grosze .= "0";
  481. elseif (strlen($grosze) > 2) $grosze = round(substr($grosze, 0, 2).".".substr($grosze, 2), 0);
  482. $zlote = strrev(wordwrap(strrev($zlote), 3, '.', true));
  483. $zloteArr = explode('.', $zlote);
  484. foreach ($zloteArr as $i => $l) {
  485. $tysiac = count($zloteArr) - $i - 1;
  486. $setka = $setki[floor($l/100)];
  487. $dziesiatka = $dziesiatki[floor(($l%100)/10)];
  488. $jednosc = $dziesiatka ? $jednosci[$l%10] : $jednosci[$l%100];
  489. if ($l == 1 and ($tysiac > 0 or count($zloteArr) == 1)) $odmiana = 0;
  490. elseif (floor($l%100/10) != 1 and $l%10 >= 2 and $l%10 <= 4) $odmiana = 2;
  491. else $odmiana = 1;
  492. if ($setka) $resultArr[] = $setka;
  493. if ($dziesiatka) $resultArr[] = $dziesiatka;
  494. if ($jednosc == $jednosci[0] && $zlote != '0') $jednosc = '';
  495. if ($jednosc) $resultArr[] = $jednosc;
  496. if ($setka || $dziesiatka || $jednosc || $tysiac == 0) $resultArr[] = $tysiace[$tysiac][$odmiana];
  497. }
  498. $resultArr[] = $grosze . "/100";
  499. return implode(" ", $resultArr);
  500. }
  501. public static function nettoOdBrutto($brutto = 0, $vat = "23") {
  502. if ($vat < 0) throw new Exception("Stawka VAT nie może być liczbą ujemną!");
  503. $netto = round($brutto/(1+$vat/100),2);
  504. if (round($netto*(1+$vat/100),2) > $brutto) $netto -= 0.01;
  505. return $netto;
  506. }
  507. public static function makePick($fieldName, $default = '', $type = null) {
  508. return function ($item) use ($fieldName, $default, $type) {
  509. return V::get($fieldName, $default, $item, $type);
  510. };
  511. }
  512. public static function pickSimgleValue($items, $fieldName) {
  513. return array_map(
  514. function ($row) use ($fieldName) {
  515. return V::get($fieldName, '', $row);
  516. }
  517. , $items
  518. );
  519. }
  520. public static function pickArrayValues($items, $fieldNames) {
  521. return $items;
  522. }
  523. public static function arrayToXML($array, $formatOutput = false, $root = "root") {
  524. $arrayToXML_rec = function($data, $dom, $node, $parent = null) use (&$arrayToXML_rec) {
  525. $child = $dom->createElement($node);
  526. if (!$parent) $parent = $dom;
  527. if (is_array($data)) {
  528. if ($data) {
  529. foreach ($data as $key => $value) {
  530. if ((string)$key === '@attributes') {
  531. foreach ($value as $attrName => $attrValue) {
  532. $attr = $dom->createAttribute($attrName);
  533. $attr->value = $attrValue;
  534. $child->appendChild($attr);
  535. }
  536. } else {
  537. if (is_numeric($key)) $arrayToXML_rec($value, $dom, $node, $parent);
  538. else $arrayToXML_rec($value, $dom, $key, $child);
  539. }
  540. }
  541. } else $parent->appendChild($child);
  542. } else {
  543. if ($data) {
  544. if ($data == htmlspecialchars($data)) $child->nodeValue = $data;
  545. else $child->appendChild($dom->createCDATASection($data));
  546. } else $parent->appendChild($child);
  547. }
  548. if ($child->hasChildNodes()) $parent->appendChild($child);
  549. };
  550. if (!is_array($array)) throw new Exception("First argument need to be an array");
  551. $dom = new DOMDocument('1.0', 'UTF-8');
  552. $dom->preserveWhiteSpace = false;
  553. $dom->formatOutput = $formatOutput;
  554. $arrayToXML_rec($array, $dom, $root);
  555. return $dom->saveXML();
  556. }
  557. // date("Y-m-d H:i:s") . substr((string)microtime(), 1, 6),
  558. // a: '2017-07-25 13:06:15.59124',
  559. // b: '2017-07-25 13:06:15.56161',
  560. // result: '0.02963'
  561. public static function milisecondsStringDiff($a, $b) {
  562. if (25 != strlen($a)) return "Wrong length in 1st arg";
  563. if (25 != strlen($b)) return "Wrong length in 2nd arg";
  564. $aTime = array_sum([
  565. intVal(substr($a, 11, 2)) * 100000 * 60 * 60, // hour
  566. intVal(substr($a, 14, 2)) * 100000 * 60, // min
  567. intVal(substr($a, 17, 2)) * 100000, // sec
  568. intVal(substr($a, 20, 5)), // mili sec (5 digits)
  569. ]);
  570. $bTime = array_sum([
  571. intVal(substr($b, 11, 2)) * 100000 * 60 * 60, // hour
  572. intVal(substr($b, 14, 2)) * 100000 * 60, // min
  573. intVal(substr($b, 17, 2)) * 100000, // sec
  574. intVal(substr($b, 20, 5)), // mili sec (5 digits)
  575. ]);
  576. return sprintf("%0.5f", abs($aTime - $bTime) / 100000);
  577. }
  578. public static function isNip($nip) {
  579. if (!(is_numeric($nip) && preg_match('/^[[:digit:]]{10}$/', $nip))) return false;
  580. $waga = [6, 5, 7, 2, 3, 4, 5, 6, 7];
  581. $c = 0;
  582. for ($i = 0; $i < 9; $i++) $c += $nip[$i] * $waga[$i];
  583. $c = ($c % 11) % 10;
  584. return ($nip[9] == $c);
  585. }
  586. public static function isRegon($regon) {
  587. if (!(is_numeric($regon) && preg_match('/^[[:digit:]]{9}$/', $regon))) return false;
  588. $waga = [8, 9, 2, 3, 4, 5, 6, 7];
  589. $c = 0;
  590. for ($i = 0; $i < 8; $i++) $c += $regon[$i] * $waga[$i];
  591. $c = ($c % 11) % 10;
  592. return ($regon[8] == $c);
  593. }
  594. static function stripInvalidXmlChars($value = "") {
  595. return array_reduce(str_split((string)$value), function ($ret, $char) {
  596. $charCode = ord($char);
  597. if (
  598. (0x9 === $charCode)
  599. || (0xA === $charCode)
  600. || (0xD === $charCode)
  601. || (($charCode >= 0x20) && ($charCode <= 0xD7FF))
  602. || (($charCode >= 0xE000) && ($charCode <= 0xFFFD))
  603. || (($charCode >= 0x10000) && ($charCode <= 0x10FFFF))
  604. ) {
  605. return $ret . $char;
  606. }
  607. return $ret;
  608. }, "");
  609. }
  610. static function deleteWholeDirectory($dir, $returnFiles = false, $doDelete = true) {
  611. if (!is_dir($dir)) throw new Exception("{$dir} must be a directory");
  612. $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
  613. $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  614. if ($doDelete) {
  615. $rmdir = 'rmdir';
  616. $unlink = 'unlink';
  617. } else {
  618. $rmdir = 'is_string';
  619. $unlink = 'is_string';
  620. }
  621. if ($returnFiles) {
  622. $return = [];
  623. foreach ($files as $file) {
  624. if ($file->isDir()) $return['dirs'][$file->getRealPath()] = @$rmdir($file->getRealPath());
  625. else $return['files'][$file->getRealPath()] = @$unlink($file->getRealPath());
  626. }
  627. $return['dirs'][$dir] = @$rmdir($dir);
  628. return $return;
  629. } else {
  630. foreach ($files as $file) {
  631. if ($file->isDir()) @$rmdir($file->getRealPath());
  632. else @$unlink($file->getRealPath());
  633. }
  634. @$rmdir($dir);
  635. }
  636. }
  637. }